repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
red-machine-games/goblin-base-server | test/issue_256/cloudFunctions/cloudFunction3.js | <gh_stars>1-10
await lock.self();
var publicProfileData = await getPublicProfileNode(selfHumanId, 'publicProfileData'); |
tnsilver/springboot-samples | springboot-rest-redis-contacts/src/main/java/com/tnsilver/contacts/repository/AuditRepositoryImpl.java | <reponame>tnsilver/springboot-samples<filename>springboot-rest-redis-contacts/src/main/java/com/tnsilver/contacts/repository/AuditRepositoryImpl.java
/*
* File: AuditRepositoryImpl.java
* Creation Date: Jul 8, 2021
*
* Copyright (c) 2021 T.N.Silverman - all rights reserved
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tnsilver.contacts.repository;
import static com.tnsilver.contacts.util.RedisUtils.copyProperties;
import static java.util.stream.Collectors.toList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.keyvalue.core.IterableConverter;
import org.springframework.data.redis.core.RedisKeyValueTemplate;
import org.springframework.data.repository.CrudRepository;
import org.springframework.util.Assert;
import com.tnsilver.contacts.annotation.AuditBeforeDelete;
import com.tnsilver.contacts.annotation.AuditBeforeModification;
import com.tnsilver.contacts.model.Audit;
import com.tnsilver.contacts.service.IdAssigningService;
/**
* Class ContactRepositoryImpl is custom implementation of a {@link Audit} making it possible to query
* Redis for hashes meeting specific search criteria, as is Spring Boot Data JPA repositories.
*
* @author T.N.Silverman
*
*/
public class AuditRepositoryImpl implements CrudRepository<Audit, Long>, AuditRepositoryCustom {
private static final Logger logger = LoggerFactory.getLogger(AuditRepositoryImpl.class);
@Autowired
private RedisKeyValueTemplate keyValueTemplate;
@Autowired
private IdAssigningService idAssigner;
// -------------------------------------------------------------------------
// Methods from CrudRepository
// -------------------------------------------------------------------------
@Override
@AuditBeforeModification
public <S extends Audit> S save(S audit) {
Assert.notNull(audit, "Audit must not be null!");
idAssigner.assignId(audit);
audit = keyValueTemplate.insert(audit);
logger.trace("saved {}", audit);
return audit;
}
@SuppressWarnings("unchecked")
@Override
public <S extends Audit> S update(S entity) {
Assert.notNull(entity, "Audit must not be null!");
Long id = entity.getId();
Optional<Audit> candidate = findById(id);
Assert.state(candidate.isPresent(), String.format("cannot update b/c no contact with id %s exists!", id));
Audit audit = candidate.get();
copyProperties(entity, audit, "createdBy", "createdOn");
entity = keyValueTemplate.update(id, (S) audit);
logger.trace("updated {}", entity);
return entity;
}
@Override
public <S extends Audit> Iterable<S> saveAll(Iterable<S> audits) {
Assert.notNull(audits, "The given iterable of audits must not be null!");
List<S> list = IterableConverter.toList(audits);
logger.trace("saving {} audits", list.size());
return list.stream().map(this::save).collect(toList());
}
@Override
public Optional<Audit> findById(Long id) {
Assert.notNull(id, "The given id must not be null!");
logger.trace("finding by id {}", id);
return keyValueTemplate.findById(id, Audit.class);
}
@Override
public boolean existsById(Long id) {
logger.trace("checking if id {} exists", id);
return findById(id).isPresent();
}
@Override
public List<Audit> findAll() {
logger.trace("finding all");
return IterableConverter.toList(keyValueTemplate.findAll(Audit.class));
}
@Override
public Iterable<Audit> findAllById(Iterable<Long> ids) {
Assert.notNull(ids, "The given iterable of id's must not be null!");
List<Long> list = IterableConverter.toList(ids);
logger.trace("finding {} ids", list.size());
return list.stream().map(this::findById).map(o -> o.orElse(null)).filter(Objects::nonNull).collect(toList());
}
@Override
public long count() {
logger.trace("counting");
return keyValueTemplate.count(Audit.class);
}
@Override
@AuditBeforeDelete
public void deleteById(Long id) {
Assert.notNull(id, "The given id must not be null!");
logger.trace("deleteing id {}", id);
keyValueTemplate.delete(id, Audit.class);
}
@Override
public void delete(Audit audit) {
Assert.notNull(audit, "The given audit must not be null!");
logger.trace("deleting {}", audit);
deleteById(audit.getId());
}
@Override
public void deleteAllById(Iterable<? extends Long> ids) {
Assert.notNull(ids, "The given iterable of ids must not be null!");
logger.trace("deleting all ids");
ids.forEach(this::deleteById);
}
@Override
public void deleteAll(Iterable<? extends Audit> audits) {
Assert.notNull(audits, "The given Iterable of entities must not be null!");
logger.trace("deleting entities");
audits.forEach(this::delete);
}
@Override
public void deleteAll() {
logger.trace("deleting all audits");
keyValueTemplate.delete(Audit.class);
}
} |
Boatdude55/staging-website | closure-templates/java/src/com/google/template/soy/sharedpasses/opti/SimplifyExprVisitor.java | /*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.template.soy.sharedpasses.opti;
import com.google.template.soy.data.SoyValue;
import com.google.template.soy.data.internalutils.InternalValueUtils;
import com.google.template.soy.data.restricted.BooleanData;
import com.google.template.soy.data.restricted.FloatData;
import com.google.template.soy.data.restricted.IntegerData;
import com.google.template.soy.data.restricted.NullData;
import com.google.template.soy.data.restricted.PrimitiveData;
import com.google.template.soy.data.restricted.StringData;
import com.google.template.soy.exprtree.AbstractExprNodeVisitor;
import com.google.template.soy.exprtree.BooleanNode;
import com.google.template.soy.exprtree.ExprNode;
import com.google.template.soy.exprtree.ExprNode.ParentExprNode;
import com.google.template.soy.exprtree.ExprNode.PrimitiveNode;
import com.google.template.soy.exprtree.ExprRootNode;
import com.google.template.soy.exprtree.FloatNode;
import com.google.template.soy.exprtree.FunctionNode;
import com.google.template.soy.exprtree.GlobalNode;
import com.google.template.soy.exprtree.IntegerNode;
import com.google.template.soy.exprtree.LegacyObjectMapLiteralNode;
import com.google.template.soy.exprtree.ListLiteralNode;
import com.google.template.soy.exprtree.MapLiteralNode;
import com.google.template.soy.exprtree.OperatorNodes.AndOpNode;
import com.google.template.soy.exprtree.OperatorNodes.ConditionalOpNode;
import com.google.template.soy.exprtree.OperatorNodes.OrOpNode;
import com.google.template.soy.exprtree.StringNode;
import com.google.template.soy.logging.LoggingFunction;
import com.google.template.soy.shared.internal.BuiltinFunction;
import com.google.template.soy.sharedpasses.render.Environment;
import com.google.template.soy.sharedpasses.render.RenderException;
/**
* Visitor for simplifying expressions based on constant values known at compile time.
*
* <p>Package-private helper for {@link SimplifyVisitor}.
*
*/
final class SimplifyExprVisitor extends AbstractExprNodeVisitor<Void> {
/** The PreevalVisitor for this instance (can reuse). */
private final PreevalVisitor preevalVisitor;
SimplifyExprVisitor() {
this.preevalVisitor = new PreevalVisitor(Environment.prerenderingEnvironment());
}
// -----------------------------------------------------------------------------------------------
// Implementation for root node.
@Override
protected void visitExprRootNode(ExprRootNode node) {
visit(node.getRoot());
}
// -----------------------------------------------------------------------------------------------
// Implementations for collection nodes.
@Override
protected void visitListLiteralNode(ListLiteralNode node) {
// Visit children only. We cannot simplify the list literal itself.
visitChildren(node);
}
@Override
protected void visitLegacyObjectMapLiteralNode(LegacyObjectMapLiteralNode node) {
// Visit children only. We cannot simplify the map literal itself.
visitChildren(node);
}
@Override
protected void visitMapLiteralNode(MapLiteralNode node) {
// Visit children only. We cannot simplify the map literal itself.
visitChildren(node);
}
// -----------------------------------------------------------------------------------------------
// Implementations for operators.
@Override
protected void visitAndOpNode(AndOpNode node) {
// Recurse.
visitChildren(node);
// Can simplify if either child is constant. We assume no side-effects.
SoyValue operand0 = getConstantOrNull(node.getChild(0));
if (operand0 != null) {
ExprNode replacementNode = operand0.coerceToBoolean() ? node.getChild(1) : node.getChild(0);
node.getParent().replaceChild(node, replacementNode);
}
}
@Override
protected void visitOrOpNode(OrOpNode node) {
// Recurse.
visitChildren(node);
// Can simplify if either child is constant. We assume no side-effects.
SoyValue operand0 = getConstantOrNull(node.getChild(0));
if (operand0 != null) {
ExprNode replacementNode = operand0.coerceToBoolean() ? node.getChild(0) : node.getChild(1);
node.getParent().replaceChild(node, replacementNode);
}
}
@Override
protected void visitConditionalOpNode(ConditionalOpNode node) {
// Recurse.
visitChildren(node);
// Can simplify if operand0 is constant. We assume no side-effects.
SoyValue operand0 = getConstantOrNull(node.getChild(0));
if (operand0 == null) {
return; // cannot simplify
}
ExprNode replacementNode = operand0.coerceToBoolean() ? node.getChild(1) : node.getChild(2);
node.getParent().replaceChild(node, replacementNode);
}
// -----------------------------------------------------------------------------------------------
// Implementations for functions.
@Override
protected void visitFunctionNode(FunctionNode node) {
// Cannot simplify nonplugin functions.
// TODO(brndn): we can actually simplify checkNotNull and quoteKeysIfJs.
if (node.getSoyFunction() instanceof BuiltinFunction) {
return;
}
if (node.getSoyFunction() instanceof LoggingFunction) {
return;
}
// Default to fallback implementation.
visitExprNode(node);
}
// -----------------------------------------------------------------------------------------------
// Fallback implementation.
@Override
protected void visitExprNode(ExprNode node) {
if (!(node instanceof ParentExprNode)) {
return;
}
ParentExprNode nodeAsParent = (ParentExprNode) node;
// Recurse.
visitChildren(nodeAsParent);
// If all children are constants, we attempt to preevaluate this node and replace it with a
// constant.
for (ExprNode child : nodeAsParent.getChildren()) {
if (!isConstant(child)) {
return; // cannot preevaluate
}
}
attemptPreeval(nodeAsParent);
}
// -----------------------------------------------------------------------------------------------
// Helpers.
/**
* Attempts to preevaluate a node. If successful, the node is replaced with a new constant node in
* the tree. If unsuccessful, the tree is not changed.
*/
private void attemptPreeval(ExprNode node) {
// Note that we need to catch RenderException because preevaluation may fail, e.g. when
// (a) the expression uses a bidi function that needs bidiGlobalDir to be in scope, but the
// apiCallScope is not currently active,
// (b) the expression uses an external function (Soy V1 syntax),
// (c) other cases I haven't thought up.
SoyValue preevalResult;
try {
preevalResult = preevalVisitor.exec(node);
} catch (RenderException e) {
return; // failed to preevaluate
}
PrimitiveNode newNode =
InternalValueUtils.convertPrimitiveDataToExpr(
(PrimitiveData) preevalResult, node.getSourceLocation());
if (newNode != null) {
node.getParent().replaceChild(node, newNode);
}
}
static boolean isConstant(ExprNode expr) {
return (expr instanceof GlobalNode && ((GlobalNode) expr).isResolved())
|| expr instanceof PrimitiveNode;
}
/** Returns the value of the given expression if it's constant, else returns null. */
static SoyValue getConstantOrNull(ExprNode expr) {
switch (expr.getKind()) {
case NULL_NODE:
return NullData.INSTANCE;
case BOOLEAN_NODE:
return BooleanData.forValue(((BooleanNode) expr).getValue());
case INTEGER_NODE:
return IntegerData.forValue(((IntegerNode) expr).getValue());
case FLOAT_NODE:
return FloatData.forValue(((FloatNode) expr).getValue());
case STRING_NODE:
return StringData.forValue(((StringNode) expr).getValue());
case GLOBAL_NODE:
GlobalNode global = (GlobalNode) expr;
if (global.isResolved()) {
return getConstantOrNull(global.getValue());
}
return null;
default:
return null;
}
}
}
|
geng890518/editor-ui | src/components/Qiniu/Qiniu.js | 'use strict';
import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { setCoverImageSuccess, delCoverImage } from 'redux/modules/editor';
import { Progress } from 'antd';
import { connect } from 'react-redux';
// import { fullImageURLForImageKey } from '../../helpers/URLHelpers';
import { Icon } from '../BasicComponents';
import { loadBasicParamsJson } from '../../redux/modules/qiniu';
var request = require('superagent-bluebird-promise');
require('./progress.css');
const isFunction = (fn) => {
var getType = {};
return fn && getType.toString.call(fn) === '[object Function]';
};
const md5 = require('blueimp-md5');
@connect(
state => ({
user: state.auth.user,
}),
dispatch => bindActionCreators({ setCoverImageSuccess, delCoverImage, loadBasicParamsJson }, dispatch)
)
export default class Qiniu extends Component {
// based on https://github.com/paramaggarwal/react-dropzone
static propTypes = {
onRef: PropTypes.func,
src: PropTypes.string,
loadBasicParamsJson: PropTypes.func,
onDrop: PropTypes.func.isRequired,
token: PropTypes.string,
// called before upload to set callback to files
size: PropTypes.number,
style: PropTypes.object,
supportClick: PropTypes.bool,
accept: PropTypes.string,
multiple: PropTypes.bool,
// Qiniu
uploadUrl: PropTypes.string,
uploadKey: PropTypes.string,
prefix: PropTypes.string,
user: PropTypes.object,
file: PropTypes.object,
createMoreImages: PropTypes.func,
updateEntityData: PropTypes.func,
setCoverImageSuccess: PropTypes.func,
setCommentImageSuccess: PropTypes.func,
delCoverImage: PropTypes.func,
setAvatarImageSuccess: PropTypes.func,
finished: PropTypes.bool,
imageURL: PropTypes.string,
type: PropTypes.oneOf([
'coverImage',
'editorImage',
'avatarImage',
'commentImage',
]),
inputType: PropTypes.string,
}
static defaultProps = {
supportClick: true,
multiple: true,
// uploadUrl: 'http://upload.qiniu.com',
uploadUrl: 'http://up-z1.qiniu.com',
prefix: 'client_uploads/images/',
inputType: 'file',
}
constructor(props) {
super(props);
if (props.src) {
this.state = {
isDragActive: false,
progress: 0,
uploading: false,
finished: true,
imageURL: props.src,
};
} else {
this.state = {
isDragActive: false,
progress: 0,
uploading: false,
finished: props.finished,
imageURL: props.imageURL,
};
}
this.deleteCover = this.deleteCover.bind(this);
this.deleteCommentImage = () => {
this.setState({
finished: false,
uploading: false,
});
};
}
componentDidMount() {
if (this.props.type === 'commentImage') {
this.props.onRef(this);
}
if (this.props.file) {
this.onDrop(null, this.props.file);
}
}
componentWillUnmount() {
if (this.props.type === 'commentImage') {
this.props.onRef(undefined);
}
}
onDragLeave() {
this.setState({
isDragActive: false
});
}
onDragOver(e) {
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
this.setState({
isDragActive: true
});
}
onDrop(e, fileObject) {
if (e) e.preventDefault();
this.setState({
isDragActive: false,
uploading: true,
});
let files;
if (e) {
if (e.dataTransfer) {
files = e.dataTransfer.files;
} else if (e.target) {
files = e.target.files;
}
} else if (fileObject) {
files = [fileObject];
}
for (let i = 0; i < files.length; i++) {
console.log('files[' + i + ']:' + files[i].name);
// console.log('files[' + i + ']:' + md5(files[i]).toUpperCase());
}
const maxFiles = (this.props.multiple) ? files.length : 1;
if (files.length > 1 && files.length <= maxFiles) {
const otherFiles = [];
for (let i = 1; i < files.length; i++) {
otherFiles.push(files[i]);
}
files = [files[0]];
this.props.createMoreImages(otherFiles); // 刨去第一个文件,用剩余的文件传回editor用于创建新的EditorImage
}
files = Array.prototype.slice.call(files, 0, maxFiles);
this.onUpload(files, e);
for (let i = 0; i < maxFiles; i++) {
const tempFile = files[i];
if (tempFile !== undefined) {
tempFile.preview = URL.createObjectURL(files[i]);
tempFile.request = this.upload(files[i]);
tempFile.uploadPromise = files[i].request.promise();
tempFile.uploadPromise.then((res) => {
this.uploadSuccess(res, tempFile);
}, (error) => {
this.uploadFailed(error, tempFile);
});
tempFile.uploadPromise.catch((error) => {
this.uploadFailed(error, tempFile);
});
}
}
if (this.props.onDrop) {
files = Array.prototype.slice.call(files, 0, maxFiles);
this.props.onDrop(files);
}
}
onClick() {
if (this.props.supportClick && this.props.token) {
this.open();
} else {
console.log(this.props);
this.props.loadBasicParamsJson();
console.error('qiniu token doesn\'t exist. 😂 😂 😂 ');
}
}
onUpload(files) {
// set onprogress function before uploading
files.map((f) => {
f.onprogress = (e) => {
this.setState({
progress: e.percent
});
};
return null;
});
}
open() {
var fileInput = this.fileInput;
fileInput.value = null;
fileInput.click();
}
upload(file) {
if (!file || file.size === 0) return null;
let key = md5(file.lastModified + file.name + file.size).toUpperCase();
file.key = this.props.user.userid + '/' + key;
if (this.props.prefix) {
key = this.props.prefix + this.props.user.userid + '/' + key;
}
if (this.props.uploadKey) {
key = this.props.uploadKey;
}
console.log('Upload:' + file.name);
const r = request
.post(this.props.uploadUrl)
.field('key', key)
.field('token', this.props.token)
.field('x:filename', file.name)
.field('x:size', file.size)
.attach('file', file, file.name)
.set('Accept', 'application/json');
if (isFunction(file.onprogress)) {
r.on('progress', file.onprogress);
}
return r;
}
uploadSuccess(res, file) {
const responseBodyObject = JSON.parse(res.text);
this.setState({
finished: true,
imageURL: responseBodyObject.url,
uploading: false,
});
const fr = new FileReader();
fr.onload = () => {
var img = new Image();
img.onload = () => {
const sizeString = '{' + img.width + ',' + img.height + '}';
if (this.props.type === 'editorImage') {
this.props.updateEntityData(sizeString, file.key, responseBodyObject.url);
} else if (this.props.type === 'coverImage') {
const coverImage = {
// name: file.key,
name: responseBodyObject.url,
original_size: sizeString,
};
this.props.setCoverImageSuccess(coverImage);
} else if (this.props.type === 'commentImage') {
const commentImage = {
zoom: 0,
original_size: sizeString,
focalpoint: '{0, 0}',
name: file.key
};
this.props.setCommentImageSuccess(commentImage);
} else if (this.props.type === 'avatarImage') {
const avatarImage = {
name: file.key,
original_size: sizeString,
};
this.props.setAvatarImageSuccess(avatarImage);
this.setState({ finished: false });
}
};
img.src = fr.result;
};
fr.readAsDataURL(file);
}
uploadFailed(error, file) {
console.log(JSON.stringify(error));
console.log('图片上传失败' + error + 'file:' + file);
this.setState({
finished: false,
uploading: false,
});
}
deleteCover() {
this.setState({
finished: false,
uploading: false,
});
this.props.delCoverImage();
}
render() {
const styles = require('./Qiniu.scss');
const borderColor = {
borderColor: 'white',
padding: '2px 8px',
};
let className = styles.dropzone;
if (this.state.isDragActive) {
className = styles.dropzoneActive;
}
let imageHeightStyle = { height: 200 };
switch (this.props.type) {
case 'coverImage':
case 'editorImage':
imageHeightStyle = {
height: 200
};
// }
break;
case 'commentImage':
imageHeightStyle = {
height: this.props.size,
border: 'none'
};
// }
break;
case 'avatarImage':
imageHeightStyle = {
height: this.props.size,
border: 'none',
borderRadius: (this.props.size / 2)
};
// }
break;
default:
}
const style = {
display: 'none'
};
let res = (
<div
className={className}
style={imageHeightStyle}
onClick={() => this.onClick()}
onDragLeave={() => this.onDragLeave()}
onDragOver={(e) => this.onDragOver(e)}
onDrop={(e) => this.onDrop(e)}
>
<input
style={style}
type={this.props.inputType}
multiple={this.props.multiple}
ref={(c) => { this.fileInput = c; }}
onChange={(e) => this.onDrop(e)}
accept={this.props.accept}
/>
{ this.props.children }
</div>
);
if (this.state.finished) {
const backgroundCover = {
backgroundImage: 'url(' + this.state.imageURL + ')',
};
if (this.props.type === 'coverImage') {
res = (
<div className={styles.imageViewBase}>
{/* <img src={this.state.imageURL} role="presentation" />*/}
<div className={styles.backgroundCover} style={backgroundCover}>
<button
className={styles.deleteButton}
style={borderColor}
onClick={this.deleteCover}
>
删除封面
</button>
</div>
</div>
);
} else if (this.props.type === 'editorImage') {
res = (
<div className={styles.imageViewBase}>
<img src={this.state.imageURL} role="presentation" />
{/* {this.props.children}*/}
{/* <div style={backgroundCover} />*/}
</div>
);
} else if (this.props.type === 'commentImage') {
const crossstyle = {
position: 'relative',
display: 'inline',
verticalAlign: 'baseline',
top: -2
};
res = (
<div className={styles.imageViewBase}>
<div className={styles.deleteForCommentImage} onClick={this.deleteCommentImage}>
<Icon width={12} height={12} type="cross" style={crossstyle} />
</div>
<div
className={styles.backgroundCoverForComment}
style={backgroundCover}
/>
</div>
);
} else if (this.props.type === 'avatarImage') {
res = (
<div className={styles.imageViewBase}>
<div className={styles.backgroundCoverForAvatar} style={backgroundCover} />
</div>
);
}
} else if (this.state.uploading) {
let cameraIconStyle;
let uploadingStyle;
let strokeWidth = 5;
let cameraIconSize = 30;
let actualHeight = 200;
switch (this.props.type) {
case 'coverImage':
case 'editorImage':
cameraIconStyle = {
top: 80,
fontSize: 14
};
uploadingStyle = {
top: 80,
fontSize: 14
};
// }
break;
case 'commentImage':
strokeWidth = 2;
cameraIconSize = 20;
actualHeight = this.props.size;
cameraIconStyle = {
top: 5,
fontSize: 12
};
uploadingStyle = {
top: 5,
fontSize: 12,
width: 50,
transform: 'scale(0.6)',
marginLeft: 0,
};
// }
break;
case 'avatarImage':
strokeWidth = 2;
cameraIconSize = 20;
actualHeight = this.props.size;
cameraIconStyle = {
top: 30,
};
uploadingStyle = {
top: 40,
fontSize: 12,
width: 100,
};
// }
break;
default:
}
// const isForCommentImage = this.props.type === 'commentImage';
// const strokeWidth = isForCommentImage ? 2 : 5;
// const cameraIconSize = isForCommentImage ? 20 : 30;
// const uploadingOriginalHeight = 200;
// const actualHeight = isForCommentImage ? this.props.size : uploadingOriginalHeight;
// const actualTop = isForCommentImage ? 5 : 80;
// const fontSize = isForCommentImage ? 12 : 14;
// const cameraIconStyle = {
// top: actualTop,
// fontSize
// };
// let uploadingStyle = {
// top: actualTop,
// fontSize
// };
// if (isForCommentImage) {
// uploadingStyle = {
// top: actualTop,
// fontSize,
// width: 50,
// transform: 'scale(0.6)',
// marginLeft: 0,
// };
// }
const forAvatarImage = this.props.type === 'avatarImage';
res = (
<div className={styles.uploading} style={{ height: actualHeight }}>
{ !forAvatarImage && <Progress percent={this.state.progress} strokeWidth={strokeWidth} showInfo={false} /> }
<div className={styles.cameraIcon} style={cameraIconStyle}>
<Icon width={cameraIconSize} height={cameraIconSize} type="camera" />
</div>
<p style={uploadingStyle}>上传中...</p>
</div>
);
}
return (
<div>
{ res }
</div>
);
}
}
|
Pixelated-Project/aosp-android-jar | android-31/src/com/android/server/backup/encryption/chunking/EncryptedChunk.java | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.backup.encryption.chunking;
import com.android.internal.util.Preconditions;
import com.android.server.backup.encryption.chunk.ChunkHash;
import java.util.Arrays;
import java.util.Objects;
/**
* A chunk of a file encrypted using AES/GCM.
*
* <p>TODO(b/116575321): After all code is ported, remove the factory method and rename
* encryptedBytes(), key() and nonce().
*/
public class EncryptedChunk {
public static final int KEY_LENGTH_BYTES = ChunkHash.HASH_LENGTH_BYTES;
public static final int NONCE_LENGTH_BYTES = 12;
/**
* Constructs a new instance with the given key, nonce, and encrypted bytes.
*
* @param key SHA-256 Hmac of the chunk plaintext.
* @param nonce Nonce with which the bytes of the chunk were encrypted.
* @param encryptedBytes Encrypted bytes of the chunk.
*/
public static EncryptedChunk create(ChunkHash key, byte[] nonce, byte[] encryptedBytes) {
Preconditions.checkArgument(
nonce.length == NONCE_LENGTH_BYTES, "Nonce does not have the correct length.");
return new EncryptedChunk(key, nonce, encryptedBytes);
}
private ChunkHash mKey;
private byte[] mNonce;
private byte[] mEncryptedBytes;
private EncryptedChunk(ChunkHash key, byte[] nonce, byte[] encryptedBytes) {
mKey = key;
mNonce = nonce;
mEncryptedBytes = encryptedBytes;
}
/** The SHA-256 Hmac of the plaintext bytes of the chunk. */
public ChunkHash key() {
return mKey;
}
/** The nonce with which the chunk was encrypted. */
public byte[] nonce() {
return mNonce;
}
/** The encrypted bytes of the chunk. */
public byte[] encryptedBytes() {
return mEncryptedBytes;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof EncryptedChunk)) {
return false;
}
EncryptedChunk encryptedChunkOrdering = (EncryptedChunk) o;
return Arrays.equals(mEncryptedBytes, encryptedChunkOrdering.mEncryptedBytes)
&& Arrays.equals(mNonce, encryptedChunkOrdering.mNonce)
&& mKey.equals(encryptedChunkOrdering.mKey);
}
@Override
public int hashCode() {
return Objects.hash(mKey, Arrays.hashCode(mNonce), Arrays.hashCode(mEncryptedBytes));
}
}
|
nmcl/wfswarm-example-arjuna-old | AdventOfCode/2019/day13/part2/Intcode.java | import java.io.*;
import java.util.*;
public class Intcode
{
public static final String DELIMITER = ",";
public static final String INITIALISED_MEMORY = "0";
public Intcode (Vector<String> values, String initialInput, boolean debug)
{
_debug = debug;
_instructionPointer = 0;
_output = new Vector<String>();
_memory = new Vector<String>(values);
_input = initialInput;
_status = Status.CREATED;
_relativeBase = 0;
}
public final boolean hasHalted ()
{
return (_status == Status.HALTED);
}
public final boolean hasPaused ()
{
return (_status == Status.PAUSED);
}
public final boolean waitingForInput ()
{
return (_status == Status.WAITING_FOR_INPUT);
}
public final int status ()
{
return _status;
}
public final boolean hasOutput ()
{
return (_output.size() > 0);
}
public final String getOutput ()
{
return _output.remove(0);
}
public final void setInput (String input)
{
_input = input;
}
public final String getInput ()
{
return _input;
}
public final String consumeInput ()
{
String toReturn = _input;
_input = null;
return toReturn;
}
public final void changeInstruction (int entry, String value)
{
_memory.setElementAt(value, entry);
}
/**
* Execute all the commands given, only returning when paused or halted.
*
* @return the current status.
*/
public int executeProgram ()
{
while (!hasHalted())
{
singleStepExecution(); // assume input only needed once!
}
return _status;
}
/**
* Execute one instruction at a time. If input is required and none is provided
* then change status and pause anyway.
*
* @return the current status.
*/
public int singleStepExecution ()
{
if (hasHalted())
{
if (_debug)
System.out.println("Intcode computer has halted!");
return _status;
}
if (_debug)
System.out.println("Intcode input <"+getInput()+"> and instruction pointer: "+_instructionPointer);
String str = getOpcode(_memory.elementAt(_instructionPointer));
int opcode = Integer.valueOf(str);
int[] modes = ParameterMode.getModes(_memory.elementAt(_instructionPointer));
if (_debug)
{
System.out.println("\nWorking on element "+_instructionPointer+" which is command "+Instructions.commandToString(opcode)+
" with parameter modes ...");
ParameterMode.printModes(modes);
}
/*
* Now factor in the parameter modes.
*/
switch (opcode)
{
case Instructions.ADD:
{
/*
* Opcode 1 adds together numbers read from two positions
* and stores the result in a third position. The three integers
* immediately after the opcode tell you these three positions - the
* first two indicate the positions from which you should read the
* input values, and the third indicates the position at which
* the output should be stored.
*/
long param1 = Long.valueOf(getValue(_instructionPointer+1, modes[0], false));
long param2 = Long.valueOf(getValue(_instructionPointer+2, modes[1], false));
int param3 = Integer.valueOf(getValue(_instructionPointer+3, modes[2], true));
if (_debug)
System.out.println("Adding "+param1+" and "+param2);
long sum = param1+param2;
if (_debug)
System.out.println("Storing "+sum+" at position "+param3);
setValue(param3, String.valueOf(sum));
_instructionPointer += 4; // move the pointer on.
}
break;
case Instructions.MULTIPLY:
{
/*
* Opcode 2 works exactly like opcode 1, except it multiplies the
* two inputs instead of adding them. Again, the three integers after
* the opcode indicate where the inputs and outputs are, not their values.
*/
long param1 = Long.valueOf(getValue(_instructionPointer+1, modes[0], false));
long param2 = Long.valueOf(getValue(_instructionPointer+2, modes[1], false));
int param3 = Integer.valueOf(getValue(_instructionPointer+3, modes[2], true));
if (_debug)
System.out.println("Multiplying "+param1+" and "+param2);
long product = Long.valueOf(param1)*Long.valueOf(param2);
if (_debug)
System.out.println("Storing "+product+" at position "+param3);
setValue(param3, String.valueOf(product));
_instructionPointer += 4; // move the pointer on.
}
break;
case Instructions.INPUT_AND_STORE:
{
/*
* Opcode 3 takes a single integer as input and saves it to
* the position given by its only parameter.
*/
if (getInput() != null)
{
int param1 = Integer.valueOf(getValue(_instructionPointer+1, modes[0], true));
if (_debug)
System.out.println("Storing "+getInput()+" at position "+param1);
setValue(param1, consumeInput());
_instructionPointer += 2; // move the pointer on.
}
else
{
if (_debug)
System.out.println("Waiting for input.");
_status = Status.WAITING_FOR_INPUT;
return _status;
}
}
break;
case Instructions.OUTPUT:
{
/*
* Opcode 4 outputs the value of its only parameter.
*/
long param1 = Long.valueOf(getValue(_instructionPointer+1, modes[0], false));
if (_debug)
System.out.println("Adding value "+param1+" to output state.");
_output.add(Long.toString(param1));
_instructionPointer += 2; // move the pointer on.
_status = Status.PAUSED;
return _status;
}
case Instructions.JUMP_IF_TRUE:
{
/*
* If the first parameter is non-zero, it sets the instruction pointer to
* the value from the second parameter. Otherwise, it does nothing.
*/
long param1 = Long.valueOf(getValue(_instructionPointer+1, modes[0], false));
long param2 = Long.valueOf(getValue(_instructionPointer+2, modes[1], false));
if (_debug)
System.out.println("Checking "+param1+" != 0 and might jump to "+param2);
if (param1 != 0)
{
_instructionPointer = (int) param2;
if (_debug)
System.out.println("Will jump to "+param2);
}
else
_instructionPointer += 3;
}
break;
case Instructions.JUMP_IF_FALSE:
{
/*
* If the first parameter is zero, it sets the instruction pointer to the value
* from the second parameter. Otherwise, it does nothing.
*/
long param1 = Long.valueOf(getValue(_instructionPointer+1, modes[0], false));
long param2 = Long.valueOf(getValue(_instructionPointer+2, modes[1], false));
if (_debug)
System.out.println("Checking "+param1+" == 0 and might jump to "+param2);
if (param1 == 0)
{
_instructionPointer = (int) param2;
if (_debug)
System.out.println("Will jump to "+param2);
}
else
_instructionPointer += 3;
}
break;
case Instructions.LESS_THAN:
{
/*
* If the first parameter is less than the second parameter, it stores 1
* in the position given by the third parameter. Otherwise, it stores 0.
*/
long param1 = Long.valueOf(getValue(_instructionPointer+1, modes[0], false));
long param2 = Long.valueOf(getValue(_instructionPointer+2, modes[1], false));
int param3 = Integer.valueOf(getValue(_instructionPointer+3, modes[2], true));
if (_debug)
{
System.out.println("Checking whether "+param1+" < "+param2);
System.out.print("Storing ");
}
if (param1 < param2)
{
if (_debug)
System.out.print("1");
setValue(param3, "1");
}
else
{
if (_debug)
System.out.print("0");
setValue(param3, "0");
}
if (_debug)
System.out.println(" at location "+param3);
_instructionPointer += 4; // move the pointer on.
}
break;
case Instructions.EQUALS:
{
/*
* If the first parameter is equal to the second parameter, it stores 1
* in the position given by the third parameter. Otherwise, it stores 0.
*/
long param1 = Long.valueOf(getValue(_instructionPointer+1, modes[0], false));
long param2 = Long.valueOf(getValue(_instructionPointer+2, modes[1], false));
int param3 = Integer.valueOf(getValue(_instructionPointer+3, modes[2], true));
if (_debug)
{
System.out.println("Checking whether "+param1+" is equal to "+param2);
System.out.print("Storing ");
}
if (param1 == param2)
{
if (_debug)
System.out.print("1");
setValue(param3, "1");
}
else
{
if (_debug)
System.out.print("0");
setValue(param3, "0");
}
if (_debug)
System.out.println(" at location "+param3);
_instructionPointer += 4; // move the pointer on.
}
break;
case Instructions.RELATIVE_BASE:
{
/*
* The relative base increases (or decreases, if the value is negative)
* by the value of the parameter.
*/
int param1 = Integer.valueOf(getValue(_instructionPointer+1, modes[0], false));
_relativeBase += param1;
if (_debug)
System.out.println("Relative base now "+_relativeBase);
_instructionPointer += 2;
}
break;
case Instructions.HALT:
{
/*
* Means that the program is finished and should immediately halt.
*/
if (_debug)
System.out.println("Halting execution.");
_instructionPointer = _memory.size();
_status = Status.HALTED;
return _status;
}
default:
{
System.out.println("Unknown opcode "+str+" encountered");
_instructionPointer = _memory.size(); // stop any further execution.
_status = Status.HALTED;
}
}
_status = Status.RUNNING;
return _status;
}
// these methods ensure capacity is available
private String getValue (int index, int mode, boolean isOutput)
{
String param = null;
switch (mode)
{
case ParameterMode.POSITION_MODE:
{
param = getValue(index);
if (!isOutput)
param = getValue(Integer.valueOf(param));
}
break;
case ParameterMode.IMMEDIATE_MODE:
{
param = getValue(index);
}
break;
case ParameterMode.RELATIVE_MODE:
{
param = getValue(index);
if (!isOutput)
param = getValue(Integer.valueOf(param) + _relativeBase);
else
param = Integer.toString(Integer.valueOf(param) + _relativeBase);
}
break;
default:
{
System.out.println("Unknown Parameter Mode found: "+mode);
param = "-1";
}
}
return param;
}
private String getValue (int i)
{
if (_memory.size() <= i)
_memory.setSize(i+EXPANSION_FACTOR);
String str = _memory.elementAt(i);
if (str == null)
{
str = INITIALISED_MEMORY;
_memory.set(i, str);
}
return str;
}
private void setValue (int i, String str)
{
if (_memory.size() <= i)
_memory.setSize(i+EXPANSION_FACTOR);
_memory.set(i, str);
}
private String getOpcode (String digits)
{
String opcode = null;
if ((digits != null) && (digits.length() > 2))
opcode = digits.substring(digits.length()-2);
else
opcode = digits;
return opcode;
}
private boolean _debug;
private int _instructionPointer;
private Vector<String> _output;
private Vector<String> _memory;
private String _input;
private int _status;
private int _relativeBase;
private static final int EXPANSION_FACTOR = 10; // if we need to increase memory, add a bit more to reduce multiple back-to-back expansions
} |
rstueven/beerme-mobile-android | beerme/src/main/java/com/beerme/android/database/TableDefs.java | package com.beerme.android.database;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import androidx.fragment.app.Fragment;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationCompat.Builder;
import android.util.Log;
import com.beerme.android.R;
import com.beerme.android.utils.SharedPref;
import com.beerme.android.utils.Utils;
import java.util.Calendar;
import java.util.HashMap;
import static com.beerme.android.utils.SharedPref.Pref.KEY_DB_LAST_UPDATE;
import static com.beerme.android.utils.SharedPref.Pref.KEY_DB_UPDATING;
public abstract class TableDefs extends Fragment {
public static final String TABLE_BREWERYNOTES = "brewerynotes";
public static final String TABLE_BEERNOTES = "beernotes";
public static final String TABLE_BREWERY = "brewery";
public static final String TABLE_BEER = "beer";
public static final String TABLE_STYLE = "style";
public static final int NOTIFICATION_BREWERY_DOWNLOAD = 1;
public static final int NOTIFICATION_BREWERY_LOAD = 2;
public static final int NOTIFICATION_BEER_DOWNLOAD = 3;
public static final int NOTIFICATION_BEER_LOAD = 4;
public static final int NOTIFICATION_STYLE_DOWNLOAD = 5;
public static final int NOTIFICATION_STYLE_LOAD = 6;
protected Context mContext;
protected NotificationManager mNotifyManager = null;
protected final static HashMap<String, String> createStatements = new HashMap<String, String>();
protected final static HashMap<String, String[]> indexStatements = new HashMap<String, String[]>();
public interface UpdateListener {
public void onDataUpdated();
}
public TableDefs() {
mContext = DbOpenHelper.getContext();
initTableDefs();
}
public final static TableDefs newInstance(int version) {
TableDefs tableDefs = null;
switch (version) {
case 1:
tableDefs = new TableDefs_1();
break;
case 2:
tableDefs = new TableDefs_2();
break;
case 3:
tableDefs = new TableDefs_3();
break;
case 4:
tableDefs = new TableDefs_4();
break;
case 5:
tableDefs = new TableDefs_5();
break;
case 6:
tableDefs = new TableDefs_6();
break;
default:
throw new IllegalArgumentException("Invalid version: " + version);
}
return tableDefs;
}
protected abstract void initTableDefs();
protected void upgrade(SQLiteDatabase db) {
Log.i(Utils.APPTAG, "upgrade(): default implementation");
}
public void updateData(SQLiteDatabase db, UpdateListener listener) {
Log.i(Utils.APPTAG, "updateData(): default implementation");
if (listener != null) {
listener.onDataUpdated();
}
}
protected void upgradeOldTables(SQLiteDatabase db) {
Log.i(Utils.APPTAG, "upgradeOldTables(): default implementation");
}
protected void installNewTables(SQLiteDatabase db) {
Log.i(Utils.APPTAG, "installNewTables(): default implementation");
}
protected final HashMap<String, String> getCreateStatements() {
return createStatements;
}
protected final HashMap<String, String[]> getIndexStatements() {
return indexStatements;
}
protected static String createIndex(String table, String column) {
return createIndex(table, column, new String[]{column});
}
protected static String[] getColumns(SQLiteDatabase db, String tableName) {
String[] ar = null;
Cursor c = db.rawQuery("select * from " + tableName + " limit 1", null);
if (c != null) {
ar = c.getColumnNames();
c.close();
}
return ar;
}
protected static String createIndex(String table, String name,
String[] columns) {
StringBuffer buffer = new StringBuffer("CREATE INDEX " + table + "_" + name + " ON " + table + " (");
int n = columns.length;
boolean first = true;
for (int i = 0; i < n; i++) {
if (!first) {
buffer.append(", ");
}
first = false;
buffer.append(columns[i]);
}
buffer.append(')');
return buffer.toString();
}
protected static void setLastUpdate() {
SharedPref.write(KEY_DB_LAST_UPDATE, DbOpenHelper.sqlDateFormat.format(Calendar.getInstance().getTime()));
}
protected static String getLastUpdate() {
return SharedPref.read(KEY_DB_LAST_UPDATE, Utils.DISTANT_PAST);
}
protected static void resetLastUpdate() {
SharedPref.write(KEY_DB_LAST_UPDATE, Utils.DISTANT_PAST);
}
protected static String getLastUpdateByTable(SQLiteDatabase db, String table) {
String newest = null;
Cursor cursor = db.rawQuery("SELECT MAX(updated) FROM " + table, null);
if (cursor.moveToFirst()) {
newest = cursor.getString(0);
}
cursor.close();
if (newest == null) {
return Utils.DISTANT_PAST;
} else {
String lastUpdate = SharedPref.read(KEY_DB_LAST_UPDATE, Utils.DISTANT_PAST);
if (lastUpdate.compareTo(newest) < 0) {
return lastUpdate;
} else {
return newest;
}
}
}
protected static void startDownloadProgress(Context context, int title, int id) {
startDownloadProgress(context, context.getString(title), id);
}
protected static void startDownloadProgress(Context context, String title,
int id) {
Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setContentText(context.getText(R.string.Download_in_progress))
.setSmallIcon(R.drawable.ic_home)
.setProgress(0, 0, true)
.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(), 0));
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(id, builder.build());
}
public static boolean isUpdating() {
return SharedPref.read(KEY_DB_UPDATING, false);
}
} |
dignsys/TizenRT | os/drivers/wireless/brcm/stm32l/wiced/wiced_wifi.h | /*
* Broadcom Proprietary and Confidential. Copyright 2016 Broadcom
* All Rights Reserved.
*
* This is UNPUBLISHED PROPRIETARY SOURCE CODE of Broadcom Corporation;
* the contents of this file may not be disclosed to third parties, copied
* or duplicated in any form, in whole or in part, without the prior
* written permission of Broadcom Corporation.
*/
/** @file
* Defines functions to perform Wi-Fi operations
*/
#pragma once
#include "wiced_utilities.h"
#include "wwd_wifi.h"
#include "wwd_debug.h"
#include "wiced_rtos.h"
#ifdef __cplusplus
extern "C" {
#endif
/******************************************************
* Macros
******************************************************/
#define WICED_WIFI_CH_TO_BAND( channel ) ( ( wwd_channel_to_wl_band( channel ) == WL_CHANSPEC_BAND_2G ) ? WICED_802_11_BAND_2_4GHZ : WICED_802_11_BAND_5GHZ )
/******************************************************
* Constants
******************************************************/
/******************************************************
* Enumerations
******************************************************/
/** WPS Connection Mode
*/
typedef enum
{
WICED_WPS_PBC_MODE = 1, /**< Push button mode */
WICED_WPS_PIN_MODE = 2 /**< PIN mode */
} wiced_wps_mode_t;
/** WPS Device Category from the WSC2.0 spec
*/
typedef enum
{
WICED_WPS_DEVICE_COMPUTER = 1, /**< COMPUTER */
WICED_WPS_DEVICE_INPUT = 2, /**< INPUT */
WICED_WPS_DEVICE_PRINT_SCAN_FAX_COPY = 3, /**< PRINT_SCAN_FAX_COPY */
WICED_WPS_DEVICE_CAMERA = 4, /**< CAMERA */
WICED_WPS_DEVICE_STORAGE = 5, /**< STORAGE */
WICED_WPS_DEVICE_NETWORK_INFRASTRUCTURE = 6, /**< NETWORK_INFRASTRUCTURE */
WICED_WPS_DEVICE_DISPLAY = 7, /**< DISPLAY */
WICED_WPS_DEVICE_MULTIMEDIA = 8, /**< MULTIMEDIA */
WICED_WPS_DEVICE_GAMING = 9, /**< GAMING */
WICED_WPS_DEVICE_TELEPHONE = 10, /**< TELEPHONE */
WICED_WPS_DEVICE_AUDIO = 11, /**< AUDIO */
WICED_WPS_DEVICE_OTHER = 0xFF, /**< OTHER */
} wiced_wps_device_category_t;
/** WPS Configuration Methods from the WSC2.0 spec
*/
typedef enum
{
WPS_CONFIG_USBA = 0x0001, /**< USBA */
WPS_CONFIG_ETHERNET = 0x0002, /**< ETHERNET */
WPS_CONFIG_LABEL = 0x0004, /**< LABEL */
WPS_CONFIG_DISPLAY = 0x0008, /**< DISPLAY */
WPS_CONFIG_EXTERNAL_NFC_TOKEN = 0x0010, /**< EXTERNAL_NFC_TOKEN */
WPS_CONFIG_INTEGRATED_NFC_TOKEN = 0x0020, /**< INTEGRATED_NFC_TOKEN */
WPS_CONFIG_NFC_INTERFACE = 0x0040, /**< NFC_INTERFACE */
WPS_CONFIG_PUSH_BUTTON = 0x0080, /**< PUSH_BUTTON */
WPS_CONFIG_KEYPAD = 0x0100, /**< KEYPAD */
WPS_CONFIG_VIRTUAL_PUSH_BUTTON = 0x0280, /**< VIRTUAL_PUSH_BUTTON */
WPS_CONFIG_PHYSICAL_PUSH_BUTTON = 0x0480, /**< PHYSICAL_PUSH_BUTTON */
WPS_CONFIG_VIRTUAL_DISPLAY_PIN = 0x2008, /**< VIRTUAL_DISPLAY_PIN */
WPS_CONFIG_PHYSICAL_DISPLAY_PIN = 0x4008 /**< PHYSICAL_DISPLAY_PIN */
} wiced_wps_configuration_method_t;
/** WICED SoftAP events */
typedef enum
{
WICED_AP_UNKNOWN_EVENT,
WICED_AP_STA_JOINED_EVENT,
WICED_AP_STA_LEAVE_EVENT,
} wiced_wifi_softap_event_t;
/******************************************************
* Type Definitions
******************************************************/
/** Soft AP event handler */
typedef void (*wiced_wifi_softap_event_handler_t)( wiced_wifi_softap_event_t event, const wiced_mac_t* mac_address );
/******************************************************
* Structures
******************************************************/
/** Wi-Fi scan result
*/
typedef struct
{
wiced_scan_result_t ap_details; /**< Access point details */
wiced_scan_status_t status;
void* user_data; /**< Pointer to user data passed into wiced_wifi_scan_networks() function */
void* next;
} wiced_scan_handler_result_t;
/** @cond !ADDTHIS*/
/* Note: Do NOT modify this type definition.
* Internal code make assumptions based on it's current definition
* */
typedef wiced_result_t (*wiced_scan_result_handler_t)( wiced_scan_handler_result_t* malloced_scan_result );
/** @endcond */
/** WPS Device category holds WSC2.0 device category information
*/
typedef struct
{
const wiced_wps_device_category_t device_category; /**< Device category */
const uint16_t sub_category; /**< Device sub-category */
const char* device_name; /**< Device name */
const char* manufacturer; /**< Manufacturer details */
const char* model_name; /**< Model name */
const char* model_number; /**< Model number */
const char* serial_number; /**< Serial number */
const uint32_t config_methods; /**< Configuration methods */
const uint32_t os_version; /**< Operating system version */
const uint16_t authentication_type_flags; /**< Supported authentication types */
const uint16_t encryption_type_flags; /**< Supported encryption types */
const uint8_t add_config_methods_to_probe_resp; /**< Add configuration methods to probe response for Windows enrollees (this is non-WPS 2.0 compliant) */
} wiced_wps_device_detail_t;
/** WPS Credentials
*/
typedef struct
{
wiced_ssid_t ssid; /**< AP SSID (name) */
wiced_security_t security; /**< AP security type */
uint8_t passphrase[64]; /**< AP passphrase */
uint8_t passphrase_length; /**< AP passphrase length */
} wiced_wps_credential_t;
/** Vendor IE details
*/
typedef struct
{
uint8_t oui[WIFI_IE_OUI_LENGTH]; /**< Unique identifier for the IE */
uint8_t subtype; /**< Sub-type of the IE */
void* data; /**< Pointer to IE data */
uint16_t length; /**< IE data length */
uint16_t which_packets; /**< Mask of the packet in which this IE details to be included */
} wiced_custom_ie_info_t;
/******************************************************
* Global Variables
******************************************************/
/******************************************************
* Function Declarations
******************************************************/
/*****************************************************************************/
/** @addtogroup wifi Wi-Fi (802.11) functions
*
* WICED functions specific to Wi-Fi
*
* @{
*/
/*****************************************************************************/
/** Negotiates securely with a Wi-Fi Protected Setup (WPS) registrar (usually an
* Access Point) and obtains credentials necessary to join the AP.
*
* @param[in] mode : Indicates whether to use Push-Button (PBC) or PIN Number mode for WPS
* @param[in] details : Pointer to a structure containing manufacturing details
* of this device
* @param[in] password : <PASSWORD> <PASSWORD>
* @param[out] credentials : An array of credential structures that will receive the
* securely negotiated credentials
* @param[out] credential_count : The number of structures in the credentials parameter
*
* @return @ref wiced_result_t
*/
extern wiced_result_t wiced_wps_enrollee( wiced_wps_mode_t mode, const wiced_wps_device_detail_t* details, const char* password, wiced_wps_credential_t* credentials, uint16_t credential_count );
/** Negotiates securely with a Wi-Fi Protected Setup (WPS) enrollee (usually a
* client device) and provides credentials necessary to join a SoftAP.
*
* @param[in] mode : Indicates whether to use Push-Button (PBC) or PIN Number mode for WPS
* @param[in] details : Pointer to a structure containing manufacturing details
* of this device
* @param[in] password : <PASSWORD> <PASSWORD>
* @param[out] credentials : An array of credential structures that will provide the
* securely negotiated credentials
* @param[out] credential_count : The number of structures in the credentials parameter
*
* @return @ref wiced_result_t
*/
extern wiced_result_t wiced_wps_registrar( wiced_wps_mode_t mode, const wiced_wps_device_detail_t* details, const char* password, wiced_wps_credential_t* credentials, uint16_t credential_count );
/** Scans for Wi-Fi networks
*
* @param[in] results_handler : A function pointer for the handler that will process
* the network details as they arrive.
* @param[in] user_data : An argument that will be passed to the results_handler function
* of this device
*
* @note @li The results_handler and user_data variables will be referenced after the function returns.
* Those variables must remain valid until the scan is complete.
*
* @return @ref wiced_result_t
*/
extern wiced_result_t wiced_wifi_scan_networks( wiced_scan_result_handler_t results_handler, void* user_data );
/** Scans for Wi-Fi networks added using wwd_pno_add_network. Scan will be done in an efficient, power-saving type manner.
* @param[in] ssid : SSID of the AP to search for during offloaded scan
* @param[in] security : security of the network to search for during offloaded scan
* @param[in] results_handler : A function pointer for the handler that will process
* the network details as they arrive.
* @param[in] user_data : An argument that will be passed to the results_handler function
* of this device
*
* @note @li The results_handler and user_data variables will be referenced after the function returns.
* Those variables must remain valid until the scan is complete.
*
* @return @ref wiced_result_t
*/
extern wiced_result_t wiced_wifi_pno_start( wiced_ssid_t *ssid, wiced_security_t security, wiced_scan_result_handler_t handler, void *user_data );
/* Halts the preferred network offload scanning process and clears all state associated with it */
extern wiced_result_t wiced_wifi_pno_stop( void );
/** Finds the AP and it's information for the given SSID
*
* @param[in] ssid : SSID of the access point for which user wants to find information.
* It must be a NULL terminated string 32 characters or less
*
* @param[out] ap_info : Pointer to the structure to store AP information.
*
* @param[in] optional_channel_list : An optional channel list to restrict which channels are scanned. Note that the last entry must be 0
* If NULL, the scan will be performed on all supported Wi-Fi channels.
*
* @return @ref wiced_result_t
*/
extern wiced_result_t wiced_wifi_find_ap( const char* ssid, wiced_scan_result_t* ap_info, const uint16_t* optional_channel_list);
/** Add Wi-Fi custom IE
*
* @param[in] interface : Interface to add custom IE
* @param[in] ie_info : Pointer to the structure which contains custom IE information
*
* @return @ref wiced_result_t
*/
extern wiced_result_t wiced_wifi_add_custom_ie( wiced_interface_t interface, const wiced_custom_ie_info_t* ie_info );
/** Remove Wi-Fi custom IE
*
* @param[in] interface : Interface to remove custom IE
* @param[in] ie_info : Pointer to the structure which contains custom IE information
*
* @return @ref wiced_result_t
*/
extern wiced_result_t wiced_wifi_remove_custom_ie( wiced_interface_t interface, const wiced_custom_ie_info_t* ie_info );
/** Brings up Wi-Fi core
*
* @return @ref wiced_result_t
*/
extern wiced_result_t wiced_wifi_up( void );
/** Bring down Wi-Fi core preserving calibration
*
* WARNING:
* This brings down the Wi-Fi core and all existing network connections.
* Bring up the Wi-Fi core using wiced_wifi_up() and bring up the required
* network connections using wiced_network_up().
*
* @return @ref wiced_result_t
*/
extern wiced_result_t wiced_wifi_down( void );
/** Set roam trigger level
*
* @param[in] trigger_level : Trigger level in dBm. The Wi-Fi device will search for a new AP to connect to once the \n
* signal from the AP (it is currently associated with) drops below the roam trigger level.
* Valid value range: 2 to -100
* 0 : Default roaming trigger
* 1 : Optimize for bandwidth roaming trigger
* 2 : Optimize for distance roaming trigger
* -1 to -100: Roaming will be triggered based on the specified RSSI value
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_set_roam_trigger( int32_t trigger_level );
/** Get roam trigger level
*
* @param trigger_level : Trigger level in dBm. Pointer to store current roam trigger level value
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_get_roam_trigger( int32_t* trigger_level );
/** Get the current channel on STA interface
*
* @param[out] channel : A pointer to the variable where the channel value will be written
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_get_channel( uint32_t* channel );
/** Retrieves the current Media Access Control (MAC) address
* (or Ethernet hardware address) of the 802.11 device
*
* @param mac Pointer to a variable that the current MAC address will be written to
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_get_mac_address( wiced_mac_t* mac );
/** Get WLAN counter statistics for the interface provided
*
* @param[in] interface : The interface for which the counters are requested
* @param[out] counters : A pointer to the structure where the counter data will be written
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_get_counters( wwd_interface_t interface, wiced_counters_t* counters );
/** Sets the 802.11 powersave listen interval for a Wi-Fi client, and communicates
* the listen interval to the Access Point. The listen interval will be set to
* (listen_interval x time_unit) seconds.
*
* The default value for the listen interval is 0. With the default value set,
* the Wi-Fi device wakes to listen for AP beacons every DTIM period.
*
* If the DTIM listen interval is non-zero, the DTIM listen interval will over ride
* the beacon listen interval value.
*
* If it is necessary to set the listen interval sent to the AP to a value other
* than the value set by this function, use the additional association listen
* interval API : wiced_wifi_set_listen_interval_assoc()
*
* @note This function applies to 802.11 powersave operation. Please read the
* WICED Powersave Application Note provided in the WICED-SDK/Doc directory for further
* information about the operation of the 802.11 listen interval.
*
* @param[in] listen_interval : The desired beacon listen interval
* @param[in] time_unit : The listen interval time unit; options are beacon period or DTIM period
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_set_listen_interval( uint8_t listen_interval, wiced_listen_interval_time_unit_t time_unit );
/** Sets the 802.11 powersave beacon listen interval communicated to Wi-Fi Access Points
*
* This function is used by Wi-Fi clients to set the value of the beacon
* listen interval sent to the AP (in the association request frame) during
* the association process.
*
* To set the client listen interval as well, use the wiced_wifi_set_listen_interval() API
*
* @note This function applies to 802.11 powersave operation. Please read the
* WICED Powersave Application Note provided in the WICED-SDK/Doc directory for further
* information about the operation of the 802.11 listen interval.
*
* @param listen_interval : The beacon listen interval sent to the AP during association.
* The time unit is specified in multiples of beacon periods.
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_set_listen_interval_assoc( uint16_t listen_interval );
/** Gets the current value of all beacon listen interval variables
*
* @param[out] li : The current value of all listen interval settings
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_get_listen_interval( wiced_listen_interval_t* li );
/** Register soft AP event handler
*
* @param[in] softap_event_handler : A function pointer to the event handler
*
* @return @ref wiced_result_t
*/
extern wiced_result_t wiced_wifi_register_softap_event_handler( wiced_wifi_softap_event_handler_t softap_event_handler );
/** Unregister soft AP event handler
*
* @return @ref wiced_result_t
*/
extern wiced_result_t wiced_wifi_unregister_softap_event_handler( void );
/** event handler to get RRM event header and RRM event data
* @param[out] const void* event_header : event header
* @param[out] const uint8_t* event_data: event_data
*
*/
typedef void (*wiced_wifi_rrm_event_handler_t)( const void* event_header, const uint8_t* event_data );
/* Register RRM event handler
* @param[in] wiced_wifi_rrm_event_handler_t : A function pointer to the event handler
*
* @return @ref wiced_result_t
*/
extern wiced_result_t wiced_wifi_register_rrm_event_handler( wiced_wifi_rrm_event_handler_t event_handler );
/* DeRegister RRM event handler
* @param void:
*
* @return @ref wiced_result_t
*/
extern wiced_result_t wiced_wifi_unregister_rrm_event_handler( void );
extern wiced_result_t wiced_wifi_register_pno_callback( wiced_scan_result_handler_t pno_handler, void *user_data );
extern wiced_result_t wiced_wifi_unregister_pno_callback( void );
/*****************************************************************************/
/** @addtogroup wifipower WLAN Power Saving functions
* @ingroup wifi
* WICED Wi-Fi functions for WLAN low power modes
*
* @{
*/
/*****************************************************************************/
/** Enables powersave mode without regard for throughput reduction
*
* This function enables (legacy) 802.11 PS-Poll mode and should be used
* to achieve the lowest power consumption possible when the Wi-Fi device
* is primarily passively listening to the network
*
* @warning An accurate 32kHz clock reference must be connected to the WLAN \n
* sleep clock input pin while the WLAN chip is in powersave mode! \n
* Failure to meet this requirement will result in poor WLAN performance. \n
* The sleep clock reference is typically configured in the file: \n
* <WICED-SDK>/include/platforms/<PLATFORM_NAME>/platform.h
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_enable_powersave( void );
/** Enables powersave mode while attempting to maximise throughput
*
* Network traffic is typically bursty. Reception of a packet often means that another
* packet will be received shortly afterwards (and vice versa for transmit)
* \p
* In high throughput powersave mode, rather then entering powersave mode immediately
* after receiving or sending a packet, the WLAN chip will wait for a timeout period before
* returning to sleep
*
* @note return_to_sleep_delay must be set to a multiple of 10.
*
*
* @warning An accurate 32kHz clock reference must be connected to the WLAN \n
* sleep clock input pin while the WLAN chip is in powersave mode! \n
* Failure to meet this requirement will result in poor WLAN performance. \n
* The sleep clock reference is typically configured in the file: \n
* <WICED-SDK>/include/platforms/<PLATFORM_NAME>/platform.h
*
* @param[in] return_to_sleep_delay : Timeout period (in milliseconds) before the WLAN chip returns to sleep
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_enable_powersave_with_throughput( uint16_t return_to_sleep_delay_ms );
/** Disable 802.11 power save mode
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_disable_powersave( void );
/** @} */
/*****************************************************************************/
/** @addtogroup packetfilter Packet Filter functions
* @ingroup wifi
* WICED Wi-Fi functions for manipulating packet filters.
*
* @{
*/
/*****************************************************************************/
/** Sets the packet filter mode (or rule) to either forward or discard packets on a match
*
* @param[in] mode : Packet filter mode
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_set_packet_filter_mode( wiced_packet_filter_mode_t mode );
/** Adds an ethernet packet filter which causes the WLAN chip to drop all packets that
* do NOT match the filter
*
* When a packet filter(s) is installed, incoming packets received by the WLAN chip are
* run through the pre-installed filter(s). Filter criteria are added using this API function.
* If the WLAN chip receives a packet that matches one of the currently installed filters,
* the host MCU is notified, and the packet is forwarded to the MCU. Packets that do
* not match any of the installed filters are dropped by the WLAN chip.
* \p
* If there are no packet filters installed, all received packets are passed from
* the WLAN chip to the host MCU
*
* @param[in] settings : Packet filter settings
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_add_packet_filter( const wiced_packet_filter_t* settings );
/** Removes (uninstalls) a previously installed packet filter
*
* @param[in] filter_id : The unique user assigned ID for the filter
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_remove_packet_filter( uint8_t filter_id );
/** Enables a previously installed packet filter
*
* @param[in] filter_id : The unique user assigned ID for the filter
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_enable_packet_filter( uint8_t filter_id );
/** Disables a previously installed packet filter
*
* @param[in] filter_id : The unique user assigned ID for the filter
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_disable_packet_filter( uint8_t filter_id );
/** Gets packet filter statistics including packets matched, packets forwarded and packets discarded.
*
* @param[in] filter_id : The unique user assigned ID for the filter
* @param[out] stats : A pointer to a structure that will be populated with filter statistics
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_get_packet_filter_stats( uint8_t filter_id, wiced_packet_filter_stats_t* stats );
/** Clear all packet filter statistics
*
* @param[in] filter_id : The unique user assigned ID for the filter
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_clear_packet_filter_stats( uint32_t filter_id );
/** Get details of packet filters
*
* @Note: does not retrieve the Filter mask and pattern. use @ref wiced_wifi_get_packet_filter_mask_and_pattern to retreive those.
*
* @param[in] max_count : The maximum number of filters to return details for.
* @param[in] offset : The location (count) of the first filter to retrieve (0=beginning)
* @param[out] list : An array which will receive the filter descriptors - must be able to fit max_count items
* @param[out] count_out: The number of filter descrptors retrieved
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_get_packet_filters( uint32_t max_count, uint32_t offset, wiced_packet_filter_t* list, uint32_t* count_out );
/** Get the filter pattern and mask for a packet filters
*
* @param[in] filter_id : The id used to create the packet filter
* @param[in] max_size : Size of the supplied pattern and mask buffers in bytes
* @param[out] mask : Byte array that will receive the packet filter mask
* @param[out] pattern : Byte array that will receive the packet filter pattern
* @param[out] size_out : The number bytes returned in each of pattern and filter buffers
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_get_packet_filter_mask_and_pattern( uint32_t filter_id, uint32_t max_size, uint8_t* mask, uint8_t* pattern, uint32_t* size_out );
/** @} */
/*****************************************************************************/
/** @addtogroup keepalive Keep-Alive functions
* @ingroup wifi
* WICED Wi-Fi functions for automatically sending regular keep alive packets
*
* @{
*/
/*****************************************************************************/
/** Add a network keep alive packet
*
* Keep alive functionality enables the WLAN chip to automatically send
* an arbitrary IP packet and/or 802.11 Null Function data frame at
* a regular interval
* \p
* This feature may be used to maintain connectivity with a Wi-Fi AP
* and/or remote network application
*
* \li A maximum of 4 keep alive packets can be configured to operate concurrently
* \li Keep alive packet functionality only works with client (STA) mode
* \li If the keep alive packet length is set to 0, a Null-Function Data frame is automatically used as the keep alive
* \li Any ethernet packet can be sent as a keep alive packet
*
* @param[in] keep_alive_packet_info : Pointer to a @ref wiced_keep_alive_packet_t structure used to setup the keep alive packet
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_add_keep_alive( wiced_keep_alive_packet_t* keep_alive_packet_info );
/** Get information about a keep alive packet
*
* \li The ID of the keep alive packet should be provided in the keep_alive_info structure
* \li The application must pre-allocate a buffer to store the keep alive packet that is read from the WLAN chip
* \li The length of the buffer must be provided in the packet_length field of the structure
* \li The repeat period and keep alive packet bytes are populated by this function upon successful return
*
* @param[in,out] keep_alive_packet_info : Pointer to the wiced_keep_alive_t structure to be populated
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_get_keep_alive( wiced_keep_alive_packet_t* keep_alive_packet_info );
/** Disable a keep alive packet specified by id
*
* @param[in] id : ID of the keep alive packet to be disabled
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_disable_keep_alive( uint8_t id );
/** @} */
/** Gets information about associated clients.
*
* @note Only applicable if softAP interface is up
*
* @param[out] client_list_buffer : pointer to a buffer that will be populated with a variable length structure defined by @ref wiced_maclist_t
* @param[in] buffer_length : length of the buffer
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_get_associated_client_list( void* client_list_buffer, uint16_t buffer_length );
/** Gets information about the AP the client interface is currently associated to
*
* @note Only applicable if STA (client) interface is associated to an AP
*
* @param[out] ap_info : Pointer to structure that will be populated with AP information
* @param[out] security : Pointer to structure that will be populated with AP security type
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_get_ap_info( wiced_bss_info_t* ap_info, wiced_security_t* security );
/** Sets the HT mode for the given interface
*
* NOTE:
* Ensure WiFi core and network is down before invoking this function.
* Refer wiced_wifi_down() and wiced_network_down() functions for details.
*
* @param[in] ht_mode : HT mode to be set for the given interface
* @param[in] interface : Interface for which HT Mode to be set
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_set_ht_mode( wiced_interface_t interface, wiced_ht_mode_t ht_mode );
/** Gets the HT mode for the given interface
*
* @param[out] ht_mode : Pointer to the enum to store the currently used HT mode of the given interface.
* @param[in] interface : Interface for which HT mode to be identified.
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_get_ht_mode( wiced_interface_t interface, wiced_ht_mode_t* ht_mode );
/** Disable / enable 11n mode
*
* NOTE:
* Ensure WiFi core and network is down before invoking this function.
* Refer wiced_wifi_down() API for details.
*
* @param[in] interface : Disables 11n mode on the given interface
* @param[in] disable : Boolean to indicate if 11n mode to be disabled/enabled. If set to WICED_TRUE, 11n mode will be disabled.
*
* @return @ref wiced_result_t
*/
static inline wiced_result_t wiced_wifi_disable_11n_support( wiced_interface_t interface, wiced_bool_t disable );
/** @} */
/******************************************************
* Inline Function Implementations
******************************************************/
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_set_roam_trigger( int32_t trigger_level )
{
return (wiced_result_t) wwd_wifi_set_roam_trigger( trigger_level );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_get_roam_trigger( int32_t* trigger_level )
{
return (wiced_result_t) wwd_wifi_get_roam_trigger( trigger_level );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_get_channel( uint32_t* channel )
{
return (wiced_result_t) wwd_wifi_get_channel(WWD_STA_INTERFACE, channel);
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_get_mac_address( wiced_mac_t* mac )
{
return (wiced_result_t) wwd_wifi_get_mac_address( mac, WWD_STA_INTERFACE );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_get_counters(wwd_interface_t interface, wiced_counters_t* counters )
{
return (wiced_result_t) wwd_wifi_get_counters( interface, counters );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_set_listen_interval( uint8_t listen_interval, wiced_listen_interval_time_unit_t time_unit )
{
return (wiced_result_t) wwd_wifi_set_listen_interval( listen_interval, time_unit );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_set_listen_interval_assoc( uint16_t listen_interval )
{
return (wiced_result_t) wwd_wifi_set_listen_interval_assoc( listen_interval );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_get_listen_interval( wiced_listen_interval_t* li )
{
return (wiced_result_t) wwd_wifi_get_listen_interval( li );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_enable_powersave( void )
{
return (wiced_result_t) wwd_wifi_enable_powersave( );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_enable_powersave_with_throughput( uint16_t return_to_sleep_delay_ms )
{
return (wiced_result_t) wwd_wifi_enable_powersave_with_throughput( return_to_sleep_delay_ms );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_disable_powersave( void )
{
return (wiced_result_t) wwd_wifi_disable_powersave( );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_set_packet_filter_mode( wiced_packet_filter_mode_t mode )
{
return (wiced_result_t) wwd_wifi_set_packet_filter_mode( mode );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_add_packet_filter( const wiced_packet_filter_t* settings )
{
return (wiced_result_t) wwd_wifi_add_packet_filter( settings );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_remove_packet_filter( uint8_t filter_id )
{
return (wiced_result_t) wwd_wifi_remove_packet_filter( filter_id );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_enable_packet_filter( uint8_t filter_id )
{
return (wiced_result_t) wwd_wifi_enable_packet_filter( filter_id );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_disable_packet_filter( uint8_t filter_id )
{
return (wiced_result_t) wwd_wifi_disable_packet_filter( filter_id );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_get_packet_filter_stats( uint8_t filter_id, wiced_packet_filter_stats_t* stats )
{
return (wiced_result_t) wwd_wifi_get_packet_filter_stats( filter_id, stats );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_clear_packet_filter_stats( uint32_t filter_id )
{
return (wiced_result_t) wwd_wifi_clear_packet_filter_stats( filter_id );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_get_packet_filters( uint32_t max_count, uint32_t offset, wiced_packet_filter_t* list, uint32_t* count_out )
{
return (wiced_result_t) wwd_wifi_get_packet_filters( max_count, offset, list, count_out );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_get_packet_filter_mask_and_pattern( uint32_t filter_id, uint32_t max_size, uint8_t* mask, uint8_t* pattern, uint32_t* size_out )
{
return (wiced_result_t) wwd_wifi_get_packet_filter_mask_and_pattern( filter_id, max_size, mask, pattern, size_out );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_add_keep_alive( wiced_keep_alive_packet_t* keep_alive_packet_info )
{
return (wiced_result_t) wwd_wifi_add_keep_alive( keep_alive_packet_info );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_get_keep_alive( wiced_keep_alive_packet_t* keep_alive_packet_info )
{
return (wiced_result_t) wwd_wifi_get_keep_alive( keep_alive_packet_info );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_disable_keep_alive( uint8_t id )
{
return (wiced_result_t) wwd_wifi_disable_keep_alive( id );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_get_associated_client_list( void* client_list_buffer, uint16_t buffer_length )
{
return (wiced_result_t) wwd_wifi_get_associated_client_list( client_list_buffer, buffer_length );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_get_ap_client_rssi( int32_t* rssi, const wiced_mac_t* client_mac_addr )
{
return (wiced_result_t) wwd_wifi_get_ap_client_rssi( rssi, client_mac_addr );
}
static inline ALWAYS_INLINE wiced_result_t wiced_wifi_get_ap_info( wiced_bss_info_t* ap_info, wiced_security_t* security )
{
return (wiced_result_t) wwd_wifi_get_ap_info( ap_info, security );
}
static inline wiced_result_t wiced_wifi_set_ht_mode( wiced_interface_t interface, wiced_ht_mode_t ht_mode )
{
return (wiced_result_t) wwd_wifi_set_ht_mode( (wwd_interface_t)interface, ht_mode );
}
static inline wiced_result_t wiced_wifi_get_ht_mode( wiced_interface_t interface, wiced_ht_mode_t* ht_mode )
{
return (wiced_result_t) wwd_wifi_get_ht_mode( (wwd_interface_t)interface, ht_mode );
}
static inline wiced_result_t wiced_wifi_disable_11n_support( wiced_interface_t interface, wiced_bool_t disable )
{
return (wiced_result_t) wwd_wifi_set_11n_support( (wwd_interface_t)interface, (disable==WICED_FALSE)?WICED_11N_SUPPORT_ENABLED : WICED_11N_SUPPORT_DISABLED );
}
/**
* Helper function to print a given MAC address
*
* @param[in] mac A pointer to the @ref wiced_mac_t address
*/
static inline void print_mac_address( const wiced_mac_t* mac )
{
UNUSED_PARAMETER(mac);
WPRINT_APP_INFO( ( "%02X:%02X:%02X:%02X:%02X:%02X", mac->octet[0],
mac->octet[1],
mac->octet[2],
mac->octet[3],
mac->octet[4],
mac->octet[5] ) );
}
#ifdef __cplusplus
} /*extern "C" */
#endif
|
fagarine/dangkang | dk-core/src/main/java/cn/laoshini/dk/expression/js/JavaScriptExpressionLogic.java | <filename>dk-core/src/main/java/cn/laoshini/dk/expression/js/JavaScriptExpressionLogic.java<gh_stars>10-100
package cn.laoshini.dk.expression.js;
import javax.script.ScriptContext;
import javax.script.SimpleScriptContext;
import cn.laoshini.dk.constant.ExpressionConstant;
import cn.laoshini.dk.expression.BaseExpressionLogic;
import cn.laoshini.dk.expression.IExpressionProcessor;
import cn.laoshini.dk.util.CollectionUtil;
/**
* 使用JavaScript脚本实现的表达式逻辑处理类
*
* @author fagarine
*/
public class JavaScriptExpressionLogic extends BaseExpressionLogic {
public JavaScriptExpressionLogic() {
super(ExpressionConstant.ExpressionTypeEnum.JS);
}
@Override
protected void initProcessors() {
super.initProcessors();
if (CollectionUtil.isNotEmpty(processors())) {
ScriptContext context = new SimpleScriptContext();
for (IExpressionProcessor processor : processors()) {
JavaScriptExpressionProcessor jsProcessor = (JavaScriptExpressionProcessor) processor;
jsProcessor.setScriptContext(context);
jsProcessor.prepare();
}
}
}
}
|
wanghongsheng01/framework_enflame | oneflow/python/test/modules/test_nllloss.py | """
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import unittest
from collections import OrderedDict
import numpy as np
import oneflow.experimental as flow
from test_util import GenArgList
def nll_loss_1d(logs, targets, reduction="none"):
input_shape = logs.shape
N = input_shape[0]
C = input_shape[1]
out = np.zeros_like(targets).astype(np.float64)
total_weight = N
for i in range(N):
cur_target = targets[i]
out[i] = -logs[i][cur_target]
if reduction == "sum":
return np.sum(out)
elif reduction == "mean":
return out.sum() / total_weight
elif reduction == "none":
return out
def nll_loss_2d(logs, targets, reduction="none"):
input_shape = logs.shape
N = input_shape[0]
H = input_shape[2]
W = input_shape[3]
out = np.zeros_like(targets).astype(np.float64)
total_weight = N * H * W
for i in range(N):
for h in range(H):
for w in range(W):
cur_target = targets[i][h][w]
out[i][h][w] = -logs[i][cur_target][h][w]
if reduction == "sum":
return np.sum(out)
elif reduction == "mean":
return out.sum() / total_weight
elif reduction == "none":
return out
def nll_loss_bert(logs, targets, reduction="none"):
input_shape = logs.shape
N = input_shape[0]
H = input_shape[2]
out = np.zeros_like(targets).astype(np.float64)
total_weight = N * H
for i in range(N):
for h in range(H):
cur_target = targets[i][h]
out[i][h] = -logs[i][cur_target][h]
if reduction == "sum":
return np.sum(out)
elif reduction == "mean":
return out.sum() / total_weight
elif reduction == "none":
return out
def _test_nllloss_none(test_case, device):
x = np.array(
[
[0.88103855, 0.9908683, 0.6226845],
[0.53331435, 0.07999352, 0.8549948],
[0.25879037, 0.39530203, 0.698465],
[0.73427284, 0.63575995, 0.18827209],
[0.05689114, 0.0862954, 0.6325046],
]
).astype(np.float32)
y = np.array([0, 2, 1, 1, 0]).astype(np.int)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="none")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_1d(input.numpy(), target.numpy())
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_mean(test_case, device):
x = np.array(
[
[0.88103855, 0.9908683, 0.6226845],
[0.53331435, 0.07999352, 0.8549948],
[0.25879037, 0.39530203, 0.698465],
[0.73427284, 0.63575995, 0.18827209],
[0.05689114, 0.0862954, 0.6325046],
]
).astype(np.float32)
y = np.array([0, 2, 1, 1, 0]).astype(np.int)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="mean")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_1d(input.numpy(), target.numpy(), reduction="mean")
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_sum(test_case, device):
x = np.array(
[
[0.88103855, 0.9908683, 0.6226845],
[0.53331435, 0.07999352, 0.8549948],
[0.25879037, 0.39530203, 0.698465],
[0.73427284, 0.63575995, 0.18827209],
[0.05689114, 0.0862954, 0.6325046],
]
).astype(np.float32)
y = np.array([0, 2, 1, 1, 0]).astype(np.int)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="sum")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_1d(input.numpy(), target.numpy(), reduction="sum")
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_segmentation_none(test_case, device):
x = np.array(
[[[[0.12, 0.36], [0.22, 0.66]], [[0.13, 0.34], [0.52, -0.96]]]]
).astype(np.float32)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
y = np.array([[[1, 0], [0, 1]]]).astype(np.int)
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="none")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_2d(input.numpy(), target.numpy())
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_segmentation_mean(test_case, device):
x = np.array(
[[[[0.12, 0.36], [0.22, 0.66]], [[0.13, 0.34], [0.52, -0.96]]]]
).astype(np.float32)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
y = np.array([[[1, 0], [0, 1]]]).astype(np.int)
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="mean")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_2d(input.numpy(), target.numpy(), reduction="mean")
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_segmentation_sum(test_case, device):
x = np.array(
[[[[0.12, 0.36], [0.22, 0.66]], [[0.13, 0.34], [0.52, -0.96]]]]
).astype(np.float32)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
y = np.array([[[1, 0], [0, 1]]]).astype(np.int)
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="sum")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_2d(input.numpy(), target.numpy(), reduction="sum")
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_bert_none(test_case, device):
x = np.array([[[0.12, 0.36, 0.22, 0.66], [0.13, 0.34, 0.52, -0.96]]]).astype(
np.float32
)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
y = np.array([[1, 0, 0, 1]]).astype(np.int)
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="none")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_bert(input.numpy(), target.numpy())
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_bert_mean(test_case, device):
x = np.array([[[0.12, 0.36, 0.22, 0.66], [0.13, 0.34, 0.52, -0.96]]]).astype(
np.float32
)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
y = np.array([[1, 0, 0, 1]]).astype(np.int)
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="mean")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_bert(input.numpy(), target.numpy(), reduction="mean")
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
def _test_nllloss_bert_sum(test_case, device):
x = np.array([[[0.12, 0.36, 0.22, 0.66], [0.13, 0.34, 0.52, -0.96]]]).astype(
np.float32
)
input = flow.Tensor(x, dtype=flow.float32, device=flow.device(device))
y = np.array([[1, 0, 0, 1]]).astype(np.int)
target = flow.Tensor(y, dtype=flow.int64, device=flow.device(device))
nll_loss = flow.nn.NLLLoss(reduction="sum")
nll_loss = nll_loss.to(device)
of_out = nll_loss(input, target)
np_out = nll_loss_bert(input.numpy(), target.numpy(), reduction="sum")
test_case.assertTrue(np.allclose(of_out.numpy(), np_out))
@unittest.skipIf(
not flow.unittest.env.eager_execution_enabled(),
".numpy() doesn't work in lazy mode",
)
class TestNLLLossModule(flow.unittest.TestCase):
def test_nllloss(test_case):
arg_dict = OrderedDict()
arg_dict["test_fun"] = [
_test_nllloss_none,
_test_nllloss_mean,
_test_nllloss_sum,
_test_nllloss_segmentation_none,
_test_nllloss_segmentation_mean,
_test_nllloss_segmentation_sum,
_test_nllloss_bert_none,
_test_nllloss_bert_mean,
_test_nllloss_bert_sum,
]
arg_dict["device"] = ["cpu", "cuda"]
for arg in GenArgList(arg_dict):
arg[0](test_case, *arg[1:])
if __name__ == "__main__":
unittest.main()
|
zesty-io/nextjs-website | src/blocks/contentBlocks/index.js | export { default as Story } from './Story';
export { default as About } from './About';
export { default as CompanyValues } from './CompanyValues';
export { default as ContactDetails } from './ContactDetails';
|
cser700/play-together | src/main/java/com/cser/play/common/model/base/BaseRewardTaskAccept.java | package com.cser.play.common.model.base;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.IBean;
/**
* Generated by JFinal, do not modify this file.
*/
@SuppressWarnings("serial")
public abstract class BaseRewardTaskAccept<M extends BaseRewardTaskAccept<M>> extends Model<M> implements IBean {
public void setId(java.lang.Integer id) {
set("id", id);
}
public java.lang.Integer getId() {
return getInt("id");
}
public void setTaskId(java.lang.Integer taskId) {
set("task_id", taskId);
}
public java.lang.Integer getTaskId() {
return getInt("task_id");
}
public void setAcceptUserId(java.lang.Integer acceptUserId) {
set("accept_user_id", acceptUserId);
}
public java.lang.Integer getAcceptUserId() {
return getInt("accept_user_id");
}
public void setAcceptUserName(java.lang.String acceptUserName) {
set("accept_user_name", acceptUserName);
}
public java.lang.String getAcceptUserName() {
return getStr("accept_user_name");
}
public void setCreateDate(java.util.Date createDate) {
set("create_date", createDate);
}
public java.util.Date getCreateDate() {
return get("create_date");
}
}
|
rumenNikodimov/Java-Script-Core | 09.Strings and Regular Expressions/06. Capture the Numbers.js | function captureTheNumbers(input) {
let pattern = /\d+/gm
result = []
let text = ''
for (let i = 0; i < input.length; i++) {
let currentElement = input[i]
text += currentElement + ' '
}
let match = pattern.exec(text)
while(match){
result.push(match[0])
match = pattern.exec(text)
}
console.log(result.join(' '))
}
captureTheNumbers(['The300', 'What is that?',
'I think it’s the 3rd movie.', 'Lets watch it at 22:45'])
captureTheNumbers([
'123a456',
'789b987',
'654c321',
'0'])
captureTheNumbers(['Let’s go11!!!11!', 'Okey!1!']) |
bartoszm/Snowmass-ONFOpenTransport | TAPI_RI/flask_server/tapi_server/models/route_compute_policy.py | <gh_stars>0
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from tapi_server.models.base_model_ import Model
from tapi_server import util
class RouteComputePolicy(Model):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, route_objective_function: str=None, diversity_policy: str=None): # noqa: E501
"""RouteComputePolicy - a model defined in Swagger
:param route_objective_function: The route_objective_function of this RouteComputePolicy. # noqa: E501
:type route_objective_function: str
:param diversity_policy: The diversity_policy of this RouteComputePolicy. # noqa: E501
:type diversity_policy: str
"""
self.swagger_types = {
'route_objective_function': str,
'diversity_policy': str
}
self.attribute_map = {
'route_objective_function': 'route-objective-function',
'diversity_policy': 'diversity-policy'
}
self._route_objective_function = route_objective_function
self._diversity_policy = diversity_policy
@classmethod
def from_dict(cls, dikt) -> 'RouteComputePolicy':
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The route-compute-policy of this RouteComputePolicy. # noqa: E501
:rtype: RouteComputePolicy
"""
return util.deserialize_model(dikt, cls)
@property
def route_objective_function(self) -> str:
"""Gets the route_objective_function of this RouteComputePolicy.
:return: The route_objective_function of this RouteComputePolicy.
:rtype: str
"""
return self._route_objective_function
@route_objective_function.setter
def route_objective_function(self, route_objective_function: str):
"""Sets the route_objective_function of this RouteComputePolicy.
:param route_objective_function: The route_objective_function of this RouteComputePolicy.
:type route_objective_function: str
"""
allowed_values = ["MIN_WORK_ROUTE_HOP", "MIN_WORK_ROUTE_COST", "MIN_WORK_ROUTE_LATENCY", "MIN_SUM_OF_WORK_AND_PROTECTION_ROUTE_HOP", "MIN_SUM_OF_WORK_AND_PROTECTION_ROUTE_COST", "MIN_SUM_OF_WORK_AND_PROTECTION_ROUTE_LATENCY", "LOAD_BALANCE_MAX_UNUSED_CAPACITY"] # noqa: E501
if route_objective_function not in allowed_values:
raise ValueError(
"Invalid value for `route_objective_function` ({0}), must be one of {1}"
.format(route_objective_function, allowed_values)
)
self._route_objective_function = route_objective_function
@property
def diversity_policy(self) -> str:
"""Gets the diversity_policy of this RouteComputePolicy.
:return: The diversity_policy of this RouteComputePolicy.
:rtype: str
"""
return self._diversity_policy
@diversity_policy.setter
def diversity_policy(self, diversity_policy: str):
"""Sets the diversity_policy of this RouteComputePolicy.
:param diversity_policy: The diversity_policy of this RouteComputePolicy.
:type diversity_policy: str
"""
allowed_values = ["SRLG", "SRNG", "SNG", "NODE", "LINK"] # noqa: E501
if diversity_policy not in allowed_values:
raise ValueError(
"Invalid value for `diversity_policy` ({0}), must be one of {1}"
.format(diversity_policy, allowed_values)
)
self._diversity_policy = diversity_policy
|
simoneb/melodie | .storybook/decorators/ipcRendererMock.js | 'use strict'
import { action } from '@storybook/addon-actions'
const invokeAction = action('invoke')
export default function (mock = () => null) {
return storyFn => {
if (!window.electron) {
window.electron = {}
}
window.electron.ipcRenderer = {
addEventListener: () => {},
removeEventListener: () => {},
invoke: (channel, service, method, ...args) => {
invokeAction(service, method, ...args)
return mock(method, ...args) || {}
}
}
return storyFn()
}
}
|
phoenixsbk/kvmmgr | frontend/webadmin/modules/userportal-gwtp/annotations/org/ovirt/engine/ui/userportal/section/main/presenter/tab/extended/ExtendedVirtualMachineSelectionChangeEvent.java | package org.ovirt.engine.ui.userportal.section.main.presenter.tab.extended;
import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.web.bindery.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.HasHandlers;
public class ExtendedVirtualMachineSelectionChangeEvent extends GwtEvent<ExtendedVirtualMachineSelectionChangeEvent.ExtendedVirtualMachineSelectionChangeHandler> {
java.util.List<org.ovirt.engine.ui.uicommonweb.models.userportal.UserPortalItemModel> selectedItems;
protected ExtendedVirtualMachineSelectionChangeEvent() {
// Possibly for serialization.
}
public ExtendedVirtualMachineSelectionChangeEvent(java.util.List<org.ovirt.engine.ui.uicommonweb.models.userportal.UserPortalItemModel> selectedItems) {
this.selectedItems = selectedItems;
}
public static void fire(HasHandlers source, java.util.List<org.ovirt.engine.ui.uicommonweb.models.userportal.UserPortalItemModel> selectedItems) {
ExtendedVirtualMachineSelectionChangeEvent eventInstance = new ExtendedVirtualMachineSelectionChangeEvent(selectedItems);
source.fireEvent(eventInstance);
}
public static void fire(HasHandlers source, ExtendedVirtualMachineSelectionChangeEvent eventInstance) {
source.fireEvent(eventInstance);
}
public interface HasExtendedVirtualMachineSelectionChangeHandlers extends HasHandlers {
HandlerRegistration addExtendedVirtualMachineSelectionChangeHandler(ExtendedVirtualMachineSelectionChangeHandler handler);
}
public interface ExtendedVirtualMachineSelectionChangeHandler extends EventHandler {
public void onExtendedVirtualMachineSelectionChange(ExtendedVirtualMachineSelectionChangeEvent event);
}
private static final Type<ExtendedVirtualMachineSelectionChangeHandler> TYPE = new Type<ExtendedVirtualMachineSelectionChangeHandler>();
public static Type<ExtendedVirtualMachineSelectionChangeHandler> getType() {
return TYPE;
}
@Override
public Type<ExtendedVirtualMachineSelectionChangeHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(ExtendedVirtualMachineSelectionChangeHandler handler) {
handler.onExtendedVirtualMachineSelectionChange(this);
}
public java.util.List<org.ovirt.engine.ui.uicommonweb.models.userportal.UserPortalItemModel> getSelectedItems(){
return selectedItems;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ExtendedVirtualMachineSelectionChangeEvent other = (ExtendedVirtualMachineSelectionChangeEvent) obj;
if (selectedItems == null) {
if (other.selectedItems != null)
return false;
} else if (!selectedItems.equals(other.selectedItems))
return false;
return true;
}
@Override
public int hashCode() {
int hashCode = 23;
hashCode = (hashCode * 37) + (selectedItems == null ? 1 : selectedItems.hashCode());
return hashCode;
}
@Override
public String toString() {
return "ExtendedVirtualMachineSelectionChangeEvent["
+ selectedItems
+ "]";
}
}
|
Drago-Dev24/Anime-Based-Bot | commands/custom/Tags.js | <reponame>Drago-Dev24/Anime-Based-Bot
module.exports = {
name: "tag",
description: "Create Custom Responded Commands For Your Server",
usage: "create <Command Name> <Command Response> | delete <Command Name> | list",
authorPermission: ["ADMINISTRATOR"],
run: async(client, message, args) => {
if (!args[0]) return client.embeds.nomal(message, "Tags", "tag create <Command Name> <Command Response>\ntag delete <Command Name>\n<tag list>")
if (args[0].toLowerCase() === 'create') {
if (!args[1]) return client.embeds.error(message, "What Should The Tag Name Be?")
if (!args.slice(2).join(" ")) return client.embeds.error(message, "What Should The Tag Response Be")
let data = await client.db.get(`${message.guild.id}.tags`)
if (data && data.find(x => x.name === args[1].toLowerCase())) return client.embeds.error(message, "There Is Already A Tag With Name")
let data2 = {
name: args[1].toLowerCase(),
response: args.slice(2).join(" ")
}
await client.db.push(`${message.guild.id}.tags`, data2)
return client.embeds.success(message, "Successfully Added That Tag")
}
if (args[0].toLowerCase() === 'delete') {
if (!args[1]) return client.embeds.error(message, "Which Tag Are You Deleting")
let data = await client.db.get(`${message.guild.id}.tags`)
if (data && !data.find(x => x.name === args[1].toLowerCase())) return client.embeds.error(message, "There Is No Such Tag Created")
let index = data.filter(x => x.name !== args[1].toLowerCase())
await client.db.set(`${message.guild.id}.tags`, index)
return client.embeds.success(message, "Removed The Tag")
}
if (args[0].toLowerCase() === 'list') {
let data = await client.db.get(`${message.guild.id}.tags`);
let array;
if (data && data.length) {
array = [];
data.forEach(x => {
array.push(x.name)
})
}
return client.embeds.normal(message, "Tags", `${array ? array : "No Tags Created Yet"}`)
}
}
} |
termux-one/EasY_HaCk | .modules/.recon-ng/modules/recon/repositories-vulnerabilities/gists_search.py | from recon.core.module import BaseModule
from urllib import quote_plus
import os
class Module(BaseModule):
meta = {
'name': 'Github Gist Searcher',
'author': '<NAME> (@LaNMaSteR53)',
'description': 'Uses the Github API to download and search Gists for possible information disclosures. Updates the \'vulnerabilities\' table with the results.',
'comments': (
'Gist searches are case sensitive. Include all desired permutations in the keyword list.',
),
'query': "SELECT DISTINCT url FROM repositories WHERE url IS NOT NULL AND resource LIKE 'Github' AND category LIKE 'gist'",
'options': (
('keywords', os.path.join(BaseModule.data_path, 'gist_keywords.txt'), True, 'file containing a list of keywords'),
),
}
def module_run(self, gists):
with open(self.options['keywords']) as fp:
# create list of keywords and filter out comments
keywords = [x.strip() for x in fp.read().splitlines() if x and not x.startswith('#')]
for gist in gists:
filename = gist.split(os.sep)[-1]
self.heading(filename, level=0)
resp = self.request(gist)
for keyword in keywords:
self.verbose('Searching Gist for: %s' % (keyword))
lines = resp.raw.splitlines()
for lineno, line in enumerate(lines):
if keyword in line:
data = {
'reference': gist,
'example': 'line %d: %s' % (lineno, line.strip()),
'category': 'Information Disclosure',
}
self.add_vulnerabilities(**data)
|
ItsSerium/seriumium | structures/settings/update/index.js | module.exports.guild = require('./guild')
module.exports.user = require('./user')
|
reines/game | game-common/src/main/java/com/game/common/codec/PacketCodecFactory.java | <gh_stars>0
package com.game.common.codec;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolEncoder;
public class PacketCodecFactory implements ProtocolCodecFactory {
private final ProtocolDecoder decoder;
private final ProtocolEncoder encoder;
public PacketCodecFactory() {
decoder = new PacketDecoder();
encoder = new PacketEncoder();
}
public ProtocolDecoder getDecoder(IoSession session) throws Exception {
return decoder;
}
public ProtocolEncoder getEncoder(IoSession session) throws Exception {
return encoder;
}
}
|
diandian-xue/ddengine | ddgl/ddgltexture.h | <filename>ddgl/ddgltexture.h
#pragma once
#include "ddgl.h"
#include "ddglmath.h"
#include "ddclstorage.h"
#include <ft2build.h>
#include FT_FREETYPE_H
#include "freetype/freetype.h"
#include <freetype/ftglyph.h>
#define DDGL_TEXTURE_EXTEND 128
typedef struct tag_ddgl_Texture {
int ref;
ddcl_Handle h;
ddgl_Size size;
char extend[DDGL_TEXTURE_EXTEND];
void(*free)(void * tex);
void(*use)(void * tex);
}ddgl_Texture;
typedef struct tag_ddgl_FontFace{
int ref;
ddcl_Handle h;
FT_Face face;
}ddgl_FontFace;
typedef struct tag_ddgl_TextDef {
unsigned maxw;
unsigned maxh;
unsigned hgap;
unsigned vgap;
unsigned size;
}ddgl_TextDef;
DDGLAPI int
ddgl_init_texture_module(ddgl * conf);
DDGLAPI void
ddgl_exit_texture_module();
DDGLAPI ddgl_Texture *
ddgl_new_texture(ddgl_Size size);
DDGLAPI ddgl_Texture *
ddgl_retain_texture(ddcl_Handle h);
DDGLAPI void
ddgl_release_texture(ddcl_Handle h);
DDGLAPI ddgl_Texture *
ddgl_new_texture_with_png_file(const char * path);
DDGLAPI ddgl_Texture *
ddgl_new_texture_with_png_data(const char * data, size_t sz);
DDGLAPI ddgl_FontFace *
ddgl_new_fontface(const char * font);
DDGLAPI ddgl_FontFace *
ddgl_retain_fontface(ddcl_Handle h);
DDGLAPI void
ddgl_release_fontface(ddcl_Handle h);
DDGLAPI ddgl_Texture *
ddgl_new_texture_with_utf8(const char * str, ddgl_FontFace * font, ddgl_Texture * def);
|
esmanda3w/tp | src/main/java/seedu/pivot/model/investigationcase/caseperson/Sex.java | <gh_stars>0
package seedu.pivot.model.investigationcase.caseperson;
import static java.util.Objects.requireNonNull;
/**
* Represents a Person's sex in PIVOT.
* Guarantees: immutable; is valid as declared in {@link #isValidSex(String)} (String)}
*/
public enum Sex {
M, F;
public static final String MESSAGE_CONSTRAINTS = "Sex can only be either M or F";
/**
* Creates a Sex Enum with given sex String.
* @param sex
* @return
*/
public static Sex createSex(String sex) {
requireNonNull(sex);
return Sex.valueOf(sex.trim().toUpperCase());
}
/**
* Returns true if a given string is a valid sex.
*/
public static boolean isValidSex(String test) {
String trimmedTest = test.trim();
for (Sex sex : Sex.values()) {
if (sex.name().equals(trimmedTest.toUpperCase())) {
return true;
}
}
return false;
}
}
|
racing19th/MiraiOS | phlibc/include/errno.h | #ifndef __PHLIBC_ERRNO_H
#define __PHLIBC_ERRNO_H
#include <uapi/errno.h>
extern int errno;
#endif |
pamu/ScalaAndroidMacroid | src/main/scala/com/fortysevendeg/scala/android/ui/main/Styles.scala | <filename>src/main/scala/com/fortysevendeg/scala/android/ui/main/Styles.scala<gh_stars>0
package com.fortysevendeg.scala.android.ui.main
import android.support.v7.widget.{CardView, RecyclerView}
import android.text.TextUtils.TruncateAt
import android.view.Gravity
import android.view.ViewGroup.LayoutParams._
import android.widget.ImageView.ScaleType
import android.widget.{ImageView, LinearLayout, TextView}
import com.fortysevendeg.macroid.extras.FrameLayoutTweaks._
import com.fortysevendeg.macroid.extras.ImageViewTweaks._
import com.fortysevendeg.macroid.extras.LinearLayoutTweaks._
import com.fortysevendeg.macroid.extras.ResourcesExtras._
import com.fortysevendeg.macroid.extras.TextTweaks._
import com.fortysevendeg.macroid.extras.ThemeExtras._
import com.fortysevendeg.macroid.extras.ViewGroupTweaks._
import com.fortysevendeg.macroid.extras.ViewTweaks._
import com.fortysevendeg.scala.android.R
import macroid.FullDsl._
import macroid.{ActivityContextWrapper, ContextWrapper, Tweak}
import scala.language.postfixOps
trait Styles {
def listStyle(implicit context: ContextWrapper): Tweak[RecyclerView] =
llMatchWeightVertical +
vPaddings(resGetDimensionPixelSize(R.dimen.padding_default)) +
vgClipToPadding(false)
def contentStyle(implicit context: ContextWrapper): Tweak[LinearLayout] =
llVertical +
vBackgroundColorResource(R.color.main_list_background)
}
trait AdapterStyles {
def cardStyle(implicit activityContext: ActivityContextWrapper): Tweak[CardView] =
vMatchWidth +
(themeGetDrawable(android.R.attr.selectableItemBackground) map flForeground getOrElse Tweak.blank)
def itemStyle: Tweak[LinearLayout] =
llVertical +
vMatchWidth
def itemTopStyle(implicit context: ContextWrapper): Tweak[LinearLayout] =
llHorizontal +
vMatchWidth +
llGravity(Gravity.CENTER_VERTICAL) +
vPadding(
paddingTop = resGetDimensionPixelSize(R.dimen.padding_default_xlarge),
paddingBottom = resGetDimensionPixelSize(R.dimen.padding_default),
paddingLeft = resGetDimensionPixelSize(R.dimen.padding_default_xlarge),
paddingRight = resGetDimensionPixelSize(R.dimen.padding_default_xlarge))
def titleStyle(implicit context: ContextWrapper): Tweak[TextView] =
llWrapWeightHorizontal +
tvSizeResource(R.dimen.font_size_medium) +
tvColorResource(R.color.primary)
def descriptionStyle(implicit context: ContextWrapper): Tweak[TextView] =
tvSizeResource(R.dimen.font_size_normal) +
tvNormalLight +
tvColorResource(R.color.main_list_description) +
tvMaxLines(3) +
vPadding(
paddingBottom = resGetDimensionPixelSize(R.dimen.padding_default_xlarge),
paddingLeft = resGetDimensionPixelSize(R.dimen.padding_default_xlarge),
paddingRight = resGetDimensionPixelSize(R.dimen.padding_default_xlarge))
def apiStyle(implicit context: ContextWrapper): Tweak[TextView] =
tvSizeResource(R.dimen.font_size_micro) +
tvColorResource(R.color.main_list_api) +
vPaddings(
paddingTopBottom = resGetDimensionPixelSize(R.dimen.padding_default_micro),
paddingLeftRight = resGetDimensionPixelSize(R.dimen.padding_default_small))
def lineHorizontalStyle(implicit context: ContextWrapper): Tweak[ImageView] =
lp[LinearLayout](MATCH_PARENT, resGetDimensionPixelSize(R.dimen.line)) +
vBackgroundColorResource(R.color.main_list_line)
val bottomContentStyle: Tweak[LinearLayout] =
vMatchWidth +
llHorizontal +
llGravity(Gravity.CENTER_VERTICAL)
def bottomUserContentStyle(implicit activityContext: ActivityContextWrapper): Tweak[LinearLayout] =
llWrapWeightHorizontal +
llHorizontal +
vPaddings(resGetDimensionPixelSize(R.dimen.padding_default)) +
llGravity(Gravity.CENTER_VERTICAL) +
(themeGetDrawable(android.R.attr.selectableItemBackground) map vBackground getOrElse Tweak.blank)
def avatarStyle(implicit context: ContextWrapper): Tweak[ImageView] = {
val size = resGetDimensionPixelSize(R.dimen.main_list_avatar_size)
lp[LinearLayout](size, size) +
ivScaleType(ScaleType.CENTER_CROP) +
vMargins(resGetDimensionPixelSize(R.dimen.padding_default_small))
}
def userNameStyle(implicit context: ContextWrapper): Tweak[TextView] =
tvSizeResource(R.dimen.font_size_normal) +
tvNormalLight +
tvColorResource(R.color.primary) +
tvMaxLines(1) +
tvEllipsize(TruncateAt.END)
def twitterStyle(implicit context: ContextWrapper): Tweak[TextView] =
tvSizeResource(R.dimen.font_size_small) +
tvNormalLight +
tvColorResource(R.color.main_list_secondary) +
tvMaxLines(1) +
tvEllipsize(TruncateAt.END)
def userNameContentStyle(implicit context: ContextWrapper): Tweak[LinearLayout] =
llMatchWeightHorizontal +
llVertical +
vPadding(paddingLeft = resGetDimensionPixelSize(R.dimen.padding_default_small)) +
llGravity(Gravity.CENTER_VERTICAL)
def lineVerticalStyle(implicit context: ContextWrapper): Tweak[ImageView] =
lp[LinearLayout](resGetDimensionPixelSize(R.dimen.line), MATCH_PARENT) +
vBackgroundColorResource(R.color.main_list_line)
def bottomLevelsContentStyle(implicit context: ContextWrapper): Tweak[LinearLayout] =
llWrapWeightHorizontal +
llVertical +
vPaddings(resGetDimensionPixelSize(R.dimen.padding_default)) +
llGravity(Gravity.CENTER_VERTICAL)
def levelItemContentStyle(implicit context: ContextWrapper): Tweak[LinearLayout] =
vWrapContent +
vPadding(paddingBottom = resGetDimensionPixelSize(R.dimen.padding_default_micro))
def levelStyle(implicit context: ContextWrapper): Tweak[TextView] =
tvSizeResource(R.dimen.font_size_small) +
tvNormalLight +
tvColorResource(R.color.main_list_secondary) +
vMinWidth(resGetDimensionPixelSize(R.dimen.main_list_min_width_levels_tag))
def levelTypeStyle(implicit context: ContextWrapper): Tweak[TextView] =
tvSizeResource(R.dimen.font_size_small) +
tvColorResource(R.color.main_list_tag) +
tvNormalLight +
vPaddings(
paddingTopBottom = 0,
paddingLeftRight = resGetDimensionPixelSize(R.dimen.padding_default_small)) +
tvMaxLines(1) +
tvEllipsize(TruncateAt.END)
}
|
Falcons-Robocup/code | packages/peripheralsInterface/include/int/motors/BallhandlerBoard.hpp | <gh_stars>1-10
// Copyright 2016-2020 <NAME> (Falcons)
// SPDX-License-Identifier: Apache-2.0
/*
* BallhandlerBoard.hpp
*
* Created on: May 3, 2016
* Author: <NAME>
*/
#ifndef INCLUDE_INT_MOTORS_BALLHANDLERBOARD_HPP_
#define INCLUDE_INT_MOTORS_BALLHANDLERBOARD_HPP_
#include <string>
#include "int/motors/MotorControllerBoard.hpp"
#include "int/motors/Communication.hpp"
#include "int/motors/DeviceManager.hpp"
using namespace std;
enum BallhandlerBoardType {
BALLHANDLER_BOARD_RIGHT,
BALLHANDLER_BOARD_LEFT
};
class BallhandlerBoard : public MotorControllerBoard {
public:
BallhandlerBoard(BallhandlerBoardType type, DeviceManager &deviceManager);
BallhandlerBoardDataOutput getBoardData();
void setSetpoint(int angle, int setpoint);
void setSettings(BallhandlerBoardSettings settings);
void setControlMode(BallhandlerBoardControlMode controlMode);
BallhandlerBoardControlMode getControlMode();
protected:
virtual void configure();
virtual bool isConfigurationDone();
virtual void handleAngleTachoZeroResponse(ReceivePackage &package);
virtual void handleDefaultResponse(ReceivePackage &package);
void finishCalibration();
void updateControlMode();
BallhandlerBoardData ballhandlerData;
BallhandlerBoardSettings ballhandlerSettings;
BallhandlerBoardControlMode ballhandlerControlMode;
bool calibrated;
};
#endif /* INCLUDE_INT_MOTORS_BALLHANDLERBOARD_HPP_ */
|
mario7lorenzo/main | src/main/java/hirelah/logic/commands/EditAttributeCommand.java | package hirelah.logic.commands;
import static hirelah.logic.util.CommandUtil.saveAttributes;
import static java.util.Objects.requireNonNull;
import hirelah.commons.exceptions.IllegalValueException;
import hirelah.commons.util.ModelUtil;
import hirelah.logic.commands.exceptions.CommandException;
import hirelah.model.Model;
import hirelah.model.hirelah.Attribute;
import hirelah.model.hirelah.AttributeList;
import hirelah.storage.Storage;
/**
* EditAttributeCommand describes the behavior when the
* client wants to update an attribute from the list.
*/
public class EditAttributeCommand extends Command {
public static final String COMMAND_WORD = "attribute";
public static final boolean DESIRED_MODEL_FINALIZED_STATE = false;
public static final String MESSAGE_FORMAT = "edit " + COMMAND_WORD + " <old attribute> -a <new attribute>";
public static final String MESSAGE_FUNCTION = ": Edits the attribute identified by the name.\n";
public static final String MESSAGE_USAGE = MESSAGE_FORMAT
+ MESSAGE_FUNCTION
+ "Example: edit " + COMMAND_WORD + " leadership -a tenacity";
public static final String MESSAGE_EDIT_ATTRIBUTE_SUCCESS = "Edited attribute: %s to %s";
private final String attributePrefix;
private final String updatedAttribute;
public EditAttributeCommand(String attributePrefix, String updatedAttribute) {
this.attributePrefix = attributePrefix;
this.updatedAttribute = updatedAttribute;
}
@Override
public CommandResult execute(Model model, Storage storage) throws CommandException {
requireNonNull(model);
ModelUtil.validateFinalisation(model, DESIRED_MODEL_FINALIZED_STATE);
AttributeList attributes = model.getAttributeList();
try {
Attribute attribute = attributes.edit(attributePrefix, updatedAttribute);
saveAttributes(model, storage);
return new ToggleCommandResult(String.format(MESSAGE_EDIT_ATTRIBUTE_SUCCESS, attribute, updatedAttribute),
ToggleView.ATTRIBUTE);
} catch (IllegalValueException e) {
throw new CommandException(e.getMessage());
}
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof EditAttributeCommand // instanceof handles nulls
&& attributePrefix.equals(((EditAttributeCommand) other).attributePrefix)
&& updatedAttribute.equals(((EditAttributeCommand) other).updatedAttribute)); // state check
}
}
|
open-o/sdno-brs | br-svc/service/src/main/java/org/openo/sdno/brs/model/roamo/PagingQueryPara.java | /*
* Copyright 2016 Huawei Technologies Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openo.sdno.brs.model.roamo;
import java.util.Map;
/**
* Paging query information.<br>
*
* @author
* @version SDNO 0.5 2016-5-19
*/
public class PagingQueryPara {
/**
* page number to query,default 0.
*/
private int pageNum = 0;
/**
* page size maximum 1000.
*/
private int pageSize = 1000;
/**
* default is base, support all,base,or name/id/location, MSS support ext, BRS not for now.
*/
private String fields = "base";
/**
* filter map.
*/
private Map<String, String> filtersMap;
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public String getFields() {
return fields;
}
public void setFields(String fields) {
if(null == fields || fields.isEmpty()) {
return;
}
this.fields = fields;
}
public Map<String, String> getFiltersMap() {
return filtersMap;
}
public void setFiltersMap(Map<String, String> filtersMap) {
this.filtersMap = filtersMap;
}
}
|
sarang-apps/darshan_browser | chrome/browser/extensions/extension_ui_util.cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_ui_util.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/themes/theme_properties.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/pref_names.h"
#include "components/prefs/pref_service.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_util.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension.h"
#include "extensions/common/image_util.h"
#include "ui/base/theme_provider.h"
namespace extensions {
namespace {
bool IsBlockedByPolicy(const Extension* app, content::BrowserContext* context) {
Profile* profile = Profile::FromBrowserContext(context);
DCHECK(profile);
return (app->id() == extensions::kWebStoreAppId ||
app->id() == extension_misc::kEnterpriseWebStoreAppId) &&
profile->GetPrefs()->GetBoolean(prefs::kHideWebStoreIcon);
}
} // namespace
namespace ui_util {
bool ShouldDisplayInAppLauncher(const Extension* extension,
content::BrowserContext* context) {
return CanDisplayInAppLauncher(extension, context);
}
bool CanDisplayInAppLauncher(const Extension* extension,
content::BrowserContext* context) {
return extension->ShouldDisplayInAppLauncher() &&
!IsBlockedByPolicy(extension, context);
}
bool ShouldDisplayInNewTabPage(const Extension* extension,
content::BrowserContext* context) {
return extension->ShouldDisplayInNewTabPage() &&
!IsBlockedByPolicy(extension, context);
}
base::string16 GetEnabledExtensionNameForUrl(const GURL& url,
content::BrowserContext* context) {
if (!url.SchemeIs(extensions::kExtensionScheme))
return base::string16();
extensions::ExtensionRegistry* extension_registry =
extensions::ExtensionRegistry::Get(context);
const extensions::Extension* extension =
extension_registry->enabled_extensions().GetByID(url.host());
return extension ? base::CollapseWhitespace(
base::UTF8ToUTF16(extension->name()), false)
: base::string16();
}
bool IsRenderedIconSufficientlyVisibleForBrowserContext(
const SkBitmap& bitmap,
content::BrowserContext* browser_context) {
Profile* const profile = Profile::FromBrowserContext(browser_context);
const ui::ThemeProvider& provider =
ThemeService::GetThemeProviderForProfile(profile);
return extensions::image_util::IsRenderedIconSufficientlyVisible(
bitmap, provider.GetColor(ThemeProperties::COLOR_TOOLBAR));
}
} // namespace ui_util
} // namespace extensions
|
Code-With-Aagam/competitive-programming | AtCoder/abc114/D.cpp | #pragma GCC optimize("O3")
#pragma GCC target("sse4")
#include <bits/stdc++.h>
using namespace std;
#define deb(x) cout << #x << " is " << x << "\n"
#define int long long
#define mod 1000000007
#define PI acos(-1)
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
template <typename T>
using max_heap = priority_queue<T>;
template <typename... T>
void read(T &... args) {
((cin >> args), ...);
}
template <typename... T>
void write(T &&... args) {
((cout << args), ...);
}
template <typename T>
void readContainer(T &t) {
for (auto &e : t) read(e);
}
template <typename T>
void writeContainer(T &t) {
for (const auto &e : t) write(e, " ");
write("\n");
}
int choose(int n, vector<int> &arr, int c) {
int ans = 0;
for (int x = 2; x <= n; x++) {
if (arr[x] + 1 >= c) ans++;
}
return ans;
}
void solve(int tc) {
// divisors of n!
// number of divisors having 75 divisors?
int n;
read(n);
vector<int> countOfPrimeFactors(n + 1, 0);
for (int i = 2; i <= n; i++) {
int curr = i;
for (int j = 2; j * j <= curr; j++) {
while (curr % j == 0) {
countOfPrimeFactors[j]++;
curr /= j;
}
}
if (curr > 1) {
countOfPrimeFactors[curr]++;
}
}
int answer = 0;
answer += ((choose(n, countOfPrimeFactors, 5) * (choose(n, countOfPrimeFactors, 5) - 1)) / 2 * (choose(n, countOfPrimeFactors, 3) - 2));
answer += (choose(n, countOfPrimeFactors, 75));
answer += (choose(n, countOfPrimeFactors, 25) * (choose(n, countOfPrimeFactors, 3) - 1));
answer += (choose(n, countOfPrimeFactors, 15) * (choose(n, countOfPrimeFactors, 5) - 1));
write(answer);
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int tc = 1;
// read(tc);
for (int curr = 1; curr <= tc; curr++) solve(curr);
return 0;
} |
iaddis/milkdrop2020 | src/script/mdp-eel2/script-yycontext.h | #pragma once
#include <stdint.h>
#include <string>
//#include "ns-eel.h"
#include "script-lextab.h"
#include "script-compiler.h"
#include "script-functype.h"
namespace Script { namespace mdpx {
typedef intptr_t INT_PTR;
#define YYSTYPE INT_PTR
struct lextab;
class CompileContext;
class Expression;
struct yycontext
{
CompileContext *compiler;
const lextab * yylextab;
int errVar;
std::string *errorMessage;
int colCount;
YYSTYPE result;
YYSTYPE yylval;
int yychar; /* the lookahead symbol */
int yynerrs; /* number of parse errors so far */
char *llsave[16]; /* Look ahead buffer */
char llbuf[100]; /* work buffer */
char *llp1;// = &llbuf[0]; /* pointer to next avail. in token */
char *llp2;// = &llbuf[0]; /* pointer to end of lookahead */
char *llend;// = &llbuf[0]; /* pointer to end of token */
char *llebuf;// = &llbuf[sizeof llbuf];
int lleof;
int yyline;// = 0;
};
INT_PTR nseel_lookup(yycontext *ctx, TokenType *typeOfObject);
#define INTCONST 1
#define DBLCONST 2
#define HEXCONST 3
#define VARIABLE 4
#define OTHER 5
YYSTYPE nseel_translate(yycontext *ctx, int type);
int nseel_yyerror(yycontext *ctx, const char *msg);
int nseel_yylex(yycontext *ctx, const char **exp);
int nseel_yyparse(yycontext *ctx, const char *exp);
void nseel_llinit(yycontext *ctx);
int nseel_gettoken(yycontext *ctx, char *lltb, int lltbsiz);
}} // namespace
|
praveennagaraj97/e-commerce-using-react-and-express | client/src/actions/index.js | <filename>client/src/actions/index.js
export {
// Login
loadLogin,
loginUser,
// signUp
loadSignUp,
signUpUser,
// accreditation
loadAccreditation,
userAccredited,
// LogoutUser
loadLogout,
// forgot password
loadForgotPassword,
loadResetPassword,
// User settings
loadUser,
getUser,
userPasswordUpdate,
} from "./userAuthActions";
export {
// Get all categories on website load
getAllCategories,
// Load products related to categories clicked
loadGetProductsOnQuery,
holdPreviousProductQuery,
getProductsOnQuery,
setLimitsPerPage,
setPageNumber,
noMoreResultsFound,
// cart
addItemToCart,
removeItemFromCart,
loadProductCart,
getProductsDetailsInCart,
setBackReachedLimit,
// View Products
loadViewProductDetail,
getProductDetail,
// Re Occuring request to avoid api over fetch!
reOccuringProductDetailRequests,
// Reviews
loadProductReview,
getProductReviews,
reviewFoundHelpful,
// Post reviews
loadNewProductReview,
// Sort
sortProductListASCE,
sortProductListDESC,
sortProductListFEATURED,
} from "./productsAction";
export {
globalFailureMessenger,
globalSuccesMessenger,
globalSuccesMessengerWithImg,
isLoading,
websiteLoad,
} from "./addon";
export { recentlyViewedItems } from "./home";
export {
productCategoryLoading,
productsLoading,
productReviewLoading,
authLoading,
checkoutLoading,
} from "./loaderAction";
export {
loadCheckout,
checkoutSuccess,
orderSuccess,
orderFailed,
} from "./payment";
|
shalomeir/generator-snippod-hackathon | grunt/tasks/wait.js | <reponame>shalomeir/generator-snippod-hackathon
// `grunt wait`
// Pause grunt execution of tasks to allow node server enough to time to restart
'use strict';
var taskConfig = function(grunt) {
grunt.registerTask('wait', 'Task that allows a set amount of time to wait for the server to reload', function() {
grunt.log.ok('Waiting for server...');
var done = this.async();
setTimeout(function() {
grunt.log.writeln('Done waiting!');
done();
}, 500);
});
};
module.exports = taskConfig;
|
anarancio/nifty-wallet | ui/app/rif/components/table/index.js | <filename>ui/app/rif/components/table/index.js
import GenericTable from './genericTable';
export {
GenericTable,
}
|
cdeitrick/isolate_parsers | dataio.py | <gh_stars>0
from pathlib import Path
from typing import Optional, Union, List
import io
import pandas
def _import_table_from_path(filename: Path, sheet_name: Optional[str] = None, index: Optional[str] = None) -> pandas.DataFrame:
""" Imports a file as a pandas.DataFrame. Infers filetype from the filename extension/suffix.
"""
if filename.suffix in {'.xls', '.xlsx'}:
data: pandas.DataFrame = pandas.read_excel(str(filename), sheet_name = sheet_name)
else:
sep = '\t' if filename.suffix in {'.tsv', '.tab'} else ','
data: pandas.DataFrame = pandas.read_table(str(filename), sep = sep)
if index and index in data.columns:
data = data.set_index(index)
return data
def _import_table_from_string(string: str, delimiter: Optional[str] = None, index: Optional[str] = None) -> pandas.DataFrame:
""" Imports a table represented as a basic string object."""
# Remove unwanted whitespace.
string = '\n'.join(i.strip() for i in string.split('\n') if i)
if not delimiter:
delimiter = '\t' if '\t' in string else ','
result = pandas.read_table(io.StringIO(string), sep = delimiter, index_col = False)
if index:
# Using `index_col` in `read_table()` doesn't work for some reason.
#result[index] = result[index].astype(str)
result.set_index(index, inplace = True)
return result
def import_table(input_table: Union[str, Path], sheet_name: Optional[str] = None, index:Optional[Union[str, List[str]]] = None) -> pandas.DataFrame:
if isinstance(input_table, Path):
data = _import_table_from_path(input_table, sheet_name, index)
else:
data = _import_table_from_string(input_table, index = index)
#data = data[sorted(data.columns, key = lambda s: str(s))]
return data
|
rafaelguzzozup/orange-talents-05-template-mercado-livre | src/main/java/br/com/zupacademy/guzzo/mercadolivre/controller/dto/DetalheOpiniaoDto.java | <gh_stars>0
package br.com.zupacademy.guzzo.mercadolivre.controller.dto;
public class DetalheOpiniaoDto {
private String titulo;
private String descricao;
public DetalheOpiniaoDto(String titulo, String descricao) {
this.titulo = titulo;
this.descricao = descricao;
}
public String getTitulo() {
return titulo;
}
public String getDescricao() {
return descricao;
}
}
|
Tenzorum/IPAS-mobile-portal | src/stores/ScannerStore.js | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
// @flow
import { Container } from 'unstated';
import transaction from '../util/transaction';
import { keccak, ethSign, brainWalletSign, decryptData } from '../util/native';
import { saveTx, loadAccountTxs } from '../util/db';
import { accountId } from '../util/account';``
import { NETWORK_TITLES, NETWORK_IDS } from '../constants';
import { type Account } from './AccountsStore';
type TXRequest = Object;
type SignedTX = {
txRequest: TXRequest,
sender: Account,
recipient: Account
};
type ScannerState = {
txRequest: TXRequest | null,
tx: Object,
sender: Account,
recipient: Account,
dataToSign: string,
signedData: string,
scanErrorMsg: string,
signedTxList: [SignedTX]
};
const defaultState = {
busy: false,
txRequest: null,
sender: null,
recipient: null,
tx: '',
dataToSign: '',
signedData: '',
scanErrorMsg: ''
};
export default class ScannerStore extends Container<ScannerState> {
state = defaultState;
async setTXRequest(txRequest, accountsStore) {
this.setBusy();
if (!(txRequest.data && txRequest.data.rlp && txRequest.data.account)) {
throw new Error(
`Scanned QR contains no valid transaction`
);
}
const tx = await transaction(txRequest.data.rlp);
const { chainId = '1' } = tx;
const sender = accountsStore.getById({
networkType: 'ethereum',
chainId,
address: txRequest.data.account
});
const networkTitle = NETWORK_TITLES[chainId];
if (!sender.encryptedSeed) {
throw new Error(
`No private key found for account ${
txRequest.data.account
} found in your signer key storage for the ${networkTitle} chain.`
);
}
const recipient = accountsStore.getById({
networkType: 'ethereum',
chainId: tx.chainId,
address: tx.action
});
const dataToSign = await keccak(txRequest.data.rlp);
this.setState({
sender,
recipient,
txRequest,
tx,
dataToSign
});
return true;
}
async signData(pin = '1') {
const sender = this.state.sender;
const seed = await decryptData(sender.encryptedSeed, pin);
const signedData = await brainWalletSign(seed, this.state.dataToSign);
this.setState({ signedData });
await saveTx({
hash: this.state.dataToSign,
tx: this.state.tx,
sender: this.state.sender,
recipient: this.state.recipient,
signature: signedData,
createdAt: new Date().getTime()
});
}
setBusy() {
this.setState({
busy: true
});
}
setReady() {
this.setState({
busy: false
});
}
isBusy() {
return this.state.busy;
}
cleanup() {
this.setState(defaultState);
}
getSender() {
return this.state.sender;
}
getRecipient() {
return this.state.recipient;
}
getTXRequest() {
return this.state.txRequest;
}
getTx() {
return this.state.tx;
}
getDataToSign() {
return this.state.dataToSign;
}
getSignedTxData() {
return this.state.signedData;
}
setErrorMsg(scanErrorMsg) {
this.setState({ scanErrorMsg });
}
getErrorMsg() {
return this.state.scanErrorMsg;
}
}
|
CardinPatson/Car_Location | backend/database/migrations/20220408161929-create-orders.js | "use strict";
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable("orders", {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
car_id: {
allowNull: false,
type: Sequelize.INTEGER
// references: {
// model: "cars",
// key: "id"
// }
},
user_id: {
allowNull: false,
type: Sequelize.INTEGER
// references: {
// model: "users",
// key: "id"
// }
},
date_order: {
allowNull: false,
type: Sequelize.DATE,
defaultValue: Sequelize.literal("CURRENT_TIMESTAMP")
},
departure_date: {
allowNull: false,
type: Sequelize.DATE
},
return_date: {
allowNull: false,
type: Sequelize.DATE
},
total_price: {
allowNull: false,
type: Sequelize.REAL
}
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable("orders");
}
};
|
tudouxian/process-cloud | process-center/src/main/java/com/workflow/process/center/service/WorkFlowModelInfoService.java | package com.workflow.process.center.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.workflow.process.center.domain.entity.WorkFlowModelInfo;
/**
* (WorkFlowModelInfo)表服务接口
*
* @author 土豆仙
* @since 2021-06-26 22:25:20
*/
public interface WorkFlowModelInfoService extends IService<WorkFlowModelInfo> {
void insertOrUpdate(WorkFlowModelInfo workFlowModelInfo);
}
|
cedricga91/framework | arcane/extras/NumericalModel/src/Mesh/Interpolator/Implementation/GaussInterpolatorService.h | <gh_stars>10-100
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
#ifndef ARCGEOSIM_INTERPOLATOR_INTERPOLATOR_GAUSSINTERPOLATORSERVICE_H
#define ARCGEOSIM_INTERPOLATOR_INTERPOLATOR_GAUSSINTERPOLATORSERVICE_H
/* Author : dipietrd at Thu May 29 14:06:52 2008
* Generated by createNew
*/
#include <arcane/MeshVariableRef.h>
#include <arcane/VariableTypedef.h>
#include "Mesh/Geometry/IGeometryMng.h"
#include "Mesh/Interpolator/IInterpolator.h"
#include "GaussInterpolator_axl.h"
#include "Appli/IAppServiceMng.h"
using namespace Arcane;
class GaussInterpolatorService : public ArcaneGaussInterpolatorObject
{
public:
/**! @name Constructors and destructors
*/
//@{
GaussInterpolatorService(const ServiceBuildInfo& sbi) :
ArcaneGaussInterpolatorObject(sbi) {}
//@}
/**! @name Typedefs
*/
//@{
//! Source field type
typedef VariableFaceReal SourceType;
//! Target field type
typedef VariableCellReal3 TargetType;
//@}
/**! @name Setters and getters
*/
//@{
//! Return cell geometrical properties
inline Integer getCellGeometricProperties() {
return IGeometryProperty::PCenter | IGeometryProperty::PMeasure;
}
//! Reture face geometrical properties
inline Integer getFaceGeometricProperties() {
return IGeometryProperty::PCenter | IGeometryProperty::PMeasure | IGeometryProperty::PNormal;
}
//! Set source field
void setSourceField(const MeshVariableRef* source);
//! Set target field
void setTargetField(MeshVariableRef* target);
//@}
/**! @name Members
*/
//@{
//! Initialize the service
void init();
//! Prepare the service
void prepare();
//! Perform interpolation
void interpolate();
//@}
private:
IAppServiceMng* m_app_service_mng;
const SourceType* m_source;
TargetType* m_target;
};
#endif /* ARCGEOSIM_INTERPOLATOR_INTERPOLATOR_GAUSSINTERPOLATORSERVICE_H */
|
yuhonghong66/menoh | menoh/mkldnn/operator.hpp | #ifndef MENOH_MKLDNN_OPERATOR_HPP
#define MENOH_MKLDNN_OPERATOR_HPP
#include <menoh/mkldnn/operator/add.hpp>
#include <menoh/mkldnn/operator/batch_norm.hpp>
#include <menoh/mkldnn/operator/concat.hpp>
#include <menoh/mkldnn/operator/conv.hpp>
#include <menoh/mkldnn/operator/conv_transpose.hpp>
#include <menoh/mkldnn/operator/eltwise.hpp>
#include <menoh/mkldnn/operator/fc.hpp>
#include <menoh/mkldnn/operator/gemm.hpp>
#include <menoh/mkldnn/operator/lrn.hpp>
#include <menoh/mkldnn/operator/pool.hpp>
#include <menoh/mkldnn/operator/softmax.hpp>
#include <menoh/mkldnn/operator/sum.hpp>
#endif // MENOH_MKLDNN_OPERATOR_HPP
|
ismo-karkkainen/datalackey | src/InputChannel.cpp | <reponame>ismo-karkkainen/datalackey
//
// InputChannel.cpp
// datalackey
//
// Created by <NAME> on 10.5.17.
// Copyright © 2017 <NAME>. All rights reserved.
//
// Licensed under Universal Permissive License. See License.txt.
#include "InputChannel.hpp"
InputChannel::~InputChannel() { }
|
FlyerMaxwell/Bubble | common/errors.h | #ifndef ERRORS_H
#define ERRORS_H
#define NO_STORAGE_SPACE_ERROR 1;
#define NULL_STORAGE_OR_PKG_ERROR 2;
#endif
|
hocktide/v-c-agentd | src/authservice/auth_service_proc.c | <filename>src/authservice/auth_service_proc.c
/**
* \file authservice/auth_service_proc.c
*
* \brief Spawn the authservice process.
*
* \copyright 2019 Velo Payments, Inc. All rights reserved.
*/
#include <agentd/authservice.h>
#include <agentd/bootstrap_config.h>
#include <agentd/config.h>
#include <agentd/fds.h>
#include <agentd/ipc.h>
#include <agentd/privsep.h>
#include <agentd/status_codes.h>
#include <cbmc/model_assert.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <vpr/parameters.h>
/**
* \brief Spawn an auth service process using the provided config structure and
* logger socket.
*
* On success, this method sets the file descriptor pointer to the file
* descriptor for the auth service socket. This can be used by the caller to
* send requests to the auth service and to receive responses from this service.
* Also, the pointer to the pid for this process is set. This can be used to
* signal and wait when this process should be terminated.
*
* \param bconf The bootstrap configuration for this service.
* \param conf The configuration for this service.
* \param logsock Pointer to the socket used to communicate with the
* logger.
* \param authsock Pointer to the auth service socket, to be updated on
* successful completion of this function.
* \param authpid Pointer to the auth service pid, to be updated on the
* successful completion of this function.
* \param runsecure Set to false if we are not being run in secure mode.
*
* \returns a status code indicating success or failure.
* - AGENTD_STATUS_SUCCESS on success.
* - AGENTD_ERROR_AUTHSERVICE_PROC_RUNSECURE_ROOT_USER_REQUIRED if spawning
* this process failed because the user is not root and runsecure is
* true.
* - AGENTD_ERROR_AUTHSERVICE_IPC_SOCKETPAIR_FAILURE if creating a
* socketpair for the dataservice process failed.
* - AGENTD_ERROR_AUTHSERVICE_FORK_FAILURE if forking the private process
* failed.
* - AGENTD_ERROR_AUTHSERVICE_PRIVSEP_LOOKUP_USERGROUP_FAILURE if there was
* a failure looking up the configured user and group for the dataservice
* process.
* - AGENTD_ERROR_AUTHSERVICE_PRIVSEP_CHROOT_FAILURE if chrooting failed.
* - AGENTD_ERROR_AUTHSERVICE_PRIVSEP_DROP_PRIVILEGES_FAILURE if dropping
* privileges failed.
* - AGENTD_ERROR_AUTHSERVICE_PRIVSEP_SETFDS_FAILURE if setting file
* descriptors failed.
* - AGENTD_ERROR_AUTHSERVICE_PRIVSEP_EXEC_PRIVATE_FAILURE if executing the
* private command failed.
* - AGENTD_ERROR_AUTHSERVICE_PRIVSEP_EXEC_SURVIVAL_WEIRDNESS if the
* process survived execution (weird!).
*/
int auth_service_proc(
const bootstrap_config_t* bconf, const agent_config_t* conf, int* logsock,
int* authsock, pid_t* authpid, bool runsecure)
{
int retval = 1;
int serversock = -1;
bool keep_authsock = false;
uid_t uid;
gid_t gid;
/* parameter sanity checks. */
MODEL_ASSERT(NULL != bconf);
MODEL_ASSERT(NULL != conf);
MODEL_ASSERT(NULL != datasock);
MODEL_ASSERT(NULL != datapid);
/* sentinel value for auth socket. */
*authsock = -1;
/* verify that this process is running as root. */
if (runsecure && 0 != geteuid())
{
fprintf(stderr, "agentd must be run as root.\n");
retval = AGENTD_ERROR_AUTHSERVICE_PROC_RUNSECURE_ROOT_USER_REQUIRED;
goto done;
}
/* create a socketpair for communication. */
retval = ipc_socketpair(AF_UNIX, SOCK_STREAM, 0, authsock, &serversock);
if (0 != retval)
{
perror("ipc_socketpair");
retval = AGENTD_ERROR_AUTHSERVICE_IPC_SOCKETPAIR_FAILURE;
goto done;
}
/* fork the process into parent and child. */
*authpid = fork();
if (*authpid < 0)
{
perror("fork");
retval = AGENTD_ERROR_AUTHSERVICE_FORK_FAILURE;
goto done;
}
/* child */
if (0 == *authpid)
{
/* close the parent's end of the socket pair. */
close(*authsock);
*authsock = -1;
/* do secure operations if requested. */
if (runsecure)
{
/* get the user and group IDs. */
retval =
privsep_lookup_usergroup(
conf->usergroup->user, conf->usergroup->group, &uid, &gid);
if (0 != retval)
{
perror("privsep_lookup_usergroup");
retval =
AGENTD_ERROR_AUTHSERVICE_PRIVSEP_LOOKUP_USERGROUP_FAILURE;
goto done;
}
/* change into the prefix directory. */
retval = privsep_chroot(bconf->prefix_dir);
if (0 != retval)
{
perror("privsep_chroot");
retval = AGENTD_ERROR_AUTHSERVICE_PRIVSEP_CHROOT_FAILURE;
goto done;
}
/* set the user ID and group ID. */
retval = privsep_drop_privileges(uid, gid);
if (0 != retval)
{
perror("privsep_drop_privileges");
retval =
AGENTD_ERROR_AUTHSERVICE_PRIVSEP_DROP_PRIVILEGES_FAILURE;
goto done;
}
}
/* move the fds out of the way. */
if (AGENTD_STATUS_SUCCESS !=
privsep_protect_descriptors(&serversock, logsock, NULL))
{
retval = AGENTD_ERROR_AUTHSERVICE_PRIVSEP_SETFDS_FAILURE;
goto done;
}
/* close standard file descriptors */
retval = privsep_close_standard_fds();
if (0 != retval)
{
perror("privsep_close_standard_fds");
retval = AGENTD_ERROR_AUTHSERVICE_PRIVSEP_SETFDS_FAILURE;
goto done;
}
/* close standard file descriptors and set fds. */
retval =
privsep_setfds(
serversock, /* ==> */ AGENTD_FD_AUTHSERVICE_SOCK,
*logsock, /* ==> */ AGENTD_FD_AUTHSERVICE_LOG,
-1);
if (0 != retval)
{
perror("privsep_setfds");
retval = AGENTD_ERROR_AUTHSERVICE_PRIVSEP_SETFDS_FAILURE;
goto done;
}
/* close any socket above the given value. */
retval =
privsep_close_other_fds(AGENTD_FD_AUTHSERVICE_LOG);
if (0 != retval)
{
perror("privsep_close_other_fds");
retval = AGENTD_ERROR_AUTHSERVICE_PRIVSEP_CLOSE_OTHER_FDS;
goto done;
}
/* spawn the child process (this does not return if successful). */
if (runsecure)
{
retval = privsep_exec_private(bconf, "authservice");
}
else
{
/* if running in non-secure mode, then we expect the caller to have
* already set the path and library path accordingly. */
retval = execlp("agentd", "agentd", "-P", "authservice", NULL);
}
/* check the exec status. */
if (AGENTD_STATUS_SUCCESS != retval)
{
perror("privsep_exec_private");
retval = AGENTD_ERROR_AUTHSERVICE_PRIVSEP_EXEC_PRIVATE_FAILURE;
goto done;
}
/* we'll never get here. */
retval = AGENTD_ERROR_AUTHSERVICE_PRIVSEP_EXEC_SURVIVAL_WEIRDNESS;
goto done;
}
/* parent */
else
{
/* close the child's end of the socket pair. */
close(serversock);
close(*logsock);
*logsock = -1;
serversock = -1;
/* let the cleanup logic know that we want to preserve authsock. */
keep_authsock = true;
/* success. */
retval = AGENTD_STATUS_SUCCESS;
goto done;
}
done:
/* clean up server socket. */
if (serversock >= 0)
{
close(serversock);
}
/* clean up data socket. */
if (!keep_authsock && *authsock >= 0)
{
close(*authsock);
}
return retval;
}
|
Frcsty/DocDex | discord/src/main/java/me/piggypiglet/docdex/bot/embed/pagination/PaginationManager.java | package me.piggypiglet.docdex.bot.embed.pagination;
import com.google.inject.Singleton;
import me.piggypiglet.docdex.bot.embed.pagination.objects.Pagination;
import me.piggypiglet.docdex.bot.emote.EmoteWrapper;
import me.piggypiglet.docdex.bot.utils.PermissionUtils;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.MessageReaction;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.exceptions.PermissionException;
import net.jodah.expiringmap.ExpirationPolicy;
import net.jodah.expiringmap.ExpiringMap;
import org.jetbrains.annotations.NotNull;
import java.util.Map;
import java.util.concurrent.TimeUnit;
// ------------------------------
// Copyright (c) PiggyPiglet 2020
// https://www.piggypiglet.me
// ------------------------------
@Singleton
public final class PaginationManager {
private final Map<String, Pagination> paginatedMessages = ExpiringMap.builder()
.expiration(15, TimeUnit.MINUTES)
.expirationPolicy(ExpirationPolicy.ACCESSED)
.build();
@NotNull
public Map<String, Pagination> getPaginatedMessages() {
return paginatedMessages;
}
public void addPaginatedMessage(@NotNull final String id, @NotNull final Pagination pagination) {
paginatedMessages.put(id, pagination);
}
public void process(@NotNull final Message message, @NotNull final User user,
@NotNull final MessageReaction reaction) {
final Pagination pagination = paginatedMessages.get(message.getId());
if (pagination == null) {
return;
}
final boolean isNotAuthor = !user.getId().equals(pagination.getAuthor());
if (message.isFromGuild() || isNotAuthor) {
try {
reaction.removeReaction(user).queue(success -> {}, failure -> {});
} catch (PermissionException exception) {
PermissionUtils.sendPermissionError(message, exception.getPermission());
}
}
if (isNotAuthor) {
return;
}
final MessageReaction.ReactionEmote reactionEmote = reaction.getReactionEmote();
final EmoteWrapper emote;
if (reactionEmote.isEmote()) {
emote = EmoteWrapper.from(reactionEmote.getEmote());
} else {
if (reactionEmote.getEmoji().equals(Pagination.TRASH.getUnicode())) {
paginatedMessages.remove(message.getId());
message.delete().queue();
return;
}
emote = EmoteWrapper.from(reactionEmote.getEmoji());
}
final MessageEmbed requestedPage = pagination.getPages().get(emote);
if (requestedPage == null) {
return;
}
message.editMessage(requestedPage).queue(success -> {}, failure -> message.getChannel().sendMessage("Something went wrong oof").queue());
}
}
|
cswarth/whylogs | src/whylogs/util/data.py | """
Utility functions for interacting with data
"""
from collections import OrderedDict
def getter(x, k: str, *args):
"""
get an attribute (from an object) or key (from a dict-like object)
`getter(x, k)` raise KeyError if `k` not present
`getter(x, k, default)` return default if `k` not present
This is a convenience function that allows you to interact the same with
an object or a dictionary
Parameters
----------
x : object, dict
Item to get attribute from
k : str
Key or attribute name
default : optional
Default value if `k` not present
Returns
-------
val : object
Associated value
"""
try:
try:
# assume x is dict-like
val = x[k]
except TypeError:
# x is not dict-like, try to get an attribute
try:
val = getattr(x, k)
except AttributeError:
# Attribute not present
raise KeyError
except KeyError as e:
if len(args) > 0:
return args[0]
else:
raise (e)
return val
def remap(x, mapping: dict):
"""
Flatten a nested dictionary/object according to a specified name mapping.
Parameters
----------
x : object, dict
An object or dict which can be treated as a nested dictionary, where
attributes can be accessed as:
`attr = x.a.b['key_name']['other_Name'].d`
Indexing list values is not implemented, e.g.:
`x.a.b[3].d['key_name']`
mapping : dict
Nested dictionary specifying the mapping. ONLY values specified in the
mapping will be returned.
For example:
.. code-block:: python
{'a': {
'b': {
'c': 'new_name'
}
}
could flatten `x.a.b.c` or `x.a['b']['c']` to `x['new_name']`
Returns
-------
flat : OrderedDict
A flattened ordered dictionary of values
"""
out = OrderedDict()
_remap(x, mapping, out)
return out
def _remap(x, mapping: dict, y: dict):
for k, mapper in mapping.items():
try:
val = getter(x, k)
except KeyError:
continue
if isinstance(mapper, dict):
# Gotta keep walking the tree
_remap(val, mapper, y)
else:
# We have found a variable we are going to re-name!
y[mapper] = val
def get_valid_filename(s):
"""
Return the given string converted to a string that can be used for a clean
filename. Remove leading and trailing spaces; convert other spaces to
underscores; and remove anything that is not an alphanumeric, dash,
underscore, or dot.
.. code-block:: python
>>> from whylogs.util.data import get_valid_filename
>>> get_valid_filename(" Background of tim's 8/1/2019 party!.jpg ")
"""
import re
s = str(s).strip().replace(" ", "_")
s = s.replace("/", "-")
return re.sub(r"(?u)[^-\w.]", "", s)
|
LJW123/YiLianMall | YiLian/src/main/java/com/yilian/mall/entity/SnatchPartEntity.java | package com.yilian.mall.entity;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
/**
* Created by Administrator on 2016/4/6.
* 夺宝详情进行中
*/
public class SnatchPartEntity extends BaseEntity {
@SerializedName("status")//进行状态 1进行中 2已揭晓
public String status;
@SerializedName("activity")//单个商品详细数据
public Act activity;
@SerializedName("log")
public ArrayList<Record> log0;
public class Act {
@SerializedName("activity_id")//活动id
public String activityId;
@SerializedName("activity_name")//活动名
public String activityName;
@SerializedName("activity_time")
public String activityTime;
@SerializedName("activity_expend")
public String activity_expend;
@SerializedName("goods_name")//商品名字
public String goodsName;
@SerializedName("goods_album")//商品相册地址
public ArrayList<String> goodsAlbum;
@SerializedName("goods_introduce")//商品介绍图集
public ArrayList goodsIntroduce;
@SerializedName("goods_id")
public String goodsId;
@SerializedName("total_count")
public int totalCount;
@SerializedName("join_count")
public int joinCount;
}
public class Record {
@SerializedName("join_time")//参与时间
public String joinTime;
@SerializedName("photo")//头像
public String photo;
@SerializedName("phone")//用户手机号
public String phone;
}
}
|
nowoh/kopo33_source_backup | kopo33/src/hw0322_Mon_ch5/P09_1.java | <reponame>nowoh/kopo33_source_backup
package hw0322_Mon_ch5;
import java.util.Scanner;
public class P09_1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (true) {
P09course.printMenu();
int Mnum = scan.nextInt();
switch (Mnum) {
case 1 :
P09course.printCourseList();
int Cnum = scan.nextInt();
P09course.getCourse(Cnum);
case 2 :
}
}
}
}
|
cvent/octopus-deploy-api-client | octopus_deploy_swagger_client/models/community_action_template_resource.py | <filename>octopus_deploy_swagger_client/models/community_action_template_resource.py
# coding: utf-8
"""
Octopus Server API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2019.6.7+Branch.tags-2019.6.7.Sha.aa18dc6809953218c66f57eff7d26481d9b23d6a
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from octopus_deploy_swagger_client.models.action_template_parameter_resource import ActionTemplateParameterResource # noqa: F401,E501
from octopus_deploy_swagger_client.models.property_value_resource import PropertyValueResource # noqa: F401,E501
class CommunityActionTemplateResource(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'id': 'str',
'type': 'str',
'name': 'str',
'author': 'str',
'description': 'str',
'version': 'int',
'website': 'str',
'history_url': 'str',
'properties': 'dict(str, PropertyValueResource)',
'parameters': 'list[ActionTemplateParameterResource]',
'links': 'dict(str, str)'
}
attribute_map = {
'id': 'Id',
'type': 'Type',
'name': 'Name',
'author': 'Author',
'description': 'Description',
'version': 'Version',
'website': 'Website',
'history_url': 'HistoryUrl',
'properties': 'Properties',
'parameters': 'Parameters',
'links': 'Links'
}
def __init__(self, id=None, type=None, name=None, author=None, description=None, version=None, website=None, history_url=None, properties=None, parameters=None, links=None): # noqa: E501
"""CommunityActionTemplateResource - a model defined in Swagger""" # noqa: E501
self._id = None
self._type = None
self._name = None
self._author = None
self._description = None
self._version = None
self._website = None
self._history_url = None
self._properties = None
self._parameters = None
self._links = None
self.discriminator = None
if id is not None:
self.id = id
if type is not None:
self.type = type
if name is not None:
self.name = name
if author is not None:
self.author = author
if description is not None:
self.description = description
if version is not None:
self.version = version
if website is not None:
self.website = website
if history_url is not None:
self.history_url = history_url
if properties is not None:
self.properties = properties
if parameters is not None:
self.parameters = parameters
if links is not None:
self.links = links
@property
def id(self):
"""Gets the id of this CommunityActionTemplateResource. # noqa: E501
:return: The id of this CommunityActionTemplateResource. # noqa: E501
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this CommunityActionTemplateResource.
:param id: The id of this CommunityActionTemplateResource. # noqa: E501
:type: str
"""
self._id = id
@property
def type(self):
"""Gets the type of this CommunityActionTemplateResource. # noqa: E501
:return: The type of this CommunityActionTemplateResource. # noqa: E501
:rtype: str
"""
return self._type
@type.setter
def type(self, type):
"""Sets the type of this CommunityActionTemplateResource.
:param type: The type of this CommunityActionTemplateResource. # noqa: E501
:type: str
"""
self._type = type
@property
def name(self):
"""Gets the name of this CommunityActionTemplateResource. # noqa: E501
:return: The name of this CommunityActionTemplateResource. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this CommunityActionTemplateResource.
:param name: The name of this CommunityActionTemplateResource. # noqa: E501
:type: str
"""
self._name = name
@property
def author(self):
"""Gets the author of this CommunityActionTemplateResource. # noqa: E501
:return: The author of this CommunityActionTemplateResource. # noqa: E501
:rtype: str
"""
return self._author
@author.setter
def author(self, author):
"""Sets the author of this CommunityActionTemplateResource.
:param author: The author of this CommunityActionTemplateResource. # noqa: E501
:type: str
"""
self._author = author
@property
def description(self):
"""Gets the description of this CommunityActionTemplateResource. # noqa: E501
:return: The description of this CommunityActionTemplateResource. # noqa: E501
:rtype: str
"""
return self._description
@description.setter
def description(self, description):
"""Sets the description of this CommunityActionTemplateResource.
:param description: The description of this CommunityActionTemplateResource. # noqa: E501
:type: str
"""
self._description = description
@property
def version(self):
"""Gets the version of this CommunityActionTemplateResource. # noqa: E501
:return: The version of this CommunityActionTemplateResource. # noqa: E501
:rtype: int
"""
return self._version
@version.setter
def version(self, version):
"""Sets the version of this CommunityActionTemplateResource.
:param version: The version of this CommunityActionTemplateResource. # noqa: E501
:type: int
"""
self._version = version
@property
def website(self):
"""Gets the website of this CommunityActionTemplateResource. # noqa: E501
:return: The website of this CommunityActionTemplateResource. # noqa: E501
:rtype: str
"""
return self._website
@website.setter
def website(self, website):
"""Sets the website of this CommunityActionTemplateResource.
:param website: The website of this CommunityActionTemplateResource. # noqa: E501
:type: str
"""
self._website = website
@property
def history_url(self):
"""Gets the history_url of this CommunityActionTemplateResource. # noqa: E501
:return: The history_url of this CommunityActionTemplateResource. # noqa: E501
:rtype: str
"""
return self._history_url
@history_url.setter
def history_url(self, history_url):
"""Sets the history_url of this CommunityActionTemplateResource.
:param history_url: The history_url of this CommunityActionTemplateResource. # noqa: E501
:type: str
"""
self._history_url = history_url
@property
def properties(self):
"""Gets the properties of this CommunityActionTemplateResource. # noqa: E501
:return: The properties of this CommunityActionTemplateResource. # noqa: E501
:rtype: dict(str, PropertyValueResource)
"""
return self._properties
@properties.setter
def properties(self, properties):
"""Sets the properties of this CommunityActionTemplateResource.
:param properties: The properties of this CommunityActionTemplateResource. # noqa: E501
:type: dict(str, PropertyValueResource)
"""
self._properties = properties
@property
def parameters(self):
"""Gets the parameters of this CommunityActionTemplateResource. # noqa: E501
:return: The parameters of this CommunityActionTemplateResource. # noqa: E501
:rtype: list[ActionTemplateParameterResource]
"""
return self._parameters
@parameters.setter
def parameters(self, parameters):
"""Sets the parameters of this CommunityActionTemplateResource.
:param parameters: The parameters of this CommunityActionTemplateResource. # noqa: E501
:type: list[ActionTemplateParameterResource]
"""
self._parameters = parameters
@property
def links(self):
"""Gets the links of this CommunityActionTemplateResource. # noqa: E501
:return: The links of this CommunityActionTemplateResource. # noqa: E501
:rtype: dict(str, str)
"""
return self._links
@links.setter
def links(self, links):
"""Sets the links of this CommunityActionTemplateResource.
:param links: The links of this CommunityActionTemplateResource. # noqa: E501
:type: dict(str, str)
"""
self._links = links
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(CommunityActionTemplateResource, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, CommunityActionTemplateResource):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
n11-TalentHub-Java-Bootcamp/second-homework-aydinsercan | src/main/java/com/sercanaydin/springboot/dao/KategoriDao.java | package com.sercanaydin.springboot.dao;
import com.sercanaydin.springboot.entity.Kategori;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface KategoriDao extends JpaRepository<Kategori, Long> {
List<Kategori> findAllByUstKategoriIsNullOrderByAdiDesc();
List<Kategori> findAllByAdiEndsWith(String adi);
} |
Raphaenn/Freelance1 | Mobile/src/components/carrosel/index.js | <reponame>Raphaenn/Freelance1
import React from "react";
import Paralax from "./paralax";
import { Container } from "./styles";
export default function Carrosel() {
return (
<Container>
<Paralax />
</Container>
)
}
|
simbatech/incubator-drill | exec/java-exec/src/main/java/org/apache/drill/exec/physical/base/Sender.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.physical.base;
import java.util.List;
import org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* A sender is one half of an exchange node operations. It is responsible for subdividing/cloning and sending a local
* record set to a set of destination locations. This is typically only utilized at the level of the execution plan.
*/
public interface Sender extends FragmentRoot {
/**
* Get the list of destination endpoints that this Sender will be communicating with.
* @return List of DrillbitEndpoints.
*/
public abstract List<DrillbitEndpoint> getDestinations();
/**
* Get the receiver major fragment id that is opposite this sender.
* @return
*/
@JsonProperty("receiver-major-fragment")
public int getOppositeMajorFragmentId();
}
|
lihop/Eldritch | Code/Libraries/Workbench/src/PEs/wbpesaturate.h | <reponame>lihop/Eldritch<gh_stars>1-10
#ifndef WBPESATURATE_H
#define WBPESATURATE_H
#include "wbpeunaryop.h"
class WBPESaturate : public WBPEUnaryOp
{
public:
WBPESaturate();
virtual ~WBPESaturate();
DEFINE_WBPE_FACTORY( Saturate );
virtual void Evaluate( const WBParamEvaluator::SPEContext& Context, WBParamEvaluator::SEvaluatedParam& EvaluatedParam ) const;
};
#endif // WBPESATURATE_H
|
benamrou/controlRoom | controlRoom_server/server/node_modules/apiconnect-wsdl/lib/extraXSD.js | <reponame>benamrou/controlRoom
/** ******************************************************* {COPYRIGHT-TOP} ***
* Licensed Materials - Property of IBM
* 5725-Z22, 5725-Z63, 5725-U33, 5725-Z63
*
* (C) Copyright IBM Corporation 2016, 2020
*
* All Rights Reserved.
* US Government Users Restricted Rights - Use, duplication or disclosure
* restricted by GSA ADP Schedule Contract with IBM Corp.
********************************************************** {COPYRIGHT-END} **/
'use strict';
const u = require('../lib/utils.js');
const parse = require('../lib/parse.js');
const generateSwagger = require('../lib/generateSwagger.js');
const parseUtils = require('../lib/parseUtils.js');
const fileUtils = require('../lib/fileUtils.js');
const JSZip = require('jszip');
const postParse = require('../lib/postParse.js');
const copts = require('../lib/createOptions.js');
const q = require('q');
const yauzl = require('yauzl');
const path = require('path');
// var g = require('strong-globalize')();
const g = require('../lib/strong-globalize-fake.js');
/**
* Get the Swagger for additional xsd schema.
* @method getDefinitionsForXSD
* @param {String} filename - xsd file
* @param {Object} auth - auth info for accessing xsd file
* @param {String[]} rootElementList - if set only process the rootElements in the list (and referencedDefs)
* @param {Object} createOperationDesc
* @return {Object} swagger.definitions
**/
async function getDefinitionsForXSD(filename, auth, rootElementList, options) {
rootElementList = u.makeSureItsAnArray(rootElementList);
let createOptions = copts.create({
fromGetDefinitionsForXSD: true,
rootElementList: rootElementList
}, options);
let serviceName = 'TEMPLATE';
let wsdlId = 'TEMPLATE';
let req = createOptions.req;
// Creates a temporary wsdl file containing xsd:imports for each
// of the schemas
let out = await createTemporaryWSDL(filename, auth, req);
let outZip = await JSZip.loadAsync(out.archive.content);
outZip.file('TEMPLATE.wsdl', out.wsdlContent);
let content = await outZip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
let allWSDLs = await parse.getJsonForWSDL(content, null, createOptions);
// Get the WSDLEntry for the serviceName
var wsdlEntry = parse.findWSDLForServiceName(allWSDLs, serviceName);
// Get the swagger for the service. This will be the template service with
// a definition section that contains our extra xsd definitions.
let swagger = generateSwagger.getSwaggerForService(wsdlEntry, serviceName, wsdlId, createOptions);
return swagger.definitions;
}
async function createTemporaryWSDL(filename, auth, req) {
// The template wsdl is "just enough" wsdl to make a swagger document.
let templateWSDL = path.resolve(__dirname, '../src/template.wsdl');
let serviceName = 'TEMPLATE';
let data = await getTargetNamespacesForXSD(filename, auth, req);
let out = await fileUtils.asContent(templateWSDL, templateWSDL, null, null, req);
// wsdlContent is the template wsdl content
// Add xsd:imports for each of the files in the fileEntryList
let wsdlContent = out.content.replace(/{SERVICE}/gi, serviceName);
var stmts = '';
for (var j = 0; j < data.files.length; j++) {
let fileEntry = data.files[j];
var stmt = '<xsd:import namespace="{TNS}" schemaLocation="{FILENAME}" {XMLNS} />\n';
stmt = stmt.replace(/{FILENAME}/gi, fileEntry.filename);
stmt = stmt.replace(/{TNS}/gi, fileEntry.targetNamespace);
var xmlns = '';
if (fileEntry.prefix) {
xmlns = 'xmlns:' + fileEntry.prefix + '="' + fileEntry.targetNamespace + '"';
}
stmt = stmt.replace(/{XMLNS}/gi, xmlns);
stmts += stmt;
}
wsdlContent = wsdlContent.replace(/{IMPORTS}/gi, stmts);
return { wsdlContent: wsdlContent, archive: data.archive };
}
/**
* Get the targetnamespaces for the indicated file
* @method getTargetNamespacesForXSD
* @param {String} filename - file name
* @param {Object} auth - authorization information
* @param {Promise} promise containing fileEntry (with targetNamespace and prefix) and new archive
*/
async function getTargetNamespacesForXSD(filename, auth, req) {
var files = [];
let out = await fileUtils.asContent(filename, filename, auth, null, req);
let archive = await fileUtils.asRawArchive(out.content, req);
function shouldIgnore(fileName, mode, req) {
// Return true to ignore the file (silently)
// Throw an error if invalid file.
if (fileUtils.isSymbolicLink(mode)) {
throw g.http(u.r(req)).Error('A file for a symbolic link was encountered in the zip. Remove the file %s.', fileName);
}
if (fileUtils.isMACOSX(fileName) || fileUtils.isDirectory(fileName)) {
return true; // silently ignore
}
if (fileUtils.isXSD(fileName) || fileUtils.isWSDL(fileName)) {
return false; // Don't ignore, process this file
}
throw g.http(u.r(req)).Error('Only .xsd and .wsdl files are allowed in the zip. Remove the file %s.', fileName);
}
function processFile(fileName, content, req) {
let shortName = fileName;
let index = fileUtils.lastPathSeparator(fileName);
if (index != -1) {
shortName = shortName.substr(index + 1);
}
var file = {
filename: shortName,
fullName: fileName,
type: 'xsd', // temp for now determined later when we actually parse it
content: content,
context: 'zip'
};
parseUtils.contentToXMLorWSDL(file, { req: req });
if (file.json.definitions) {
// This is WSDL, skip it.
} else if (file.json.schema) {
// Get namespaces
files.push(file);
file.namespaces = {};
if (file.json.schema['undefined'] && file.json.schema['undefined'].targetNamespace) {
file.targetNamespace = file.json.schema['undefined'].targetNamespace;
file.prefix = u.getPrefixForNamespace(file.targetNamespace,
file.json.schema.xmlns);
}
return {
fileName: fileName
};
} else {
// Ignore other files
}
return null;
}
out = await fileUtils.pipeArchive(archive, req, shouldIgnore, processFile);
// Collect any localized errors from the file processing, and reject if any found
let messages = [];
for (let i = 0; i < out.files.length; i++) {
if (out.files[i].error) {
messages.push(out.files[i].fileName + ': ' + out.files[i].error.message);
}
}
if (messages.length > 0) {
throw new Error(messages.join('\n'));
}
return { files: files, archive: out.archive };
}
exports.createTemporaryWSDL = createTemporaryWSDL;
exports.getDefinitionsForXSD = getDefinitionsForXSD;
|
NifTK/NifTK | MITK/Modules/DnDDisplay/Testing/niftkItkSignalCollector.cxx | <filename>MITK/Modules/DnDDisplay/Testing/niftkItkSignalCollector.cxx<gh_stars>10-100
/*=============================================================================
NifTK: A software platform for medical image computing.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include "niftkItkSignalCollector.h"
#include <mitkSliceNavigationController.h>
#include <mitkFocusManager.h>
#include <algorithm>
namespace niftk
{
//-----------------------------------------------------------------------------
ItkSignalCollector::ItkSignalCollector()
: itk::Command()
{
}
//-----------------------------------------------------------------------------
ItkSignalCollector::~ItkSignalCollector()
{
ObserverMap::iterator observerTagIt = m_ObserverTags.begin();
ObserverMap::iterator observerTagEnd = m_ObserverTags.end();
for ( ; observerTagIt != observerTagEnd; ++observerTagIt)
{
itk::Object* object = observerTagIt->first;
unsigned long observerTag = observerTagIt->second;
object->RemoveObserver(observerTag);
}
this->Clear();
}
//-----------------------------------------------------------------------------
void ItkSignalCollector::Connect(itk::Object* object, const itk::EventObject& event)
{
unsigned long observerTag = object->AddObserver(event, this);
m_ObserverTags.insert(ObserverMap::value_type(object, observerTag));
}
//-----------------------------------------------------------------------------
void ItkSignalCollector::AddListener(ItkSignalListener* listener)
{
std::vector<ItkSignalListener*>::iterator it = std::find(m_Listeners.begin(), m_Listeners.end(), listener);
if (it == m_Listeners.end())
{
m_Listeners.push_back(listener);
}
}
//-----------------------------------------------------------------------------
void ItkSignalCollector::RemoveListener(ItkSignalListener* listener)
{
std::vector<ItkSignalListener*>::iterator it = std::find(m_Listeners.begin(), m_Listeners.end(), listener);
if (it != m_Listeners.end())
{
m_Listeners.erase(it);
}
}
//-----------------------------------------------------------------------------
void ItkSignalCollector::Execute(itk::Object* caller, const itk::EventObject& event)
{
this->ProcessEvent(caller, event);
}
//-----------------------------------------------------------------------------
void ItkSignalCollector::Execute(const itk::Object* caller, const itk::EventObject& event)
{
this->ProcessEvent(caller, event);
}
//-----------------------------------------------------------------------------
void ItkSignalCollector::ProcessEvent(const itk::Object* caller, const itk::EventObject& event)
{
/// Create a copy of the event as a newly allocated object.
m_Signals.push_back(Signal(caller, event.MakeObject()));
std::vector<ItkSignalListener*>::iterator it = m_Listeners.begin();
std::vector<ItkSignalListener*>::iterator listenersEnd = m_Listeners.end();
for ( ; it != listenersEnd; ++it)
{
(*it)->OnItkSignalReceived(caller, event);
}
}
//-----------------------------------------------------------------------------
const ItkSignalCollector::Signals& ItkSignalCollector::GetSignals() const
{
return m_Signals;
}
//-----------------------------------------------------------------------------
ItkSignalCollector::Signals ItkSignalCollector::GetSignals(const itk::EventObject& event) const
{
return this->GetSignals(0, event);
}
//-----------------------------------------------------------------------------
ItkSignalCollector::Signals ItkSignalCollector::GetSignals(const itk::Object* object, const itk::EventObject& event) const
{
Signals selectedSignals;
Signals::const_iterator it = m_Signals.begin();
Signals::const_iterator signalsEnd = m_Signals.end();
for ( ; it != signalsEnd; ++it)
{
Signal itkSignal = *it;
if ((object == 0 || object == itkSignal.first)
&& event.CheckEvent(itkSignal.second))
{
selectedSignals.push_back(itkSignal);
}
}
return selectedSignals;
}
//-----------------------------------------------------------------------------
void ItkSignalCollector::Clear()
{
/// Destruct the copies of the original events.
Signals::iterator it = m_Signals.begin();
Signals::iterator signalsEnd = m_Signals.end();
for ( ; it != signalsEnd; ++it)
{
delete it->second;
}
/// Remove the elements.
m_Signals.clear();
}
//-----------------------------------------------------------------------------
void ItkSignalCollector::PrintSelf(std::ostream & os, itk::Indent indent) const
{
Signals::const_iterator it = m_Signals.begin();
Signals::const_iterator signalsEnd = m_Signals.end();
int i = 0;
for ( ; it != signalsEnd; ++it, ++i)
{
os << indent << i << ": " << ((void*) it->first) << ": " << it->second->GetEventName() << std::endl;
}
}
}
|
chogba6/ONE | compiler/locomotiv/src/Node/DepthwiseFilterEncode.test.cpp | <gh_stars>100-1000
/*
* Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "NodeExecution.h"
#include "locomotiv/NodeData.h"
#include "NodeDataImpl.h"
#include "NodeDomain.h"
#include <loco/IR/PermutingCodec.h>
#include <nncc/core/ADT/tensor/Shape.h>
#include <nncc/core/ADT/tensor/Buffer.h>
#include <nncc/core/ADT/tensor/LexicalLayout.h>
#include <nncc/core/ADT/tensor/IndexEnumerator.h>
#include <gtest/gtest.h>
using nncc::core::ADT::tensor::Index;
using nncc::core::ADT::tensor::Shape;
using nncc::core::ADT::tensor::LexicalLayout;
using nncc::core::ADT::tensor::make_buffer;
using nncc::core::ADT::tensor::IndexEnumerator;
TEST(NodeExecution_DepthwiseFilterEncode, f32)
{
const uint32_t H = 2;
const uint32_t W = 3;
const uint32_t C = 4;
const uint32_t M = 5;
auto g = loco::make_graph();
// Pull
auto pull = g->nodes()->create<loco::Pull>();
pull->dtype(loco::DataType::FLOAT32);
// Make and assign "MHWC" data to pull node
auto pull_buf = make_buffer<float, LexicalLayout>(Shape{M, H, W, C});
float f = 1;
for (IndexEnumerator e{pull_buf.shape()}; e.valid(); e.advance())
{
pull_buf.at(e.current()) = f;
f += 0.1f; // Doesn't matter what it is
}
auto pull_data = locomotiv::make_data(pull_buf);
locomotiv::annot_data(pull, std::move(pull_data));
locomotiv::annot_domain(pull, loco::Domain::Tensor);
// Encoder to correctly read input tensor as MHWC
auto encoder = std::unique_ptr<loco::PermutingEncoder<loco::Domain::DepthwiseFilter>>(
new loco::PermutingEncoder<loco::Domain::DepthwiseFilter>);
encoder->perm()->axis(loco::DepthwiseFilterAxis::Multiplier) = 0;
encoder->perm()->axis(loco::DepthwiseFilterAxis::Height) = 1;
encoder->perm()->axis(loco::DepthwiseFilterAxis::Width) = 2;
encoder->perm()->axis(loco::DepthwiseFilterAxis::Depth) = 3;
// DepthwiseFilterEncode
auto enc = g->nodes()->create<loco::DepthwiseFilterEncode>();
enc->input(pull);
enc->encoder(std::move(encoder));
locomotiv::NodeExecution::get().run(enc);
auto enc_data = locomotiv::annot_data(enc);
ASSERT_NE(enc_data, nullptr);
ASSERT_EQ(loco::DataType::FLOAT32, enc_data->dtype());
ASSERT_EQ((Shape{H, W, C, M}), *(enc_data->shape())); // locomotiv depthwise filter is HWCM
auto enc_buf = enc_data->as_f32_bufptr();
for (uint32_t h = 0; h < H; ++h)
for (uint32_t w = 0; w < W; ++w)
for (uint32_t c = 0; c < C; ++c)
for (uint32_t m = 0; m < M; ++m)
ASSERT_FLOAT_EQ(enc_buf->at(Index{h, w, c, m}), pull_buf.at(Index{m, h, w, c}));
ASSERT_EQ(loco::Domain::DepthwiseFilter, locomotiv::annot_domain(enc));
}
|
antmicro/OpenFPGA | openfpga/src/fpga_sdc/sdc_memory_utils.cpp | /********************************************************************
* Most utilized function used to constrain memory cells in FPGA
* fabric using SDC commands
*******************************************************************/
/* Headers from vtrutil library */
#include "vtr_assert.h"
#include "vtr_log.h"
/* Headers from openfpgautil library */
#include "openfpga_wildcard_string.h"
#include "openfpga_digest.h"
#include "openfpga_naming.h"
#include "sdc_writer_utils.h"
#include "sdc_memory_utils.h"
/* begin namespace openfpga */
namespace openfpga {
/********************************************************************
* Print SDC commands to disable outputs of all the configurable memory modules
* in a given module
* This function will be executed in a recursive way,
* using a Depth-First Search (DFS) strategy
* It will iterate over all the configurable children under each module
* and print a SDC command to disable its outputs
*
* Note:
* - When flatten_names is true
* this function will not apply any wildcard to names
* - When flatten_names is false
* It will straightforwardly output the instance name and port name
* This function will try to apply wildcard to names
* so that SDC file size can be minimal
*******************************************************************/
void rec_print_pnr_sdc_disable_configurable_memory_module_output(std::fstream& fp,
const bool& flatten_names,
const ModuleManager& module_manager,
const ModuleId& parent_module,
const std::string& parent_module_path) {
/* Build wildcard names for the instance names of multiple-instanced-blocks (MIB)
* We will find all the instance names and see there are common prefix
* If so, we can use wildcards
*/
std::map<ModuleId, std::vector<std::string>> wildcard_names;
/* For each configurable child, we will go one level down in priority */
for (size_t child_index = 0; child_index < module_manager.configurable_children(parent_module).size(); ++child_index) {
std::string child_module_path = parent_module_path;
ModuleId child_module_id = module_manager.configurable_children(parent_module)[child_index];
size_t child_instance_id = module_manager.configurable_child_instances(parent_module)[child_index];
std::string child_instance_name;
if (true == module_manager.instance_name(parent_module, child_module_id, child_instance_id).empty()) {
child_instance_name = generate_instance_name(module_manager.module_name(child_module_id), child_instance_id);
} else {
child_instance_name = module_manager.instance_name(parent_module, child_module_id, child_instance_id);
}
if (false == flatten_names) {
/* Try to adapt to a wildcard name: replace all the numbers with a wildcard character '*' */
WildCardString wildcard_str(child_instance_name);
/* If the wildcard name is already in the list, we can skip this
* Otherwise, we have to
* - output this instance
* - record the wildcard name in the map
*/
if ( (0 < wildcard_names.count(child_module_id))
&& (wildcard_names.at(child_module_id).end() != std::find(wildcard_names.at(child_module_id).begin(),
wildcard_names.at(child_module_id).end(),
wildcard_str.data())) ) {
continue;
}
child_module_path += wildcard_str.data();
wildcard_names[child_module_id].push_back(wildcard_str.data());
} else {
child_module_path += child_instance_name;
}
child_module_path = format_dir_path(child_module_path);
rec_print_pnr_sdc_disable_configurable_memory_module_output(fp, flatten_names,
module_manager,
child_module_id,
child_module_path);
}
/* If there is no configurable children any more, this is a leaf module, print a SDC command for disable timing */
if (0 < module_manager.configurable_children(parent_module).size()) {
return;
}
/* Validate file stream */
valid_file_stream(fp);
/* Disable timing for each output port of this module */
for (const BasicPort& output_port : module_manager.module_ports_by_type(parent_module, ModuleManager::MODULE_OUTPUT_PORT)) {
fp << "set_disable_timing ";
fp << parent_module_path << output_port.get_name();
fp << std::endl;
}
}
} /* end namespace openfpga */
|
mrkahfi/stradetegy | src/Jariff/SuperAdminBundle/Resources/public/js/grid-inbound.js | <reponame>mrkahfi/stradetegy
$(document).ready(function () {
function filter(dataIndx, value) {
$grid.pqGrid("filter", {
data: [{ dataIndx: dataIndx, value: value}]
});
}
var obj = {
width :1080,
height :400,
title : "Inbound",
flexHeight :false,
flexWidth :false,
filterModel: { on: true, mode: "AND", header:true },
};
obj.colModel = [
{ title: "Id", width: 10, dataIndx:"id" },
{ title : "Show", editable : false, width : 10, sortable : false, render : function (ui) {
var id = ui.rowData.id;
var url = Routing.generate('admin_inbound_show', { "id": id });
return "<a class='ajax' href='" + url + "'><img class='view' src='/bundles/jariffproject/admin/img/icons/stuttgart-icon-pack/16x16/zoom.png' /></a>";
}},
{ title: "Source", width: 100, dataIndx:"i.source", filter: {
type : 'textbox', condition : 'contain', listeners : [{ change: function (evt, ui) {
filter("i.source", $(this).val());
}}]
}},
{ title: "Email", width: 100, dataIndx:"m.email", filter: {
type : 'textbox', condition : 'contain', listeners : [{ change: function (evt, ui) {
filter("m.email", $(this).val());
}}]
}},
{ title: "Phone", width: 100, dataIndx:"i.phone", filter: {
type : 'textbox', condition : 'contain', listeners : [{ change: function (evt, ui) {
filter("i.phone", $(this).val());
}}]
}},
{ title: "Business", width: 100, dataIndx:"i.business" },
{ title: "Date Create", width: 100, dataIndx:"i.dateCreate" },
{ title: "Date Finish", width: 100, dataIndx:"i.dateFinish" },
{ title: "Date Update", width: 100, dataIndx:"i.dateUpdate" },
{ title: "Description", width: 100, dataIndx:"i.description" },
{ title: "Flag", width: 100, dataIndx:"i.flag" },
{ title: "Ip Address", width: 100, dataIndx:"i.ipAddress" },
{ title: "Lead", width: 100, dataIndx:"i.lead" },
{ title: "Queue", width: 100, dataIndx:"i.queue" },
{ title: "Time Lapsed", width: 100, dataIndx:"i.timeLapsed" },
{ title: "Visited Page", width: 500, dataIndx:"i.visitedPage" },
];
obj.dataModel = {
location : "remote",
sorting : "remote",
paging : "remote",
method : "GET",
curPage : 1,
rPP : 20,
sortIndx : ["i.id"],
sortDir : ["down"],
rPPOptions : [20, 50, 100],
url : Routing.generate('admin_inbound_json_index'),
getData : function (dataJSON) {
return { curPage: dataJSON.curPage, totalRecords: dataJSON.totalRecords, data: dataJSON.data };
}
};
obj.refresh = function () {
};
var $grid = $("#grid_paging").pqGrid(obj);
}); |
ckeiner/Test-Bddy | src/main/java/com/xceptance/testbddy/core/bdd/steps/Step.java | package com.xceptance.testbddy.core.bdd.steps;
import com.aventstack.extentreports.GherkinKeyword;
/**
* Describes a BDD Step without test data. <br>
* To execute it, see the {@link #test()} method.
*
* @author ckeiner
*/
public class Step extends AbstractStep<Runnable>
{
/**
* Creates a Step with the specified keyword, description and behavior.
*
* @param keyword
* The {@link GherkinKeyword} of the step.
* @param description
* A String describing what this step does.
* @param behavior
* A Runnable containing the behavior.
* @see AbstractStep#AbstractStep(GherkinKeyword, String, Object)
* @see GherkinKeyword
*/
public Step(GherkinKeyword keyword, String description, Runnable behavior)
{
super(keyword, description, behavior);
}
/**
* Runs the Runnable.
*/
@Override
protected void executeStep()
{
getBehavior().run();
}
}
|
From-pErfo/FastLogin | core/src/main/java/com/github/games647/fastlogin/core/shared/ForceLoginManagement.java | <filename>core/src/main/java/com/github/games647/fastlogin/core/shared/ForceLoginManagement.java<gh_stars>1-10
/*
* SPDX-License-Identifier: MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2015-2022 games647 and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.games647.fastlogin.core.shared;
import com.github.games647.fastlogin.core.storage.SQLStorage;
import com.github.games647.fastlogin.core.StoredProfile;
import com.github.games647.fastlogin.core.hooks.AuthPlugin;
import com.github.games647.fastlogin.core.shared.event.FastLoginAutoLoginEvent;
public abstract class ForceLoginManagement<P extends C, C, L extends LoginSession, T extends PlatformPlugin<C>>
implements Runnable {
protected final FastLoginCore<P, C, T> core;
protected final P player;
protected final L session;
public ForceLoginManagement(FastLoginCore<P, C, T> core, P player, L session) {
this.core = core;
this.player = player;
this.session = session;
}
@Override
public void run() {
if (!isOnline(player)) {
core.getPlugin().getLog().info("Player {} disconnected", player);
return;
}
if (session == null) {
core.getPlugin().getLog().info("No valid session found for {}", player);
return;
}
SQLStorage storage = core.getStorage();
StoredProfile playerProfile = session.getProfile();
try {
if (isOnlineMode()) {
//premium player
AuthPlugin<P> authPlugin = core.getAuthPluginHook();
if (authPlugin == null) {
//maybe only bungeecord plugin
onForceActionSuccess(session);
} else {
boolean success = true;
String playerName = getName(player);
if (core.getConfig().get("autoLogin", true)) {
if (session.needsRegistration()
|| (core.getConfig().get("auto-register-unknown", false)
&& !authPlugin.isRegistered(playerName))) {
success = forceRegister(player);
} else if (!callFastLoginAutoLoginEvent(session, playerProfile).isCancelled()) {
success = forceLogin(player);
}
}
if (success) {
//update only on success to prevent corrupt data
if (playerProfile != null) {
playerProfile.setId(session.getUuid());
playerProfile.setPremium(true);
storage.save(playerProfile);
}
onForceActionSuccess(session);
}
}
} else if (playerProfile != null) {
//cracked player
playerProfile.setId(null);
playerProfile.setPremium(false);
storage.save(playerProfile);
}
} catch (Exception ex) {
core.getPlugin().getLog().warn("ERROR ON FORCE LOGIN of {}", getName(player), ex);
}
}
public boolean forceRegister(P player) {
core.getPlugin().getLog().info("Register player {}", getName(player));
String generatedPassword = core.getPasswordGenerator().getRandomPassword(player);
boolean success = core.getAuthPluginHook().forceRegister(player, generatedPassword);
String message = core.getMessage("auto-register");
if (success && message != null) {
message = message.replace("%password", generatedPassword);
core.getPlugin().sendMessage(player, message);
}
return success;
}
public boolean forceLogin(P player) {
core.getPlugin().getLog().info("Logging player {} in", getName(player));
boolean success = core.getAuthPluginHook().forceLogin(player);
if (success) {
core.sendLocaleMessage("auto-login", player);
}
return success;
}
public abstract FastLoginAutoLoginEvent callFastLoginAutoLoginEvent(LoginSession session, StoredProfile profile);
public abstract void onForceActionSuccess(LoginSession session);
public abstract String getName(P player);
public abstract boolean isOnline(P player);
public abstract boolean isOnlineMode();
}
|
ekhidbor/FUMe | src/fume/vrs/ob.cpp | <gh_stars>0
/**
* This file is a part of the FUMe project.
*
* To the extent possible under law, the person who associated CC0 with
* FUMe has waived all copyright and related or neighboring rights
* to FUMe.
*
* You should have received a copy of the CC0 legalcode along with this
* work. If not, see http://creativecommons.org/publicdomain/zero/1.0/.
*/
// std
#include <limits>
// local public
#include "diction.h"
// local private
#include "fume/vr_data_parser.h"
#include "fume/source_callback_io.h"
#include "fume/get_value_function_sink.h"
#include "fume/encapsulated_value_impl.h"
#include "fume/memory_stream.h"
#include "fume/vrs/ob.h"
using std::numeric_limits;
using std::unique_ptr;
using fume::write_data_from_function;
namespace fume
{
namespace vrs
{
typedef encapsulated_value_impl<memory_stream> encapsulated_value_t;
ob::ob()
: value_representation( 1u, 1u, 1u ),
m_stream( new encapsulated_value_t() )
{
}
ob::ob( const ob& rhs )
: value_representation( 1u, 1u, 1u ),
m_stream( rhs.m_stream->clone() )
{
}
ob::~ob()
{
}
MC_STATUS ob::to_stream( tx_stream& stream, TRANSFER_SYNTAX syntax )
{
return m_stream->write_vr_data_to_stream( stream, syntax );
}
MC_STATUS ob::from_stream( rx_stream& stream, TRANSFER_SYNTAX syntax )
{
unique_ptr<encapsulated_value> tmp( new encapsulated_value_t() );
MC_STATUS ret = read_vr_data( stream, syntax, *tmp );
if( ret == MC_NORMAL_COMPLETION )
{
m_stream.swap( tmp );
}
else
{
// Leave value unchanged and return error
}
return ret;
}
MC_STATUS ob::set( const set_func_parms& val )
{
unique_ptr<encapsulated_value> tmp( new encapsulated_value_t() );
MC_STATUS ret = write_data_from_function( val, *tmp );
if( ret == MC_NORMAL_COMPLETION )
{
m_stream.swap( tmp );
}
else
{
// Leave value unchanged and return error
}
return ret;
}
MC_STATUS ob::set_null()
{
return m_stream->clear();
}
MC_STATUS ob::set_encapsulated( const set_func_parms& val )
{
MC_STATUS ret = m_stream->clear();
if( ret == MC_NORMAL_COMPLETION )
{
uint32_t dummy_table = 0;
ret = m_stream->provide_offset_table( &dummy_table,
0,
EXPLICIT_LITTLE_ENDIAN );
if( ret == MC_NORMAL_COMPLETION )
{
ret = set_next_encapsulated( val );
}
else
{
// Return error
}
}
else
{
// Return error
}
return ret;
}
MC_STATUS ob::set_next_encapsulated( const set_func_parms& val )
{
// HACK: we don't have the frame size yet and don't want to read
// the entire frame into memory. When we call end_of_sequence
// it will clean up the size values
MC_STATUS ret = m_stream->start_of_frame( 0u, EXPLICIT_LITTLE_ENDIAN );
if( ret == MC_NORMAL_COMPLETION )
{
ret = write_data_from_function( val, *m_stream );
}
else
{
// Return error
}
return ret;
}
MC_STATUS ob::close_encapsulated()
{
return m_stream->end_of_sequence( EXPLICIT_LITTLE_ENDIAN );
}
MC_STATUS ob::get( const get_func_parms& val )
{
MC_STATUS ret = MC_CANNOT_COMPLY;
if( val.callback != nullptr )
{
get_value_function_sink dest( val, false );
// encapsulated values are always written in explicit little endian
ret = m_stream->write_data_to_stream( dest, EXPLICIT_LITTLE_ENDIAN );
}
else
{
ret = MC_NULL_POINTER_PARM;
}
return ret;
}
MC_STATUS ob::get_encapsulated( const get_func_parms& val )
{
MC_STATUS ret = MC_CANNOT_COMPLY;
if( val.callback != nullptr )
{
get_value_function_sink dest( val, false );
ret = m_stream->write_first_frame_to_stream( dest,
EXPLICIT_LITTLE_ENDIAN );
}
else
{
ret = MC_NULL_POINTER_PARM;
}
return ret;
}
MC_STATUS ob::get_next_encapsulated( const get_func_parms& val )
{
MC_STATUS ret = MC_CANNOT_COMPLY;
if( val.callback != nullptr )
{
get_value_function_sink dest( val, false );
ret = m_stream->write_next_frame_to_stream( dest,
EXPLICIT_LITTLE_ENDIAN );
}
else
{
ret = MC_NULL_POINTER_PARM;
}
return ret;
}
MC_STATUS ob::get_frame( unsigned int idx, const get_func_parms& val )
{
MC_STATUS ret = MC_CANNOT_COMPLY;
if( val.callback != nullptr )
{
get_value_function_sink dest( val, false );
ret = m_stream->write_frame_to_stream( idx,
dest,
EXPLICIT_LITTLE_ENDIAN );
}
else
{
ret = MC_NULL_POINTER_PARM;
}
return ret;
}
bool ob::is_null() const
{
return m_stream->size() == 0;
}
unique_ptr<value_representation> ob::clone() const
{
return unique_ptr<value_representation>( new ob( *this ) );
}
} // namespace vrs
} // namespace fume
|
duo-dinamico/ServiceReports | api/routes/api.router.js | <gh_stars>0
const apiRouter = require("express").Router();
const {methodNotAllowed} = require("../errors");
const clientsRouter = require("./clients.router");
const usersRouter = require("./users.router");
const departmentsRouter = require("./departments.router");
const machinesRouter = require("./machines.router");
const servicesRouter = require("./services.router");
apiRouter.use("/users", usersRouter);
apiRouter.use("/clients", clientsRouter);
apiRouter.use("/departments", departmentsRouter);
apiRouter.use("/machines", machinesRouter);
apiRouter.use("/services", servicesRouter);
apiRouter.route("/").all(methodNotAllowed);
module.exports = apiRouter;
|
SNL-GMS/GMS-PI7-OPEN | gms-common/java/gms/core/data-acquisition/css30-loader/css-reader/src/test/java/gms/dataacquisition/css/converters/flatfilereaders/WfdiscRecordTest.java | <reponame>SNL-GMS/GMS-PI7-OPEN
package gms.dataacquisition.css.converters.flatfilereaders;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import gms.dataacquisition.cssreader.data.WfdiscRecord;
import gms.dataacquisition.cssreader.data.WfdiscRecord32;
import gms.dataacquisition.cssreader.flatfilereaders.FlatFileWfdiscReader;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
/**
* Tests WfdiscRecord, which is a class that both represents and parses CSS 3.0 WfdiscRecord files.
*/
public class WfdiscRecordTest {
private WfdiscRecord32 wfdisc;
private double comparisonDelta = 0.000001;
@Before
public void setup() {
wfdisc = new WfdiscRecord32();
}
// tests on 'sta'
@Test(expected = Exception.class)
public void testSetNullSta() {
wfdisc.setSta(null);
wfdisc.validate();
}
////////////////////////////////////////////////////////////////////////
// tests on 'chan'
@Test(expected = Exception.class)
public void testSetNullChan() {
wfdisc.setChan(null);
wfdisc.validate();
}
////////////////////////////////////////////////////////////////////////
// tests on 'time'
@Test(expected = Exception.class)
public void testSetNullTime() {
wfdisc.setTime(null);
wfdisc.validate();
}
@Test(expected = Exception.class)
public void testSetTimeWithBadString() {
wfdisc.setTime("not a number");
}
@Test
public void testSetTime() {
wfdisc.setTime("1274317219.75"); // epoch seconds with millis, just as in flatfilereaders files
assertNotNull(wfdisc.getTime());
Instant expected = Instant.ofEpochMilli((long) (1274317219.75 * 1000L));
assertEquals(wfdisc.getTime(), expected);
}
////////////////////////////////////////////////////////////////////////
// tests on 'wfid'
@Test(expected = Exception.class)
public void testSetWfIdNull() {
wfdisc.setWfid(null);
}
@Test(expected = Exception.class)
public void testSetWfIdBad() {
wfdisc.setWfid("not a number");
}
@Test
public void testSetWfId() {
wfdisc.setWfid("12345");
assertEquals(wfdisc.getWfid(), 12345);
}
////////////////////////////////////////////////////////////////////////
// tests on 'chanid'
@Test(expected = Exception.class)
public void testSetChanIdNull() {
wfdisc.setChanid(null);
}
@Test(expected = Exception.class)
public void testSetChanIdBad() {
wfdisc.setChanid("not a number");
}
@Test
public void testSetChanId() {
wfdisc.setChanid("12345");
assertEquals(wfdisc.getChanid(), 12345);
}
////////////////////////////////////////////////////////////////////////
// tests on 'jdate'
@Test(expected = Exception.class)
public void testSetJdateNull() {
wfdisc.setJdate(null);
}
@Test(expected = Exception.class)
public void testSetJdateBad() {
wfdisc.setJdate("not a number");
}
@Test(expected = Exception.class)
public void testSetJdateTooLow() {
wfdisc.setJdate("1500001"); // ah, the first day of 1500 AD. What a glorious time to be alive.
wfdisc.validate();
}
@Test(expected = Exception.class)
public void testSetJdateTooHigh() {
wfdisc.setJdate("2900001"); // If this code is still running in 2900 AD, that's impressive.
wfdisc.validate();
}
@Test
public void testSetJdate() {
wfdisc.setJdate("2012123");
assertEquals(wfdisc.getJdate(), 2012123);
}
////////////////////////////////////////////////////////////////////////
// tests on 'endtime'
@Test(expected = Exception.class)
public void testSetNullEndtime() {
wfdisc.setEndtime(null);
}
@Test(expected = Exception.class)
public void testSetEndtimeWithBadString() {
wfdisc.setEndtime("not a number");
}
@Test
public void testSetEndtime() {
wfdisc.setEndtime("1274317219.75"); // epoch seconds with millis, just as in wfdiscreaders files
assertNotNull(wfdisc.getEndtime());
Instant expected = Instant.ofEpochMilli((long) (1274317219.75 * 1000L));
assertEquals(wfdisc.getEndtime(), expected);
}
////////////////////////////////////////////////////////////////////////
// tests on 'nsamp'
@Test(expected = Exception.class)
public void testSetNsampNull() {
wfdisc.setNsamp(null);
}
@Test(expected = Exception.class)
public void testSetNsampBad() {
wfdisc.setNsamp("not a number");
}
@Test(expected = Exception.class)
public void testSetNsampNegative() {
wfdisc.setNsamp("-123");
wfdisc.validate();
}
@Test
public void testSetNsamp() {
wfdisc.setNsamp("5000");
assertEquals(wfdisc.getNsamp(), 5000);
}
////////////////////////////////////////////////////////////////////////
// tests on 'samprate'
@Test(expected = Exception.class)
public void testSetSamprateNull() {
wfdisc.setSamprate(null);
}
@Test(expected = Exception.class)
public void testSetSamprateBad() {
wfdisc.setSamprate("not a number");
}
@Test(expected = Exception.class)
public void testSetSamprateNegative() {
wfdisc.setSamprate("-123");
wfdisc.validate();
}
@Test
public void testSetSamprate() {
wfdisc.setSamprate("40.0");
assertEquals(wfdisc.getSamprate(), 40.0, 0.0);
}
////////////////////////////////////////////////////////////////////////
// tests on 'calib'
@Test(expected = Exception.class)
public void testSetCalibNull() {
wfdisc.setCalib(null);
}
@Test(expected = Exception.class)
public void testSetCalibBad() {
wfdisc.setCalib("not a number");
}
@Test(expected = Exception.class)
public void testSetCalibNegative() {
wfdisc.setCalib("-123");
wfdisc.validate();
}
@Test
public void testSetCalib() {
wfdisc.setCalib("1.0");
assertEquals(wfdisc.getCalib(), 1.0, 0.0);
}
////////////////////////////////////////////////////////////////////////
// tests on 'calper'
@Test(expected = Exception.class)
public void testSetCalperNull() {
wfdisc.setCalper(null);
}
@Test(expected = Exception.class)
public void testSetCalperNegative() {
wfdisc.setCalper("-123");
wfdisc.validate();
}
@Test(expected = Exception.class)
public void testSetCalperBad() {
wfdisc.setCalper("not a number");
}
@Test
public void testSetCalper() {
wfdisc.setCalper("1.0");
assertEquals(wfdisc.getCalper(), 1.0, 0.0);
}
////////////////////////////////////////////////////////////////////////
// tests on 'instype'
@Test(expected = Exception.class)
public void testSetNullInstype() {
wfdisc.setInstype(null);
wfdisc.validate();
}
////////////////////////////////////////////////////////////////////////
// tests on 'segtype'
@Test(expected = Exception.class)
public void testSetSegtypeNull() {
wfdisc.setSegtype(null);
wfdisc.validate();
}
@Test(expected = Exception.class)
public void testSetSegtypeBad() {
wfdisc.setSegtype("not a valid segtype");
wfdisc.validate();
}
@Test
public void testSetSegtype() {
String seg = "o";
wfdisc.setSegtype(seg);
assertEquals(wfdisc.getSegtype(), seg);
}
////////////////////////////////////////////////////////////////////////
// tests on 'datatype'
@Test(expected = Exception.class)
public void testSetDatatypeNull() {
wfdisc.setDatatype(null);
wfdisc.validate();
}
@Test
public void testSetDatatype() {
String dt = "s4";
wfdisc.setDatatype(dt); // format code from CSS 3.0
assertEquals(wfdisc.getDatatype(), dt);
}
////////////////////////////////////////////////////////////////////////
// tests on 'clip'
@Test
public void testSetClip() {
wfdisc.setClip("-");
assertFalse(wfdisc.getClip());
wfdisc.setClip("some random string that isn't just 'c'");
assertFalse(wfdisc.getClip());
wfdisc.setClip("c");
assertTrue(wfdisc.getClip());
}
////////////////////////////////////////////////////////////////////////
// tests on 'dir'
@Test(expected = Exception.class)
public void testSetNullDir() {
wfdisc.setDir(null);
wfdisc.validate();
}
////////////////////////////////////////////////////////////////////////
// tests on 'dfile'
@Test(expected = Exception.class)
public void testSetNullDfile() {
wfdisc.setDfile(null);
wfdisc.validate();
}
////////////////////////////////////////////////////////////////////////
// tests on 'foff'
@Test(expected = Exception.class)
public void testSetFoffNull() {
wfdisc.setFoff(null);
}
@Test(expected = Exception.class)
public void testSetFoffBad() {
wfdisc.setFoff("not a number");
}
@Test(expected = Exception.class)
public void testSetFoffNegative() {
wfdisc.setFoff("-123");
wfdisc.validate();
}
@Test
public void testSetFoff() {
wfdisc.setFoff("12345");
assertEquals(wfdisc.getFoff(), 12345);
}
////////////////////////////////////////////////////////////////////////
// tests on 'commid'
@Test(expected = Exception.class)
public void testSetCommidNull() {
wfdisc.setCommid(null);
}
@Test(expected = Exception.class)
public void testSetCommidBad() {
wfdisc.setCommid("not a number");
}
@Test
public void testSetCommid() {
wfdisc.setCommid("12345");
assertEquals(wfdisc.getCommid(), 12345);
}
////////////////////////////////////////////////////////////////////////
// tests on 'lddate'
@Test(expected = Exception.class)
public void testSetNullLddate() {
wfdisc.setLddate(null);
wfdisc.validate();
}
// TODO: if ldddate gets read into a Date or something in the future,
// add a test verifying this works.
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// tests reading flatfilereaders against known values
@Test
public void testWfdiscReadAll() throws Exception {
FlatFileWfdiscReader reader = new FlatFileWfdiscReader();
List<WfdiscRecord> wfdiscs = reader.read("src/test/resources/css/WFS4/wfdisc_gms_s4.txt");
assertEquals(wfdiscs.size(), 76);
WfdiscRecord wfdisc = wfdiscs.get(1);
assertEquals(wfdisc.getSta(), "DAVOX");
assertEquals(wfdisc.getChan(), "HHE");
assertEquals(wfdisc.getTime(), Instant.ofEpochMilli(1274317199108l));
assertEquals(wfdisc.getWfid(), 64583325);
assertEquals(wfdisc.getChanid(), 4248);
assertEquals(wfdisc.getJdate(), 2010140);
assertEquals(wfdisc.getEndtime(), Instant.ofEpochMilli(1274317201991l));
assertEquals(wfdisc.getNsamp(), 347);
assertEquals(wfdisc.getSamprate(), 119.98617, this.comparisonDelta);
assertEquals(wfdisc.getCalib(), 0.253, this.comparisonDelta);
assertEquals(wfdisc.getCalper(), 1, this.comparisonDelta);
assertEquals(wfdisc.getInstype(), "STS-2");
assertEquals(wfdisc.getSegtype().toString(), "o");
assertEquals(wfdisc.getDatatype(), "s4");
assertEquals(wfdisc.getClip(), false);
assertEquals(wfdisc.getDir(), "src/test/resources/css/WFS4/");
assertEquals(wfdisc.getDfile(), "DAVOX0.w");
assertEquals(wfdisc.getFoff(), 63840);
assertEquals(wfdisc.getCommid(), -1);
assertEquals(wfdisc.getLddate(), "08-APR-15");
}
@Test
public void testWfdiscReadFilter() throws Exception {
ArrayList<String> stations = new ArrayList<>(1);
stations.add("MLR");
ArrayList<String> channels = new ArrayList<>(1);
channels.add("BHZ");
FlatFileWfdiscReader reader = new FlatFileWfdiscReader(stations, channels, null, null);
List<WfdiscRecord> wfdiscs = reader.read("src/test/resources/css/WFS4/wfdisc_gms_s4.txt");
assertEquals(wfdiscs.size(), 3);
WfdiscRecord wfdisc = wfdiscs.get(1);
assertEquals(wfdisc.getSta(), "MLR");
assertEquals(wfdisc.getChan(), "BHZ");
assertEquals(wfdisc.getTime(), Instant.ofEpochMilli(1274317190019l));
assertEquals(wfdisc.getWfid(), 64587196);
assertEquals(wfdisc.getChanid(), 4162);
assertEquals(wfdisc.getJdate(), 2010140);
assertEquals(wfdisc.getEndtime(), Instant.ofEpochMilli(1274317209994l));
assertEquals(wfdisc.getNsamp(), 800);
assertEquals(wfdisc.getSamprate(), 40, this.comparisonDelta);
assertEquals(wfdisc.getCalib(), 0.0633, this.comparisonDelta);
assertEquals(wfdisc.getCalper(), 1, this.comparisonDelta);
assertEquals(wfdisc.getInstype(), "STS-2");
assertEquals(wfdisc.getSegtype().toString(), "o");
assertEquals(wfdisc.getDatatype(), "s4");
assertEquals(wfdisc.getClip(), false);
assertEquals(wfdisc.getDir(), "src/test/resources/css/WFS4/");
assertEquals(wfdisc.getDfile(), "MLR0.w");
assertEquals(wfdisc.getFoff(), 2724800);
assertEquals(wfdisc.getCommid(), -1);
assertEquals(wfdisc.getLddate(), "08-APR-15");
}
}
|
FutureHax/Marvin-Android | app/src/main/java/com/futurehax/marvin/fragments/GeneralPreferenceFragment.java | package com.futurehax.marvin.fragments;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.support.v4.preference.PreferenceFragment;
import com.futurehax.marvin.R;
import com.futurehax.marvin.UberEstimoteApplication;
import com.futurehax.marvin.activities.LoginActivity;
import com.futurehax.marvin.manager.PreferencesProvider;
import com.futurehax.marvin.service.HeartBeatService;
public class GeneralPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
setHasOptionsMenu(true);
getActivity().setTitle("Settings");
Preference host = findPreference("host");
String hostName = new PreferencesProvider(getActivity()).getHost();
if (hostName != null) {
host.setSummary(hostName);
}
host.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Intent i = new Intent(preference.getContext(), LoginActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
preference.getContext().startActivity(i);
return true;
}
});
findPreference("enable_backup").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
UberEstimoteApplication app = ((UberEstimoteApplication) getActivity().getApplication());
boolean value = (boolean) newValue;
if (value) {
app.startupListener();
} else {
app.stopListener();
}
return true;
}
});
findPreference("enable_tracking_lights").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
HeartBeatService.sendHeartBeat(preference.getContext());
return true;
}
});
}
}
|
16underscore/Insane | src/main/java/me/sixteen_/insane/command/CommandManager.java | package me.sixteen_.insane.command;
import me.sixteen_.insane.Insane;
import me.sixteen_.insane.command.commands.Bind;
import me.sixteen_.insane.command.commands.Clear;
import me.sixteen_.insane.command.commands.Config;
import me.sixteen_.insane.command.commands.Help;
import me.sixteen_.insane.command.commands.Login;
import me.sixteen_.insane.command.commands.Panic;
import me.sixteen_.insane.command.commands.Toggle;
import me.sixteen_.insane.command.commands.Value;
import me.sixteen_.insane.event.ScreenSendMessageCallback;
import me.sixteen_.insane.util.Logger;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
/**
* @author 16_
*/
@Environment(EnvType.CLIENT)
public class CommandManager {
private Command[] commands;
private String prefix = ".";
private Insane insane;
private Logger logger;
public CommandManager() {
insane = Insane.getInstance();
logger = insane.getLogger();
commands = new Command[] { //
new Bind(), //
new Clear(), //
new Config(), //
new Help(), //
new Login(), //
new Panic(), //
new Toggle(), //
new Value() //
};
ScreenSendMessageCallback.EVENT.register((message, toHud) -> {
if (message.startsWith(prefix)) {
input(message);
return true;
}
return false;
});
}
/**
* @param input needs the command input
*/
public void input(String input) {
String[] cmd = input.substring(prefix.length()).split(" ");
for (Command command : getCommands()) {
if (command.getName().equalsIgnoreCase(cmd[0])) {
try {
command.run(cmd);
} catch (IllegalArgumentException e) {
logger.log(e.getMessage()).log(command.syntax());
} catch (Exception e) {
logger.log(command.syntax());
}
return;
}
}
for (Command command : getCommands()) {
logger.log(command.syntax());
}
}
/**
* @return an Array of {@link Command}
*/
public Command[] getCommands() {
return commands;
}
} |
weiboad/adbase | docs/dc/df2/structadbase_1_1_time_zone_1_1_data.js | <filename>docs/dc/df2/structadbase_1_1_time_zone_1_1_data.js
var structadbase_1_1_time_zone_1_1_data =
[
[ "abbreviation", "dc/df2/structadbase_1_1_time_zone_1_1_data.html#ae526635e7ecbe4b158de98b358920b52", null ],
[ "localtimes", "dc/df2/structadbase_1_1_time_zone_1_1_data.html#aed3c92f32e97f3d8e2fcd52f19c855ef", null ],
[ "names", "dc/df2/structadbase_1_1_time_zone_1_1_data.html#a102cf7c96e9fe083cdc13bfbd4421760", null ],
[ "transitions", "dc/df2/structadbase_1_1_time_zone_1_1_data.html#a405916cf25c0636d2fe59fe93472ac9d", null ]
]; |
alichherawalla/react-native-graphql-appsync | app/containers/HomeScreen/index.js | import React, { useEffect } from 'react'
import { RefreshControl, ScrollView, StyleSheet } from 'react-native'
import { connect } from 'react-redux'
import { compose } from 'redux'
import { PropTypes } from 'prop-types'
import { FAB, List } from 'react-native-paper'
import { createStructuredSelector } from 'reselect'
import get from 'lodash/get'
import gql from 'graphql-tag'
import { graphql } from 'react-apollo'
import { injectIntl } from 'react-intl'
import AppContainer from 'app/components/Container'
import For from 'app/components/For'
import NavigationService from 'app/services/NavigationService'
import { getAppBarWithMenu } from 'app/components/AppBar'
import If from 'app/components/If'
import ProgressPlaceholder from 'app/components/ProgressPlaceholder'
import { withAuthenticator } from 'aws-amplify-react-native'
import { NEW_EMPLOYEE, SIGNUP_CONFIG, timeout } from 'app/utils'
import { colors } from 'app/themes'
import {
selectEmployeeData,
selectEmployeeDataError,
selectLoadingEmployeeData
} from './selectors'
import { HomeScreenActions } from './reducer'
function HomeScreen({
intl,
employeeData,
loadingEmployeeData,
fetchEmployeeData,
dispatchRequestDeleteEmployee
}) {
const [refreshing, setRefreshing] = React.useState(false)
const onRefresh = React.useCallback(() => {
setRefreshing(true)
fetchEmployeeData()
timeout(2000).then(() => setRefreshing(false))
}, [refreshing])
useEffect(() => {
fetchEmployeeData()
}, [])
const handleEmployeeDelete = employee => {
dispatchRequestDeleteEmployee(employee)
NavigationService.navigateAndReset('HomeScreen')
}
const navigate = (screeName, params) => () =>
NavigationService.navigate(screeName, params)
const renderListItem = employee => (
<List.Item
onPress={navigate('EmployeeDetails', {
employee,
handleEmployeeDelete
})}
title={employee.firstname}
description={`Addresses: ${get(
employee,
'address.items.length',
0
)}\nSkills: ${get(employee, 'skills.items.length', 0)}`}
/>
)
return (
<>
{getAppBarWithMenu(intl.formatMessage({ id: 'employee_list' }))}
<AppContainer>
<ProgressPlaceholder
show={loadingEmployeeData}
placeholderText="Fetching employee data"
/>
<ScrollView
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
}
>
<If condition={!!employeeData}>
<For of={employeeData} renderItem={renderListItem} />
</If>
</ScrollView>
<FAB
style={styles.fab}
color={colors.white}
icon="plus"
onPress={navigate('EditEmployeeDetailsScreen', NEW_EMPLOYEE)}
/>
</AppContainer>
</>
)
}
const styles = StyleSheet.create({
fab: {
position: 'absolute',
backgroundColor: colors.purple,
margin: 16,
right: 0,
bottom: 0
}
})
HomeScreen.propTypes = {
fetchEmployeeData: PropTypes.func,
intl: PropTypes.object,
employeeData: PropTypes.array,
loadingEmployeeData: PropTypes.bool,
dispatchRequestDeleteEmployee: PropTypes.func
}
const mapStateToProps = createStructuredSelector({
employeeData: selectEmployeeData(),
loadingEmployeeData: selectLoadingEmployeeData(),
employeeDataError: selectEmployeeDataError()
})
const mapDispatchToProps = dispatch => ({
fetchEmployeeData: () => dispatch(HomeScreenActions.requestGetEmployeeData()),
dispatchRequestDeleteEmployee: employee =>
dispatch(HomeScreenActions.requestDeleteEmployee(employee))
})
const withConnect = connect(mapStateToProps, mapDispatchToProps)
const authHoC = () =>
withAuthenticator(HomeScreen, { signUpConfig: SIGNUP_CONFIG })
export const HomeScreenTest = injectIntl(HomeScreen)
const H = graphql(gql`
query {
listEmployees {
items {
id
firstname
lastname
address {
items {
id
line1
line2
city
state
zipcode
}
}
skills {
items {
id
name
}
}
}
}
}
`)(HomeScreen)
export default compose(withConnect, injectIntl, authHoC)(H)
|
DavidWz/Myun-Lang | src/myun/AST/constraints/FunctionHasReturnConstraint.java | package myun.AST.constraints;
import myun.AST.*;
/**
* Checks whether each program flow in a function has a return statement.
*/
class FunctionHasReturnConstraint implements Constraint, ASTVisitor<Boolean> {
@Override
public void check(ASTCompileUnit compileUnit) {
compileUnit.accept(this);
}
@Override
public Boolean visit(ASTAssignment node) {
return false;
}
@Override
public Boolean visit(ASTBlock node) {
// if the block has a return statement at the end
// we do not need to check the rest of the block any more
if (node.getFuncReturn().isPresent()) {
return true;
}
// if there is no return statement at the end
// we need to traverse the statements from end to start and check for return statements
else {
for (int i = node.getStatements().size() - 1; i >= 0; i--) {
if (node.getStatements().get(i).accept(this)) {
return true;
}
}
return false;
}
}
@Override
public Boolean visit(ASTBranch node) {
return node.getElseBlock().isPresent() && node.getBlocks().stream().allMatch(block -> block.accept(this));
}
@Override
public Boolean visit(ASTCompileUnit node) {
return node.getFuncDefs().stream().allMatch(funcDef -> funcDef.accept(this));
}
@Override
public <CT> Boolean visit(ASTConstant<CT> node) {
return false;
}
@Override
public Boolean visit(ASTDeclaration node) {
return false;
}
@Override
public Boolean visit(ASTForLoop node) {
return false;
}
@Override
public Boolean visit(ASTFuncCall node) {
return false;
}
@Override
public Boolean visit(ASTFuncDef node) {
if (!node.getBlock().accept(this)) {
throw new ReturnMissingException(node);
}
return true;
}
@Override
public Boolean visit(ASTFuncReturn node) {
return true;
}
@Override
public Boolean visit(ASTLoopBreak node) {
return false;
}
@Override
public Boolean visit(ASTScript node) {
return false;
}
@Override
public Boolean visit(ASTProcCall node) {
return false;
}
@Override
public Boolean visit(ASTVariable node) {
return false;
}
@Override
public Boolean visit(ASTWhileLoop node) {
return false;
}
}
|
masud-technope/ACER-Replication-Package-ASE2017 | corpus/class/eclipse.jdt.ui/2937.java | <reponame>masud-technope/ACER-Replication-Package-ASE2017
public class T9815 {
void f1() {
String j = ex();
}
String ex() {
/*[*/
return /*]*/
"text";
}
}
|
TonyChengTW/Rmail | src/global/record.c | /*++
/* NAME
/* record 3
/* SUMMARY
/* simple typed record I/O
/* SYNOPSIS
/* #include <record.h>
/*
/* int rec_get(stream, buf, maxsize)
/* VSTREAM *stream;
/* VSTRING *buf;
/* int maxsize;
/*
/* int rec_put(stream, type, data, len)
/* VSTREAM *stream;
/* int type;
/* const char *data;
/* int len;
/* AUXILIARY FUNCTIONS
/* int rec_put_type(stream, type, offset)
/* VSTREAM *stream;
/* int type;
/* long offset;
/*
/* int rec_fprintf(stream, type, format, ...)
/* VSTREAM *stream;
/* int type;
/* const char *format;
/*
/* int rec_fputs(stream, type, str)
/* VSTREAM *stream;
/* int type;
/* const char *str;
/*
/* int REC_PUT_BUF(stream, type, buf)
/* VSTREAM *stream;
/* int type;
/* VSTRING *buf;
/*
/* int rec_vfprintf(stream, type, format, ap)
/* VSTREAM *stream;
/* int type;
/* const char *format;
/* va_list ap;
/* DESCRIPTION
/* This module reads and writes typed variable-length records.
/* Each record contains a 1-byte type code (0..255), a length
/* (1 or more bytes) and as much data as the length specifies.
/*
/* rec_get() retrieves a record from the named record stream
/* and returns the record type. The \fImaxsize\fR argument is
/* zero, or specifies a maximal acceptable record length.
/* The result is REC_TYPE_EOF when the end of the file was reached,
/* and REC_TYPE_ERROR in case of a bad record. The result buffer is
/* null-terminated for convenience. Records may contain embedded
/* null characters.
/*
/* rec_put() stores the specified record and returns the record
/* type, or REC_TYPE_ERROR in case of problems.
/*
/* rec_put_type() updates the type field of the record at the
/* specified file offset. The result is the new record type,
/* or REC_TYPE_ERROR in case of trouble.
/*
/* rec_fprintf() and rec_vfprintf() format their arguments and
/* write the result to the named stream. The result is the same
/* as with rec_put().
/*
/* rec_fputs() writes a record with as contents a copy of the
/* specified string. The result is the same as with rec_put().
/*
/* REC_PUT_BUF() is a wrapper for rec_put() that makes it
/* easier to handle VSTRING buffers. It is an unsafe macro
/* that evaluates some arguments more than once.
/* DIAGNOSTICS
/* Panics: interface violations. Fatal errors: insufficient memory.
/* Warnings: corrupted file.
/* LICENSE
/* .ad
/* .fi
/* The Secure Mailer license must be distributed with this software.
/* AUTHOR(S)
/* <NAME>
/* <NAME> Research
/* P.O. Box 704
/* Yorktown Heights, NY 10598, USA
/*--*/
/* System library. */
#include <sys_defs.h>
#include <stdlib.h> /* 44BSD stdarg.h uses abort() */
#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#ifndef NBBY
#define NBBY 8 /* XXX should be in sys_defs.h */
#endif
/* Utility library. */
#include <msg.h>
#include <mymalloc.h>
#include <vstream.h>
#include <vstring.h>
/* Global library. */
#include <record.h>
/* rec_put_type - update record type field */
int rec_put_type(VSTREAM *stream, int type, long offset)
{
if (type < 0 || type > 255)
msg_panic("rec_put_type: bad record type %d", type);
if (msg_verbose > 2)
msg_info("rec_put_type: %d at %ld", type, offset);
if (vstream_fseek(stream, offset, SEEK_SET) < 0
|| VSTREAM_PUTC(type, stream) != type) {
return (REC_TYPE_ERROR);
} else {
return (type);
}
}
/* rec_put - store typed record */
int rec_put(VSTREAM *stream, int type, const char *data, int len)
{
int len_rest;
int len_byte;
if (type < 0 || type > 255)
msg_panic("rec_put: bad record type %d", type);
if (msg_verbose > 2)
msg_info("rec_put: type %c len %d data %.10s", type, len, data);
/*
* Write the record type, one byte.
*/
if (VSTREAM_PUTC(type, stream) == VSTREAM_EOF)
return (REC_TYPE_ERROR);
/*
* Write the record data length in 7-bit portions, using the 8th bit to
* indicate that there is more. Use as many length bytes as needed.
*/
len_rest = len;
do {
len_byte = len_rest & 0177;
if (len_rest >>= 7)
len_byte |= 0200;
if (VSTREAM_PUTC(len_byte, stream) == VSTREAM_EOF) {
return (REC_TYPE_ERROR);
}
} while (len_rest != 0);
/*
* Write the record data portion. Use as many length bytes as needed.
*/
if (len && vstream_fwrite(stream, data, len) != len)
return (REC_TYPE_ERROR);
return (type);
}
/* rec_get - retrieve typed record */
int rec_get(VSTREAM *stream, VSTRING *buf, int maxsize)
{
char *myname = "rec_get";
int type;
int len;
int len_byte;
int shift;
/*
* Sanity check.
*/
if (maxsize < 0)
msg_panic("%s: bad record size limit: %d", myname, maxsize);
/*
* Extract the record type.
*/
if ((type = VSTREAM_GETC(stream)) == VSTREAM_EOF)
return (REC_TYPE_EOF);
/*
* Find out the record data length. Return an error result when the
* record data length is malformed or when it exceeds the acceptable
* limit.
*/
for (len = 0, shift = 0; /* void */ ; shift += 7) {
if (shift >= (int) (NBBY * sizeof(int))) {
msg_warn("%s: too many length bits, record type %d",
VSTREAM_PATH(stream), type);
return (REC_TYPE_ERROR);
}
if ((len_byte = VSTREAM_GETC(stream)) == VSTREAM_EOF) {
msg_warn("%s: unexpected EOF reading length, record type %d",
VSTREAM_PATH(stream), type);
return (REC_TYPE_ERROR);
}
len |= (len_byte & 0177) << shift;
if ((len_byte & 0200) == 0)
break;
}
if (len < 0 || (maxsize > 0 && len > maxsize)) {
msg_warn("%s: illegal length %d, record type %d",
VSTREAM_PATH(stream), len, type);
while (len-- > 0 && VSTREAM_GETC(stream) != VSTREAM_EOF)
/* void */ ;
return (REC_TYPE_ERROR);
}
/*
* Reserve buffer space for the result, and read the record data into the
* buffer.
*/
VSTRING_RESET(buf);
VSTRING_SPACE(buf, len);
if (vstream_fread(stream, vstring_str(buf), len) != len) {
msg_warn("%s: unexpected EOF in data, record type %d length %d",
VSTREAM_PATH(stream), type, len);
return (REC_TYPE_ERROR);
}
VSTRING_AT_OFFSET(buf, len);
VSTRING_TERMINATE(buf);
if (msg_verbose > 2)
msg_info("%s: type %c len %d data %.10s", myname,
type, len, vstring_str(buf));
return (type);
}
/* rec_vfprintf - write formatted string to record */
int rec_vfprintf(VSTREAM *stream, int type, const char *format, va_list ap)
{
static VSTRING *vp;
if (vp == 0)
vp = vstring_alloc(100);
/*
* Writing a formatted string involves an extra copy, because we must
* know the record length before we can write it.
*/
vstring_vsprintf(vp, format, ap);
return (REC_PUT_BUF(stream, type, vp));
}
/* rec_fprintf - write formatted string to record */
int rec_fprintf(VSTREAM *stream, int type, const char *format,...)
{
int result;
va_list ap;
va_start(ap, format);
result = rec_vfprintf(stream, type, format, ap);
va_end(ap);
return (result);
}
/* rec_fputs - write string to record */
int rec_fputs(VSTREAM *stream, int type, const char *str)
{
return (rec_put(stream, type, str, str ? strlen(str) : 0));
}
|
emory-irlab/liveqa | src/main/scala/edu/emory/mathcs/ir/liveqa/util/TermIdf.scala | package edu.emory.mathcs.ir.liveqa.util
import java.io.{BufferedInputStream, BufferedReader, FileInputStream, InputStreamReader}
import java.util.zip.GZIPInputStream
import com.typesafe.config.ConfigFactory
import com.typesafe.scalalogging.LazyLogging
/**
* Returns inverse document frequencies of terms.
*/
object TermIdf extends LazyLogging {
val cfg = ConfigFactory.load()
val termCounts = loadIdfData()
assert(termCounts.contains(""))
val docCount = termCounts.get("").get
private def loadIdfData(): Map[String, Long] = {
logger.info("Reading term document count information")
val reader = scala.io.Source.fromInputStream(
new GZIPInputStream(
new BufferedInputStream(
new FileInputStream(
cfg.getString("qa.term_doccount_file")))))
val data = reader.getLines.map { line =>
val fields = line.split("\t")
if (fields.length > 1)
(fields(0).toLowerCase, fields(1).toLong)
else
("", fields(0).toLong)
}.toList
reader.close()
val termCounts = data.groupBy(_._1).mapValues(l => l.map(_._2).sum)
logger.info("Done reading term counts")
termCounts
}
def apply(term: String): Float = {
val tf = termCounts.getOrElse(term, 1L)
math.log((docCount - tf + 0.5f) / (tf + 0.5)).toFloat
}
}
|
ashish-s/twilio-ruby | lib/twilio-ruby/framework/obsolete_client.rb | <reponame>ashish-s/twilio-ruby<filename>lib/twilio-ruby/framework/obsolete_client.rb
# frozen_string_literal: true
module Twilio
module REST
class ObsoleteClient
def initialize(*)
raise ObsoleteError, "#{self.class} has been removed from this version of the library. "\
'Please refer to current documentation for guidance.'
end
end
end
end
|
apereo-tesuto/tesuto | tesuto-ui/src/main/java/org/cccnext/tesuto/web/controller/StudentCollegeAffiliationController.java | <reponame>apereo-tesuto/tesuto
/*******************************************************************************
* Copyright © 2019 by California Community Colleges Chancellor's Office
*
* 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.cccnext.tesuto.web.controller;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.cccnext.tesuto.admin.dto.StudentCollegeAffiliationDto;
import org.cccnext.tesuto.exception.NotFoundException;
import org.cccnext.tesuto.web.service.StudentCollegeAffiliationService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
/**
* @author <NAME> (<EMAIL>)
*/
@Service
public class StudentCollegeAffiliationController {
@Resource(name = "studentCollegeAffiliationService")
StudentCollegeAffiliationService service;
public ResponseEntity<List<StudentCollegeAffiliationDto>> read() {
return new ResponseEntity<>(service.findAll(), HttpStatus.OK);
}
public ResponseEntity<StudentCollegeAffiliationDto> findByCccIdAndMisCode(String cccId, String misCode) {
return new ResponseEntity<StudentCollegeAffiliationDto>(service.findByCccIdAndMisCode(cccId, misCode),
HttpStatus.OK);
}
public ResponseEntity<List<StudentCollegeAffiliationDto>> findByCccId(String cccId) {
return new ResponseEntity<List<StudentCollegeAffiliationDto>>(service.findByStudentCccId(cccId), HttpStatus.OK);
}
public ResponseEntity<List<StudentCollegeAffiliationDto>> recent() {
List<StudentCollegeAffiliationDto> recent = service.findTenMostRecent();
if(CollectionUtils.isEmpty(recent)) {
new ResponseEntity<List<StudentCollegeAffiliationDto>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<StudentCollegeAffiliationDto>>(recent, HttpStatus.OK);
}
public ResponseEntity<?> delete(String eppn, String cccId, String misCode) {
StudentCollegeAffiliationDto affiliation = service.find(eppn, cccId, misCode);
if (affiliation == null) {
throw new NotFoundException(
"Unable to find an affiliation for eppn: " + eppn + " cccId: " + cccId + " misCode: " + misCode);
}
service.delete(affiliation);
return new ResponseEntity<Void>(HttpStatus.OK);
}
}
|
Kamesuta/TofuCraft | src/main/java/tsuteto/tofu/block/BlockTcOre.java | package tsuteto.tofu.block;
import net.minecraft.block.material.Material;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import java.util.Random;
public class BlockTcOre extends TcBlock
{
private Item itemContained;
private int itemDmgContained;
private int minXp;
private int maxXp;
public BlockTcOre(int minXp, int maxXp)
{
this(Material.rock, minXp, maxXp);
}
public BlockTcOre(Material material, int minXp, int maxXp)
{
super(material);
this.minXp = minXp;
this.maxXp = maxXp;
this.setCreativeTab(CreativeTabs.tabBlock);
}
public BlockTcOre setItemContained(ItemStack itemstack)
{
this.itemContained = itemstack.getItem();
this.itemDmgContained = itemstack.getItemDamage();
return this;
}
public BlockTcOre setItemContained(Item item)
{
this.itemContained = item;
this.itemDmgContained = 0;
return this;
}
/**
* Returns the ID of the items to drop on destruction.
*/
@Override
public Item getItemDropped(int par1, Random par2Random, int par3)
{
return this.itemContained;
}
/**
* Returns the quantity of items to drop on block destruction.
*/
@Override
public int quantityDropped(Random par1Random)
{
return 1;
}
/**
* Returns the usual quantity dropped by the block plus a bonus of 1 to 'i' (inclusive).
*/
@Override
public int quantityDroppedWithBonus(int par1, Random par2Random)
{
if (par1 > 0 && Item.getItemFromBlock(this) != this.getItemDropped(0, par2Random, par1))
{
int j = par2Random.nextInt(par1 + 2) - 1;
if (j < 0)
{
j = 0;
}
return this.quantityDropped(par2Random) * (j + 1);
}
else
{
return this.quantityDropped(par2Random);
}
}
/**
* Drops the block items with a specified chance of dropping the specified items
*/
@Override
public void dropBlockAsItemWithChance(World par1World, int par2, int par3, int par4, int par5, float par6, int par7)
{
super.dropBlockAsItemWithChance(par1World, par2, par3, par4, par5, par6, par7);
if (this.getItemDropped(par5, par1World.rand, par7) != Item.getItemFromBlock(this))
{
int j1 = MathHelper.getRandomIntegerInRange(par1World.rand, 2, 5);
this.dropXpOnBlockBreak(par1World, par2, par3, par4, j1);
}
}
/**
* Determines the damage on the item the block drops. Used in cloth and wood.
*/
@Override
public int damageDropped(int par1)
{
return itemDmgContained;
}
}
|
tpasternak/pants | src/python/pants/backend/python/lint/pylint/rules_integration_test.py | # Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from functools import partialmethod
from textwrap import dedent
from typing import List, Optional
import pytest
from pants.backend.python.lint.pylint.rules import PylintTarget
from pants.backend.python.lint.pylint.rules import rules as pylint_rules
from pants.backend.python.targets.python_library import PythonLibrary
from pants.base.specs import OriginSpec, SingleAddress
from pants.build_graph.address import Address
from pants.build_graph.build_file_aliases import BuildFileAliases
from pants.engine.fs import FileContent, InputFilesContent, Snapshot
from pants.engine.legacy.structs import PythonTargetAdaptor, PythonTargetAdaptorWithOrigin
from pants.engine.rules import RootRule
from pants.engine.selectors import Params
from pants.rules.core.lint import LintResult
from pants.source.wrapped_globs import EagerFilesetWithSpec
from pants.testutil.option.util import create_options_bootstrapper
from pants.testutil.test_base import TestBase
class PylintIntegrationTest(TestBase):
# See http://pylint.pycqa.org/en/latest/user_guide/run.html#exit-codes for exit codes.
source_root = "src/python"
good_source = FileContent(
path=f"{source_root}/good.py", content=b"'''docstring'''\nUPPERCASE_CONSTANT = ''\n",
)
bad_source = FileContent(
path=f"{source_root}/bad.py", content=b"'''docstring'''\nlowercase_constant = ''\n",
)
create_python_library = partialmethod(
TestBase.create_library, path=source_root, target_type="python_library", name="target",
)
def write_file(self, file_content: FileContent) -> None:
self.create_file(relpath=file_content.path, contents=file_content.content.decode())
@classmethod
def alias_groups(cls) -> BuildFileAliases:
return BuildFileAliases(targets={"python_library": PythonLibrary})
@classmethod
def rules(cls):
return (*super().rules(), *pylint_rules(), RootRule(PylintTarget))
def run_pylint(
self,
source_files: List[FileContent],
*,
config: Optional[str] = None,
passthrough_args: Optional[str] = None,
interpreter_constraints: Optional[str] = None,
skip: bool = False,
origin: Optional[OriginSpec] = None,
) -> LintResult:
args = ["--backend-packages2=pants.backend.python.lint.pylint"]
if config:
# TODO(#9148): The config file exists but parser.py cannot find it
self.create_file(relpath="pylintrc", contents=config)
args.append("--pylint-config=pylintrc")
if passthrough_args:
args.append(f"--pylint-args='{passthrough_args}'")
if skip:
args.append(f"--pylint-skip")
input_snapshot = self.request_single_product(Snapshot, InputFilesContent(source_files))
adaptor = PythonTargetAdaptor(
sources=EagerFilesetWithSpec(self.source_root, {"globs": []}, snapshot=input_snapshot),
address=Address.parse(f"{self.source_root}:target"),
compatibility=[interpreter_constraints] if interpreter_constraints else None,
)
if origin is None:
origin = SingleAddress(directory="test", name="target")
target = PylintTarget(PythonTargetAdaptorWithOrigin(adaptor, origin))
return self.request_single_product(
LintResult, Params(target, create_options_bootstrapper(args=args)),
)
def test_single_passing_source(self) -> None:
self.create_python_library()
self.write_file(self.good_source)
result = self.run_pylint([self.good_source])
assert result.exit_code == 0
assert "Your code has been rated at 10.00/10" in result.stdout.strip()
def test_single_failing_source(self) -> None:
self.create_python_library()
self.write_file(self.bad_source)
result = self.run_pylint([self.bad_source])
assert result.exit_code == 16 # convention message issued
assert "bad.py:2:0: C0103" in result.stdout
def test_mixed_sources(self) -> None:
self.create_python_library()
self.write_file(self.good_source)
self.write_file(self.bad_source)
result = self.run_pylint([self.good_source, self.bad_source])
assert result.exit_code == 16 # convention message issued
assert "good.py" not in result.stdout
assert "bad.py:2:0: C0103" in result.stdout
def test_precise_file_args(self) -> None:
self.create_python_library()
self.write_file(self.good_source)
self.write_file(self.bad_source)
result = self.run_pylint([self.good_source])
assert result.exit_code == 0
assert "Your code has been rated at 10.00/10" in result.stdout.strip()
@pytest.mark.skip(reason="#9148: The config file exists but parser.py cannot find it")
def test_respects_config_file(self) -> None:
self.create_python_library()
self.write_file(self.bad_source)
result = self.run_pylint([self.bad_source], config="[pylint]\ndisable = C0103\n")
assert result.exit_code == 0
assert result.stdout.strip() == ""
def test_respects_passthrough_args(self) -> None:
self.create_python_library()
self.write_file(self.bad_source)
result = self.run_pylint([self.bad_source], passthrough_args="--disable=C0103")
assert result.exit_code == 0
assert "Your code has been rated at 10.00/10" in result.stdout.strip()
def test_includes_direct_dependencies(self) -> None:
self.create_python_library(name="library")
self.create_python_library(
name="dependency", sources=["dependency.py"], dependencies=[":library"],
)
self.write_file(
FileContent(
path=f"{self.source_root}/dependency.py",
content=dedent(
"""\
# No docstring because Pylint doesn't lint dependencies
from transitive_dep import doesnt_matter_if_variable_exists
THIS_VARIABLE_EXISTS = ''
"""
).encode(),
)
)
source = FileContent(
path=f"{self.source_root}/test_dependency.py",
content=dedent(
"""\
'''Code is not executed, but Pylint will check that variables exist and are used'''
from dependency import THIS_VARIABLE_EXISTS
print(THIS_VARIABLE_EXISTS)
"""
).encode(),
)
self.create_python_library(sources=["test_dependency.py"], dependencies=[":dependency"])
self.write_file(source)
result = self.run_pylint([source])
assert result.exit_code == 0
assert "Your code has been rated at 10.00/10" in result.stdout.strip()
def test_skip(self) -> None:
result = self.run_pylint([self.bad_source], skip=True)
assert result == LintResult.noop()
|
d4x337/reloaded | db/migrate/20120702074611_create_mini_post_likings.rb | class CreateMiniPostLikings < ActiveRecord::Migration
def self.up
create_table :mini_post_likings do |t|
t.boolean :liking,:default => true
t.datetime :created_at, :null => false
t.integer :mini_post_id, :default => 0,:null => false
t.integer :user_id,:default => 0,:null => false
t.boolean :deleted,:default =>false
end
end
def self.down
drop_table :mini_post_likings
end
end
|
marwahan/test-os | www/app/modules/biospecimen/participant/specimen/module.js |
angular.module('os.biospecimen.specimen',
[
'ui.router',
'os.biospecimen.specimen.addedit',
'os.biospecimen.specimen.detail',
'os.biospecimen.specimen.overview',
'os.biospecimen.specimen.close',
'os.biospecimen.specimen.addaliquots',
'os.biospecimen.specimen.addderivative',
'os.biospecimen.specimen.bulkaddevent'
])
.config(function($stateProvider) {
$stateProvider
.state('specimen', {
url: '/specimens/:specimenId',
controller: function($state, params) {
$state.go('specimen-detail.overview', params, {location: 'replace'});
},
resolve: {
params: function($stateParams, Specimen) {
return Specimen.getRouteIds($stateParams.specimenId);
}
},
parent: 'signed-in'
})
.state('specimen-root', {
url: '/specimens?specimenId&srId',
template: '<div ui-view></div>',
resolve: {
specimen: function($stateParams, cpr, Specimen) {
if ($stateParams.specimenId) {
return Specimen.getById($stateParams.specimenId);
} else if ($stateParams.srId) {
return Specimen.getAnticipatedSpecimen($stateParams.srId);
}
return new Specimen({
lineage: 'New',
visitId: $stateParams.visitId,
labelFmt: cpr.specimenLabelFmt
});
}
},
controller: function($scope, specimen) {
$scope.specimen = $scope.object = specimen;
$scope.entityType = 'Specimen';
$scope.extnState = 'specimen-detail.extensions.';
},
abstract: true,
parent: 'visit-root'
})
.state('specimen-addedit', {
url: '/addedit-specimen',
templateProvider: function(PluginReg, $q) {
var defaultTmpl = "modules/biospecimen/participant/specimen/addedit.html";
return $q.when(PluginReg.getTmpls("specimen-addedit", "page-body", defaultTmpl)).then(
function(tmpls) {
return '<div ng-include src="\'' + tmpls[0] + '\'"></div>';
}
);
},
resolve: {
extensionCtxt: function(specimen) {
return specimen.getExtensionCtxt();
}
},
controller: 'AddEditSpecimenCtrl',
parent: 'specimen-root'
})
.state('specimen-detail', {
url: '/detail',
templateUrl: 'modules/biospecimen/participant/specimen/detail.html',
controller: 'SpecimenDetailCtrl',
parent: 'specimen-root'
})
.state('specimen-detail.overview', {
url: '/overview',
templateProvider: function(PluginReg, $q) {
var defaultTmpl = "modules/biospecimen/participant/specimen/overview.html";
return $q.when(PluginReg.getTmpls("specimen-detail", "overview", defaultTmpl)).then(
function(tmpls) {
return '<div ng-include src="\'' + tmpls[0] + '\'"></div>';
}
);
},
controller: 'SpecimenOverviewCtrl',
parent: 'specimen-detail'
})
.state('specimen-detail.extensions', {
url: '/extensions',
template: '<div ui-view></div>',
controller: function($scope, specimen) {
$scope.extnOpts = {
update: $scope.specimenResource.updateOpts,
entity: specimen,
isEntityActive: (specimen.activityStatus == 'Active')
};
},
abstract: true,
parent: 'specimen-detail'
})
.state('specimen-detail.extensions.list', {
url: '/list',
templateUrl: 'modules/biospecimen/extensions/list.html',
controller: 'FormsListCtrl',
parent: 'specimen-detail.extensions'
})
.state('specimen-detail.extensions.addedit', {
url: '/addedit?formId&recordId&formCtxId',
templateUrl: 'modules/biospecimen/extensions/addedit.html',
resolve: {
formDef: function($stateParams, Form) {
return Form.getDefinition($stateParams.formId);
},
postSaveFilters: function() {
return [
function(specimen, formName, formData) {
if (formName == "SpecimenReceivedEvent") {
specimen.createdOn = formData.time
} else if (formName == "SpecimenFrozenEvent" && formData.incrementFreezeThaw == 1) {
++specimen.freezeThawCycles;
} else if (formName == "SpecimenThawEvent" && formData.incrementFreezeThaw == 1) {
++specimen.freezeThawCycles;
}
return formData
}
];
}
},
controller: 'FormRecordAddEditCtrl',
parent: 'specimen-detail.extensions'
})
.state('specimen-detail.events', {
url: '/events',
templateUrl: 'modules/biospecimen/participant/specimen/events.html',
controller: function($scope, specimen, ExtensionsUtil) {
$scope.entityType = 'SpecimenEvent';
$scope.extnState = 'specimen-detail.events';
$scope.events = specimen.getEvents();
$scope.eventForms = specimen.getForms({entityType: 'SpecimenEvent'});
$scope.deleteEvent = function(event) {
var record = {recordId: event.id, formId: event.formId, formCaption: event.name};
ExtensionsUtil.deleteRecord(
record,
function() {
var idx = $scope.events.indexOf(event);
$scope.events.splice(idx, 1);
}
);
}
},
parent: 'specimen-detail'
})
.state('specimen-create-derivative', {
url: '/derivative',
templateProvider: function(PluginReg, $q) {
var defaultTmpl = "modules/biospecimen/participant/specimen/add-derivative.html";
return $q.when(PluginReg.getTmpls("specimen-create-derivative", "page-body", defaultTmpl)).then(
function(tmpls) {
return '<div ng-include src="\'' + tmpls[0] + '\'"></div>';
}
);
},
resolve: {
extensionCtxt: function(Specimen) {
return Specimen.getExtensionCtxt({"lineage": "Derived"});
}
},
controller: 'AddDerivativeCtrl',
parent: 'specimen-root'
})
.state('specimen-create-aliquots', {
url: '/aliquots',
templateProvider: function(PluginReg, $q) {
var defaultTmpl = "modules/biospecimen/participant/specimen/add-aliquots.html";
return $q.when(PluginReg.getTmpls("specimen-create-aliquots", "page-body", defaultTmpl)).then(
function(tmpls) {
return '<div ng-include src="\'' + tmpls[0] + '\'"></div>';
}
);
},
resolve: {
extensionCtxt: function(Specimen) {
return Specimen.getExtensionCtxt();
}
},
controller: 'AddAliquotsCtrl',
parent: 'specimen-root'
})
.state('bulk-add-event', {
url: '/bulk-add-event',
templateUrl: 'modules/biospecimen/participant/specimen/bulk-add-event.html',
controller: 'BulkAddEventCtrl',
parent: 'signed-in'
});
})
.run(function($state, QuickSearchSvc, Specimen, Alerts) {
var opts = {
template: 'modules/biospecimen/participant/specimen/quick-search.html',
caption: 'entities.specimen',
order: 3,
search: function(searchData) {
Specimen.listByLabels(searchData.label).then(
function(specimens) {
if (specimens == undefined || specimens.length == 0) {
Alerts.error('search.error', {entity: 'Specimen', key: searchData.label});
return;
}
var specimen = specimens[0];
var params = {
cpId: specimen.cpId,
visitId: specimen.visitId,
cprId: specimen.cprId,
specimenId: specimen.id
};
$state.go('specimen-detail.overview', params);
}
);
}
}
QuickSearchSvc.register('specimen', opts);
});
|
oicqtian/vue_admin_template | src/views/home/homeSiderRight/HomeSiderRight.class.js | export default {
name: 'homeSiderRight', // 右侧
components: {
},
data() {
return {};
},
mounted() {},
methods: {},
render(h) {
return <div class="home-rigth"></div>;
}
};
|
archivemanager/server | src/main/java/org/archivemanager/services/search/IndexCreationRequest.java | <reponame>archivemanager/server
package org.archivemanager.services.search;
import java.util.HashMap;
import java.util.Map;
import org.archivemanager.services.search.indexing.FieldMapping;
public class IndexCreationRequest {
private Map<String,FieldMapping> mappings = new HashMap<String,FieldMapping>();
public Map<String, FieldMapping> getMappings() {
return mappings;
}
public void setMappings(Map<String, FieldMapping> mappings) {
this.mappings = mappings;
}
}
|
alexqdh/PaddleFlow | pkg/fs/server/api/request/link.go | <reponame>alexqdh/PaddleFlow<gh_stars>1-10
/*
Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
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 request
type CreateLinkRequest struct {
FsName string `json:"fsName"`
Url string `json:"url"`
Properties map[string]string `json:"properties"`
Username string `json:"username"`
FsPath string `json:"fsPath"`
}
type DeleteLinkRequest struct {
FsName string `json:"fsName"`
Username string `json:"username"`
FsPath string `json:"fsPath"`
}
type GetLinkRequest struct {
Marker string `json:"marker"`
MaxKeys int32 `json:"maxKeys"`
Username string `json:"username"`
FsID string `json:"fsID"`
FsPath string `json:"fsPath"`
}
|
zerotheft/zerotheft-holon-node | app/services/calcEngineServices/index.js | <reponame>zerotheft/zerotheft-holon-node
/* eslint-disable no-underscore-dangle */
const fs = require('fs')
const { get, min, max, isEmpty, difference } = require('lodash')
const { pathsByNation } = require('zerotheft-node-utils').paths
const config = require('zerotheft-node-utils/config')
const cacheDir = `${config.APP_PATH}/.cache/calc_data`
const { writeFile, exportsDir, createAndWrite } = require('../../common')
const { getReportPath, getAppRoute } = require('../../../config')
const { cacheServer } = require('../redisService')
const { dataCachingPerPath } = require('../../workers/reports/dataCacheWorker')
const {
generatePDFReport,
generateNoVotePDFReport,
generatePDFMultiReport,
generateNoVoteMultiPDFReport,
deleteJsonFile,
mergePdfLatex,
} = require('./reportCommands')
const { createLog, SINGLE_REPORT_PATH, ERROR_PATH, MAIN_PATH } = require('../LogInfoServices')
const reportsPath = fromWorker => `${getReportPath()}reports${fromWorker ? '_in_progress' : ''}`
const multiIssueReportPath = fromWorker => `${reportsPath(fromWorker)}/multiIssueReport`
const singleIssueReportPath = fromWorker => `${reportsPath(fromWorker)}/ztReport`
/**
* Before report generation, all data from the blockchain were exported and go through a calculation algorithm.
* Calculation engine creates a summary json file that is then used for report generation process.
* This method actually scans the calc_summary.json file and returns a JSON object whereever needed in the report generation process.
*/
const allYearCachedData = async nation => {
createLog(MAIN_PATH, 'Fetching data from cache and do year wise mapping...')
try {
const jsonFile = fs.readFileSync(`${cacheDir}/${nation}/calc_summary.json`)
return JSON.parse(jsonFile)
} catch {
return {}
}
}
/**
* Generate single report based on economic hierarchy path. This method is also called from worker itself
* Ultimate pdf is generated for a single path.
*/
const singleIssueReport = async (leafPath, fromWorker = false) => {
createLog(SINGLE_REPORT_PATH, 'Single report generation initiation......', leafPath)
const fileName = `${leafPath.replace(/\//g, '-')}`
try {
const filePath = singleIssueReportPath(fromWorker)
if (fromWorker || !fs.existsSync(`${filePath}/${fileName}.pdf`)) {
const nation = leafPath.split('/')[0]
const nationPaths = await pathsByNation(nation)
const allYearData = await allYearCachedData(nation)
const lPath = leafPath.split('/').slice(1).join('/')
if (
!isEmpty(allYearData) &&
get(allYearData, `paths.${lPath}`) &&
!get(allYearData, `paths.${lPath}.missing`) &&
get(allYearData, `paths.${lPath}._totals.votes`) > 0 &&
get(allYearData, `paths.${lPath}._totals.proposals`) > 0
) {
const leafJson = {
yearData: allYearData,
holon: getAppRoute(false),
leafPath,
actualPath: lPath,
allPaths: nationPaths,
}
createLog(SINGLE_REPORT_PATH, `Writing to input jsons => ${fileName}.json`, leafPath)
await writeFile(`${getReportPath()}input_jsons/${fileName}.json`, leafJson)
createLog(SINGLE_REPORT_PATH, `Generating report for => ${fileName}`, leafPath)
await generatePDFReport(nation, 'ztReport', fileName, fromWorker)
return { report: `${fileName}.pdf` }
}
await generateNoVotePDFReport('ztReport', fileName, leafPath, getAppRoute(false), nationPaths, fromWorker)
return { report: `${fileName}.pdf` }
}
if (fs.existsSync(`${filePath}/${fileName}.pdf`)) {
return { report: `${fileName}.pdf` }
}
return { message: 'Issue not present' }
} catch (e) {
// eslint-disable-next-line no-console
console.log(`path: ${leafPath}`, e)
createLog(SINGLE_REPORT_PATH, `Exceptions in single report generation with Exception: ${e.message}`, leafPath)
createLog(
ERROR_PATH,
`calcEngineServices=>singleIssueReport()::Exceptions in single report generation for ${leafPath} with Exception: ${e.message}`
)
return { error: e.message }
} finally {
createLog(SINGLE_REPORT_PATH, `Deleting json file => ${fileName}`, leafPath)
await deleteJsonFile(fileName)
}
}
/**
* Get the avilable paths for report generation.
* All pdf files are named after the specific paths. It runs through all the paths passed as method params and create a tex file name based on path.
*/
const listAvailablePdfsPaths = (paths, path, fromWorker) => {
let availablePaths = []
const childrenKeys = difference(Object.keys(paths), ['metadata', 'parent'])
const regex = new RegExp(`^${reportsPath(fromWorker)}/([^\.]+).tex$`)
childrenKeys.forEach(childPath => {
const childData = paths[childPath]
const childFullPath = `${path}/${childPath}`
const childFile = childFullPath.replace(/\//g, '-')
const singleFile = `${singleIssueReportPath(fromWorker)}/${childFile}.tex`
const multiFile = `${multiIssueReportPath(fromWorker)}/${childFile}_full.tex`
if (get(childData, 'leaf') && fs.existsSync(singleFile)) {
const matches = singleFile.match(regex)
if (matches) {
availablePaths.push(matches[1].replace(/-/g, '/'))
}
} else if ((get(childData, 'metadata.umbrella') || get(childData, 'parent')) && fs.existsSync(multiFile)) {
availablePaths = [...availablePaths, ...listAvailablePdfsPaths(childData, childFullPath, fromWorker)]
}
})
return [`multiIssueReport/${path}`, ...availablePaths]
}
/**
* This method generates a umbrella report.
* Paths are either a umbrella or leaf path. Report for umbrella path is quite different than the leaft path.
*/
const multiIssuesReport = async (path, fromWorker = false) => {
// createLog(MULTI_REPORT_PATH, 'Multi report generation initiation......', path)
const fileName = `${path.replace(/\//g, '-')}`
try {
if (fromWorker || !fs.existsSync(`${multiIssueReportPath(fromWorker)}/${fileName}.pdf`)) {
const pathData = path.split('/')
const nation = pathData[0]
const noNationPath = pathData.slice(1).join('/')
const nationPaths = await pathsByNation(nation)
const allPaths = get(nationPaths, path.split('/').join('.'))
const availablePdfsPaths = listAvailablePdfsPaths(allPaths, path, fromWorker)
// let allYearData = { '2001': '' }
// TODO: uncomment this
const allYearData = await allYearCachedData(nation)
if (
!get(allYearData, `paths.${noNationPath}.missing`) ||
get(allYearData, `paths.${noNationPath}._totals.value_parent`) === 'children' ||
allPaths.parent
) {
const pathsJson = {
yearData: allYearData,
actualPath: path,
holon: getAppRoute(false),
allPaths: nationPaths,
subPaths: allPaths,
}
// createLog(MULTI_REPORT_PATH, `Writing to input jsons => ${fileName}.json`, path)
// TODO: uncomment this
await writeFile(`${getReportPath()}input_jsons/${fileName}.json`, pathsJson)
await generatePDFMultiReport('multiIssueReport', fileName, availablePdfsPaths, fromWorker)
return { report: `${fileName}.pdf` }
}
await generateNoVoteMultiPDFReport(
'multiIssueReport',
fileName,
path,
getAppRoute(false),
allPaths,
availablePdfsPaths,
fromWorker
)
return { report: `${fileName}.pdf` }
// return { message: 'No Issues for the path' }
}
if (fs.existsSync(`${multiIssueReportPath(fromWorker)}/${fileName}.pdf`)) {
return { report: `${fileName}.pdf` }
}
return { message: 'No Issues for the path' }
} catch (e) {
// createLog(MULTI_REPORT_PATH, `Exceptions in single report generation with Exception: ${e.message}`, path)
// createLog(ERROR_PATH, `calcEngineServices=>multiIssuesReport()::Exceptions in single report generation for ${path} with Exception: ${e.message}`)
// eslint-disable-next-line no-console
console.log(`path: ${path}`, e)
return { error: e.message }
} finally {
// createLog(MULTI_REPORT_PATH, `Deleting json file => ${fileName}`, path)
// TODO: uncomment this
await deleteJsonFile(fileName)
}
}
/**
* List all the tex file generated so far which is then used to generate a single tex file.
*/
const getTexsSequence = async (path, fromWorker) => {
const nation = path.split('/')[0]
const nationPaths = await pathsByNation(nation)
delete nationPaths.Alias
const childrens = get(nationPaths, path.replace(/\//g, '.'))
const childrenNodes = Object.keys(childrens)
//extract children of industries only
let industriesChildrens = []
childrenNodes.forEach(child => {
if (child === "industries") {
industriesChildrens = Object.keys(childrens[child])
}
})
childrenNodes.shift() // remove industries key
const allNodes = [...industriesChildrens, ...childrenNodes]
const childrenKeys = difference(allNodes, ['metadata', 'parent'])
const texsSequence = []
childrenKeys.forEach(childPath => {
let childData = childrens[childPath]
//If childPath is a child of industries then we treat them differently
if (industriesChildrens.includes(childPath)) {
childData = childrens["industries"][childPath]
childPath = `industries-${childPath}`
}
const childFile = `${path}/${childPath}`.replace(/\//g, '-')
const singleFile = `${singleIssueReportPath(fromWorker)}/${childFile}.tex`
const multiFile = `${multiIssueReportPath(fromWorker)}/${childFile}_full.tex`
if (get(childData, 'leaf') && fs.existsSync(singleFile)) {
texsSequence.push(singleFile)
} else if ((get(childData, 'metadata.umbrella') || get(childData, 'parent')) && fs.existsSync(multiFile)) {
texsSequence.push(multiFile)
}
})
const fileName = `${path.replace(/\//g, '-')}.tex`
const reportPathTex = `${multiIssueReportPath(fromWorker)}/${fileName}`
if (texsSequence.length > 0 || fs.existsSync(reportPathTex)) {
texsSequence.unshift(reportPathTex)
}
return texsSequence
}
/**
* Generate mixed report after merging umbrella node and the children nodes.
* It is generally invoked when generating reports for "industries","economic-crisis","tax","healthcare","pharma" and other umbrella nodes in future.
* But we donot need to generate reports for industries as this is parent node not actually an umbrella.
* It uses mixedReport.tex and generates a pdf.
*/
const multiIssuesFullReport = async (path, fromWorker = false) => {
// createLog(FULL_REPORT_PATH, `Full report generation initiation......`)
try {
const fullFileName = `${path.replace(/\//g, '-')}_full`
const filePath = multiIssueReportPath(fromWorker)
const reportExists = fs.existsSync(`${filePath}/${fullFileName}.pdf`)
if (fromWorker || !reportExists) {
await multiIssuesReport(path, fromWorker)
const texsSequence = await getTexsSequence(path, fromWorker)
// create full umbrealla report
await mergePdfLatex(fullFileName, texsSequence, fromWorker, getAppRoute(false))
return { report: `${fullFileName}.pdf` }
}
if (reportExists) {
return { report: `${fullFileName}.pdf` }
}
return { message: 'Full Umbrella Report Generation will take time. Come back later.' }
} catch (e) {
// createLog(FULL_REPORT_PATH, `Exceptions in full report generation for ${path} with Exception: ${e.message}`)
// createLog(ERROR_PATH, `calcEngineServices=>nationReport()::Exceptions in full report generation for ${path} with Exception: ${e.message}`)
return { error: e.message }
}
}
/**
* @dev Method generates full report of the nation
* @param {bool} fromWorker
* @param {string} nation
* @returns JSON will full report url
*/
const nationReport = async (fromWorker = false, nation = 'USA') => {
// createLog(FULL_REPORT_PATH, `Full report generation initiation......`)
try {
const fullFileName = `${nation}_full`
const reportExists = fs.existsSync(`${multiIssueReportPath(fromWorker)}/${fullFileName}.pdf`)
if (fromWorker || !reportExists) {
await multiIssuesReport(nation, fromWorker)
const texsSequence = await getTexsSequence(nation, fromWorker)
// create full nation report
await mergePdfLatex(fullFileName, texsSequence, fromWorker, getAppRoute(false))
return { report: `${fullFileName}.pdf` }
}
if (reportExists) {
return { report: `${fullFileName}.pdf` }
}
return { message: 'Full Country Report Generation will take time. Come back later.' }
} catch (e) {
// createLog(FULL_REPORT_PATH, `Exceptions in full report generation for ${nation} with Exception: ${e.message}`)
// createLog(ERROR_PATH, `calcEngineServices=>nationReport()::Exceptions in full report generation for ${nation} with Exception: ${e.message}`)
console.log(e)
return { error: e.message }
}
}
const theftInfo = async (fromWorker = false, nation = 'USA') => {
const exportFile = `${exportsDir}/calc_data/${nation}/calc_summary.json`
try {
const dataInCache = await cacheServer.getAsync(`CALC_SUMMARY_SYNCED`)
if (!fromWorker && (dataInCache || fs.existsSync(exportFile))) {
// if path has been sychrnoized and not from worker
// const result = await cacheServer.getAsync(nation)
const nationData = JSON.parse(fs.readFileSync(exportFile))
// = JSON.parse(result[nation])
const { paths } = nationData
// eslint-disable-next-line no-underscore-dangle
const agg = { [nation]: nationData._totals }
let allTheftYears = []
Object.keys(paths).forEach(path => {
// eslint-disable-next-line no-underscore-dangle
const totals = paths[path]._totals
if (totals.votes !== 0) {
agg[`${nation}/${path}`] = totals
}
allTheftYears = allTheftYears.concat(Object.keys(get(totals, 'voted_year_thefts', [])))
})
// check cache for past
// let yearTh = await getPastYearThefts(nation)
// if (yearTh.length == 0) throw new Error('no past thefts data in cache')
const minYr = min(allTheftYears)
const maxYr = max(allTheftYears)
// for (i = 0; i < yearTh.length; i++) {
// yr = yearTh[i]
// if (!minYr || parseInt(yr['Year']) < parseInt(minYr)) {
// minYr = parseInt(yr['Year'])
// } else {
// minYr = parseInt(minYr)
// }
// if (!maxYr || parseInt(yr['Year'])) {
// maxYr = parseInt(yr['Year'])
// } else {
// maxYr = parseInt(maxYr)
// }
// totalTh += yr['theft']
// }
agg.info = {}
agg.info.total = nationData._totals.theft
agg.info.last_year_theft = nationData._totals.last_year_theft
// agg['info']['each_year'] = nationData['_totals']['theft'] / usaPopulation(year)
// agg['info']['population'] = usaPopulation(year)
agg.info.many_years = nationData._totals.theft
agg.info.max_year = maxYr
agg.info.min_year = minYr
agg.info.between_years = maxYr - minYr + 1
agg.info.votes = nationData._totals.votes
agg.info.proposals = nationData._totals.proposals
// log the aggregated data in file inside exports directory
let exportFileData = {}
if (fs.existsSync(exportFile)) {
exportFileData = JSON.parse(fs.readFileSync(exportFile))
}
exportFileData.info = agg.info
await createAndWrite(`${exportsDir}/calc_data/${nation}`, `calc_summary.json`, exportFileData)
// If data is not in redis cache then run in background
if (!dataInCache) {
dataCachingPerPath(nation) // Background task for processing and saving data into cache
}
return agg
}
const response = dataCachingPerPath(nation) // Background task for processing and saving data into cache
createLog(MAIN_PATH, `Background task for processing and saving data into cache for ${nation}`)
return response
} catch (e) {
console.log(e)
createLog(ERROR_PATH, `calcEngineServices=>theftInfo()::Exception occurs in theftInfo with ${e.message}`)
return { error: e.message }
}
}
/**
* Reports are generated in every 4 hours. No reports are purged or deleted. Report generation always takes time.
* Util report generation is completed in progress reports are kept in different directory as `reports_in_progress` and then directory name is changed to `reports`
*/
const setupForReportsInProgress = () => {
const time = new Date()
const reportPath = `${exportsDir}/${time.getFullYear()}/${time.getMonth() + 1
}/${time.getDate()}/${time.getHours()}_hrs_${time.getMinutes()}_mins_${time.getSeconds()}_secs/reports`
// const reportPath = `${exportsDir}/${time.getFullYear()}/${time.getMonth()}/${time.getDate()}/reports`
fs.mkdirSync(`${reportPath}/multiIssueReport`, { recursive: true })
fs.mkdirSync(`${reportPath}/ztReport`, { recursive: true })
const symLinkPath = `${config.APP_PATH}/zt_report/reports_in_progress`
try {
fs.unlinkSync(symLinkPath)
} catch (e) { }
fs.symlinkSync(reportPath, symLinkPath, 'dir')
}
/**
* When report generation is complete then `reports_in_progress` is then changed to `reports` and served in holon UI
*/
const setupForReportsDirs = (replaceDirs = true) => {
const symLinkPath = `${config.APP_PATH}/zt_report/reports_in_progress`
const currentReportsSymLinkPath = `${config.APP_PATH}/zt_report/reports`
if (!(replaceDirs || !fs.existsSync(currentReportsSymLinkPath))) return
if (!fs.existsSync(symLinkPath)) {
setupForReportsInProgress()
}
const reportPath = fs.realpathSync(symLinkPath)
try {
fs.unlinkSync(currentReportsSymLinkPath)
} catch (e) { }
fs.symlinkSync(reportPath, currentReportsSymLinkPath, 'dir')
}
module.exports = {
allYearCachedData,
singleIssueReport,
multiIssuesReport,
theftInfo,
nationReport,
multiIssuesFullReport,
setupForReportsInProgress,
setupForReportsDirs,
}
|
ryanb93/newrelic-java-agent | newrelic-agent/src/main/java/com/newrelic/agent/normalization/Normalizer.java | /*
*
* * Copyright 2020 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package com.newrelic.agent.normalization;
import java.util.List;
public interface Normalizer {
/**
* Normalize the given name.
*
* @return either null for ignore; the given name if not normalized; or the normalized name
*/
String normalize(String name);
/**
* For testing.
*/
List<NormalizationRule> getRules();
} |
Solidstatewater/Anubis-Engine | Graphics/install-sh/include/sh/ShSwizzle.hpp | <gh_stars>1-10
// Sh: A GPU metaprogramming language.
//
// Copyright (c) 2003 University of Waterloo Computer Graphics Laboratory
// Project administrator: <NAME>
// Authors: <NAME>, <NAME>, <NAME>, <NAME>,
// <NAME>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must
// not claim that you wrote the original software. If you use this
// software in a product, an acknowledgment in the product documentation
// would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//////////////////////////////////////////////////////////////////////////////
#ifndef SHSWIZZLE_HPP
#define SHSWIZZLE_HPP
#include <iosfwd>
//#include <vector>
#include "ShDllExport.hpp"
#include "ShException.hpp"
namespace SH {
/** Represents swizzling of a variable.
* Swizzling takes at least one element from an n-tuple and in
* essence makes a new n-tuple with those elements in it. To actually
* perform a swizzle using Sh, you should use the operator() on the
* variable you are swizzling. This class is internal to Sh.
*
* Swizzles can be combined ("swizzle algebra") using the
* operator*(). This class currently only supports host-time constant
* swizzles, ie. you cannot use shader variables to specify swizzling
* order.
*
* This class is also used for write masks, at least at the
* intermediate level.
*
* Note that, at the moment, when combining swizzles indices are
* checked to be sane, but original indices are not checked for
* sanity, since currently swizzles don't know anything about (in
* particular the size of) the tuple which they are swizzling.
*/
class
SH_DLLEXPORT
ShSwizzle {
public:
// Null swizzle
ShSwizzle();
/// Identity swizzle: does nothing at all.
ShSwizzle(int srcSize);
/// Use one element from the original tuple.
ShSwizzle(int srcSize, int i0);
/// Use two elements from the original tuple.
ShSwizzle(int srcSize, int i0, int i1);
/// Use three elements from the original tuple.
ShSwizzle(int srcSize, int i0, int i1, int i2);
/// Use four elements from the original tuple.
ShSwizzle(int srcSize, int i0, int i1, int i2, int i3);
/// Use an arbitrary number of elements from the original tuple.
ShSwizzle(int srcSize, int size, int* indices);
ShSwizzle(const ShSwizzle& other);
~ShSwizzle();
ShSwizzle& operator=(const ShSwizzle& other);
/// Combine a swizzle with this one, as if it occured after this
/// swizzle occured.
ShSwizzle& operator*=(const ShSwizzle& other);
/// Combine two swizzles with left-to-right precedence.
ShSwizzle operator*(const ShSwizzle& other) const;
/// Determine how many elements this swizzle results in.
int size() const { return m_size; }
/// Obtain the index of the \a i'th element. 0 <= i < size().
/// This is int so that printing out the result won't give something
/// weird
int operator[](int i) const;
/// Determine whether this is an identity swizzle.
bool identity() const;
/// Determine whether two swizzles are identical
bool operator==(const ShSwizzle& other) const;
private:
// copies the other swizzle's elements
void copy(const ShSwizzle &other, bool islocal);
// throws an exception if index < 0 or index >= m_srcSize
void checkSrcSize(int index);
// allocates the m_indices array to current m_size
// returns true
bool alloc();
// deallocates the m_indices array
void dealloc();
// returns whether we're using local
bool local() const;
// returns the identity swiz value on this machine
int idswiz() const;
// Declare these two first so alignment problems don't make the ShSwizzle struct larger
int m_srcSize;
int m_size;
// when srcSize <= 255 and size <= 4, use local.
// local is always initialized to 0x03020101, so identity comparison is
// just an integer comparison using intval
union {
unsigned char local[4];
int intval;
int* ptr;
} m_index;
friend SH_DLLEXPORT std::ostream& operator<<(std::ostream& out, const ShSwizzle& swizzle);
};
/// Thrown when an invalid swizzle is specified (e.g. an index in the
/// swizzle is out of range).
class
SH_DLLEXPORT ShSwizzleException : public ShException
{
public:
ShSwizzleException(const ShSwizzle& s, int idx, int size);
};
}
#include "ShSwizzleImpl.hpp"
#endif
|
kkkkv/tgnms | tgnms/fbcnms-projects/tgnms/app/components/taskBasedConfig/__tests__/ConfigTaskForm-test.js | <gh_stars>10-100
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*
* @format
* @flow strict-local
*/
import * as React from 'react';
import ConfigTaskForm from '../ConfigTaskForm';
import {FORM_CONFIG_MODES} from '@fbcnms/tg-nms/app/constants/ConfigConstants';
import {TestApp, renderAsync} from '@fbcnms/tg-nms/app/tests/testHelpers';
import {act, fireEvent, render} from '@testing-library/react';
const defaultProps = {
title: 'testTitle',
description: 'test description',
editMode: FORM_CONFIG_MODES.NETWORK,
onClose: jest.fn(),
};
beforeEach(() => {
jest
.spyOn(require('@fbcnms/tg-nms/app/hooks/useNodeConfig'), 'useNodeConfig')
.mockReturnValue({
loading: false,
configData: [{field: ['test', 'param']}],
configParams: {nodeOverridesConfig: {}, networkOverridesConfig: {}},
reloadConfig: jest.fn(),
});
});
test('renders loading initially', () => {
jest
.spyOn(require('@fbcnms/tg-nms/app/hooks/useNodeConfig'), 'useNodeConfig')
// using mockReturnValue. this can render multiple times before we query it
.mockReturnValue({
loading: true,
configData: [{field: ['test', 'param']}],
configParams: {},
});
const {getByTestId} = render(
<TestApp>
<ConfigTaskForm {...defaultProps}>test</ConfigTaskForm>
</TestApp>,
);
expect(getByTestId('loading-box')).toBeInTheDocument();
});
test('renders after loading without crashing', async () => {
const {getByText} = await renderAsync(
<TestApp>
<ConfigTaskForm {...defaultProps}>test</ConfigTaskForm>
</TestApp>,
);
expect(getByText('test')).toBeInTheDocument();
});
test('renders with network props', async () => {
const {getByText} = await renderAsync(
<TestApp>
<ConfigTaskForm showSubmitButton={true} {...defaultProps}>
test
</ConfigTaskForm>
</TestApp>,
);
expect(getByText('test')).toBeInTheDocument();
});
test('renders with node props', async () => {
const {getByText} = await renderAsync(
<TestApp>
<ConfigTaskForm
{...defaultProps}
mode={FORM_CONFIG_MODES.NODE}
nodeName="testNodeName">
test
</ConfigTaskForm>
</TestApp>,
);
expect(getByText('test')).toBeInTheDocument();
});
test('cancel calls onClose if its a modal', async () => {
const {getByText} = await renderAsync(
<TestApp>
<ConfigTaskForm {...defaultProps} showSubmitButton={true}>
test
</ConfigTaskForm>
</TestApp>,
);
expect(getByText('Cancel')).toBeInTheDocument();
act(() => {
fireEvent.click(getByText('Cancel'));
});
expect(defaultProps.onClose).toHaveBeenCalled();
});
|
bialang/bia | bia/util/contract.hpp | <gh_stars>1-10
#ifndef BIA_UTIL_CONTRACT_HPP_
#define BIA_UTIL_CONTRACT_HPP_
#include "config.hpp"
#if BIA_UTIL_CONTRACT_BEHAVIOR_THROW
# include <bia/error/contract_violation.hpp>
# define BIA_ASSERT(cond) \
if (!(cond)) \
throw bia::error::Contract_violation("assertion ( " #cond " ) was violated", BIA_CURRENT_SOURCE_LOCATION)
# define BIA_EXPECTS(cond) \
if (!(cond)) \
throw bia::error::Contract_violation("precondition ( " #cond " ) was violated", \
BIA_CURRENT_SOURCE_LOCATION)
# define BIA_ENSURES(cond) \
if (!(cond)) \
throw bia::error::Contract_violation("postcondition ( " #cond " ) was violated", \
BIA_CURRENT_SOURCE_LOCATION)
#elif BIA_UTIL_CONTRACT_BEHAVIOR_ABORT
# include <cstdlib>
# define BIA_ASSERT(cond) \
if (!(cond)) \
std::abort()
# define BIA_EXPECTS(cond) \
if (!(cond)) \
std::abort()
# define BIA_ENSURES(cond) \
if (!(cond)) \
std::abort()
#else
# define BIA_ASSERT(cond) ((void) 0)
# define BIA_EXPECTS(cond) ((void) 0)
# define BIA_ENSURES(cond) ((void) 0)
#endif
#endif
|
nfp-projects/isaland_mail | test/user/routes.test.js | <reponame>nfp-projects/isaland_mail
import assert from 'assert-extended'
import sinon from 'sinon'
import 'sinon-as-promised'
import { model } from '../helper.db'
describe('User (Routes)', () => {
const routes = require('../../server/user/routes')
const User = require('../../server/user/model').default
let ctx
let sandbox
let testUser
beforeEach(() => {
sandbox = sinon.sandbox.create()
ctx = {
request: { body: {} },
body: null,
redirect: sandbox.spy(),
}
})
afterEach(() => {
sandbox.restore()
})
describe('#deleteUser()', () => {
let stubGetSingle
let dateNow
beforeEach(() => {
stubGetSingle = sandbox.stub(User, 'getSingle')
dateNow = new Date().getTime()
})
it('should fetch user and fail if too long has passed', async () => {
const assertId = '123'
const assertEmail = '<EMAIL>'
testUser = model(sandbox, 'domain', {
id: assertId,
email: assertEmail,
created: new Date(dateNow - 1000 * 60 * 60 * 24 - 1),
})
stubGetSingle.resolves(testUser)
ctx.request.body.id = assertId
let err = await assert.isRejected(routes.deleteUser(ctx))
assert.strictEqual(stubGetSingle.firstCall.args[0], assertId)
assert.notOk(testUser.remove.called)
assert.match(err.message, /delete/)
assert.match(err.message, new RegExp(assertEmail))
})
it('delete errors should propogate', async () => {
const assertError = new Error('testety')
testUser = model(sandbox, 'domain', {
created: new Date(),
})
stubGetSingle.resolves(testUser)
testUser.remove.rejects(assertError)
let err = await assert.isRejected(routes.deleteUser(ctx))
assert.strictEqual(err, assertError)
})
it('should delete user if within 24 hours', async () => {
testUser = model(sandbox, 'domain', {
created: new Date(dateNow - 1000 * 60 * 60 * 24 + 2000),
})
stubGetSingle.resolves(testUser)
await assert.isFulfilled(routes.deleteUser(ctx))
assert.ok(testUser.remove.called)
assert.ok(ctx.redirect.called)
assert.strictEqual(ctx.redirect.firstCall.args[0], '/')
})
})
describe('#createUser()', () => {
let stubCreate
beforeEach(() => {
stubCreate = sandbox.stub(User, 'create')
ctx.request.body = {
email: '<EMAIL>',
password: '<PASSWORD>',
}
})
it('should fail if body does not have correct email format', async () => {
delete ctx.request.body.email
await assert.isRejected(routes.createUser(ctx))
ctx.request.body.email = ''
await assert.isRejected(routes.createUser(ctx))
ctx.request.body.email = 'testety'
await assert.isRejected(routes.createUser(ctx))
})
it('should fail if password is not defined or too short', async () => {
delete ctx.request.body.password
await assert.isRejected(routes.createUser(ctx))
ctx.request.body.password = ''
await assert.isRejected(routes.createUser(ctx))
ctx.request.body.password = '<PASSWORD>'
await assert.isRejected(routes.createUser(ctx))
})
it('create errors should propogate', async () => {
const assertError = new Error('bla bla')
stubCreate.rejects(assertError)
let err = await assert.isRejected(routes.createUser(ctx))
assert.strictEqual(err, assertError)
})
it('should otherwise call create and redirect', async () => {
const assertPassword = '<PASSWORD>'
ctx.request.body.password = <PASSWORD>
await assert.isFulfilled(routes.createUser(ctx))
assert.ok(stubCreate.called)
assert.notStrictEqual(assertPassword, ctx.request.body.password)
assert.deepEqual(stubCreate.firstCall.args[0], ctx.request.body)
assert.ok(ctx.redirect.called)
assert.strictEqual(ctx.redirect.firstCall.args[0], '/')
})
})
})
|
defunSM/code | c++/object.h | <reponame>defunSM/code
#ifndef _object_h
#define _object_h
typedef enum {
NORTH, SOUTH, EAST, WEST
} Direction;
typedef struct {
char *description;
int (*init)(void *self);
void (*describe)(void *self);
void (*destroy)(void *self);
void *(*move)(void *self, Direction direction);
int (*attack)(void *self, int damage);
} Object;
int Object_init(void *self);
void Object_destroy(void *self);
void Object_describe(void *self);
void *Object_move(void *self, Direction direction);
int Object_attack(void *self, int damage);
void *Object_new(size_t size, Object proto, char *description);
#define NEW(T, N) Object_new(sizeof(T), T##Proto, N)
#define _(N) proto.N
#endif
|
cuipy/tijian | src/main/java/com/thinkgem/jeesite/modules/sys/entity/SysSequence.java | <filename>src/main/java/com/thinkgem/jeesite/modules/sys/entity/SysSequence.java<gh_stars>0
/**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.sys.entity;
import com.thinkgem.jeesite.common.persistence.DataEntity;
/**
* 系统编号对象实体
* @author cuipengyu
* @version 2018-03-20
*/
public class SysSequence extends DataEntity<SysSequence> {
private static final long serialVersionUID = 1L;
/**
* 序列编号表达式
*/
private String express;
private String seqTemp;
private Integer seqVal;
public SysSequence(){
super();
}
public SysSequence(String id){
super(id);
}
public String getExpress() {
return express;
}
public void setExpress(String express) {
this.express = express;
}
public String getSeqTemp() {
return seqTemp;
}
public void setSeqTemp(String seqTemp) {
this.seqTemp = seqTemp;
}
public Integer getSeqVal() {
return seqVal;
}
public void setSeqVal(Integer seqVal) {
this.seqVal = seqVal;
}
} |
ezgikaysi/koding | go/src/socialapi/workers/notification/models/replynotification.go | package models
import (
"time"
)
type ReplyNotification struct {
TargetId int64
ListerId int64
MessageId int64
NotifierId int64
}
func (n *ReplyNotification) GetNotifiedUsers(notificationContentId int64) ([]int64, error) {
// fetch all subscribers
notifiees, err := fetchNotifiedUsers(notificationContentId)
if err != nil {
return nil, err
}
filteredNotifiees := make([]int64, 0)
// append subscribed users and regress notifier
for _, accountId := range notifiees {
if accountId != n.NotifierId {
filteredNotifiees = append(filteredNotifiees, accountId)
}
}
return filteredNotifiees, nil
}
func (n *ReplyNotification) GetType() string {
return NotificationContent_TYPE_COMMENT
}
func (n *ReplyNotification) GetTargetId() int64 {
return n.TargetId
}
func (n *ReplyNotification) SetTargetId(targetId int64) {
n.TargetId = targetId
}
func (n *ReplyNotification) FetchActors(naList []NotificationActivity) (*ActorContainer, error) {
if len(naList) == 0 {
return NewActorContainer(), nil
}
notification := NewNotification()
notification.NotificationContentId = naList[0].NotificationContentId
notification.AccountId = n.ListerId
if err := notification.FetchByContent(); err != nil {
return nil, err
}
if notification.UnsubscribedAt.Equal(ZeroDate()) {
notification.UnsubscribedAt = time.Now().UTC()
}
actors := make([]int64, 0)
actorMap := map[int64]struct{}{}
for _, na := range naList {
_, ok := actorMap[na.ActorId]
if !ok && na.ActorId != n.ListerId && !na.Obsolete &&
na.CreatedAt.After(notification.SubscribedAt) &&
na.CreatedAt.Before(notification.UnsubscribedAt) {
actors = append(actors, na.ActorId)
actorMap[na.ActorId] = struct{}{}
}
}
return prepareActorContainer(actors), nil
}
func (n *ReplyNotification) SetListerId(listerId int64) {
n.ListerId = listerId
}
func (n *ReplyNotification) GetActorId() int64 {
return n.NotifierId
}
func (n *ReplyNotification) SetActorId(actorId int64) {
n.NotifierId = actorId
}
func NewReplyNotification() *ReplyNotification {
return &ReplyNotification{}
}
func (n *ReplyNotification) GetDefinition() string {
return NotificationContent_TYPE_COMMENT
}
func (n *ReplyNotification) GetActivity() string {
if n.ListerId == n.NotifierId {
return "commented on your"
}
return "also commented on"
}
func (n *ReplyNotification) GetMessageId() int64 {
return n.MessageId
}
|
GenaAiv/portfolio-website | node_modules/@material-ui/utils/refType.js | <filename>node_modules/@material-ui/utils/refType.js
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _propTypes = _interopRequireDefault(require("prop-types"));
var refType = _propTypes.default.oneOfType([_propTypes.default.func, _propTypes.default.object]);
var _default = refType;
exports.default = _default; |
filipecn/helios | helios/geometry/animated_transform.cpp | // Created by filipecn on 2019-01-06.
/*
* Copyright (c) 2019 FilipeCN
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "animated_transform.h"
namespace helios {
/*
AnimatedTransform::AnimatedTransform(const HTransform *t1, real_t time1,
const HTransform *t2, real_t time2)
: startTime(time1), endTime(time2), startTransform(t1), endTransform(t2),
actuallyAnimated(*startTransform != *endTransform) {
decompose(startTransform->matrix(), &T[0], &R[0], &S[0]);
decompose(endTransform->matrix(), &T[1], &R[1], &S[1]);
// flip R[1] if needed to select shortest path
if (ponos::dot(R[0], R[1]) < 0)
R[1] = -R[1];
hasRotation = ponos::dot(R[0], R[1]) < 0.9995f;
// compute terms of motion derivative functions
}
AnimatedTransform::~AnimatedTransform() {}
void AnimatedTransform::decompose(const ponos::mat4 &m, ponos::vec3 *T,
ponos::Quaternion *Rquat, ponos::mat4 *s) {
// extract translation T from transformation matrix
T->x = m.m[0][3];
T->y = m.m[1][3];
T->z = m.m[2][3];
// compute new transformation matrix M without translation
ponos::mat4 M = m;
for (int i = 0; i < 3; i++)
M.m[i][3] = M.m[3][i] = 0.f;
M.m[3][3] = 1.f;
ponos::mat4 r;
// extract rotation R from transformation matrix
// and scale S
ponos::decompose(M, r, *s);
*Rquat = ponos::Quaternion(r);
}
*/
} // namespace helios |
Dr-Turtle/DRG_ModPresetManager | Source/FSD/Private/StatusEffectsFunctionLibrary.cpp | <gh_stars>1-10
#include "StatusEffectsFunctionLibrary.h"
#include "Templates/SubclassOf.h"
class UStatusEffect;
class UDamageClass;
class AActor;
float UStatusEffectsFunctionLibrary::GetMaxResistance(TSubclassOf<UStatusEffect> StatusEffect) {
return 0.0f;
}
UDamageClass* UStatusEffectsFunctionLibrary::GetDamageClass(TSubclassOf<UStatusEffect> StatusEffect) {
return NULL;
}
bool UStatusEffectsFunctionLibrary::CanTrigger(TSubclassOf<UStatusEffect> StatusEffect, AActor* OtherActor) {
return false;
}
UStatusEffectsFunctionLibrary::UStatusEffectsFunctionLibrary() {
}
|
lintonv/aws-sdk-cpp | aws-cpp-sdk-lightsail/source/model/InstanceNetworking.cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/lightsail/model/InstanceNetworking.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Lightsail
{
namespace Model
{
InstanceNetworking::InstanceNetworking() :
m_monthlyTransferHasBeenSet(false),
m_portsHasBeenSet(false)
{
}
InstanceNetworking::InstanceNetworking(JsonView jsonValue) :
m_monthlyTransferHasBeenSet(false),
m_portsHasBeenSet(false)
{
*this = jsonValue;
}
InstanceNetworking& InstanceNetworking::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("monthlyTransfer"))
{
m_monthlyTransfer = jsonValue.GetObject("monthlyTransfer");
m_monthlyTransferHasBeenSet = true;
}
if(jsonValue.ValueExists("ports"))
{
Array<JsonView> portsJsonList = jsonValue.GetArray("ports");
for(unsigned portsIndex = 0; portsIndex < portsJsonList.GetLength(); ++portsIndex)
{
m_ports.push_back(portsJsonList[portsIndex].AsObject());
}
m_portsHasBeenSet = true;
}
return *this;
}
JsonValue InstanceNetworking::Jsonize() const
{
JsonValue payload;
if(m_monthlyTransferHasBeenSet)
{
payload.WithObject("monthlyTransfer", m_monthlyTransfer.Jsonize());
}
if(m_portsHasBeenSet)
{
Array<JsonValue> portsJsonList(m_ports.size());
for(unsigned portsIndex = 0; portsIndex < portsJsonList.GetLength(); ++portsIndex)
{
portsJsonList[portsIndex].AsObject(m_ports[portsIndex].Jsonize());
}
payload.WithArray("ports", std::move(portsJsonList));
}
return payload;
}
} // namespace Model
} // namespace Lightsail
} // namespace Aws
|
mzhg/PostProcessingWork | parsing/src/main/java/jet/parsing/cplus/ue4/UE4HeaderParser.java | package jet.parsing.cplus.ue4;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import jet.opengl.postprocessing.util.DebugTools;
import jet.opengl.postprocessing.util.StringUtils;
public class UE4HeaderParser {
public static void main(String[] args){
String source = UPROPERTYParser.getTextFromClipBoard();
List<Object> results = parseSourceCode(source);
printMembers(results);
}
private static List<Object> parseSourceCode(String source){
List<Object> results = new ArrayList<>();
int offset = 0;
final int length = source.length();
String globalModifier = "public";
List<String> comments = new ArrayList<>();
List<String> processers = new ArrayList<>(); // #if
while (offset < length && offset >=0){
offset = StringUtils.firstNotEmpty(source, offset);
// Parseing the global modifer.
while (offset >= 0 && isModifer(source, offset)){
globalModifier = getModifer(source, offset);
offset +=globalModifier.length() + 1;
offset = StringUtils.firstNotEmpty(source, offset);
}
// Parsing the comments.
int commentEnd;
while (offset >= 0 && (commentEnd = UPROPERTYParser.isDocument(source, offset)) > 0){
String comment = UPROPERTYParser.parseDocument(source, offset, commentEnd);
comments.add(comment);
offset = commentEnd + 2;
offset = StringUtils.firstNotEmpty(source, offset);
}
// parsing the processors.
while (offset >= 0 && isProcessor(source, offset)){
offset = source.indexOf('\n', offset); // go the line end
if(offset < 0)
offset = source.length();
offset = StringUtils.firstNotEmpty(source, offset);
}
// parsing the methods.
int methodEnd;
while (offset >= 0 && (methodEnd = isMethod(source, offset)) > 0){
UMethod method = parsingMethod(source, offset, methodEnd);
method.modifier = globalModifier;
method.documents = combineComments(comments);
results.add(method);
offset = StringUtils.firstNotEmpty(source, methodEnd+1);
}
int fieldEnd;
while (offset >= 0 && (fieldEnd = isField(source, offset)) > 0 ){
UField field = parseingField(source, offset, fieldEnd);
field.modifier = globalModifier;
field.documents = combineComments(comments);
results.add(field);
offset = StringUtils.firstNotEmpty(source, fieldEnd+1);
}
}
return results;
}
private static boolean isModifer(String source, int offset){
if(source.startsWith("public", offset)){
return true;
}
if(source.startsWith("protected", offset)){
return true;
}
if(source.startsWith("private", offset)){
return true;
}
return false;
}
private static String getModifer(String source, int offset){
int end = source.indexOf(':', offset);
if(end < 0)
throw new IllegalStateException("Inner error");
return source.substring(offset, end);
}
private static boolean isProcessor(String source, int offset){
if(source.startsWith("#", offset)){
offset = StringUtils.firstNotEmpty(source, offset);
if(source.startsWith("if",offset) || source.startsWith("else",offset) || source.startsWith("endif",offset)){
return true;
}
if(source.startsWith("#include")){
// unable to parsint the include processor.
int end = source.indexOf('\n', offset);
if(end < 0)
end = source.length();
throw new IllegalStateException("Unable to handle the include procssor : "+ source.substring(offset, end));
}
}
return false;
}
private static int isMethod(String source, int offset){
if(isModifer(source, offset) || isComments(source, offset) || isProcessor(source, offset))
return -1;
final int leftBrackt = StringUtils.indexOfWithComments(source, offset, '(');
if(leftBrackt < 0)
return -1;
final int end = StringUtils.indexOfWithComments(source, offset, ';');
if(end < 0 || leftBrackt < end){
// We got a method.
final int rightBrackt = StringUtils.findEndBrackek('(', ')',source, leftBrackt);
if(rightBrackt < 0)
throw new IllegalArgumentException("Invalid source");
final int startBrackt = StringUtils.indexOfWithComments(source, rightBrackt+1, '{');
if(startBrackt > 0 && startBrackt < end){
// may be the body of the method. But need to check.
String token = StringUtils.removeComments(source.substring(rightBrackt + 1, startBrackt)).trim();
if(token.isEmpty() || token.equals("const")){
// Yes we found a method.
return StringUtils.findEndBrackek('{','}', source, startBrackt) + 1;
}
}else{
// There is no '{', may be it's a pure virtual method.
if(end < 0){
// no ';' found
return -1;
}else{
if(rightBrackt + 1 == end){
// This is no space between the ');'
return end;
}
String token = StringUtils.removeComments(source.substring(rightBrackt + 1, end)).trim();
token = StringUtils.removeBlank(token); // remove all of the blanks
if(token.isEmpty() || token.equals("=0") || token.equals("const=0")){
return end;
}
}
}
}
return -1;
}
private static UMethod parsingMethod(String source, int offset, int end){
final String methodContent = StringUtils.removeComments(source.substring(offset, end)).trim();
final int leftBrackt = StringUtils.indexOfWithComments(methodContent, 0, '(');
if(leftBrackt < 0)
throw new IllegalStateException("Inner error!");
// Get the method name
int blankIndex = StringUtils.lastSpecifedCharacter(methodContent, " >", leftBrackt-1);
if(blankIndex < 0 )
throw new IllegalStateException("Inner error!");
String methodName = StringUtils.removeComments(methodContent.substring(blankIndex+1, leftBrackt));
// Get the type name
String typeStr = methodContent.substring(0, blankIndex).trim();
boolean isInline = typeStr.contains("inline");
boolean isVoid = typeStr.contains("void");
boolean isSingleWorld = typeStr.indexOf(' ') > 0 || typeStr.indexOf('<') > 0|| typeStr.indexOf('>') > 0;
boolean isVirtual = typeStr.contains("virtual");
// Get the parameters
final int rightBrackt = StringUtils.findEndBrackek('(', ')',methodContent, leftBrackt);
final String paramContent = methodContent.substring(leftBrackt+1, rightBrackt).trim();
List<UField> uFields = parsingParameters(paramContent);
// Get the body of method.
int startBracket = methodContent.indexOf('{');
String methodBody = null;
if(startBracket < 0){
// no body
}else{
int endBracket = StringUtils.findEndBrackek('{', '}', methodContent, startBracket);
methodBody = methodContent.substring(startBracket+1, endBracket);
}
UMethod method = new UMethod();
method.body = methodBody;
method.returnType = typeStr;
method.parameters = uFields;
method.name = methodName;
return method;
}
private static List<UField> parsingParameters(String paramContent){
if(StringUtils.isBlank(paramContent) || paramContent.equals("void")){
return Collections.emptyList();
}
List<UField> uFields = new ArrayList<>();
int lastCursor = 0;
int cursor = 0;
while (cursor < paramContent.length() && cursor >= 0){
cursor = StringUtils.firstNotEmpty(paramContent, cursor);
// first we need to find the single paramter token
String token = null;
boolean foundEqual = false;
for(int i = cursor; i < paramContent.length(); i++){
final char c = paramContent.charAt(i);
if(c == '='){
if(foundEqual)
throw new IllegalArgumentException("Invalid paramContent: " + paramContent);
foundEqual = true;
}else if(c == '(' || c =='<'){
final char endChar = c == '(' ? ')' : '>';
// go to the end
int endBrackek = StringUtils.findEndBrackek(c, endChar, paramContent, i);
if(endBrackek < 0)
throw new IllegalArgumentException("Invalid paramContent: " + paramContent.substring(i));
i = endBrackek +1;
continue;
}else if(c == ','){
// we got a token, stopping the loop
cursor = i+1;
token = paramContent.substring(lastCursor, i).trim();
lastCursor = cursor;
break;
}
}
if(token == null){
int blankIndex = paramContent.lastIndexOf(' ');
if(blankIndex > lastCursor && blankIndex > cursor){
token = paramContent.substring(lastCursor);
cursor = paramContent.length(); // goto the end
}
}
// parsing the parameter
if(token != null){
String defualtValue = null;
if(foundEqual){
// Parsing the value
String[] tokens = StringUtils.split(token, "=");
defualtValue = tokens[1].trim();
token = tokens[0].trim();
if(StringUtils.isBlank(token))
throw new IllegalStateException("Inner error!");
}
// parsing the type and varname
String type;
String name;
char splitChar = ' ';
int blankIndex = token.lastIndexOf(splitChar);
if(blankIndex < 0){
// It's a generic type
blankIndex = token.lastIndexOf('>');
if(blankIndex < 0)
throw new IllegalStateException("Invalid parameter: " + token);
}
type = token.substring(0, blankIndex).trim();
name = token.substring(blankIndex+1).trim();
UField uField = new UField();
uField.documents = null;
uField.isParameter = true;
uField.modifier= null;
uField.name = name;
uField.type = type;
uField.defualtValue = defualtValue;
uFields.add(uField);
}
}
return uFields;
}
static boolean isComments(String source, int offset){
if(source.startsWith("/*", offset)){
return true;
}
if(source.startsWith("//", offset)){
return true;
}
return false;
}
private static int isField(String source, int offset){
if(isModifer(source, offset) || isComments(source, offset) || isProcessor(source, offset))
return -1;
if(isMethod(source, offset) >= 0)
return -1;
int end = StringUtils.indexOfWithComments(source,offset,';');
if(end < 0)
return -1;
return end;
}
private static UField parseingField(String source, int offset, int end){
final String fieldContent = StringUtils.removeComments(source.substring(offset, end)).trim();
String defualtValue = null;
String token = fieldContent;
int foundEqual = fieldContent.indexOf('=');
if(foundEqual > 0){
// Parsing the value
String[] tokens = StringUtils.split(fieldContent, "=");
defualtValue = tokens[1].trim();
token = tokens[0].trim();
if(StringUtils.isBlank(token))
throw new IllegalStateException("Inner error!");
}
// parsing the type and varname
String type;
String name;
char splitChar = ' ';
int blankIndex = token.lastIndexOf(splitChar);
if(blankIndex < 0){
// It's a generic type
blankIndex = token.lastIndexOf('>');
if(blankIndex < 0)
throw new IllegalStateException("Invalid parameter: " + token);
}
type = token.substring(0, blankIndex).trim();
name = token.substring(blankIndex+1).trim();
UField uField = new UField();
uField.name = name;
uField.type = type;
uField.defualtValue = defualtValue;
return uField;
}
private static String combineComments(List<String> comments){
if(comments.isEmpty())
return null;
StringBuilder sb = new StringBuilder();
for(String source : comments){
String[] tokens = StringUtils.split(source, "\n");
for(String s : tokens){
int startIndex = StringUtils.firstNotEmpty(s);
if(startIndex < 0)
continue;
if(s.startsWith("* ", startIndex)){
sb.append(s.substring(startIndex+2));
}else{
sb.append(s.substring(startIndex));
}
sb.append('\n');
}
}
if(sb.length() > 0){
sb.setLength(sb.length());
}
comments.clear();
return sb.toString();
}
private static void printMembers(List<Object> members){
for (Object m : members){
if(m instanceof UField){
System.out.println(makeFieldStr((UField)m));
}else{
System.out.println(makeMethodStr((UMethod)m));
}
}
}
private static String makeFieldStr(UField field){
StringBuilder sb = new StringBuilder();
UPROPERTYParser.makeCommentStr(sb, field.documents);
UPROPERTYParser.makeStr(sb, field.type, field.name, field.defualtValue);
return sb.toString();
}
private static String makeMethodStr(UMethod method){
StringBuilder sb = new StringBuilder();
UPROPERTYParser.makeCommentStr(sb, method.documents);
sb.append('\t');
if(method.modifier != null)
sb.append(method.modifier).append(' ');
if(!StringUtils.isBlank(method.returnType)) {
// sb.append(method.returnType);
UPROPERTYParser.makeReadWriteType(sb, method.returnType);
sb.append(' ');
}
sb.append(method.name).append('(');
FieldTypeDesc desc = new FieldTypeDesc();
if(method.parameters != null){
for(UField field : method.parameters){
parsingFileType(field.type, desc);
if(UPROPERTYParser.isIngoreType(desc.javaType)){
// TODO
}else{
sb.append(makeParameterTypeStr(desc)).append(' ').append(field.name);
if(field.defualtValue != null){
sb.append("/* = ").append(field.defualtValue).append("*/");
}
sb.append(',');
sb.append(' ');
}
}
if(!method.parameters.isEmpty())
sb.setLength(sb.length() - 2);
sb.append(')');
}
sb.append('{').append('\n');
if(!StringUtils.isEmpty(method.body) && !StringUtils.isBlank(method.body)){
sb.append(method.body);
}else{
sb.append("\t\tthrow new UnsupportedOperationException();\n\t");
}
sb.append('}').append('\n');
return sb.toString();
}
private static final class FieldTypeDesc{
String typeSource;
String cType;
String javaType;
int pointerLevel;
boolean isReference;
boolean isInnerConstant;
boolean isOutConstant;
String[] templateTypes;
void reset(){
typeSource = null;
cType = null;
javaType = null;
pointerLevel = 0;
isOutConstant = false;
isInnerConstant = false;
isReference = false;
}
}
private static boolean parsingFileType(String type, FieldTypeDesc outDesc){
type = type.trim();
outDesc.reset();
outDesc.typeSource = type;
final String CONST = "const";
if(type.startsWith(CONST)){
outDesc.isOutConstant = true;
type = type.substring(CONST.length()).trim();
}
final String CLASS = "class";
if(type.startsWith(CLASS)){
// remove the class modifer.
type = type.substring(CLASS.length()).trim();
}
// next it must be a type
char currentChar = type.charAt(0);
if(StringUtils.isProgrammingLanguageFieldValidStartChar(currentChar)){
int index = 1;
for(; index < type.length(); index ++){
currentChar = type.charAt(index);
if(currentChar == '<'){
// template in the type.
int start = index;
int end = StringUtils.findEndBrackek('<','>', type, start);
List<Object> templatesType = UPROPERTYParser.parseLine(type.substring(start+1, end));
outDesc.templateTypes = new String[templatesType.size()];
for(int l = 0; l < templatesType.size(); l++){
outDesc.templateTypes[l] = (String)templatesType.get(l);
}
index = end + 1;
continue;
}else if(!(Character.isLetterOrDigit(currentChar) || currentChar == '_' || currentChar == ':')){
break;
}
}
String cType = type.substring(0, index);
outDesc.javaType = UPROPERTYParser.getJavaType(cType);
while (index < type.length()){
currentChar = type.charAt(index);
if(currentChar == '*'){
outDesc.pointerLevel ++;
index ++;
}else if(currentChar == '&'){
outDesc.isReference = true;
index++;
}else if(currentChar == 'c'){
if(type.startsWith(CONST, index)){
if(outDesc.isInnerConstant)
throw new IllegalStateException("invalid field type: " + outDesc.typeSource);
outDesc.isInnerConstant = true;
index += CONST.length();
}else if(type.startsWith(CLASS, index)){
index += CLASS.length();
}
}else if(currentChar == ' '){
index = StringUtils.firstNotEmpty(type, index);
}else if(currentChar == ':'){
index ++;
}
}
}else{
throw new IllegalStateException("Unable to parse the type: " + type);
}
return true;
}
private static CharSequence makeParameterTypeStr(FieldTypeDesc desc){
StringBuilder sb = new StringBuilder();
if(desc.isInnerConstant || desc.isOutConstant) {
UPROPERTYParser.makeReadType(sb, desc.javaType);
}else{
sb.append(desc.javaType);
}
if(desc.templateTypes != null && desc.templateTypes.length > 0){
sb.append('<');
sb.append(desc.templateTypes[0]);
sb.append('>');
}
return sb;
}
}
|
riadnassiffe/Simulator | src/tools/ecos/ecos/include/spla.h | <reponame>riadnassiffe/Simulator<filename>src/tools/ecos/ecos/include/spla.h
/*
* ECOS - Embedded Conic Solver.
* Copyright (C) 2012-2015 <NAME> [<EMAIL>],
* Automatic Control Lab, ETH Zurich & embotech GmbH, Zurich, Switzerland.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Sparse linear algebra library for solver, i.e. no memory manager
* such as malloc is accessed by this module.
*/
#ifndef __SPLA_H__
#define __SPLA_H__
#include "glblopts.h"
/* Data structure for sparse matrices */
typedef struct spmat{
idxint* jc;
idxint* ir;
pfloat* pr;
idxint n;
idxint m;
idxint nnz;
} spmat;
/* SPARSE MATRIX OPERATIONS PROVIDED BY THIS MODULE -------------------- */
/*
* Sparse matrix-vector multiply for operations
*
* y = A*x (if a > 0 && newVector == 1)
* y += A*x (if a > 0 && newVector == 0)
* y = -A*x (if a < 0 && newVector == 1)
* y -= A*x (if a < 0 && newVector == 0)
*
* where A is a sparse matrix and both x and y are assumed to be dense.
*/
void sparseMV(spmat* A, pfloat* x, pfloat* y, idxint a, idxint newVector);
/*
* Sparse matrix-transpose-vector multiply with subtraction.
*
* If newVector > 0, then this computes y = -A'*x,
* otherwise y -= A'*x,
*
* where A is a sparse matrix and both x and y are assumed to be dense.
* If skipDiagonal == 1, then the contributions of diagonal elements are
* not counted.
*
* NOTE: The product is calculating without explicitly forming the
* transpose.
*/
void sparseMtVm(spmat* A, pfloat* x, pfloat* y, idxint newVector, idxint skipDiagonal);
/*
* Vector addition y += x of size n.
*/
void vadd(idxint n, pfloat* x, pfloat* y);
/*
* Vector subtraction with scaling: y -= a*x of size n.
*/
void vsubscale(idxint n, pfloat a, pfloat* x, pfloat* y);
/*
* 2-norm of a vector.
*/
pfloat norm2(pfloat* v, idxint n);
/*
* inf-norm of a vector.
*/
pfloat norminf(pfloat* v, idxint n);
/*
* ECOS dot product z = x'*y of size n.
*/
pfloat eddot(idxint n, pfloat* x, pfloat* y);
#endif
|
NCIP/catrip | codebase/projects/catissuecore-beans/src/edu/wustl/catissuecore/domainobject/DistributionProtocol.java | /*L
* Copyright Duke Comprehensive Cancer Center
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/catrip/LICENSE.txt for details.
*/
// Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
package edu.wustl.catissuecore.domainobject;
import java.util.Collection;
// Referenced classes of package edu.wustl.catissuecore.domainobject:
// SpecimenProtocol
public interface DistributionProtocol
extends SpecimenProtocol
{
public abstract Collection getSpecimenRequirementCollection();
public abstract void setSpecimenRequirementCollection(Collection collection);
public abstract Collection getCollectionProtocolCollection();
public abstract void setCollectionProtocolCollection(Collection collection);
}
|
lukhnos/objclucene | include/org/apache/lucene/search/DisiPriorityQueue.h | //
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: ./core/src/java/org/apache/lucene/search/DisiPriorityQueue.java
//
#include "J2ObjC_header.h"
#pragma push_macro("INCLUDE_ALL_OrgApacheLuceneSearchDisiPriorityQueue")
#ifdef RESTRICT_OrgApacheLuceneSearchDisiPriorityQueue
#define INCLUDE_ALL_OrgApacheLuceneSearchDisiPriorityQueue 0
#else
#define INCLUDE_ALL_OrgApacheLuceneSearchDisiPriorityQueue 1
#endif
#undef RESTRICT_OrgApacheLuceneSearchDisiPriorityQueue
#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif
#if !defined (OrgApacheLuceneSearchDisiPriorityQueue_) && (INCLUDE_ALL_OrgApacheLuceneSearchDisiPriorityQueue || defined(INCLUDE_OrgApacheLuceneSearchDisiPriorityQueue))
#define OrgApacheLuceneSearchDisiPriorityQueue_
#define RESTRICT_JavaLangIterable 1
#define INCLUDE_JavaLangIterable 1
#include "java/lang/Iterable.h"
@class OrgApacheLuceneSearchDisiWrapper;
@protocol JavaUtilFunctionConsumer;
@protocol JavaUtilIterator;
@protocol JavaUtilSpliterator;
/*!
@brief A priority queue of DocIdSetIterators that orders by current doc ID.
This specialization is needed over <code>PriorityQueue</code> because the
pluggable comparison function makes the rebalancing quite slow.
*/
@interface OrgApacheLuceneSearchDisiPriorityQueue : NSObject < JavaLangIterable >
#pragma mark Public
- (instancetype __nonnull)initWithInt:(jint)maxSize;
- (OrgApacheLuceneSearchDisiWrapper *)addWithOrgApacheLuceneSearchDisiWrapper:(OrgApacheLuceneSearchDisiWrapper *)entry_;
- (id<JavaUtilIterator>)iterator;
- (OrgApacheLuceneSearchDisiWrapper *)pop;
- (jint)size;
- (OrgApacheLuceneSearchDisiWrapper *)top;
/*!
@brief Get the list of scorers which are on the current doc.
*/
- (OrgApacheLuceneSearchDisiWrapper *)topList;
- (OrgApacheLuceneSearchDisiWrapper *)updateTop;
#pragma mark Package-Private
- (void)downHeapWithInt:(jint)size;
+ (jint)leftNodeWithInt:(jint)node;
+ (jint)parentNodeWithInt:(jint)node;
+ (jint)rightNodeWithInt:(jint)leftNode;
- (OrgApacheLuceneSearchDisiWrapper *)updateTopWithOrgApacheLuceneSearchDisiWrapper:(OrgApacheLuceneSearchDisiWrapper *)topReplacement;
- (void)upHeapWithInt:(jint)i;
// Disallowed inherited constructors, do not use.
- (instancetype __nonnull)init NS_UNAVAILABLE;
@end
J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneSearchDisiPriorityQueue)
FOUNDATION_EXPORT jint OrgApacheLuceneSearchDisiPriorityQueue_leftNodeWithInt_(jint node);
FOUNDATION_EXPORT jint OrgApacheLuceneSearchDisiPriorityQueue_rightNodeWithInt_(jint leftNode);
FOUNDATION_EXPORT jint OrgApacheLuceneSearchDisiPriorityQueue_parentNodeWithInt_(jint node);
FOUNDATION_EXPORT void OrgApacheLuceneSearchDisiPriorityQueue_initWithInt_(OrgApacheLuceneSearchDisiPriorityQueue *self, jint maxSize);
FOUNDATION_EXPORT OrgApacheLuceneSearchDisiPriorityQueue *new_OrgApacheLuceneSearchDisiPriorityQueue_initWithInt_(jint maxSize) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT OrgApacheLuceneSearchDisiPriorityQueue *create_OrgApacheLuceneSearchDisiPriorityQueue_initWithInt_(jint maxSize);
J2OBJC_TYPE_LITERAL_HEADER(OrgApacheLuceneSearchDisiPriorityQueue)
#endif
#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneSearchDisiPriorityQueue")
|
akiyamalab/restretto | src/OBMol.hpp | #include <istream>
#include <vector>
#include <openbabel/mol.h>
#include <openbabel/obconversion.h>
#include <openbabel/babelconfig.h>
#include <openbabel/op.h>
#include <openbabel/graphsym.h>
#include "Molecule.hpp"
#ifndef OBMOL_H_
#define OBMOL_H_
namespace format{
std::vector<OpenBabel::OBMol> ParseFileToOBMol(const std::vector<std::string>& filepaths);
std::vector<OpenBabel::OBMol> ParseFileToOBMol(const std::string& filepath);
std::vector<OpenBabel::OBMol> ParseFileToOBMol(std::istream& stream, const std::string& in_format);
fragdock::Molecule toFragmentMol(const OpenBabel::OBMol& mol);
OpenBabel::OBMol toOBMol(const fragdock::Molecule &mol, const OpenBabel::OBMol& original_obmol);
}
namespace OpenBabel{
class outputOBMol {
std::ofstream ofs;
OpenBabel::OBConversion conv;
public:
outputOBMol(const std::string& filepath) {
ofs.open(filepath);
conv = OpenBabel::OBConversion(NULL, &ofs);
conv.SetOutFormat("sdf");
}
void write(const OpenBabel::OBMol& mol) {
conv.Write(&const_cast<OpenBabel::OBMol&>(mol));
}
void close() {
ofs.close();
}
};
std::string canonicalSmiles(const OpenBabel::OBMol& mol);
void toCanonical(OpenBabel::OBMol& mol);
void getRenumber(OpenBabel::OBMol& mol, std::vector<unsigned int>& canon_labels);
void UpdateCoords(OpenBabel::OBMol& mol, const fragdock::Molecule& ref_mol);
void outputOBMolsToSDF(const std::string& filepath, const std::vector<OpenBabel::OBMol>& mols);
void outputOBMolsToSDF(const std::string& filepath, const std::vector<std::vector<OpenBabel::OBMol> >& molss);
OpenBabel::OBMol CreateSubMolecule(const OpenBabel::OBMol& reference, const std::vector<int>& atom_ids);
}
#endif
|
enotio/Tempest | Tempest/system/androidapi.cpp | <filename>Tempest/system/androidapi.cpp<gh_stars>1-10
#include "androidapi.h"
using namespace Tempest;
#ifdef __ANDROID__
#include <Tempest/Application>
#include <Tempest/Window>
#include <Tempest/Event>
#include <Tempest/Log>
#include <Tempest/Assert>
#include <Tempest/DisplaySettings>
#include <Tempest/JniExtras>
#include <thread>
#include <map>
#include <queue>
#include <EGL/egl.h>
#include <GLES/gl.h>
#include <pthread.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <dlfcn.h>
#include <limits.h>
#include <jni.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <android/bitmap.h>
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include <android/keycodes.h>
#include <android/obb.h>
#ifdef __arm__
//#include <machine/cpu-features.h>
//extern int android_getCpuCount(void);
#endif
#include <cmath>
#include <locale>
Tempest::signal<> AndroidAPI::onSurfaceDestroyed;
struct Guard {
Guard( pthread_mutex_t& m ):m(m){
pthread_mutex_lock(&m);
}
~Guard(){
pthread_mutex_unlock(&m);
}
pthread_mutex_t& m;
};
static struct Android {
std::unordered_map<jobject, Tempest::Window*> wndWx;
JavaVM *vm =nullptr;
JNIEnv *env=nullptr;
//Jni::Object assets;
AAssetManager* assets=nullptr;
Jni::Class activityClass;
Jni::Class surfaceClass;
Jni::Class tempestClass;
Jni::Class applicationClass;
Jni::Object applicationObject;
pthread_mutex_t appMutex, assetsPreloadedMutex;
int (*mainFunc)(int,char**) = nullptr;
std::string mainFnArgs;
bool isPaused=true;
std::vector<char> internal, external;
std::string locale;
float density;
enum MainThreadMessage {
MSG_NONE = 0,
MSG_WINDOW_SET,
MSG_SURFACE_RESIZE,
MSG_START,
MSG_STOP,
MSG_TOUCH,
MSG_PAUSE,
MSG_RESUME,
MSG_CHAR,
MSG_KEYDOWN_EVENT,
MSG_KEYUP_EVENT,
MSG_CLOSE,
MSG_WAIT,
MSG_RENDER_LOOP_EXIT
};
struct Message{
Message( MainThreadMessage m ):msg(m){
data.x = 0;
data.y = 0;
data1 = 0;
data2 = 0;
}
struct {
union {
int x,w;
void* ptr;
};
union {
int y,h;
};
} data;
int data1, data2;
MainThreadMessage msg;
};
std::vector<Message> msg;
void pushMsg( const Message& m ){
Guard g( appMutex );
(void)g;
msg.push_back(m);
}
void msgClear(){
Guard g( appMutex );
(void)g;
msg.clear();
}
size_t msgSize(){
Guard g( appMutex );
(void)g;
return msg.size();
}
void waitForQueue(){
while(true){
if(msgSize()==0)
return;
sleep();
}
}
Message takeMsg(){
Guard g( appMutex );
(void)g;
if(msg.size())
return msg[0];
return MSG_NONE;
}
struct MousePointer{
int nativeID;
bool valid;
Point pos;
};
std::vector<MousePointer> mouse;
std::unordered_map< std::string, std::unique_ptr< std::vector<char>> > asset_files;
AAsset* open( const std::string& a ){
//JNIEnv * env = 0;
//vm->AttachCurrentThread( &env, NULL);
AAsset* asset = AAssetManager_open(assets, a.c_str(), AASSET_MODE_UNKNOWN);
return asset;
}
int pointerId( int nid ){
for( size_t i=0; i<mouse.size(); ++i )
if( mouse[i].nativeID==nid && mouse[i].valid ){
return i;
}
MousePointer p;
p.nativeID = nid;
p.valid = true;
mouse.push_back(p);
return mouse.size()-1;
}
Point& pointerPos( int id ){
return mouse[id].pos;
}
void unsetPointer( int nid ){
for( size_t i=0; i<mouse.size(); ++i )
if( mouse[i].nativeID==nid ){
mouse[i].valid = false;
}
while( mouse.size() && !mouse.back().valid )
mouse.pop_back();
}
static void sleep(){
Application::sleep(10);
}
Android(){
density = 1.5;
msg. reserve(256);
mouse.reserve(8);
pthread_mutex_init(&appMutex, 0);
pthread_mutex_init(&assetsPreloadedMutex, 0);
}
~Android(){
pthread_mutex_destroy(&assetsPreloadedMutex);
pthread_mutex_destroy(&appMutex);
}
SystemAPI::Window *createWindow();
} android;
using namespace Tempest;
AndroidAPI::AndroidAPI(){
TranslateKeyPair k[] = {
{ AKEYCODE_DPAD_LEFT, Event::K_Left },
{ AKEYCODE_DPAD_RIGHT, Event::K_Right },
{ AKEYCODE_DPAD_UP, Event::K_Up },
{ AKEYCODE_DPAD_DOWN, Event::K_Down },
//{ AKEYCODE_BACK, Event::K_ESCAPE },
{ AKEYCODE_DEL, Event::K_Back },
{ AKEYCODE_HOME, Event::K_Home },
{ AKEYCODE_0, Event::K_0 },
{ AKEYCODE_A, Event::K_A },
{ AKEYCODE_ENTER, Event::K_Return },
{ 0, Event::K_NoKey }
};
setupKeyTranslate(k);
setFuncKeysCount(0);
}
AndroidAPI::~AndroidAPI(){
}
JavaVM *AndroidAPI::jvm() {
return android.vm;
}
JNIEnv *AndroidAPI::jenvi() {
return android.env;
}
Jni::Object AndroidAPI::surface(jobject activity) {
while( true ) {
jobject obj = android.activityClass.callObject(*android.env,activity,"nativeSurface","()Landroid/view/Surface;");
if( obj!=nullptr ) {
return Jni::Object(*android.env,obj);
}
if( android.env->ExceptionOccurred() )
return Jni::Object();
std::this_thread::yield();
}
}
Jni::AndroidWindow AndroidAPI::nWindow(void* hwnd) {
Jni::Object jsurface = AndroidAPI::surface(reinterpret_cast<jobject>(hwnd));
JNIEnv* env = jenvi();
Jni::AndroidWindow wnd;
while(true) {
wnd = Jni::AndroidWindow(*env,jsurface);
if( wnd )
return wnd;
std::this_thread::yield();
Application::sleep(10);
}
return Jni::AndroidWindow();
}
const Jni::Class& AndroidAPI::appClass() {
return android.activityClass;
}
Jni::Object AndroidAPI::app() {
return android.applicationObject;
}
const char *AndroidAPI::internalStorage() {
mkdir( android.internal.data(), 0770 );
return android.internal.data();
}
const char *AndroidAPI::externalStorage() {
mkdir( android.external.data(), 0770 );
return android.external.data();
}
float AndroidAPI::densityDpi(){
return android.density;
}
void AndroidAPI::toast( const std::string &s ) {
Android &a = android;
jstring str = a.env->NewStringUTF( s.c_str() );
a.activityClass.callStaticVoid(*a.env,"showToast", "(Ljava/lang/String;)V");
a.env->DeleteLocalRef(str);
}
void AndroidAPI::showSoftInput() {
Android &a = android;
if( android.wndWx.empty() )
return;
jobject w = android.wndWx.begin()->first;
a.activityClass.callVoid(*a.env,w,"showSoftInput", "()V");
}
void AndroidAPI::hideSoftInput() {
Android &a = android;
if( android.wndWx.empty() )
return;
jobject w = android.wndWx.begin()->first;
a.activityClass.callVoid(*a.env,w,"hideSoftInput", "()V");
}
void AndroidAPI::toggleSoftInput(){
Android &a = android;
if( android.wndWx.empty() )
return;
jobject w = android.wndWx.begin()->first;
a.activityClass.callVoid(*a.env,w,"toggleSoftInput", "()V");
}
const std::string &AndroidAPI::iso3Locale() {
return android.locale;
}
AndroidAPI::Window* AndroidAPI::createWindow(int /*w*/, int /*h*/) {
return android.createWindow();
}
AndroidAPI::Window* AndroidAPI::createWindowMaximized(){
return android.createWindow();
}
AndroidAPI::Window* AndroidAPI::createWindowMinimized(){
return android.createWindow();
}
AndroidAPI::Window* AndroidAPI::createWindowFullScr(){
return android.createWindow();
}
Widget *AndroidAPI::addOverlay(WindowOverlay *ov) {
if( android.wndWx.empty() ){
delete ov;
return 0;
}
Tempest::Window* w = android.wndWx.begin()->second;
SystemAPI::addOverlay(w, ov);
return ov;
}
bool AndroidAPI::testDisplaySettings( Window* , const DisplaySettings & s ) {
return s.bits==16 &&
s.fullScreen;
}
bool AndroidAPI::setDisplaySettings( Window* w, const DisplaySettings &s) {
return testDisplaySettings(w,s);
}
AndroidAPI::CpuInfo AndroidAPI::cpuInfoImpl(){
CpuInfo info;
memset(&info, 0, sizeof(info));
#ifdef __arm__
info.cpuCount = 1;//android_getCpuCount();
#else
info.cpuCount = 1;
#endif
return info;
}
struct AndroidAPI::DroidFile {
std::vector<char> preAsset;
FILE* h =nullptr;
AAsset* asset=nullptr;
char* buf =nullptr;
size_t remSize=0;
size_t size =0;
bool isSmall() const { return size<1024*1024; }
};
AndroidAPI::File *AndroidAPI::fopenImpl( const char16_t *fname, const char *mode ) {
return fopenImpl( toUtf8(fname).data(), mode );
}
AndroidAPI::File *AndroidAPI::fopenImpl( const char *fname, const char *mode ) {
bool wr = 0;
for( int i=0; mode[i]; ++i ){
if( mode[i]=='w' )
wr = 1;
}
DroidFile* f = new DroidFile();
if( fname[0]=='/'||fname[0]=='.' ){
f->h = ::fopen(fname, mode);
} else
if( !wr ) {
f->asset = android.open(fname);
if( f->asset )
f->size = size_t(AAsset_getLength64(f->asset));
if(f->isSmall() && f->size>0) {
f->preAsset.resize(f->size);
f->buf=&f->preAsset[0];
f->remSize=f->size;
AAsset_read(f->asset,f->buf,f->size);
}
}
if( !f->h && !f->asset ){
delete f;
return 0;
}
return reinterpret_cast<SystemAPI::File*>(f);
}
size_t AndroidAPI::readDataImpl(SystemAPI::File *f, char *dest, size_t count) {
DroidFile *fn = reinterpret_cast<DroidFile*>(f);
if( fn->buf ) {
count=std::min(count,fn->remSize);
memcpy(dest,fn->buf,count);
fn->buf +=count;
fn->remSize-=count;
return count;
}
if( fn->h ){
return fread(dest, 1, count, fn->h);
}
int rd = AAsset_read(fn->asset,dest,count);
if( rd<0 )
return 0;
return size_t(rd);
}
size_t AndroidAPI::peekImpl(SystemAPI::File *f, size_t skip, char *dest, size_t count) {
DroidFile *fn = reinterpret_cast<DroidFile*>(f);
if( fn->buf ) {
if( skip+count>fn->size )
return 0;
memcpy(dest,fn->buf+skip,count);
return count;
}
if( fn->h ){
off_t pos = ftell( fn->h );
fseek( fn->h, skip, SEEK_CUR );
size_t c = fread( dest, 1, count, fn->h );
fseek( fn->h , pos, SEEK_SET );
return c;
}
if(fn->asset) {
if( skip+count>fn->size )
return 0;
size_t pos = size_t(fn->size - AAsset_getRemainingLength64(fn->asset));
if(pos!=skip)
AAsset_seek(fn->asset,skip,SEEK_CUR);
size_t c = readDataImpl(f,dest,count);
AAsset_seek(fn->asset,pos,SEEK_SET);
return c;
}
return 0;
}
size_t AndroidAPI::writeDataImpl(SystemAPI::File *f, const char *data, size_t count) {
DroidFile *fn = reinterpret_cast<DroidFile*>(f);
return fwrite(data, 1, count, fn->h );
}
void AndroidAPI::flushImpl(SystemAPI::File *f) {
DroidFile *fn = reinterpret_cast<DroidFile*>(f);
if( fn->h )
fflush( fn->h );
}
size_t AndroidAPI::skipImpl(SystemAPI::File *f, size_t count) {
DroidFile *fn = reinterpret_cast<DroidFile*>(f);
if( fn->buf ) {
if( count>fn->remSize )
return 0;
fn->remSize-=count;
fn->buf +=count;
return count;
}
if( fn->h ){
off_t pos = ftell( fn->h );
fseek( fn->h, off_t(count), SEEK_CUR );
return ftell(fn->h) - pos;
}
size_t pos = size_t(fn->size - AAsset_getRemainingLength64( fn->asset ));
if(pos==count)
return 0;
off_t newPos = AAsset_seek(fn->asset,count,SEEK_CUR);
if(newPos<0)
return 0;
return newPos-pos;
}
bool AndroidAPI::eofImpl(SystemAPI::File *f) {
DroidFile *fn = reinterpret_cast<DroidFile*>(f);
if( fn->buf ) {
return fn->remSize==0;
}
if( fn->h ){
return feof( fn->h );
} else {
return AAsset_getRemainingLength64(fn->asset)==0;
}
return fn->size==0;
}
size_t AndroidAPI::fsizeImpl( File* f ){
DroidFile *fn = reinterpret_cast<DroidFile*>(f);
if( fn->h ){
FILE *file = fn->h;
size_t pos = ftell(file);
fseek( file, 0, SEEK_SET );
size_t s = ftell(file);
fseek( file, 0, SEEK_END );
size_t e = ftell(file);
fseek( file, pos, SEEK_SET );
return e-s;
}
if( fn->asset )
return fn->size;
return 0;
}
void AndroidAPI::fcloseImpl(SystemAPI::File *f) {
DroidFile *fn = reinterpret_cast<DroidFile*>(f);
if( fn->h ){
::fclose( fn->h );
}
if( fn->asset )
AAsset_close(fn->asset);
delete fn;
}
Size AndroidAPI::implScreenSize() {
return Size();//android.window_w, android.window_h);
}
bool AndroidAPI::startRender( Window * ) {
return 1;
}
bool AndroidAPI::present(SystemAPI::Window *) {
return 0;
}
void AndroidAPI::startApplication( ApplicationInitArgs * ) {
}
void AndroidAPI::endApplication() {
}
static Tempest::KeyEvent makeKeyEvent( int32_t k, bool scut = false ){
Tempest::KeyEvent::KeyType e = SystemAPI::translateKey(k);
if( !scut ){
if( Event::K_0<=e && e<= Event::K_9 )
e = Tempest::KeyEvent::K_NoKey;
if( Event::K_A<=e && e<= Event::K_Z )
e = Tempest::KeyEvent::K_NoKey;
}
return Tempest::KeyEvent( e );
}
static void render();
int AndroidAPI::nextEvents(bool &quit) {
int r = 0;
while( !quit ){
int sz = 0;
{
Android::MainThreadMessage msg = android.takeMsg().msg;
if( android.wndWx.size()==0 && msg!=Android::MSG_RENDER_LOOP_EXIT ){
android.sleep();
return 1;
}
sz = msg!=Android::MSG_NONE;
}
r = nextEvent(quit);
if( sz==0 )
return r;
}
return r;
}
int AndroidAPI::nextEvent(bool &quit) {
bool hasWindow = true;
Android::Message msg = Android::MSG_NONE;
{
Guard g(android.appMutex);
(void)g;
hasWindow = !android.wndWx.empty();//android.window;
if( android.msg.size() ){
msg = android.msg[0];
if( !hasWindow && msg.msg!=Android::MSG_RENDER_LOOP_EXIT ){
android.sleep();
return 0;
}
android.msg.erase( android.msg.begin() );
}
}
if( android.wndWx.size()==0 )
return 0;
Tempest::Window* wnd = android.wndWx.begin()->second;
switch( msg.msg ) {
case Android::MSG_WINDOW_SET:
if(msg.data.ptr) {
SystemAPI::activateEvent( wnd, true);
} else {
onSurfaceDestroyed();
SystemAPI::activateEvent( wnd, false);
}
break;
case Android::MSG_SURFACE_RESIZE:
SystemAPI::sizeEvent(wnd,msg.data.w,msg.data.h);
break;
case Android::MSG_RENDER_LOOP_EXIT:
quit = true;
break;
case Android::MSG_CHAR:
{
Tempest::KeyEvent e = Tempest::KeyEvent( uint32_t(msg.data1) );
int wrd[3] = {
AKEYCODE_DEL,
AKEYCODE_BACK,
0
};
if( 0 == *std::find( wrd, wrd+2, msg.data1) ){
Tempest::KeyEvent ed( e.key, e.u16, Event::KeyDown );
SystemAPI::emitEvent( wnd, ed);
Tempest::KeyEvent eu( e.key, e.u16, Event::KeyUp );
SystemAPI::emitEvent( wnd, eu);
}
}
case Android::MSG_KEYDOWN_EVENT:{
SystemAPI::emitEvent( wnd,
makeKeyEvent(msg.data1),
makeKeyEvent(msg.data1, true),
Event::KeyDown );
}
break;
case Android::MSG_KEYUP_EVENT:{
Tempest::KeyEvent e = makeKeyEvent(msg.data1);
Tempest::KeyEvent eu( e.key, e.u16, Event::KeyUp );
SystemAPI::emitEvent( wnd, eu);
}
break;
case Android::MSG_TOUCH: {
int id = android.pointerId( msg.data2 );
if( msg.data1==0 ){
MouseEvent e( msg.data.x, msg.data.y,
MouseEvent::ButtonLeft, 0, id,
Event::MouseDown );
android.pointerPos(id) = Point(msg.data.x, msg.data.y);
SystemAPI::emitEvent(wnd, e);
}
if( msg.data1==1 ){
MouseEvent e( msg.data.x, msg.data.y,
MouseEvent::ButtonLeft, 0, id,
Event::MouseUp );
SystemAPI::emitEvent(wnd, e);
android.unsetPointer(msg.data2);
}
if( msg.data1==2 ){
MouseEvent e( msg.data.x, msg.data.y,
MouseEvent::ButtonLeft, 0, id,
Event::MouseMove );
if( android.pointerPos(id) != Point(msg.data.x, msg.data.y) ){
android.pointerPos(id) = Point(msg.data.x, msg.data.y);
SystemAPI::emitEvent(wnd, e);
}
}
}
break;
case Android::MSG_CLOSE: {
Tempest::CloseEvent e;
SystemAPI::emitEvent(wnd, e);
if( !e.isAccepted() ){
android.pushMsg( Android::MSG_RENDER_LOOP_EXIT );
}
}
break;
case Android::MSG_START:
SystemAPI::setShowMode(wnd, Tempest::Window::Maximized);
break;
case Android::MSG_STOP:
SystemAPI::setShowMode(wnd, Tempest::Window::Minimized);
break;
case Android::MSG_PAUSE:
android.isPaused = true;
break;
case Android::MSG_RESUME:
android.isPaused = false;
break;
case Android::MSG_NONE:
if( !android.isPaused && wnd->showMode()!=Tempest::Window::Minimized)
render(); else
android.sleep();
break;
default:
break;
}
return 0;
}
Point AndroidAPI::windowClientPos ( Window* ){
return Point(0,0);
}
Size AndroidAPI::windowClientRect( Window* hwnd ){
Jni::AndroidWindow window = AndroidAPI::nWindow(hwnd);
EGLint w=ANativeWindow_getWidth (window);
EGLint h=ANativeWindow_getHeight(window);
return Size(w,h);
}
void AndroidAPI::deleteWindow( Window *w ) {
if( w!=nullptr ) {
jobject ptr = reinterpret_cast<jobject>(w);
android.activityClass.callStaticVoid(*android.env,"nativeDelWindow","(Lcom/tempest/engine/Activity;)V",ptr);
android.env->DeleteGlobalRef(ptr);
android.wndWx.erase(ptr);
}
}
void AndroidAPI::show(Window *hwnd) {
ANativeWindow* window = AndroidAPI::nWindow(hwnd);
jobject ptr = reinterpret_cast<jobject>(hwnd);
Tempest::Window* wnd = nullptr;
auto i = android.wndWx.find(ptr);
if( i!= android.wndWx.end() )
wnd = i->second;
EGLint w=ANativeWindow_getWidth (window);
EGLint h=ANativeWindow_getHeight(window);
if( wnd )
SystemAPI::sizeEvent(wnd, w, h);
}
void AndroidAPI::setGeometry( Window */*hw*/, int /*x*/, int /*y*/, int /*w*/, int /*h*/ ) {
}
void AndroidAPI::bind( Window *hwnd, Tempest::Window *wx ) {
jobject w = reinterpret_cast<jobject>(hwnd);
android.wndWx[w] = wx;
SystemAPI::activateEvent(wx, true);
}
static void render() {
Android& e = android;
for(auto& i:e.wndWx) {
Tempest::Window& wnd=*i.second;
if( !wnd.size().isEmpty() )
if( wnd.showMode()!=Tempest::Window::Minimized && wnd.isActive() )
wnd.render();
}
}
AndroidAPI::Window* Android::createWindow() {
JNIEnv* e = android.env;
if( !e )
return nullptr;
while( true ) {
jobject obj = android.activityClass.callStaticObject(*e,"nativeNewWindow","()Lcom/tempest/engine/Activity;");
if(!obj)
continue;
obj = env->NewGlobalRef(obj);
return reinterpret_cast<AndroidAPI::Window*>(obj);
}
}
static void* tempestMainFunc(void*);
static void JNICALL resize( JNIEnv * , jobject, jobject, jint w, jint h ) {
Android::Message m = Android::MSG_SURFACE_RESIZE;
m.data.w = w;
m.data.h = h;
android.pushMsg(m);
}
static void JNICALL start(JNIEnv* /*jenv*/, jobject /*obj*/) {
Log::i("nativeOnStart");
android.pushMsg(Android::MSG_START);
}
static void JNICALL stop(JNIEnv* /*jenv*/, jobject /*obj*/) {
Log::i("nativeOnStop");
android.pushMsg(Android::MSG_STOP);
}
static void JNICALL resume(JNIEnv* /*jenv*/, jobject /*obj*/) {
Log::i("nativeOnResume");
android.pushMsg( Android::MSG_RESUME );
}
static void JNICALL pauseA(JNIEnv* /*jenv*/, jobject /*obj*/) {
Log::i("nativeOnPause");
android.msg.push_back( Android::MSG_PAUSE );
}
static void JNICALL setAssets(JNIEnv* jenv, jobject /*obj*/, jobject jassets ) {
Log::i("setAssets");
android.assets = AAssetManager_fromJava(jenv, jassets);
}
static void JNICALL nativeOnTouch( JNIEnv* , jobject ,
jint x, jint y, jint act, jint pid ){
Android::Message m = Android::MSG_TOUCH;
m.data.x = x;
m.data.y = y;
m.data1 = act;
m.data2 = pid;
if( act!=2 || android.msgSize()<64 )
android.pushMsg(m);
}
static void JNICALL nativeSetSurface( JNIEnv* /*jenv*/, jobject /*obj*/, jobject surface) {
Guard g( android.appMutex );
(void)g;
Android::Message m = Android::MSG_WINDOW_SET;
m.data.ptr = surface;
android.msg.push_back( m );
}
static void JNICALL onKeyDownEvent(JNIEnv* , jobject, jint key ) {
Log::i("onKeyDownEvent");
if( key!=AKEYCODE_BACK ){
const int K_a = AKEYCODE_A, K_A = 29;
if( K_a<=key && key<K_a+26 ){
Android::Message m = Android::MSG_CHAR;
m.data1 = key+97-K_a;
android.pushMsg(m);
} else
if( K_A<=key && key<K_A+26 ){
Android::Message m = Android::MSG_CHAR;
m.data1 = key+65-K_A;
android.pushMsg(m);
} else
if( AKEYCODE_0<=key && key<AKEYCODE_0+10 ){
Android::Message m = Android::MSG_CHAR;
m.data1 = key+48-AKEYCODE_0;
android.pushMsg(m);
} else {
Android::Message m = Android::MSG_KEYDOWN_EVENT;
m.data1 = key;
android.pushMsg(m);
}
} else {
android.pushMsg( Android::MSG_CLOSE );
}
}
static void JNICALL onKeyUpEvent(JNIEnv* , jobject, jint key ) {
Log::i("onKeyUpEvent");
if( key!=AKEYCODE_BACK ){
Android::Message m = Android::MSG_KEYUP_EVENT;
m.data1 = key;
android.pushMsg(m);
} else {
android.pushMsg( Android::MSG_RENDER_LOOP_EXIT );
}
}
static void JNICALL onKeyCharEvent( JNIEnv* env, jobject,
jstring k ) {
const char* str = env->GetStringUTFChars( k, 0);
if( str ){
std::u16string s16 = SystemAPI::toUtf16(str);
for( size_t i=0; i<s16.size(); ++i ){
Android::Message m = Android::MSG_CHAR;
m.data1 = s16[i];
android.pushMsg(m);
}
}
env->ReleaseStringUTFChars( k, str );
}
static jint JNICALL nativeCloseEvent( JNIEnv* , jobject ){
{
Guard g( android.appMutex );
(void)g;
android.msg.push_back( Android::MSG_CLOSE );
android.msg.push_back( Android::MSG_WAIT );
}
android.waitForQueue();
return 1;
}
static void JNICALL nativeSetupStorage( JNIEnv* , jobject,
jstring internal, jstring external ) {
JNIEnv * env = 0;
android.vm->AttachCurrentThread( &env, NULL);
android.internal.clear();
android.external.clear();
const char* str = 0;
str = env->GetStringUTFChars( internal, 0);
if( str ){
for( int i=0; str[i]; ++i )
android.internal.push_back(str[i]);
android.internal.push_back('/');
android.internal.push_back(0);
}
env->ReleaseStringUTFChars( internal, str );
str = env->GetStringUTFChars( external, 0);
if( str ){
for( int i=0; str[i]; ++i )
android.external.push_back(str[i]);
android.external.push_back('/');
android.external.push_back(0);
}
env->ReleaseStringUTFChars( external, str );
}
static void JNICALL nativeSetApplication(JNIEnv* env, jobject, jobject app){
android.applicationObject=Jni::Object(*env,app);
android.applicationClass =Jni::Class(*env,env->GetObjectClass(app));
}
static void JNICALL nativeInitLocale( JNIEnv* , jobject,
jstring loc ){
JNIEnv * env = 0;
android.vm->AttachCurrentThread( &env, NULL);
const char* str = env->GetStringUTFChars( loc, 0);
if( str ){
android.locale = str;
} else {
android.locale = "eng";
}
env->ReleaseStringUTFChars( loc, str );
}
static void JNICALL setupDpi( JNIEnv* , jobject,
jfloat d ){
android.density = d;
}
static void JNICALL invokeMain(JNIEnv* env, jobject, jstring ndkLib ){
android.mainFnArgs = env->GetStringUTFChars( ndkLib, 0);
void* handle = dlopen(android.mainFnArgs.c_str(), RTLD_NOW);
if( !handle )
return;
void** pptr=reinterpret_cast<void**>(&android.mainFunc);
*pptr = dlsym(handle, "main");
tempestMainFunc(nullptr);
//android.thread_create(&android.mainThread, 0, tempestMainFunc, 0);
}
extern "C" jint JNICALL JNI_OnLoad(JavaVM *vm, void */*reserved*/){
Log::i("Tempest JNI_OnLoad");
android.vm = vm;
static std::initializer_list<JNINativeMethod> appMethodTable = {
{"nativeSetApplication", "(Landroid/app/Application;)V", (void *)nativeSetApplication },
{"nativeInitLocale", "(Ljava/lang/String;)V", (void *)nativeInitLocale },
{"nativeSetupDpi", "(F)V", (void *)setupDpi },
{"invokeMainImpl", "(Ljava/lang/String;)V", (void *)invokeMain },
{"nativeSetAssets", "(Landroid/content/res/AssetManager;)V", (void *)setAssets },
{"nativeSetupStorage", "(Ljava/lang/String;Ljava/lang/String;)V", (void *)nativeSetupStorage }
};
static std::initializer_list<JNINativeMethod> surfaceMethodTable = {
{"nativeOnStart", "()V", (void *) start },
{"nativeOnResume", "()V", (void *) resume },
{"nativeOnPause", "()V", (void *) pauseA },
{"nativeOnStop", "()V", (void *) stop },
{"nativeOnTouch", "(IIII)V", (void *)nativeOnTouch },
{"onKeyDownEvent", "(I)V", (void *)onKeyDownEvent },
{"onKeyUpEvent", "(I)V", (void *)onKeyUpEvent },
{"onKeyCharEvent", "(Ljava/lang/String;)V", (void *)onKeyCharEvent },
{"nativeCloseEvent", "()I", (void *) nativeCloseEvent },
{"nativeSetSurface", "(Landroid/view/Surface;)V", (void *) nativeSetSurface },
{"nativeOnResize", "(Landroid/view/Surface;II)V", (void *) resize }
};
JNIEnv* env;
if( vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK ){
Log::i("Failed to get the environment");
return -1;
}
android.activityClass = Jni::Class(*env,SystemAPI::androidActivityClass().c_str());
android.surfaceClass = Jni::Class(*env,"com/tempest/engine/WindowSurface");
android.tempestClass = Jni::Class(*env,"com/tempest/engine/Tempest");
if( !android.surfaceClass.registerNatives(*env,surfaceMethodTable) |
!android.tempestClass.registerNatives(*env,appMethodTable) ) {
Log::i("failed to get ",SystemAPI::androidActivityClass().c_str()," class reference");
jthrowable err = env->ExceptionOccurred();
if( err ) {
env->ExceptionDescribe();
env->ExceptionClear();
}
}
Log::i("Tempest ~JNI_OnLoad");
return JNI_VERSION_1_6;
}
static void* tempestMainFunc(void*){
Android &a = android;
a.vm->GetEnv(reinterpret_cast<void**>(&a.env),JNI_VERSION_1_6);
pthread_setname_np(pthread_self(),"main");
Log::i("Tempest MainFunc[1]");
static char* ch[]={
NULL,
NULL
};
ch[0] = &android.mainFnArgs[0];
android.mainFunc(1,ch);
android.msgClear();
Log::i("~Tempest MainFunc");
return 0;
}
#endif |
irentu/openengsb | components/ekb/graphdb-orient/src/test/java/org/openengsb/core/ekb/graph/orient/OrientModelGraphTest.java | /**
* Licensed to the Austrian Association for Software Tool Integration (AASTI)
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. The AASTI 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.openengsb.core.ekb.graph.orient;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openengsb.core.api.model.ModelDescription;
import org.openengsb.core.ekb.api.transformation.TransformationDescription;
import org.openengsb.core.ekb.graph.orient.internal.OrientModelGraph;
import org.openengsb.core.ekb.graph.orient.internal.OrientModelGraphUtils;
import org.openengsb.core.ekb.graph.orient.models.ModelA;
import org.openengsb.core.ekb.graph.orient.models.ModelB;
import org.openengsb.core.ekb.graph.orient.models.ModelC;
import org.osgi.framework.Version;
public class OrientModelGraphTest {
private static OrientModelGraph graph;
@BeforeClass
public static void init() {
graph = new OrientModelGraph();
}
@Before
public void start() {
graph.cleanDatabase();
graph.addModel(getModelADescription());
graph.addModel(getModelBDescription());
graph.addModel(getModelCDescription());
}
@AfterClass
public static void shutdown() {
graph.shutdown();
}
private static ModelDescription getModelADescription() {
return new ModelDescription(ModelA.class, new Version(1, 0, 0).toString());
}
private static ModelDescription getModelBDescription() {
return new ModelDescription(ModelB.class, new Version(1, 0, 0).toString());
}
private static ModelDescription getModelCDescription() {
return new ModelDescription(ModelC.class, new Version(1, 0, 0).toString());
}
private TransformationDescription getDescriptionForModelAToModelB() {
return new TransformationDescription(getModelADescription(), getModelBDescription());
}
private TransformationDescription getDescriptionForModelBToModelC() {
return new TransformationDescription(getModelBDescription(), getModelCDescription());
}
private TransformationDescription getDescriptionForModelAToModelC() {
return new TransformationDescription(getModelADescription(), getModelCDescription());
}
@Test
public void testIsTransformationPossible_shouldFindPath() throws Exception {
TransformationDescription description = getDescriptionForModelAToModelB();
description.setId("test");
graph.addTransformation(description);
boolean possible = graph.isTransformationPossible(getModelADescription(), getModelBDescription(), null);
assertThat(possible, is(true));
}
@Test
public void testIsTransformationPossiblePath_shouldFindPath() throws Exception {
TransformationDescription description = getDescriptionForModelAToModelB();
graph.addTransformation(description);
TransformationDescription description2 = getDescriptionForModelBToModelC();
graph.addTransformation(description2);
boolean possible = graph.isTransformationPossible(getModelADescription(), getModelBDescription(), null);
assertThat(possible, is(true));
}
@Test
public void testFindTransformationPathWithIDs_shouldFindDifferentPaths() throws Exception {
TransformationDescription description1 = getDescriptionForModelAToModelB();
description1.setId("test1");
graph.addTransformation(description1);
TransformationDescription description2 = getDescriptionForModelAToModelB();
description2.setId("test2");
graph.addTransformation(description2);
TransformationDescription description3 = getDescriptionForModelBToModelC();
graph.addTransformation(description3);
List<TransformationDescription> path1 =
graph.getTransformationPath(getModelADescription(), getModelCDescription(), Arrays.asList("test1"));
List<TransformationDescription> path2 =
graph.getTransformationPath(getModelADescription(), getModelCDescription(), Arrays.asList("test2"));
assertThat(path1.get(0).getId(), is("test1"));
assertThat(path2.get(0).getId(), is("test2"));
}
@Test
public void testIfModelDeactivationWorks_shouldWork() throws Exception {
graph.removeModel(getModelADescription());
assertThat(graph.isModelActive(getModelADescription()), is(false));
graph.addModel(getModelADescription());
assertThat(graph.isModelActive(getModelADescription()), is(true));
}
@Test
public void testIfDeactivatedModelsAreNotUsed_shouldIgnoreInactiveModels() throws Exception {
TransformationDescription description = getDescriptionForModelAToModelB();
description.setId("test1");
graph.addTransformation(description);
description = getDescriptionForModelBToModelC();
description.setId("test2");
graph.addTransformation(description);
boolean possible1 = graph.isTransformationPossible(getModelADescription(), getModelCDescription(), null);
graph.removeModel(getModelBDescription());
boolean possible2 = graph.isTransformationPossible(getModelADescription(), getModelCDescription(), null);
description = getDescriptionForModelAToModelC();
description.setId("test3");
graph.addTransformation(description);
boolean possible3 = graph.isTransformationPossible(getModelADescription(), getModelCDescription(), null);
assertThat(possible1, is(true));
assertThat(possible2, is(false));
assertThat(possible3, is(true));
}
@Test
public void testIfLoadingByFilenameWorks_shouldLoadByFilename() throws Exception {
TransformationDescription description = getDescriptionForModelAToModelB();
description.setId("test1");
graph.addTransformation(description);
description = getDescriptionForModelBToModelC();
description.setId("test2");
graph.addTransformation(description);
description = getDescriptionForModelAToModelB();
description.setId("test3");
description.setFileName("testfile");
graph.addTransformation(description);
description = getDescriptionForModelBToModelC();
description.setId("test4");
graph.addTransformation(description);
List<TransformationDescription> result = graph.getTransformationsPerFileName("testfile");
assertThat(result.size(), is(1));
assertThat(result.get(0).getId(), is("test3"));
}
@Test
public void testIfTransformationDeletionWorks_shouldDeleteTransformationDescription() throws Exception {
TransformationDescription description = getDescriptionForModelAToModelB();
description.setId("test1");
graph.addTransformation(description);
boolean possible1 = graph.isTransformationPossible(getModelADescription(), getModelBDescription(), null);
graph.removeTransformation(description);
boolean possible2 = graph.isTransformationPossible(getModelADescription(), getModelBDescription(), null);
assertThat(possible1, is(true));
assertThat(possible2, is(false));
}
@Test
public void testIfPropertyConnectionFlatteningWorks_shouldWork() throws Exception {
Map<String, Set<String>> connections = new TreeMap<String, Set<String>>();
Set<String> set = new TreeSet<String>();
set.add("B-1");
set.add("B-2");
set.add("B-3");
connections.put("A-1", set);
set = new TreeSet<String>();
set.add("B-1");
set.add("B-3");
connections.put("A-2", set);
Map<String, String> result = OrientModelGraphUtils.convertPropertyConnectionsToSimpleForm(connections);
assertThat(result.get("A-1"), is("B-1,B-2,B-3"));
assertThat(result.get("A-2"), is("B-1,B-3"));
}
}
|
npocmaka/Windows-Server-2003 | base/win32/fusion/sxs/nodefactory.cpp | <reponame>npocmaka/Windows-Server-2003<gh_stars>10-100
/*
Copyright (c) Microsoft Corporation
*/
#include "stdinc.h"
#include "actctxgenctx.h"
//
// ISSUE: jonwis 3/9/2002 - This file is full of missing parameter checking.
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Parameter checking (#1)
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - FN_PROLOG/EPILOG (#2)
#define DEFINE_ATTRIBUTE(attributeName, attributeType, typePrefix) \
{ \
L ## #attributeName, \
offsetof(CNodeFactory, m_ ## typePrefix ## _ ## attributeName), \
offsetof(CNodeFactory, m_f ## attributeName ## _ ## Present), \
&CNodeFactory::XMLParser_Parse_ ## attributeType \
},
const static ASSEMBLY_VERSION assemblyVersion0 = {0,0,0,0};
typedef enum _in_xml_tag_when_identity_generated_{
SXS_IN_INVALID_XML_TAG_WHEN_ASSEMBLY_IDENTITY_GENERATED,
SXS_IN_ASSEMBLY_TAG,
SXS_IN_DEPENDENCY_TAG
}SXS_IN_XML_TAG_WHEN_IDENTITY_GENERATED;
VOID
SxspDbgPrintXmlNodeInfo(
ULONG Level,
XML_NODE_INFO *pNode
);
PCSTR
SxspFormatXmlNodeType(
DWORD dwType
);
struct EventIdErrorPair
{
DWORD dwEventId;
LONG nError;
};
const static EventIdErrorPair eventIdToErrorMap[] =
{
#include "messages.hi" // generated from .x file, like .mc
};
// deliberately no extra paranetheses here
#define NODEFACTORY_STRING_AND_LENGTH(x) x, NUMBER_OF(x) - 1
const static SXS_NAME_LENGTH_PAIR IgnoredAttributesInDependencyTagForIdentity[]={
//maybe more later
{ NODEFACTORY_STRING_AND_LENGTH(L"Description") }
};
const DWORD IGNORED_ATTRIBUTE_NUM_IN_DEPENDENCY_TAG = NUMBER_OF(IgnoredAttributesInDependencyTagForIdentity);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(baseInterface);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(clsid);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(description);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(flags);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(hash);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(hashalg);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(helpdir);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(iid);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(language);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(loadFrom);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(manifestVersion);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(metadataSatellite);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(name);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(newVersion);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(numMethods);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(oldVersion);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(optional);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(processorArchitecture);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(progid);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(proxyStubClsid32);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(publicKeyToken);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(publicKey);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(resourceid);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(runtimeVersion);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(size);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(threadingModel);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(tlbid);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(type);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(version);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(versioned);
DECLARE_STD_ATTRIBUTE_NAME_DESCRIPTOR(apply);
// How to interpret the parser worker rules here:
//
// First, the state of the parser must match m_xps for the rule to be considered.
// If the value eNotParsing is in the table, it matches any current parser
// state. Use this to globally ignore some particular tag type when
// combined with a NULL m_pszTag and NULL m_pfn.
// Second, the type of the tag from the XML parser must match m_dwType.
// If m_pszTag is not NULL, a case-insensitive comparison is done between the
// string m_pszTag points to and the tag from the XML parser. An m_pszTag
// value of NULL matches any tag.
// If the three criteria match, the worker function is called. The worker function
// pointer may be NULL, in which case no action is taken. (This is useful for
// callbacks from the parser about XML_WHITESPACE where we don't really have to do
// anything at all.)
//
#define DEFINE_TAG_WORKER_IGNOREALLOFTYPE(dwType) { CNodeFactory::eNotParsing, (dwType), NULL, NULL, NULL, 0, 0, 0, NULL }
//
// Notes on use of the DEFINE_TAG_WORKER_ELEMENT() macro:
//
// The first parameter, sourceState, is part of the name of a XMLParseState
// enumeration value. It is concatenated onto "eParsing" to form the name of
// the state which the rule will match.
//
// The second parameter is both the text of the tag to match and is used to
// form the name of the function to invoke if the rule matches. The tag is
// compared case-insensitively, and the name of the member function invoked
// is XMLParser_Element_ followed by the sourceState string followed by another
// underscore, followed by the tagName string. So, for example, the following
// rule:
//
// DEFINE_TAG_WORKER_ELEMENT(DepAssy, Version)
//
// says that when the parser is in the eParsingDepAssy state and a "Version"
// tag is found, call the function CNodeFactory::XMLParser_Element_DepAssy_Version().
//
#define DEFINE_TAG_WORKER_ELEMENT(sourceState, tagName) \
{ \
CNodeFactory::eParsing_ ## sourceState, \
XML_ELEMENT, \
SXS_ASSEMBLY_MANIFEST_STD_NAMESPACE, \
L ## #tagName, \
s_rg_ ## sourceState ## _ ## tagName ## _attributes, \
NUMBER_OF(SXS_ASSEMBLY_MANIFEST_STD_NAMESPACE) - 1, \
NUMBER_OF(L ## #tagName) - 1, \
NUMBER_OF(s_rg_ ## sourceState ## _ ## tagName ## _attributes), \
&CNodeFactory::XMLParser_Element_ ## sourceState ## _ ## tagName, \
CNodeFactory::eParsing_ ## sourceState ## _ ## tagName \
}
#define DEFINE_TAG_WORKER_ELEMENT_NOCB(sourceState, tagName) \
{ \
CNodeFactory::eParsing_ ## sourceState, \
XML_ELEMENT, \
SXS_ASSEMBLY_MANIFEST_STD_NAMESPACE, \
L ## #tagName, \
s_rg_ ## sourceState ## _ ## tagName ## _attributes, \
NUMBER_OF(SXS_ASSEMBLY_MANIFEST_STD_NAMESPACE) - 1, \
NUMBER_OF(L ## #tagName) - 1, \
NUMBER_OF(s_rg_ ## sourceState ## _ ## tagName ## _attributes), \
NULL, \
CNodeFactory::eParsing_ ## sourceState ## _ ## tagName \
}
#define DEFINE_TAG_WORKER_ELEMENT_NONS(sourceState, tagName) \
{ \
CNodeFactory::eParsing_ ## sourceState, \
XML_ELEMENT, \
NULL, \
L ## #tagName, \
s_rg_ ## sourceState ## _ ## tagName ## _attributes, \
0, \
NUMBER_OF(L ## #tagName) - 1, \
NUMBER_OF(s_rg_ ## sourceState ## _ ## tagName ## _attributes), \
&CNodeFactory::XMLParser_Element_ ## sourceState ## _ ## tagName, \
CNodeFactory::eParsing_ ## sourceState ## _ ## tagName \
}
#define BEGIN_ELEMENT_LEGAL_ATTRIBUTES(_element) \
const static ELEMENT_LEGAL_ATTRIBUTE s_rg_ ## _element ## _attributes[] = { \
{ ELEMENT_LEGAL_ATTRIBUTE_FLAG_IGNORE, NULL, NULL },
#define DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(attributeName, validatorFlags, validator) { ELEMENT_LEGAL_ATTRIBUTE_FLAG_REQUIRED, &s_AttributeName_ ## attributeName, validator, validatorFlags },
#define DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(attributeName, validatorFlags, validator) { 0, &s_AttributeName_ ## attributeName, validator, validatorFlags },
#define END_ELEMENT_LEGAL_ATTRIBUTES(_element) };
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(manifestVersion, 0, NULL)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_description)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_description)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_noInherit)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_noInherit)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_noInheritable)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_noInheritable)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_assemblyIdentity)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(name, 0, NULL)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(version, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(type, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(processorArchitecture, SXSP_VALIDATE_PROCESSOR_ARCHITECTURE_ATTRIBUTE_FLAG_WILDCARD_ALLOWED, &::SxspValidateProcessorArchitectureAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(publicKeyToken, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(language, 0, &::SxspValidateLanguageAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(publicKey, 0, NULL)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_assemblyIdentity)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_dependency)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(optional, 0, &::SxspValidateBoolAttribute)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_dependency)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_dependency_dependentAssembly)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_dependency_dependentAssembly)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_dependency_dependentAssembly_assemblyIdentity)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(name, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(type, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(version, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(processorArchitecture, SXSP_VALIDATE_PROCESSOR_ARCHITECTURE_ATTRIBUTE_FLAG_WILDCARD_ALLOWED, &::SxspValidateProcessorArchitectureAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(publicKeyToken, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(language, SXSP_VALIDATE_LANGUAGE_ATTRIBUTE_FLAG_WILDCARD_ALLOWED, &::SxspValidateLanguageAttribute)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_dependency_dependentAssembly_assemblyIdentity)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_dependency_dependentAssembly_bindingRedirect)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(oldVersion, 0, NULL)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(newVersion, 0, NULL)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_dependency_dependentAssembly_bindingRedirect)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_file)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(name, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(hash, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(hashalg, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(loadFrom, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(size, 0, &::SxspValidateUnsigned64Attribute)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_file)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_file_comClass)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(clsid, 0, &::SxspValidateGuidAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(threadingModel, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(progid, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(tlbid, 0, &::SxspValidateGuidAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(description, 0, NULL)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_file_comClass)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_file_comClass_progid)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_file_comClass_progid)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_clrClass)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(name, 0, NULL)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(clsid, 0, &::SxspValidateGuidAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(progid, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(tlbid, 0, &::SxspValidateGuidAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(description, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(runtimeVersion, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(threadingModel, 0, NULL)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_clrClass)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_clrSurrogate)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(clsid, 0, &::SxspValidateGuidAttribute)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(name, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(runtimeVersion, 0, NULL)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_file_clrSurrogate)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_clrClass_progid)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_clrClass_progid)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_file_comInterfaceProxyStub)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(iid, 0, &::SxspValidateGuidAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(tlbid, 0, &::SxspValidateGuidAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(name, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(numMethods, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(baseInterface, 0, &::SxspValidateGuidAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(proxyStubClsid32, 0, &::SxspValidateGuidAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(threadingModel, 0, NULL)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_file_comInterfaceProxyStub)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_file_typelib)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(tlbid, 0, &::SxspValidateGuidAttribute)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(version, 0, NULL)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(helpdir, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(resourceid, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(flags, 0, NULL)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_file_typelib)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_file_windowClass)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(versioned, 0, &::SxspValidateBoolAttribute)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_file_windowClass)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_comInterfaceExternalProxyStub)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(iid, 0, &::SxspValidateGuidAttribute)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(name, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(proxyStubClsid32, 0, &::SxspValidateGuidAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(tlbid, 0, &::SxspValidateGuidAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(numMethods, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(baseInterface, 0, &::SxspValidateGuidAttribute)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_assembly_comInterfaceExternalProxyStub)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows_assemblyBinding)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows_assemblyBinding)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows_assemblyBinding_assemblyIdentity)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(name, 0, NULL)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(version, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(type, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(processorArchitecture, 0, &::SxspValidateProcessorArchitectureAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(publicKeyToken, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(language, 0, &::SxspValidateLanguageAttribute)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows_assemblyBinding_assemblyIdentity)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows_assemblyBinding_dependentAssembly_publisherPolicy)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(apply, 0, &::SxspValidateBoolAttribute)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows_assemblyBinding_dependentAssembly_publisherPolicy)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows_assemblyBinding_publisherPolicy)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(apply, 0, &::SxspValidateBoolAttribute)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows_assemblyBinding_publisherPolicy)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows_assemblyBinding_dependentAssembly)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows_assemblyBinding_dependentAssembly)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows_assemblyBinding_dependentAssembly_assemblyIdentity)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(name, 0, NULL)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(processorArchitecture, 0, &::SxspValidateProcessorArchitectureAttribute)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(type, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(publicKeyToken, 0, NULL)
DEFINE_ELEMENT_NONS_OPTIONAL_ATTRIBUTE(language, 0, &::SxspValidateLanguageAttribute)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows_assemblyBinding_dependentAssembly_assemblyIdentity)
BEGIN_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows_assemblyBinding_dependentAssembly_bindingRedirect)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(oldVersion, 0, NULL)
DEFINE_ELEMENT_NONS_REQUIRED_ATTRIBUTE(newVersion, 0, NULL)
END_ELEMENT_LEGAL_ATTRIBUTES(doc_configuration_windows_assemblyBinding_dependentAssembly_bindingRedirect)
static const struct
{
CNodeFactory::XMLParseState m_xpsOld;
DWORD m_dwType;
PCWSTR m_pszNamespace;
PCWSTR m_pszName;
PCELEMENT_LEGAL_ATTRIBUTE m_prgLegalAttributes;
UCHAR m_cchNamespace; // We use UCHAR here just for greater data density. Changing this and rebuilding
UCHAR m_cchName; // this module should work fine if you really need namespaces or names longer than
// 255 characters.
UCHAR m_cLegalAttributes;
CNodeFactory::XMLParserWorkerFunctionPtr m_pfn;
CNodeFactory::XMLParseState m_xpsNew;
} s_rgWorkers[] =
{
DEFINE_TAG_WORKER_IGNOREALLOFTYPE(XML_WHITESPACE),
DEFINE_TAG_WORKER_IGNOREALLOFTYPE(XML_COMMENT),
DEFINE_TAG_WORKER_ELEMENT(doc, assembly),
DEFINE_TAG_WORKER_ELEMENT(doc_assembly, assemblyIdentity),
DEFINE_TAG_WORKER_ELEMENT_NOCB(doc_assembly, description),
DEFINE_TAG_WORKER_ELEMENT(doc_assembly, noInherit),
DEFINE_TAG_WORKER_ELEMENT(doc_assembly, noInheritable),
DEFINE_TAG_WORKER_ELEMENT(doc_assembly, dependency),
DEFINE_TAG_WORKER_ELEMENT(doc_assembly_dependency, dependentAssembly),
DEFINE_TAG_WORKER_ELEMENT(doc_assembly_dependency_dependentAssembly, assemblyIdentity),
DEFINE_TAG_WORKER_ELEMENT(doc_assembly_dependency_dependentAssembly, bindingRedirect),
DEFINE_TAG_WORKER_ELEMENT_NOCB(doc_assembly, file),
DEFINE_TAG_WORKER_ELEMENT_NOCB(doc_assembly_file, comClass),
DEFINE_TAG_WORKER_ELEMENT_NOCB(doc_assembly_file_comClass, progid),
DEFINE_TAG_WORKER_ELEMENT_NOCB(doc_assembly, clrClass),
DEFINE_TAG_WORKER_ELEMENT_NOCB(doc_assembly_clrClass, progid),
DEFINE_TAG_WORKER_ELEMENT_NOCB(doc_assembly_file, comInterfaceProxyStub),
DEFINE_TAG_WORKER_ELEMENT_NOCB(doc_assembly_file, typelib),
DEFINE_TAG_WORKER_ELEMENT_NOCB(doc_assembly_file, windowClass),
DEFINE_TAG_WORKER_ELEMENT_NOCB(doc_assembly, clrSurrogate),
DEFINE_TAG_WORKER_ELEMENT_NOCB(doc_assembly, comInterfaceExternalProxyStub),
// All app config productions go here, just for neatness
DEFINE_TAG_WORKER_ELEMENT_NONS(doc, configuration),
DEFINE_TAG_WORKER_ELEMENT_NONS(doc_configuration, windows),
DEFINE_TAG_WORKER_ELEMENT(doc_configuration_windows, assemblyBinding),
DEFINE_TAG_WORKER_ELEMENT(doc_configuration_windows_assemblyBinding, assemblyIdentity),
DEFINE_TAG_WORKER_ELEMENT(doc_configuration_windows_assemblyBinding, dependentAssembly),
DEFINE_TAG_WORKER_ELEMENT(doc_configuration_windows_assemblyBinding, publisherPolicy),
DEFINE_TAG_WORKER_ELEMENT(doc_configuration_windows_assemblyBinding_dependentAssembly, assemblyIdentity),
DEFINE_TAG_WORKER_ELEMENT(doc_configuration_windows_assemblyBinding_dependentAssembly, bindingRedirect),
DEFINE_TAG_WORKER_ELEMENT(doc_configuration_windows_assemblyBinding_dependentAssembly, publisherPolicy),
};
BOOL
SxspIsNamespaceDeclaration(XML_NODE_INFO *pNodeInfo)
{
FN_TRACE();
ASSERT(pNodeInfo->dwType == XML_ATTRIBUTE);
//
// ISSUE: jonwis 3/8/2002 - Could use FusionpCompareString rather than doing it the 'hard way'
//
if (pNodeInfo->ulLen >= 5)
{ // "xmlns" : prefix for namespace declaration, default ns or non-default ns
if ((pNodeInfo->pwcText[0] == L'x') &&
(pNodeInfo->pwcText[1] == L'm') &&
(pNodeInfo->pwcText[2] == L'l') &&
(pNodeInfo->pwcText[3] == L'n') &&
(pNodeInfo->pwcText[4] == L's'))
{
if (pNodeInfo->ulLen == 5) // like xmlns="", default ns declaration
return TRUE;
else
if (pNodeInfo->pwcText[5] == L':')
return TRUE;
}
}
return FALSE;
}
//In this function, two tasks:
// 1) verify PublicKey and StrongName
// 2) create AssemblyIdentity based on xmlnode array
// 3) for (name, processorArchitecure, version. langid) they would be unique with SXS_ASSEMBLY_MANIFEST_STD_NAMESPACE
// 4) if there are dup triples {nsURL, name, value), only one is count, this is done with SxsCreateAssemblyIdentity
BOOL
SxspCreateAssemblyIdentityFromIdentityElement(
DWORD Flags,
PCACTCTXCTB_PARSE_CONTEXT ParseContext,
ULONG Type,
PASSEMBLY_IDENTITY *AssemblyIdentityOut,
DWORD cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
BOOL fSuccess = FALSE;
FN_TRACE_WIN32(fSuccess);
DWORD i;
//
// ISSUE: 3/9/2002 - Consider using a smart pointer here for AssemblyIdentity
// CSxsPointerWithNamedDestructor<ASSEMBLY_IDENTITY, ::SxsDestroyAssemblyIdentity> AssemblyIdentity;
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Leaking memory here if AssemblyIdentity isn't cleaned up (#3)
PASSEMBLY_IDENTITY AssemblyIdentity = NULL;
CStringBuffer buffValue;
if (AssemblyIdentityOut != NULL)
*AssemblyIdentityOut = NULL;
PARAMETER_CHECK((Flags & ~(SXSP_CREATE_ASSEMBLY_IDENTITY_FROM_IDENTITY_TAG_FLAG_VERIFY_PUBLIC_KEY_IF_PRESENT)) == 0);
PARAMETER_CHECK((Type == ASSEMBLY_IDENTITY_TYPE_DEFINITION) || (Type == ASSEMBLY_IDENTITY_TYPE_REFERENCE));
PARAMETER_CHECK(AssemblyIdentityOut != NULL);
PARAMETER_CHECK(prgNodeInfo != NULL);
PARAMETER_CHECK(prgNodeInfo[0].Type == XML_ELEMENT);
IFW32FALSE_EXIT(::SxsCreateAssemblyIdentity(0, Type, &AssemblyIdentity, 0, NULL));
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Why not use a 'for' loop? (#4)
i = 1;
while (i<cNumRecs)
{
ULONG j;
INTERNAL_ERROR_CHECK(prgNodeInfo[i].Type == XML_ATTRIBUTE);
buffValue.Clear();
//
// ISSUE: jonwis 3/9/2002 - Consider moving this to a for() loop for optimization's sake:
// for (j = i + 1; ((j < cNumRec) && (prgNodeInfo[j].Type == XML_PCDATA)); j++)
//
j = i + 1;
while ((j < cNumRecs) && (prgNodeInfo[j].Type == XML_PCDATA))
{
IFW32FALSE_EXIT(buffValue.Win32Append(prgNodeInfo[j].pszText, prgNodeInfo[j].cchText));
j++;
}
// if this is a special attribute, we'll handle it ... specially.
if ((prgNodeInfo[i].NamespaceStringBuf.Cch() == 0) &&
(::FusionpCompareStrings(
SXS_ASSEMBLY_IDENTITY_STD_ATTRIBUTE_NAME_PUBLIC_KEY,
SXS_ASSEMBLY_IDENTITY_STD_ATTRIBUTE_NAME_PUBLIC_KEY_CCH,
prgNodeInfo[i].pszText,
prgNodeInfo[i].cchText,
false) == 0))
{// ignore publicKey if it appears in assembly identity
}
else
{
//
// ISSUE: jonwis 3/9/2002 - Consider moving this to initialization rather than assignment
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Compiler is better than you are (#5)
ASSEMBLY_IDENTITY_ATTRIBUTE Attribute;
Attribute.Flags = 0;
Attribute.NamespaceCch = prgNodeInfo[i].NamespaceStringBuf.Cch();
Attribute.Namespace = prgNodeInfo[i].NamespaceStringBuf;
Attribute.NameCch = prgNodeInfo[i].cchText;
Attribute.Name = prgNodeInfo[i].pszText;
Attribute.ValueCch = buffValue.Cch();
Attribute.Value = buffValue;
IFW32FALSE_EXIT(::SxsInsertAssemblyIdentityAttribute(0, AssemblyIdentity, &Attribute));
}
i = j;
}
*AssemblyIdentityOut = AssemblyIdentity;
AssemblyIdentity = NULL;
fSuccess = TRUE;
Exit:
if (AssemblyIdentity != NULL)
::SxsDestroyAssemblyIdentity(AssemblyIdentity);
return fSuccess;
}
//
// ISSUE: jonwis 3/9/2002 - Consider reordering initializers to read more like what's in the
// class def for simpler reading. Also consider using a smart-pointer object to manage
// the m_Assembly, rather than doing our own management. Same for the ASSEMBLY_IDENTITY
// m_CurrentPolicyDependentAssemblyIdentity
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Odd ordering of initializers (#6)
CNodeFactory::CNodeFactory()
: m_ActCtxGenCtx(NULL),
m_Assembly(NULL),
m_fFirstCreateNodeCall(true),
m_cUnknownChildDepth(0),
m_xpsParseState(eParsing_doc),
m_fAssemblyFound(false),
m_fIdentityFound(false),
m_AssemblyContext(NULL),
m_CurrentPolicyDependentAssemblyIdentity(NULL),
m_CurrentPolicyStatement(NULL),
m_IntuitedParseType(eActualParseType_Undetermined),
m_pApplicationPolicyTable(NULL),
m_fNoInheritableFound(false)
{
m_ParseContext.XMLElementDepth = 0;
m_ParseContext.ElementPath = NULL;
m_ParseContext.ElementPathCch = 0;
m_ParseContext.ElementName = NULL;
m_ParseContext.ElementPathCch = 0;
m_ParseContext.ElementHash = 0;
}
CNodeFactory::~CNodeFactory()
{
CSxsPreserveLastError ple;
if ((m_CurrentPolicyStatement != NULL) &&
(m_CurrentPolicyDependentAssemblyIdentity != NULL) &&
(m_pApplicationPolicyTable != NULL))
{
#if 1
if (m_pApplicationPolicyTable->Find(m_buffCurrentApplicationPolicyIdentityKey, m_CurrentPolicyStatement))
m_CurrentPolicyStatement = NULL;
#else
CStringBuffer EncodedPolicyIdentity;
if (::SxspGenerateTextuallyEncodedPolicyIdentityFromAssemblyIdentity(
SXSP_GENERATE_TEXTUALLY_ENCODED_POLICY_IDENTITY_FROM_ASSEMBLY_IDENTITY_FLAG_OMIT_ENTIRE_VERSION,
m_CurrentPolicyDependentAssemblyIdentity,
EncodedPolicyIdentity,
NULL))
{
if (m_pApplicationPolicyTable->Find(EncodedPolicyIdentity, m_CurrentPolicyStatement))
{
m_CurrentPolicyStatement = NULL; // leave the cleanup work to outer destructor
}
}
#endif
}
FUSION_DELETE_SINGLETON(m_CurrentPolicyStatement);
if (m_CurrentPolicyDependentAssemblyIdentity != NULL)
::SxsDestroyAssemblyIdentity(m_CurrentPolicyDependentAssemblyIdentity);
if (m_Assembly != NULL)
{
m_Assembly->Release();
m_Assembly = NULL;
}
ple.Restore();
}
BOOL
CNodeFactory::Initialize(
PACTCTXGENCTX ActCtxGenCtx,
PASSEMBLY Assembly,
PACTCTXCTB_ASSEMBLY_CONTEXT AssemblyContext
)
{
FN_PROLOG_WIN32
PARAMETER_CHECK(Assembly != NULL);
IFW32FALSE_EXIT(m_XMLNamespaceManager.Initialize());
m_ActCtxGenCtx = ActCtxGenCtx;
Assembly->AddRef();
if (m_Assembly != NULL)
m_Assembly->Release();
m_Assembly = Assembly;
m_AssemblyContext = AssemblyContext;
m_ParseContext.AssemblyContext = AssemblyContext;
m_ParseContext.ErrorCallbacks.MissingRequiredAttribute = &CNodeFactory::ParseErrorCallback_MissingRequiredAttribute;
m_ParseContext.ErrorCallbacks.AttributeNotAllowed = &CNodeFactory::ParseErrorCallback_AttributeNotAllowed;
m_ParseContext.ErrorCallbacks.InvalidAttributeValue = &CNodeFactory::ParseErrorCallback_InvalidAttributeValue;
m_ParseContext.SourceFilePathType = AssemblyContext->ManifestPathType;
m_ParseContext.SourceFile = AssemblyContext->ManifestPath;
m_ParseContext.SourceFileCch = AssemblyContext->ManifestPathCch;
m_ParseContext.LineNumber = 0;
FN_EPILOG
}
VOID
CNodeFactory::ResetParseState()
{
m_fFirstCreateNodeCall = true;
m_fAssemblyFound = false;
m_fIdentityFound = false;
m_fNoInheritableFound = false;
FUSION_DELETE_SINGLETON(m_CurrentPolicyStatement);
m_CurrentPolicyStatement = NULL;
::SxsDestroyAssemblyIdentity(m_CurrentPolicyDependentAssemblyIdentity);
m_CurrentPolicyDependentAssemblyIdentity = NULL;
}
HRESULT
CNodeFactory::QueryInterface(
REFIID riid,
LPVOID *ppvObj
)
{
FN_PROLOG_HR
IUnknown *pIUnknown = NULL;
if (ppvObj != NULL)
*ppvObj = NULL;
else
ORIGINATE_HR_FAILURE_AND_EXIT(CNodeFactory::QueryInterface, E_POINTER);
if (riid == __uuidof(this))
pIUnknown = this;
else if ((riid == IID_IUnknown) || (riid == IID_IXMLNodeFactory))
pIUnknown = static_cast<IXMLNodeFactory *>(this);
else
ORIGINATE_HR_FAILURE_AND_EXIT(CNodeFactory::QueryInterface, E_NOINTERFACE);
pIUnknown->AddRef();
*ppvObj = pIUnknown;
FN_EPILOG
}
HRESULT
CNodeFactory::NotifyEvent(
IXMLNodeSource *pSource,
XML_NODEFACTORY_EVENT iEvt
)
{
return NOERROR;
}
HRESULT
CNodeFactory::ConvertXMLNodeInfoToSXSNodeInfo(
const XML_NODE_INFO *pNodeInfo,
SXS_NODE_INFO &rSXSNodeInfo
)
{
//
// ISSUE: jonwis 3/9/2002 - Consider filling out a private SXS_NODE_INFO and assigning it to
// the output SXSNodeInfo on success.
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Use a private SXS_NODE_INFO (#7)
HRESULT hr = NOERROR;
FN_TRACE_HR(hr);
INTERNAL_ERROR_CHECK(pNodeInfo != NULL);
rSXSNodeInfo.Size = pNodeInfo->dwSize;
rSXSNodeInfo.Type = pNodeInfo->dwType;
switch (pNodeInfo->dwType)
{
case XML_ELEMENT:
{
SIZE_T cchNamespacePrefix;
IFCOMFAILED_EXIT(
m_XMLNamespaceManager.Map(
0,
pNodeInfo,
&rSXSNodeInfo.NamespaceStringBuf,
&cchNamespacePrefix));
// +1 to skip colon
rSXSNodeInfo.pszText = pNodeInfo->pwcText + ((cchNamespacePrefix != 0) ? (cchNamespacePrefix + 1) : 0);
rSXSNodeInfo.cchText = pNodeInfo->ulLen - ((cchNamespacePrefix != 0) ? (cchNamespacePrefix + 1) : 0);
break;
}
case XML_ATTRIBUTE:
{
SIZE_T cchNamespacePrefix;
//
// ISSUE: jonwis 3/9/2002 - I think this is questionable. Why are we allowing through
// attributes named "xmlns:" and "xmlns="? Shouldn't these have been fixed earlier?
//
// ISSUE:2002-3-29:jonwis - I also think that this is a gross method of doing this work. Calling
// wcslen on constants is a "bad thing." There's got to be something better we
// could be doing here.
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Wierd passthroughs of xmlns variants
// if this is a namespace definition, ignore
const PCWSTR pwcText = pNodeInfo->pwcText;
if ((pwcText[0] == L'x') &&
(pwcText[1] == L'm') &&
(pwcText[2] == L'l') &&
(pwcText[3] == L'n') &&
(pwcText[4] == L's') &&
((pwcText[5] == L':') ||
(pwcText[5] == L'=')))
{
rSXSNodeInfo.pszText = pNodeInfo->pwcText;
rSXSNodeInfo.cchText = pNodeInfo->ulLen;
}
else
{
IFCOMFAILED_EXIT(
m_XMLNamespaceManager.Map(
CXMLNamespaceManager::eMapFlag_DoNotApplyDefaultNamespace,
pNodeInfo,
&rSXSNodeInfo.NamespaceStringBuf,
&cchNamespacePrefix));
// +1 to skip colon
rSXSNodeInfo.pszText = pNodeInfo->pwcText + ((cchNamespacePrefix != 0) ? (cchNamespacePrefix + 1) : 0);
rSXSNodeInfo.cchText = pNodeInfo->ulLen - ((cchNamespacePrefix != 0) ? (cchNamespacePrefix + 1) : 0);
}
break;
}
default:
// Otherwise we'll assume there's no namespace processing to do...
rSXSNodeInfo.NamespaceStringBuf.Clear();
rSXSNodeInfo.pszText = pNodeInfo->pwcText;
rSXSNodeInfo.cchText = pNodeInfo->ulLen;
break;
}
FN_EPILOG
}
HRESULT
CNodeFactory::BeginChildren(
IXMLNodeSource *pSource,
XML_NODE_INFO *pNodeInfo
)
{
FN_PROLOG_HR
ULONG i = 0;
SXS_NODE_INFO SXSNodeInfo;
IFCOMFAILED_EXIT(m_XMLNamespaceManager.OnBeginChildren(pSource, pNodeInfo));
IFCOMFAILED_EXIT(this->ConvertXMLNodeInfoToSXSNodeInfo(pNodeInfo, SXSNodeInfo));
for (i=0; i<m_ActCtxGenCtx->m_ContributorCount; i++)
{
IFW32FALSE_EXIT(
m_ActCtxGenCtx->m_Contributors[i].Fire_BeginChildren(
m_ActCtxGenCtx,
m_AssemblyContext,
&m_ParseContext,
&SXSNodeInfo));
}
FN_EPILOG
}
HRESULT
CNodeFactory::EndChildren(
IXMLNodeSource *pSource,
BOOL Empty,
XML_NODE_INFO *pNodeInfo
)
{
FN_PROLOG_HR
ULONG i = 0;
PWSTR Bang = NULL;
SXS_NODE_INFO SXSNodeInfo;
// Short-circuit PIs, XML-decls, whitespace and comments
if ((pNodeInfo->dwType == XML_PI) ||
(pNodeInfo->dwType == XML_XMLDECL) ||
(pNodeInfo->dwType == XML_COMMENT) ||
(pNodeInfo->dwType == XML_WHITESPACE))
{
FN_SUCCESSFUL_EXIT();
}
IFCOMFAILED_EXIT(m_XMLNamespaceManager.OnEndChildren(pSource, Empty, pNodeInfo));
// We hit the end of something; if we're skipping stuff, we're one level back towards
// paying attention.
if (m_cUnknownChildDepth != 0)
{
m_cUnknownChildDepth--;
}
else
{
ULONG j;
for (j=0; j<NUMBER_OF(s_rgWorkers); j++)
{
if (s_rgWorkers[j].m_xpsNew == m_xpsParseState)
{
m_xpsParseState = s_rgWorkers[j].m_xpsOld;
break;
}
}
if (j == NUMBER_OF(s_rgWorkers))
{
::FusionpDbgPrintEx(
FUSION_DBG_LEVEL_ERROR,
"SXS.DLL: %s() called when we were not expecting it. m_xpsParseState = %d\n", __FUNCTION__, m_xpsParseState);
INTERNAL_ERROR_CHECK(FALSE);
// Hey, how the heck did we get here?
}
// One time end-of-manifest checks...
if (m_xpsParseState == eParsing_doc)
{
switch (m_ParseType)
{
default:
INTERNAL_ERROR_CHECK(false);
break;
case XML_FILE_TYPE_COMPONENT_CONFIGURATION:
case XML_FILE_TYPE_APPLICATION_CONFIGURATION:
break;
case XML_FILE_TYPE_MANIFEST:
// If this is not the root assembly, this is not a noInherit actctx and the noInheritable
// element was not found, issue an error.
if (((m_AssemblyContext->Flags & ACTCTXCTB_ASSEMBLY_CONTEXT_IS_ROOT_ASSEMBLY) == 0) &&
m_ActCtxGenCtx->m_NoInherit &&
!m_fNoInheritableFound)
{
this->LogParseError(MSG_SXS_NOINHERIT_REQUIRES_NOINHERITABLE);
ORIGINATE_WIN32_FAILURE_AND_EXIT(NoInheritRequiresNoInheritable, ERROR_SXS_MANIFEST_PARSE_ERROR);
}
break;
}
}
}
if (pNodeInfo->dwType != XML_XMLDECL)
{
IFCOMFAILED_EXIT(this->ConvertXMLNodeInfoToSXSNodeInfo(pNodeInfo, SXSNodeInfo));
for (i=0; i<m_ActCtxGenCtx->m_ContributorCount; i++)
{
IFW32FALSE_EXIT(
m_ActCtxGenCtx->m_Contributors[i].Fire_EndChildren(
m_ActCtxGenCtx,
m_AssemblyContext,
&m_ParseContext,
Empty,
&SXSNodeInfo));
}
INTERNAL_ERROR_CHECK(m_ParseContext.XMLElementDepth != 0);
//
// ISSUE: jonwis 3/9/2002 - Comment this better! It's hard to figure out what this is doing.
// It's apparently turning "foo!bar!bas" into "foo!bar", and "foo" into "". This
// could probably be done much better with some cleaning.
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Cleanup this string-fixer code (#9)
m_ParseContext.XMLElementDepth--;
Bang = wcsrchr(m_buffElementPath, L'!');
INTERNAL_ERROR_CHECK(((Bang == NULL) == (m_ParseContext.XMLElementDepth == 0)));
if (Bang != NULL)
{
m_buffElementPath.Left(Bang - m_buffElementPath);
m_ParseContext.ElementPathCch = m_buffElementPath.Cch();
m_ParseContext.ElementPath = m_buffElementPath;
m_ParseContext.ElementName = wcsrchr(m_buffElementPath, L'!');
if (m_ParseContext.ElementName == NULL)
{
m_ParseContext.ElementName = m_buffElementPath;
m_ParseContext.ElementNameCch = m_buffElementPath.Cch();
}
else
{
m_ParseContext.ElementName++;
m_ParseContext.ElementNameCch = m_buffElementPath.Cch() - (m_ParseContext.ElementName - m_buffElementPath);
}
IFW32FALSE_ORIGINATE_AND_EXIT(
::SxspHashString(
m_buffElementPath,
m_ParseContext.ElementPathCch,
&m_ParseContext.ElementHash,
false));
}
else
{
m_buffElementPath.Clear();
m_ParseContext.ElementPath = NULL;
m_ParseContext.ElementPathCch = 0;
m_ParseContext.ElementName = NULL;
m_ParseContext.ElementNameCch = 0;
m_ParseContext.ElementHash = 0;
m_ParseContext.XMLElementDepth = 0;
}
}
FN_EPILOG
}
HRESULT
CNodeFactory::Error(
IXMLNodeSource *pSource,
HRESULT hrErrorCode,
USHORT cNumRecs,
XML_NODE_INFO **apNodeInfo
)
{
CSxsPreserveLastError ple;
::FusionpConvertCOMFailure(hrErrorCode);
::FusionpSetLastErrorFromHRESULT(hrErrorCode);
this->LogParseError(MSG_SXS_WIN32_ERROR_MSG_WHEN_PARSING_MANIFEST, CEventLogLastError());
ple.Restore();
return NOERROR;
}
HRESULT
CNodeFactory::FirstCreateNodeCall(
IXMLNodeSource *pSource,
PVOID pNodeParent,
USHORT NodeCount,
const SXS_NODE_INFO *prgNodeInfo
)
{
FN_PROLOG_HR
ULONG i = 0;
bool fGotGoodManifestVersion = false;
bool fGotAnyManifestVersion = false;
// It's our first IXMLNodeFactory::CreateNode() call. This had better
// be an <ASSEMBLY MANIFESTVERSION="1.0" ...> deal.
for (i=0; i<NodeCount; i++)
{
if (prgNodeInfo[i].Type == XML_ELEMENT)
{
INTERNAL_ERROR_CHECK(i == 0);
switch (m_ParseType)
{
default:
INTERNAL_ERROR_CHECK(false);
break;
//
// ISSUE: jonwis 3/9/2002 - My goodness, this is gross. Use FusionEqualStrings
// instead. Doing memcmps between strings is totally bogus.
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Memcmping here is bogus
case XML_FILE_TYPE_MANIFEST:
case XML_FILE_TYPE_COMPONENT_CONFIGURATION:
if ((prgNodeInfo[i].cchText != (NUMBER_OF(SXS_ASSEMBLY_MANIFEST_STD_ELEMENT_NAME_ASSEMBLY) - 1)) ||
(prgNodeInfo[i].NamespaceStringBuf.Cch() != (NUMBER_OF(SXS_ASSEMBLY_MANIFEST_STD_NAMESPACE) - 1)) ||
(memcmp(prgNodeInfo[i].pszText, SXS_ASSEMBLY_MANIFEST_STD_ELEMENT_NAME_ASSEMBLY, prgNodeInfo[i].cchText * sizeof(WCHAR)) != 0) ||
(memcmp(prgNodeInfo[i].NamespaceStringBuf, SXS_ASSEMBLY_MANIFEST_STD_NAMESPACE, prgNodeInfo[i].NamespaceStringBuf.Cch() * sizeof(WCHAR)) != 0))
{
IFCOMFAILED_EXIT(this->LogParseError(MSG_SXS_MANIFEST_INCORRECT_ROOT_ELEMENT));
}
break;
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Memcmping here is bogus
case XML_FILE_TYPE_APPLICATION_CONFIGURATION:
if ((prgNodeInfo[i].cchText != SXS_APPLICATION_CONFIGURATION_MANIFEST_STD_ELEMENT_NAME_CONFIGURATION_CCH) ||
(prgNodeInfo[i].NamespaceStringBuf.Cch() != 0) ||
(memcmp(prgNodeInfo[i].pszText, SXS_APPLICATION_CONFIGURATION_MANIFEST_STD_ELEMENT_NAME_CONFIGURATION,
SXS_APPLICATION_CONFIGURATION_MANIFEST_STD_ELEMENT_NAME_CONFIGURATION_CCH * sizeof(WCHAR)) != 0))
{
IFCOMFAILED_EXIT(this->LogParseError(MSG_SXS_MANIFEST_INCORRECT_ROOT_ELEMENT));
}
break;
}
}
else if (prgNodeInfo[i].Type == XML_ATTRIBUTE)
{
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Memcmping here is bogus
if ((prgNodeInfo[i].cchText == (NUMBER_OF(SXS_ASSEMBLY_MANIFEST_STD_ATTRIBUTE_NAME_MANIFEST_VERSION) - 1)) &&
(prgNodeInfo[i].NamespaceStringBuf.Cch() == 0) &&
(memcmp(prgNodeInfo[i].pszText, SXS_ASSEMBLY_MANIFEST_STD_ATTRIBUTE_NAME_MANIFEST_VERSION, prgNodeInfo[i].cchText * sizeof(WCHAR)) == 0))
{
fGotAnyManifestVersion = true;
ULONG j = i + 1;
//
// ISSUE: jonwis 3/9/2002 - Any reason these can't be a single if statement?
// - Oh, an NO MEMCMPING STRINGS
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Memcmping here is bogus
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Unrolled if (a&&b) is strange, but not wrong
if (j < NodeCount)
{
if (prgNodeInfo[j].Type == XML_PCDATA)
{
if (prgNodeInfo[j].cchText == 3)
{
if (memcmp(prgNodeInfo[j].pszText, L"1.0", prgNodeInfo[j].cchText * sizeof(WCHAR)) == 0)
{
fGotGoodManifestVersion = true;
}
}
}
}
}
}
}
if ((m_ParseType == XML_FILE_TYPE_MANIFEST) ||
(m_ParseType == XML_FILE_TYPE_COMPONENT_CONFIGURATION))
{
if (fGotAnyManifestVersion)
{
if (!fGotGoodManifestVersion)
IFCOMFAILED_EXIT(this->LogParseError(MSG_SXS_MANIFEST_VERSION_ERROR));
}
else
IFCOMFAILED_EXIT(this->LogParseError(MSG_SXS_MANIFEST_VERSION_MISSING));
}
m_Assembly->m_ManifestVersionMajor = 1;
m_Assembly->m_ManifestVersionMinor = 0;
FN_EPILOG
}
HRESULT
CNodeFactory::CreateNode(
IXMLNodeSource *pSource,
PVOID pNodeParent,
USHORT NodeCount,
XML_NODE_INFO **apNodeInfo
)
{
HRESULT hr = S_OK;
FN_TRACE_HR(hr);
ULONG i;
//
// ISSUE: jonwis 3/9/2002 - Consider making both of these smart-pointers to simplify cleanup
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Smart pointers would make cleanup cake
PSXS_XML_NODE pXmlNode = NULL;
PSXS_NODE_INFO pSXSNodeInfo = NULL;
SIZE_T cchTemp;
m_ParseContext.LineNumber = pSource->GetLineNumber();
INTERNAL_ERROR_CHECK(NodeCount != 0);
#if DBG
::FusionpDbgPrintEx(
FUSION_DBG_LEVEL_NODEFACTORY,
"SXS.DLL: " __FUNCTION__ "() entered\n"
" m_ParseContext.XMLElementDepth = %lu\n",
m_ParseContext.XMLElementDepth);
for (i=0; i<NodeCount; i++)
::SxspDbgPrintXmlNodeInfo(FUSION_DBG_LEVEL_NODEFACTORY, apNodeInfo[i]);
#endif
// Short-circuit PIs, XML-decls, whitespace and comments
if ((apNodeInfo[0]->dwType == XML_PI) ||
(apNodeInfo[0]->dwType == XML_XMLDECL) ||
(apNodeInfo[0]->dwType == XML_COMMENT) ||
(apNodeInfo[0]->dwType == XML_WHITESPACE))
{
FN_SUCCESSFUL_EXIT();
}
IFCOMFAILED_EXIT(m_XMLNamespaceManager.OnCreateNode(pSource, pNodeParent, NodeCount, apNodeInfo));
IFALLOCFAILED_EXIT(pSXSNodeInfo = new SXS_NODE_INFO[NodeCount]);
for (i=0; i<NodeCount; i++)
IFCOMFAILED_EXIT(this->ConvertXMLNodeInfoToSXSNodeInfo(apNodeInfo[i], pSXSNodeInfo[i]));
if (m_fFirstCreateNodeCall)
{
if ((apNodeInfo[0]->dwType == XML_COMMENT) ||
(apNodeInfo[0]->dwType == XML_XMLDECL) ||
(apNodeInfo[0]->dwType == XML_WHITESPACE))
{
hr = S_OK;
goto Cont;
}
m_fFirstCreateNodeCall = FALSE;
IFCOMFAILED_EXIT(this->FirstCreateNodeCall(pSource, pNodeParent, NodeCount, pSXSNodeInfo));
}
Cont:
if (m_cUnknownChildDepth == 0)
{
for (i=0; i<NUMBER_OF(s_rgWorkers); i++)
{
bool fTemp = false;
if ((s_rgWorkers[i].m_xpsOld == eNotParsing) ||
(m_xpsParseState == s_rgWorkers[i].m_xpsOld))
fTemp = true;
const bool fParseStateMatches = fTemp;
fTemp = false;
if (fParseStateMatches)
{
if (s_rgWorkers[i].m_dwType == apNodeInfo[0]->dwType)
fTemp = true;
}
const bool fTypeMatches = fTemp;
fTemp = false;
if (fTypeMatches)
{
if (s_rgWorkers[i].m_cchName == 0)
fTemp = true;
else
{
if (s_rgWorkers[i].m_cchNamespace == pSXSNodeInfo[0].NamespaceStringBuf.Cch())
{
if (s_rgWorkers[i].m_cchName == pSXSNodeInfo[0].cchText)
{
if (::FusionpCompareStrings(
s_rgWorkers[i].m_pszNamespace,
s_rgWorkers[i].m_cchNamespace,
pSXSNodeInfo[0].NamespaceStringBuf,
pSXSNodeInfo[0].NamespaceStringBuf.Cch(),
false) == 0)
{
if (::FusionpCompareStrings(
s_rgWorkers[i].m_pszName,
s_rgWorkers[i].m_cchName,
pSXSNodeInfo[0].pszText,
pSXSNodeInfo[0].cchText,
false) == 0)
{
fTemp = true;
}
}
}
}
}
}
if (fTemp)
{
m_xpsParseState = s_rgWorkers[i].m_xpsNew;
IFW32FALSE_EXIT(
this->ValidateElementAttributes(
pSXSNodeInfo,
NodeCount,
s_rgWorkers[i].m_prgLegalAttributes,
s_rgWorkers[i].m_cLegalAttributes));
if (s_rgWorkers[i].m_pfn != NULL)
IFW32FALSE_EXIT((this->*s_rgWorkers[i].m_pfn)(NodeCount, pSXSNodeInfo));
break;
}
}
if (i == NUMBER_OF(s_rgWorkers))
{
bool fEquals;
// If we hit an unrecognized element and its namespace is the one we own, error!
IFW32FALSE_EXIT(
pSXSNodeInfo[0].NamespaceStringBuf.Win32Equals(
SXS_ASSEMBLY_MANIFEST_STD_NAMESPACE,
SXS_ASSEMBLY_MANIFEST_STD_NAMESPACE_CCH,
fEquals,
false));
if (fEquals)
{
this->LogParseError(
MSG_SXS_MANIFEST_ELEMENT_USED_IN_INVALID_CONTEXT,
CUnicodeString(apNodeInfo[0]->pwcText, apNodeInfo[0]->ulLen),
CUnicodeString(m_ParseContext.ElementName, m_ParseContext.ElementNameCch));
ORIGINATE_WIN32_FAILURE_AND_EXIT(ElementInInvalidContext, ERROR_SXS_MANIFEST_PARSE_ERROR);
}
// For an unknown child element, the built-in XML parsing should start to ignore the subtree at this point.
if (apNodeInfo[0]->dwType == XML_ELEMENT)
m_cUnknownChildDepth = 1;
}
}
else
{
if ((NodeCount != 0) &&
(apNodeInfo[0]->dwType == XML_ELEMENT))
{
// We're handling an unknown series of elements; increment the depth.
m_cUnknownChildDepth++;
}
}
// Fire the right callbacks for XML_ELEMENT, XML_PCDATA and XML_CDATA nodes:
switch (apNodeInfo[0]->dwType)
{
case XML_ELEMENT:
#if defined(MSG_SXS_MANIFEST_PARSE_NO_INHERIT_CHILDREN_NOT_ALLOWED)
if (m_cUnknownChildDepth != 0 && m_xpsParseState == eParsing_doc_assembly_noInherit)
{
ORIGINATE_HR_FAILURE_AND_EXIT(CNodeFactory::CreateNode, this->LogParseError(MSG_SXS_MANIFEST_PARSE_NO_INHERIT_CHILDREN_NOT_ALLOWED));
}
#endif
if (m_buffElementPath.Cch() != 0)
IFW32FALSE_EXIT(m_buffElementPath.Win32Append(L"!", 1));
cchTemp = m_buffElementPath.Cch();
//
// ISSUE: jonwis 3/9/2002 - Use mutli-append here, maybe?
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - A multi-append here will frobble the heap less
if (pSXSNodeInfo[0].NamespaceStringBuf.Cch() != 0)
{
IFW32FALSE_EXIT(m_buffElementPath.Win32Append(pSXSNodeInfo[0].NamespaceStringBuf));
IFW32FALSE_EXIT(m_buffElementPath.Win32Append(L"^", 1));
}
IFW32FALSE_EXIT(m_buffElementPath.Win32Append(pSXSNodeInfo[0].pszText, pSXSNodeInfo[0].cchText));
m_ParseContext.ElementPathCch = m_buffElementPath.Cch();
m_ParseContext.ElementPath = m_buffElementPath;
m_ParseContext.ElementName = static_cast<PCWSTR>(m_buffElementPath) + cchTemp;
m_ParseContext.ElementNameCch = m_buffElementPath.Cch() - cchTemp;
IFW32FALSE_EXIT(::SxspHashString(m_buffElementPath, m_buffElementPath.Cch(), &m_ParseContext.ElementHash, true));
m_ParseContext.XMLElementDepth++;
//
// ISSUE: jonwis 3/9/2002 - Maybe there needs to be a more general way of dispatching
// this sort of stuff off to the contributors, rather than having embedded
// loops everywhere. Easier to read, easier to maintain (esp. if we end up
// doing some sort of filtering later.
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Lots of places seem to do something similar, consider collapsing
for (i=0; i<m_ActCtxGenCtx->m_ContributorCount; i++)
{
IFW32FALSE_EXIT(
m_ActCtxGenCtx->m_Contributors[i].Fire_ElementParsed(
m_ActCtxGenCtx,
m_AssemblyContext,
&m_ParseContext,
NodeCount,
pSXSNodeInfo));
}
break;
case XML_PCDATA:
for (i=0; i<m_ActCtxGenCtx->m_ContributorCount; i++)
{
IFW32FALSE_EXIT(
m_ActCtxGenCtx->m_Contributors[i].Fire_PCDATAParsed(
m_ActCtxGenCtx,
m_AssemblyContext,
&m_ParseContext,
apNodeInfo[0]->pwcText,
apNodeInfo[0]->ulLen));
}
break;
case XML_CDATA:
for (i=0; i<m_ActCtxGenCtx->m_ContributorCount; i++)
{
IFW32FALSE_EXIT(
m_ActCtxGenCtx->m_Contributors[i].Fire_CDATAParsed(
m_ActCtxGenCtx,
m_AssemblyContext,
&m_ParseContext,
apNodeInfo[0]->pwcText,
apNodeInfo[0]->ulLen));
}
break;
}
hr = NOERROR;
Exit:
if (pSXSNodeInfo != NULL)
FUSION_DELETE_ARRAY(pSXSNodeInfo);
if (pXmlNode != NULL)
FUSION_DELETE_SINGLETON(pXmlNode);
return hr;
}
BOOL
CNodeFactory::SetParseType(
ULONG ParseType,
ULONG PathType,
const CBaseStringBuffer &Path,
const FILETIME &rftLastWriteTime
)
{
FN_PROLOG_WIN32
PARAMETER_CHECK(
(ParseType == XML_FILE_TYPE_MANIFEST) ||
(ParseType == XML_FILE_TYPE_APPLICATION_CONFIGURATION) ||
(ParseType == XML_FILE_TYPE_COMPONENT_CONFIGURATION));
PARAMETER_CHECK(PathType == ACTIVATION_CONTEXT_PATH_TYPE_WIN32_FILE);
IFW32FALSE_EXIT(m_buffCurrentFileName.Win32Assign(Path));
m_ParseContext.SourceFilePathType = PathType;
m_ParseContext.SourceFile = m_buffCurrentFileName;
m_ParseContext.SourceFileCch = m_buffCurrentFileName.Cch();
m_ParseContext.SourceFileLastWriteTime = rftLastWriteTime;
m_ParseType = ParseType;
FN_EPILOG
}
BOOL
CNodeFactory::XMLParser_Element_doc_assembly(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
FN_PROLOG_WIN32
ULONG i;
ASSERT(cNumRecs != 0);
ASSERT(prgNodeInfo != NULL);
if (m_fAssemblyFound)
{
CUnicodeString s;
PCWSTR ManifestPath;
IFW32FALSE_EXIT(m_Assembly->GetManifestPath(&ManifestPath, NULL));
s = ManifestPath;
ORIGINATE_HR_FAILURE_AND_EXIT(CNodeFactory::XMLParser_Element_doc_assembly, this->LogParseError(MSG_SXS_MANIFEST_MULTIPLE_TOP_ASSEMBLY, &s));
}
m_fAssemblyFound = true;
m_fMetadataSatelliteAlreadyFound = false;
// Now let's tell all the contributors that we're about to begin a parsing session.
for (i=0; i<m_ActCtxGenCtx->m_ContributorCount; i++)
{
IFW32FALSE_EXIT(m_ActCtxGenCtx->m_Contributors[i].Fire_ParseBeginning(
m_ActCtxGenCtx,
m_AssemblyContext,
0, // FileFlags
m_ParseType,
m_ParseContext.SourceFilePathType,
m_ParseContext.SourceFile,
m_ParseContext.SourceFileCch,
m_ParseContext.SourceFileLastWriteTime,
m_Assembly->m_ManifestVersionMajor,
m_Assembly->m_ManifestVersionMinor,
m_Assembly->m_MetadataSatelliteRosterIndex));
}
FN_EPILOG
}
BOOL
CNodeFactory::XMLParser_Element_doc_assembly_assemblyIdentity(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
BOOL fSuccess = FALSE;
FN_TRACE_WIN32(fSuccess);
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Better cleanup in general here with smart pointers
PASSEMBLY_IDENTITY AssemblyIdentity = NULL;
const BOOL fGeneratingActCtx = (m_ActCtxGenCtx->m_ManifestOperation == MANIFEST_OPERATION_GENERATE_ACTIVATION_CONTEXT);
ULONG i;
DWORD dwValidateFlags = 0;
if (m_fIdentityFound)
{
this->LogParseError(MSG_SXS_MULTIPLE_IDENTITY, CEventLogString(prgNodeInfo[0].pszText, prgNodeInfo[0].cchText));
::FusionpDbgPrintEx(
FUSION_DBG_LEVEL_ERROR,
"SXS.DLL: Manifest %ls has multiple identities\n", static_cast<PCWSTR>(m_buffCurrentFileName));
ORIGINATE_WIN32_FAILURE_AND_EXIT(
MultipleIdentities,
ERROR_SXS_MANIFEST_PARSE_ERROR);
}
m_fIdentityFound = true;
IFW32FALSE_EXIT(
::SxspCreateAssemblyIdentityFromIdentityElement(
0, // DWORD Flags,
&m_ParseContext,
ASSEMBLY_IDENTITY_TYPE_DEFINITION, // ULONG Type,
&AssemblyIdentity, // PASSEMBLY_IDENTITY *AssemblyIdentityOut,
cNumRecs,
prgNodeInfo));
// If the identity that was created is a policy statement, then we
// set the internal parse type to our special 'intuited' parse type
// for later checks of missing attributes and whatnot. This does
// duplicate work in ValidateAssembly that does the same thing, but
// we need to preemptively set this parse type before we go validating.
// if (m_IntuitedParseType == eActualParseType_Undetermined)
{
BOOL fIsPolicy = FALSE;
IFW32FALSE_EXIT(::SxspDetermineAssemblyType(AssemblyIdentity, fIsPolicy));
if (fIsPolicy)
m_IntuitedParseType = eActualParseType_PolicyManifest;
else
m_IntuitedParseType = eActualParseType_Undetermined;
}
if ((m_IntuitedParseType == eActualParseType_Manifest) ||
(m_IntuitedParseType == eActualParseType_PolicyManifest) ||
(m_ParseType == XML_FILE_TYPE_MANIFEST) ||
(m_ParseType == XML_FILE_TYPE_COMPONENT_CONFIGURATION))
{
dwValidateFlags = eValidateIdentity_VersionRequired;
}
IFW32FALSE_EXIT(
this->ValidateIdentity(
dwValidateFlags,
ASSEMBLY_IDENTITY_TYPE_DEFINITION,
AssemblyIdentity));
if (fGeneratingActCtx)
{
if (m_Assembly->IsRoot())
{
// If we're generating the actctx and this is the root assembly, it's possible
// that we got to it by a filesystem path (e.g. private assembly) rather than
// an actual reference, so we need to fix up the assembly's identity information
// appropriately.
IFW32FALSE_EXIT(m_Assembly->m_ProbedAssemblyInformation.SetProbedIdentity(AssemblyIdentity));
}
else
{
// If we're generating the actctx and this isn't the root assembly, we need to verify
// that it's the right one.
BOOL fEqual;
IFW32FALSE_EXIT(
::SxsAreAssemblyIdentitiesEqual(
SXS_ARE_ASSEMBLY_IDENTITIES_EQUAL_FLAG_ALLOW_REF_TO_MATCH_DEF,
m_Assembly->GetAssemblyIdentity(),
AssemblyIdentity,
&fEqual));
if (!fEqual)
{
ORIGINATE_HR_FAILURE_AND_EXIT(
CNodeFactory::XMLParser_Element_doc_assembly_assemblyIdentity,
this->LogParseError(MSG_SXS_COMPONENT_MANIFEST_PROBED_IDENTITY_MISMATCH));
// LogParseError sets the last error appropriate to the message logged
}
}
}
if (m_IntuitedParseType == eActualParseType_PolicyManifest)
{
//
// ISSUE: jonwis 3/11/2002 - Stomps on m_CurrentPolicyStatement if it was non-null. Consider
// using INTERNAL_ERROR_CHECK to make sure it's NULL first.
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Track possible leaks here better
IFALLOCFAILED_EXIT(m_CurrentPolicyStatement = new CPolicyStatement);
IFW32FALSE_EXIT(m_CurrentPolicyStatement->Initialize());
}
// Tell everyone that we're sure who we are...
for (i=0; i<m_ActCtxGenCtx->m_ContributorCount; i++)
{
IFW32FALSE_EXIT(
m_ActCtxGenCtx->m_Contributors[i].Fire_IdentityDetermined(
m_ActCtxGenCtx,
m_AssemblyContext,
&m_ParseContext,
AssemblyIdentity));
}
// fix up assembly and assembly context so we know where to copy to
// also save the manifest
IFW32FALSE_EXIT(m_Assembly->m_ProbedAssemblyInformation.SetAssemblyIdentity(AssemblyIdentity));
if (m_AssemblyContext->AssemblyIdentity != NULL)
::SxsDestroyAssemblyIdentity(const_cast<PASSEMBLY_IDENTITY>(m_AssemblyContext->AssemblyIdentity));
m_AssemblyContext->AssemblyIdentity = AssemblyIdentity;
AssemblyIdentity = NULL;
fSuccess = TRUE;
Exit:
if (AssemblyIdentity != NULL)
::SxsDestroyAssemblyIdentity(AssemblyIdentity);
return fSuccess;
}
BOOL
CNodeFactory::XMLParser_Element_doc_assembly_noInherit(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
FN_PROLOG_WIN32
INTERNAL_ERROR_CHECK(
(m_ParseType == XML_FILE_TYPE_MANIFEST) ||
(m_ParseType == XML_FILE_TYPE_APPLICATION_CONFIGURATION) ||
(m_ParseType == XML_FILE_TYPE_COMPONENT_CONFIGURATION));
switch (m_ParseType)
{
case XML_FILE_TYPE_MANIFEST:
if (cNumRecs != 1)
{
ORIGINATE_HR_FAILURE_AND_EXIT(
CNodeFactory::XMLParser_Element_doc_assembly_noInherit,
this->LogParseError(MSG_SXS_MANIFEST_PARSE_NO_INHERIT_ATTRIBUTES_NOT_ALLOWED));
}
if (m_ActCtxGenCtx->m_NoInherit)
{
ORIGINATE_HR_FAILURE_AND_EXIT(
CNodeFactory::XMLParser_Element_doc_assembly_noInherit,
this->LogParseError(MSG_SXS_MANIFEST_PARSE_MULTIPLE_NO_INHERIT));
}
if (m_fIdentityFound)
{
ORIGINATE_HR_FAILURE_AND_EXIT(
CNodeFactory::XMLParser_Element_doc_assembly_noInherit,
this->LogParseError(
MSG_SXS_MANIFEST_ELEMENT_MUST_OCCUR_BEFORE,
CEventLogString(L"noInherit"),
CEventLogString(L"assemblyIdentity")));
}
m_ActCtxGenCtx->m_NoInherit = true;
break;
case XML_FILE_TYPE_APPLICATION_CONFIGURATION:
ORIGINATE_HR_FAILURE_AND_EXIT(
CNodeFactory::XMLParser_Element_doc_assembly_noInherit,
this->LogParseError(MSG_SXS_POLICY_PARSE_NO_INHERIT_NOT_ALLOWED));
break;
default:
INTERNAL_ERROR_CHECK(FALSE);
break;
}
FN_EPILOG
}
BOOL
CNodeFactory::XMLParser_Element_doc_assembly_noInheritable(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
BOOL fSuccess = FALSE;
FN_TRACE_WIN32(fSuccess);
INTERNAL_ERROR_CHECK(
(m_ParseType == XML_FILE_TYPE_MANIFEST) ||
(m_ParseType == XML_FILE_TYPE_APPLICATION_CONFIGURATION) ||
(m_ParseType == XML_FILE_TYPE_COMPONENT_CONFIGURATION));
switch (m_ParseType)
{
case XML_FILE_TYPE_MANIFEST:
if (cNumRecs != 1)
{
this->LogParseError(MSG_SXS_MANIFEST_PARSE_NO_INHERIT_ATTRIBUTES_NOT_ALLOWED);
goto Exit;
}
if (m_fNoInheritableFound)
{
this->LogParseError(MSG_SXS_MANIFEST_PARSE_MULTIPLE_NOINHERITABLE);
goto Exit;
}
if (m_fIdentityFound)
{
this->LogParseError(
MSG_SXS_MANIFEST_ELEMENT_MUST_OCCUR_BEFORE,
CEventLogString(L"noInheritable"),
CEventLogString(L"assemblyIdentity"));
goto Exit;
}
m_fNoInheritableFound = true;
break;
case XML_FILE_TYPE_APPLICATION_CONFIGURATION:
case XML_FILE_TYPE_COMPONENT_CONFIGURATION:
this->LogParseError(MSG_SXS_POLICY_PARSE_NO_INHERIT_NOT_ALLOWED);
goto Exit;
default:
::FusionpSetLastWin32Error(ERROR_INTERNAL_ERROR);
goto Exit;
}
fSuccess = TRUE;
Exit:
return fSuccess;
}
BOOL
CNodeFactory::XMLParser_Element_doc_assembly_dependency(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
FN_PROLOG_WIN32
bool fFound;
SIZE_T cb;
m_fIsDependencyOptional = false;
m_fDependencyChildHit = false;
m_fIsMetadataSatellite = false;
IFW32FALSE_EXIT(
::SxspGetAttributeValue(
0,
&s_AttributeName_optional,
prgNodeInfo,
cNumRecs,
&m_ParseContext,
fFound,
sizeof(m_fIsDependencyOptional),
&m_fIsDependencyOptional,
cb,
&::SxspValidateBoolAttribute,
0));
if (!fFound)
m_fIsDependencyOptional = false;
FN_EPILOG
}
BOOL
CNodeFactory::XMLParser_Element_doc_assembly_dependency_dependentAssembly(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
FN_PROLOG_WIN32
bool fFound;
SIZE_T cb;
if (m_fDependencyChildHit == false)
{
m_fDependencyChildHit = true;
}
else
{
ORIGINATE_HR_FAILURE_AND_EXIT(
CNodeFactory::XMLParser_Element_doc_assembly_dependency_dependentAssembly,
this->LogParseError(MSG_SXS_MANIFEST_MULTIPLE_DEPENDENTASSEMBLY_IN_DEPENDENCY));
}
m_fAssemblyIdentityChildOfDependenctAssemblyHit = false;
IFW32FALSE_EXIT(
::SxspGetAttributeValue(
0,
&s_AttributeName_metadataSatellite,
prgNodeInfo,
cNumRecs,
&m_ParseContext,
fFound,
sizeof(m_fIsMetadataSatellite),
&m_fIsMetadataSatellite,
cb,
&::SxspValidateBoolAttribute,
0));
if (!fFound)
m_fIsMetadataSatellite = false;
FN_EPILOG
}
BOOL
CNodeFactory::XMLParser_Element_doc_assembly_dependency_dependentAssembly_bindingRedirect(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
BOOL fSuccess = FALSE;
FN_TRACE_WIN32(fSuccess);
bool fFound;
bool fValid;
SIZE_T cb;
CSmallStringBuffer buffOldVersion;
CSmallStringBuffer buffNewVersion;
INTERNAL_ERROR_CHECK(m_CurrentPolicyStatement != NULL);
if (m_IntuitedParseType != eActualParseType_PolicyManifest)
{
this->LogParseError(MSG_SXS_BINDING_REDIRECTS_ONLY_IN_COMPONENT_CONFIGURATION);
goto Exit;
}
IFW32FALSE_EXIT(
::SxspGetAttributeValue(
SXSP_GET_ATTRIBUTE_VALUE_FLAG_REQUIRED_ATTRIBUTE,
&s_AttributeName_oldVersion,
prgNodeInfo,
cNumRecs,
&m_ParseContext,
fFound,
sizeof(buffOldVersion),
&buffOldVersion,
cb,
NULL,
0));
INTERNAL_ERROR_CHECK(fFound);
IFW32FALSE_EXIT(
::SxspGetAttributeValue(
SXSP_GET_ATTRIBUTE_VALUE_FLAG_REQUIRED_ATTRIBUTE,
&s_AttributeName_newVersion,
prgNodeInfo,
cNumRecs,
&m_ParseContext,
fFound,
sizeof(buffNewVersion),
&buffNewVersion,
cb,
NULL,
0));
INTERNAL_ERROR_CHECK(fFound);
IFW32FALSE_EXIT(m_CurrentPolicyStatement->AddRedirect(buffOldVersion, buffNewVersion, fValid));
if (!fValid)
{
this->LogParseError(MSG_SXS_BINDING_REDIRECT_MISSING_REQUIRED_ATTRIBUTES);
goto Exit;
}
fSuccess = TRUE;
Exit:
return fSuccess;
}
BOOL
CNodeFactory::XMLParser_Element_doc_assembly_dependency_dependentAssembly_assemblyIdentity(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
FN_PROLOG_WIN32
CSmartPtrWithNamedDestructor<ASSEMBLY_IDENTITY, ::SxsDestroyAssemblyIdentity> pAssemblyIdentity;
ULONG ParseType;
ASSERT(cNumRecs != 0);
ASSERT(prgNodeInfo != NULL);
// We're either parsing a manifest or a policy file; what else??
INTERNAL_ERROR_CHECK(
(m_ParseType == XML_FILE_TYPE_MANIFEST) ||
(m_ParseType == XML_FILE_TYPE_APPLICATION_CONFIGURATION) ||
(m_ParseType == XML_FILE_TYPE_COMPONENT_CONFIGURATION));
if (m_fAssemblyIdentityChildOfDependenctAssemblyHit == false)
m_fAssemblyIdentityChildOfDependenctAssemblyHit = true;
else
{
this->LogParseError(MSG_SXS_MANIFEST_MULTIPLE_ASSEMBLYIDENTITY_IN_DEPENDENCYASSEMBLY);
goto Exit;
}
switch (m_IntuitedParseType)
{
case eActualParseType_Undetermined:
ParseType = m_ParseType;
break;
case eActualParseType_PolicyManifest:
ParseType = XML_FILE_TYPE_COMPONENT_CONFIGURATION;
break;
case eActualParseType_Manifest:
ParseType = XML_FILE_TYPE_MANIFEST;
break;
default:
INTERNAL_ERROR_CHECK(FALSE);
ParseType = m_ParseType;
break;
}
switch (ParseType)
{
case XML_FILE_TYPE_MANIFEST:
IFW32FALSE_EXIT(
::SxspCreateAssemblyIdentityFromIdentityElement(
0,
&m_ParseContext,
ASSEMBLY_IDENTITY_TYPE_REFERENCE,
&pAssemblyIdentity,
cNumRecs,
prgNodeInfo));
IFW32FALSE_EXIT(
this->ValidateIdentity(
eValidateIdentity_PoliciesNotAllowed| eValidateIdentity_VersionRequired,
ASSEMBLY_IDENTITY_TYPE_REFERENCE,
pAssemblyIdentity));
//
// If we're not installing, process the identity...
//
// Note that in a strange twist on refcounting, SxspEnqueueAssemblyReference does not
// hold the reference, it clones it. That's why we don't .Detach from the pAssemblyIdentity
// smart pointer here.
//
if (m_ActCtxGenCtx->m_ManifestOperation == MANIFEST_OPERATION_GENERATE_ACTIVATION_CONTEXT)
IFW32FALSE_EXIT(::SxspEnqueueAssemblyReference(m_ActCtxGenCtx, m_Assembly, pAssemblyIdentity, m_fIsDependencyOptional, m_fIsMetadataSatellite));
break;
case XML_FILE_TYPE_COMPONENT_CONFIGURATION:
{
BOOL fValidDependencyAssemblyIdentity = FALSE;
PCWSTR pszName1 = NULL, pszName2 = NULL;
SIZE_T cchName1 = 0, cchName2 = 0;
if (m_CurrentPolicyDependentAssemblyIdentity != NULL)
{
this->LogParseError(MSG_SXS_COMPONENT_CONFIGURATION_MANIFESTS_MAY_ONLY_HAVE_ONE_DEPENDENCY);
goto Exit;
}
IFW32FALSE_EXIT(
::SxspCreateAssemblyIdentityFromIdentityElement(
0,
&m_ParseContext,
ASSEMBLY_IDENTITY_TYPE_REFERENCE,
&pAssemblyIdentity,
cNumRecs,
prgNodeInfo));
// check the name in dependency-assemblyidentity match with the name in assembly-assemblyidentity
IFW32FALSE_EXIT(
::SxspGetAssemblyIdentityAttributeValue(
SXSP_GET_ASSEMBLY_IDENTITY_ATTRIBUTE_VALUE_FLAG_NOT_FOUND_RETURNS_NULL,
m_Assembly->GetAssemblyIdentity(),
&s_IdentityAttribute_name,
&pszName1, // something in a format of "Policy.1212.1221.assemblyname"
&cchName1));
IFW32FALSE_EXIT(
::SxspGetAssemblyIdentityAttributeValue(
SXSP_GET_ASSEMBLY_IDENTITY_ATTRIBUTE_VALUE_FLAG_NOT_FOUND_RETURNS_NULL,
pAssemblyIdentity,
&s_IdentityAttribute_name,
&pszName2, // would be something as "assemblyname"
&cchName2));
if ((cchName1 > cchName2) && (cchName2 !=0))
{
if ( (*(pszName1 + (cchName1 - cchName2 -1)) == L'.') && (::FusionpCompareStrings(
pszName1 + (cchName1 - cchName2), cchName2,
pszName2, cchName2, FALSE // must be case-sensitive for values
) == 0 ))
{
fValidDependencyAssemblyIdentity = TRUE;
}
}
if (fValidDependencyAssemblyIdentity)
{
IFW32FALSE_EXIT(
this->ValidateIdentity(
eValidateIdentity_PoliciesNotAllowed | eValidateIdentity_VersionNotAllowed,
ASSEMBLY_IDENTITY_TYPE_REFERENCE,
pAssemblyIdentity));
// We'll keep track of this so that we can recognize multiple dependentAssembly elements on installation
// of policies.
INTERNAL_ERROR_CHECK(m_CurrentPolicyDependentAssemblyIdentity == NULL);
m_CurrentPolicyDependentAssemblyIdentity = pAssemblyIdentity.Detach();
}
else // print a message and ignore this entry
{
::FusionpDbgPrintEx(
FUSION_DBG_LEVEL_POLICY | FUSION_DBG_LEVEL_INFO,
"SXS.DLL: unexpected assemblyidentity within dependency tag in component policy \"%ls\"\n",
m_buffCurrentFileName
);
}
} // end of this case
break;
default:
// Internal error!
INTERNAL_ERROR_CHECK(FALSE);
}
FN_EPILOG
}
BOOL
CNodeFactory::XMLParser_Element_doc_configuration(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
BOOL fSuccess = FALSE;
FN_TRACE_WIN32(fSuccess);
ULONG i;
ASSERT(cNumRecs != 0);
ASSERT(prgNodeInfo != NULL);
if (m_fAssemblyFound)
{
CUnicodeString s;
PCWSTR ManifestPath;
IFW32FALSE_EXIT(m_Assembly->GetManifestPath(&ManifestPath, NULL));
s = ManifestPath;
this->LogParseError(MSG_SXS_MANIFEST_MULTIPLE_TOP_ASSEMBLY, &s);
goto Exit;
}
m_fAssemblyFound = true;
m_fMetadataSatelliteAlreadyFound = false;
// Now let's tell all the contributors that we're about to begin a parsing session.
for (i=0; i<m_ActCtxGenCtx->m_ContributorCount; i++)
{
IFW32FALSE_EXIT(
m_ActCtxGenCtx->m_Contributors[i].Fire_ParseBeginning(
m_ActCtxGenCtx,
m_AssemblyContext,
0, // FileFlags
m_ParseType,
m_ParseContext.SourceFilePathType,
m_ParseContext.SourceFile,
m_ParseContext.SourceFileCch,
m_ParseContext.SourceFileLastWriteTime,
m_Assembly->m_ManifestVersionMajor,
m_Assembly->m_ManifestVersionMinor,
m_Assembly->m_MetadataSatelliteRosterIndex));
}
fSuccess = TRUE;
Exit:
return fSuccess;
}
BOOL
CNodeFactory::XMLParser_Element_doc_configuration_windows(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
BOOL fSuccess = FALSE;
FN_TRACE_WIN32(fSuccess);
fSuccess = TRUE;
// Exit:
return fSuccess;
}
BOOL
CNodeFactory::XMLParser_Element_doc_configuration_windows_assemblyBinding(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
BOOL fSuccess = FALSE;
FN_TRACE_WIN32(fSuccess);
fSuccess = TRUE;
// Exit:
return fSuccess;
}
BOOL
CNodeFactory::XMLParser_Element_doc_configuration_windows_assemblyBinding_assemblyIdentity(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
FN_PROLOG_WIN32;
CSmartPtrWithNamedDestructor<ASSEMBLY_IDENTITY, ::SxsDestroyAssemblyIdentity> pAssemblyIdentity;
IFW32FALSE_EXIT(
::SxspCreateAssemblyIdentityFromIdentityElement(
0,
&m_ParseContext,
ASSEMBLY_IDENTITY_TYPE_REFERENCE,
&pAssemblyIdentity,
cNumRecs,
prgNodeInfo));
IFW32FALSE_EXIT(
this->ValidateIdentity(
eValidateIdentity_PoliciesNotAllowed | eValidateIdentity_VersionRequired,
ASSEMBLY_IDENTITY_TYPE_REFERENCE,
pAssemblyIdentity));
FN_EPILOG;
}
BOOL
CNodeFactory::XMLParser_Element_doc_configuration_windows_assemblyBinding_dependentAssembly(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
BOOL fSuccess = FALSE;
FN_TRACE_WIN32(fSuccess);
fSuccess = TRUE;
// Exit:
return fSuccess;
}
BOOL
CNodeFactory::XMLParser_Element_doc_configuration_windows_assemblyBinding_dependentAssembly_assemblyIdentity(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
FN_PROLOG_WIN32;
CSmartPtrWithNamedDestructor<ASSEMBLY_IDENTITY, ::SxsDestroyAssemblyIdentity> pAssemblyIdentity;
CSmartPtr<CPolicyStatement> pPolicyStatement;
CPolicyStatement *pFoundPolicyStatement = NULL;
IFW32FALSE_EXIT(
::SxspCreateAssemblyIdentityFromIdentityElement(
0,
&m_ParseContext,
ASSEMBLY_IDENTITY_TYPE_REFERENCE,
&pAssemblyIdentity,
cNumRecs,
prgNodeInfo));
IFW32FALSE_EXIT(
this->ValidateIdentity(
eValidateIdentity_PoliciesNotAllowed | eValidateIdentity_VersionNotAllowed,
ASSEMBLY_IDENTITY_TYPE_REFERENCE,
pAssemblyIdentity));
IFW32FALSE_EXIT(
::SxspGenerateTextuallyEncodedPolicyIdentityFromAssemblyIdentity(
SXSP_GENERATE_TEXTUALLY_ENCODED_POLICY_IDENTITY_FROM_ASSEMBLY_IDENTITY_FLAG_OMIT_ENTIRE_VERSION,
pAssemblyIdentity,
m_buffCurrentApplicationPolicyIdentityKey,
NULL));
IFW32FALSE_EXIT(m_ActCtxGenCtx->m_ApplicationPolicyTable.Find(m_buffCurrentApplicationPolicyIdentityKey, pFoundPolicyStatement));
if (pFoundPolicyStatement != NULL)
{
this->LogParseError(MSG_SXS_APPLICATION_CONFIGURATION_MANIFEST_MAY_ONLY_HAVE_ONE_DEPENDENTASSEMBLY_PER_IDENTITY);
goto Exit;
}
IFALLOCFAILED_EXIT(pPolicyStatement.Win32Allocate(__FILE__, __LINE__));
IFW32FALSE_EXIT(pPolicyStatement->Initialize());
IFW32FALSE_EXIT(m_ActCtxGenCtx->m_ApplicationPolicyTable.Insert(m_buffCurrentApplicationPolicyIdentityKey, pPolicyStatement));
// preset it to be global value about m_fApplyPublisherPolicy,
// and be reset in dependentAssembly_publisherPolicy function if present
if ((this->m_ActCtxGenCtx->m_fAppApplyPublisherPolicy == SXS_PUBLISHER_POLICY_APPLY_YES) || (this->m_ActCtxGenCtx->m_fAppApplyPublisherPolicy == SXS_PUBLISHER_POLICY_APPLY_DEFAULT))
pPolicyStatement->m_fApplyPublisherPolicy = true;
else
pPolicyStatement->m_fApplyPublisherPolicy = false;
m_CurrentPolicyStatement = pPolicyStatement.Detach();
if (m_CurrentPolicyDependentAssemblyIdentity != NULL)
{
::SxsDestroyAssemblyIdentity(m_CurrentPolicyDependentAssemblyIdentity);
m_CurrentPolicyDependentAssemblyIdentity = NULL;
}
m_CurrentPolicyDependentAssemblyIdentity = pAssemblyIdentity.Detach();
FN_EPILOG;
}
BOOL
CNodeFactory::XMLParser_Element_doc_configuration_windows_assemblyBinding_dependentAssembly_publisherPolicy(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
FN_PROLOG_WIN32;
if (m_CurrentPolicyStatement == NULL)
{
this->LogParseError(MSG_SXS_APPLICATION_CONFIGURATION_MANIFEST_DEPENDENTASSEMBLY_MISSING_IDENTITY);
goto Exit;
}
if (this->m_ActCtxGenCtx->m_fAppApplyPublisherPolicy == SXS_PUBLISHER_POLICY_APPLY_NO)
m_CurrentPolicyStatement->m_fApplyPublisherPolicy = false;
else
{
bool fFound, fApplyPolicy;
SIZE_T cb;
IFW32FALSE_EXIT(
::SxspGetAttributeValue(
0,
&s_AttributeName_apply,
prgNodeInfo,
cNumRecs,
&m_ParseContext,
fFound,
sizeof(fApplyPolicy),
&fApplyPolicy,
cb,
SxspValidateBoolAttribute,
0));
INTERNAL_ERROR_CHECK(fFound); // if not found, syntax error in the manifest
if (fApplyPolicy == false)
{
//
// if this tag appears, appcompat flags must be set, otherwise it is an error
//
if (!(this->m_ActCtxGenCtx->m_Flags & SXS_GENERATE_ACTCTX_APP_RUNNING_IN_SAFEMODE))
{
::FusionpDbgPrintEx(
FUSION_DBG_LEVEL_ERROR,
"SXS.DLL: %s() app-level PublisherPolicy try to be set but there is no appcompat flags been set.\n", __FUNCTION__);
::SetLastError(ERROR_SXS_MANIFEST_PARSE_ERROR);
goto Exit;
}
}
m_CurrentPolicyStatement->m_fApplyPublisherPolicy = fApplyPolicy;
}
FN_EPILOG;
}
BOOL
CNodeFactory::XMLParser_Element_doc_configuration_windows_assemblyBinding_publisherPolicy(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
FN_PROLOG_WIN32;
bool fFound, fApplyPolicy;
SIZE_T cb;
if (this->m_ActCtxGenCtx->m_fAppApplyPublisherPolicy != SXS_PUBLISHER_POLICY_APPLY_DEFAULT)
{
::FusionpDbgPrintEx(
FUSION_DBG_LEVEL_ERROR,
"SXS.DLL: %s() called but app-level PublisherPolicy has already been set.\n", __FUNCTION__);
::SetLastError(ERROR_SXS_MANIFEST_PARSE_ERROR);
goto Exit;
}
IFW32FALSE_EXIT(
::SxspGetAttributeValue(
0,
&s_AttributeName_apply,
prgNodeInfo,
cNumRecs,
&m_ParseContext,
fFound,
sizeof(fApplyPolicy),
&fApplyPolicy,
cb,
SxspValidateBoolAttribute,
0));
INTERNAL_ERROR_CHECK(fFound);
if (!fApplyPolicy)
{
//
// if this tag set to be "no", appcompat flags must be set, otherwise it is an error
//
if (!(this->m_ActCtxGenCtx->m_Flags & SXS_GENERATE_ACTCTX_APP_RUNNING_IN_SAFEMODE))
{
::FusionpDbgPrintEx(
FUSION_DBG_LEVEL_ERROR,
"SXS.DLL: %s() app-level PublisherPolicy try to be set but there is no appcompat flags been set.\n", __FUNCTION__);
::SetLastError(ERROR_SXS_MANIFEST_PARSE_ERROR);
goto Exit;
}
this->m_ActCtxGenCtx->m_fAppApplyPublisherPolicy = SXS_PUBLISHER_POLICY_APPLY_NO;
}
else
this->m_ActCtxGenCtx->m_fAppApplyPublisherPolicy = SXS_PUBLISHER_POLICY_APPLY_YES;
FN_EPILOG;
}
BOOL
CNodeFactory::XMLParser_Element_doc_configuration_windows_assemblyBinding_dependentAssembly_bindingRedirect(
USHORT cNumRecs,
PCSXS_NODE_INFO prgNodeInfo
)
{
BOOL fSuccess = FALSE;
FN_TRACE_WIN32(fSuccess);
CSmallStringBuffer buffOldVersion;
CSmallStringBuffer buffNewVersion;
bool fFound;
bool fValid;
SIZE_T cb;
if (m_CurrentPolicyStatement == NULL)
{
this->LogParseError(MSG_SXS_APPLICATION_CONFIGURATION_MANIFEST_DEPENDENTASSEMBLY_MISSING_IDENTITY);
goto Exit;
}
IFW32FALSE_EXIT(
::SxspGetAttributeValue(
SXSP_GET_ATTRIBUTE_VALUE_FLAG_REQUIRED_ATTRIBUTE,
&s_AttributeName_oldVersion,
prgNodeInfo,
cNumRecs,
&m_ParseContext,
fFound,
sizeof(buffOldVersion),
&buffOldVersion,
cb,
NULL,
0));
INTERNAL_ERROR_CHECK(fFound);
IFW32FALSE_EXIT(
::SxspGetAttributeValue(
SXSP_GET_ATTRIBUTE_VALUE_FLAG_REQUIRED_ATTRIBUTE,
&s_AttributeName_newVersion,
prgNodeInfo,
cNumRecs,
&m_ParseContext,
fFound,
sizeof(buffNewVersion),
&buffNewVersion,
cb,
NULL,
0));
INTERNAL_ERROR_CHECK(fFound);
// If either are not found, log an error
if (!fFound)
{
this->LogParseError(MSG_SXS_BINDING_REDIRECT_MISSING_REQUIRED_ATTRIBUTES);
goto Exit;
}
IFW32FALSE_EXIT(m_CurrentPolicyStatement->AddRedirect(buffOldVersion, buffNewVersion, fValid));
if (! fValid)
{
// log an error
::FusionpLogError(
MSG_SXS_POLICY_VERSION_OVERLAP,
CEventLogString(m_AssemblyContext->PolicyPath),
CEventLogString(buffOldVersion),
CEventLogString(buffNewVersion));
ORIGINATE_WIN32_FAILURE_AND_EXIT(PolicyVersionOverlap, ERROR_SXS_MANIFEST_PARSE_ERROR);
}
fSuccess = TRUE;
Exit:
return fSuccess;
}
//
// ISSUE: jonwis 3/11/2002 - Smells like dead code. CPartialAssemblyVersion isn't constrcted anywhere,
// and this function isn't called by anyone.
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Dead code, probably
BOOL
CNodeFactory::XMLParser_Parse_PartialAssemblyVersion(
PVOID pvDatum,
BOOL fAlreadyFound,
CBaseStringBuffer &rbuff
)
{
return reinterpret_cast<CPartialAssemblyVersion *>(pvDatum)->Parse(rbuff, rbuff.Cch());
}
//
// ISSUE: jonwis 3/11/2002 - Same here... never called anywhere, dead code.
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Dead code, probably
BOOL
CNodeFactory::XMLParser_Parse_String(
LPVOID pvDatum,
BOOL fAlreadyFound,
CBaseStringBuffer &rbuff)
{
return ((CBaseStringBuffer *) pvDatum)->Win32Assign(rbuff);
}
//
// ISSUE: jonwis 3/11/2002 - More dead code. Will the madness ever end??
//
// NTRAID#NTBUG9 - 572507 - jonwis - 2002/04/25 - Dead code probably
BOOL
CNodeFactory::ParseElementAttributes(
USHORT cNumRecs,
XML_NODE_INFO **prgpNodeInfo,
SIZE_T cEntries,
const AttributeMapEntry *prgEntries
)
{
FN_PROLOG_WIN32
ULONG i, j;
for (i=1; i<cNumRecs; i++)
{
// Skip things we don't understand.
if (prgpNodeInfo[i]->dwType != XML_ATTRIBUTE)
continue;
for (j=0; j<cEntries; j++)
{
if (::FusionpEqualStrings(
prgEntries[j].m_pszAttributeName,
prgEntries[j].m_cchAttributeName,
prgpNodeInfo[i]->pwcText,
prgpNodeInfo[i]->ulLen,
false))
{
// Because attribute values may be multipart due to entity references,
// we accumulate the attibute value into buffTemp to start, and then do
// the parsing/whatever afterwards.
CStringBuffer buffTemp;
BOOL *pfIndicator = (BOOL *) (((ULONG_PTR) this) + prgEntries[j].m_offsetIndicator);
while ((++i < cNumRecs) &&
(prgpNodeInfo[i]->dwType == XML_PCDATA))
{
IFW32FALSE_EXIT(buffTemp.Win32Append(prgpNodeInfo[i]->pwcText, prgpNodeInfo[i]->ulLen));
}
// The outer for(;;) loop is going to increment i, so we need to back it up one
// place...
i--;
// Call the appropriate value type handler function...
if (prgEntries[j].m_pfn != NULL)
{
IFW32FALSE_EXIT((this->*(prgEntries[j].m_pfn))(((LPBYTE) this) + prgEntries[j].m_offsetData, *pfIndicator, buffTemp));
}
*pfIndicator = TRUE;
break;
}
}
}
FN_EPILOG
}
HRESULT
CNodeFactory::LogParseError(
DWORD dwLastParseError,
const UNICODE_STRING *p1,
const UNICODE_STRING *p2,
const UNICODE_STRING *p3,
const UNICODE_STRING *p4,
const UNICODE_STRING *p5,
const UNICODE_STRING *p6,
const UNICODE_STRING *p7,
const UNICODE_STRING *p8,
const UNICODE_STRING *p9,
const UNICODE_STRING *p10,
const UNICODE_STRING *p11,
const UNICODE_STRING *p12,
const UNICODE_STRING *p13,
const UNICODE_STRING *p14,
const UNICODE_STRING *p15,
const UNICODE_STRING *p16,
const UNICODE_STRING *p17,
const UNICODE_STRING *p18,
const UNICODE_STRING *p19,
const UNICODE_STRING *p20
)
{
return
::FusionpLogParseError(
m_ParseContext.SourceFile,
m_ParseContext.SourceFileCch,
m_ParseContext.LineNumber,
dwLastParseError,
p1, p2, p3, p4, p5,
p6, p7, p8, p9, p10,
p11, p12, p13, p14, p15,
p16, p17, p18, p19, p20);
}
VOID
CNodeFactory::ParseErrorCallback_MissingRequiredAttribute(
PCACTCTXCTB_PARSE_CONTEXT ParseContext,
IN PCATTRIBUTE_NAME_DESCRIPTOR AttributeName
)
{
// CNodeFactory *pThis = (CNodeFactory *) ErrorContext;
::FusionpLogRequiredAttributeMissingParseError(
ParseContext->SourceFile,
ParseContext->SourceFileCch,
ParseContext->LineNumber,
ParseContext->ElementName,
ParseContext->ElementNameCch,
AttributeName->Name,
AttributeName->NameCch);
}
VOID
CNodeFactory::ParseErrorCallback_InvalidAttributeValue(
PCACTCTXCTB_PARSE_CONTEXT ParseContext,
IN PCATTRIBUTE_NAME_DESCRIPTOR AttributeName
)
{
// CNodeFactory *pThis = (CNodeFactory *) ErrorContext;
::FusionpLogInvalidAttributeValueParseError(
ParseContext->SourceFile,
ParseContext->SourceFileCch,
ParseContext->LineNumber,
ParseContext->ElementName,
ParseContext->ElementNameCch,
AttributeName->Name,
AttributeName->NameCch);
}
VOID
CNodeFactory::ParseErrorCallback_AttributeNotAllowed(
PCACTCTXCTB_PARSE_CONTEXT ParseContext,
IN PCATTRIBUTE_NAME_DESCRIPTOR AttributeName
)
{
// CNodeFactory *pThis = (CNodeFactory *) ErrorContext;
::FusionpLogAttributeNotAllowedParseError(
ParseContext->SourceFile,
ParseContext->SourceFileCch,
ParseContext->LineNumber,
ParseContext->ElementName,
ParseContext->ElementNameCch,
AttributeName->Name,
AttributeName->NameCch);
}
VOID
SxspDbgPrintXmlNodeInfo(
ULONG Level,
XML_NODE_INFO *pNode
)
{
CUnicodeString s(pNode->pwcText, pNode->ulLen);
#if DBG_SXS
::FusionpDbgPrintEx(Level, "SXS.DLL: XML_NODE_INFO at %p\n", pNode);
::FusionpDbgPrintEx(Level, " dwSize = %d\n", pNode->dwSize);
::FusionpDbgPrintEx(Level, " dwType = %d (%s)\n", pNode->dwType, SxspFormatXmlNodeType(pNode->dwType));
::FusionpDbgPrintEx(Level, " dwSubType = %d\n", pNode->dwSubType);
::FusionpDbgPrintEx(Level, " fTerminal = %d\n", pNode->fTerminal);
::FusionpDbgPrintEx(Level, " pwcText = %p (\"%wZ\")\n", pNode->pwcText, &s);
::FusionpDbgPrintEx(Level, " ulLen = %d\n", pNode->ulLen);
::FusionpDbgPrintEx(Level, " ulNsPrefixLen = %d\n", pNode->ulNsPrefixLen);
::FusionpDbgPrintEx(Level, " pNode = %p\n", pNode->pNode);
::FusionpDbgPrintEx(Level, " pReserved = %p\n", pNode->pReserved);
#else
::FusionpDbgPrintEx(Level, "SXS.DLL: XML_NODE_INFO at %p: \"%wZ\"\n", pNode, &s);
#endif
}
PCSTR
SxspFormatXmlNodeType(
DWORD dwType
)
{
PCSTR Result = "Unknown";
#define HANDLE_NODE_TYPE(x) case static_cast<DWORD>(x): Result = #x; break;
switch (dwType)
{
HANDLE_NODE_TYPE(XML_ELEMENT)
HANDLE_NODE_TYPE(XML_ATTRIBUTE)
HANDLE_NODE_TYPE(XML_PI)
HANDLE_NODE_TYPE(XML_XMLDECL)
HANDLE_NODE_TYPE(XML_DOCTYPE)
HANDLE_NODE_TYPE(XML_DTDATTRIBUTE)
HANDLE_NODE_TYPE(XML_ENTITYDECL)
HANDLE_NODE_TYPE(XML_ELEMENTDECL)
HANDLE_NODE_TYPE(XML_ATTLISTDECL)
HANDLE_NODE_TYPE(XML_NOTATION)
HANDLE_NODE_TYPE(XML_GROUP)
HANDLE_NODE_TYPE(XML_INCLUDESECT)
HANDLE_NODE_TYPE(XML_PCDATA)
HANDLE_NODE_TYPE(XML_CDATA)
HANDLE_NODE_TYPE(XML_IGNORESECT)
HANDLE_NODE_TYPE(XML_COMMENT)
HANDLE_NODE_TYPE(XML_ENTITYREF)
HANDLE_NODE_TYPE(XML_WHITESPACE)
HANDLE_NODE_TYPE(XML_NAME)
HANDLE_NODE_TYPE(XML_NMTOKEN)
HANDLE_NODE_TYPE(XML_STRING)
HANDLE_NODE_TYPE(XML_PEREF)
HANDLE_NODE_TYPE(XML_MODEL)
HANDLE_NODE_TYPE(XML_ATTDEF)
HANDLE_NODE_TYPE(XML_ATTTYPE)
HANDLE_NODE_TYPE(XML_ATTPRESENCE)
HANDLE_NODE_TYPE(XML_DTDSUBSET)
}
return Result;
}
BOOL
CNodeFactory::ValidateIdentity(
DWORD Flags,
ULONG Type,
PCASSEMBLY_IDENTITY AssemblyIdentity
)
{
FN_PROLOG_WIN32
PCWSTR pszTemp = NULL;
SIZE_T cchTemp = 0;
bool fSyntaxValid = false;
bool fError = false;
BOOL fIsPolicy;
PARAMETER_CHECK((Flags & ~(
eValidateIdentity_VersionRequired |
eValidateIdentity_PoliciesNotAllowed |
eValidateIdentity_VersionNotAllowed)) == 0);
PARAMETER_CHECK((Type == ASSEMBLY_IDENTITY_TYPE_DEFINITION) || (Type == ASSEMBLY_IDENTITY_TYPE_REFERENCE));
PARAMETER_CHECK(AssemblyIdentity != NULL);
//
// only one of these flags is allowed
//
PARAMETER_CHECK(
(Flags & (eValidateIdentity_VersionRequired | eValidateIdentity_VersionNotAllowed)) !=
(eValidateIdentity_VersionRequired | eValidateIdentity_VersionNotAllowed));
//
// Get the type of this assembly
//
IFW32FALSE_EXIT(::SxspDetermineAssemblyType(AssemblyIdentity, fIsPolicy));
//
// If it's policy, then make sure that policies are allowed. Otherwise, fail out.
//
if (fIsPolicy)
{
m_AssemblyContext->Flags |= ACTCTXCTB_ASSEMBLY_CONTEXT_IS_SYSTEM_POLICY_INSTALLATION;
if (Flags & eValidateIdentity_PoliciesNotAllowed)
{
CUnicodeString usType(pszTemp, cchTemp);
fError = true;
::FusionpDbgPrintEx(
FUSION_DBG_LEVEL_ERROR,
"SXS.DLL: Manifest \"%ls\" (line %d) has invalid type attribute \"%wZ\"; report to owner of \"%ls\"\n",
m_ParseContext.SourceFile,
m_ParseContext.LineNumber,
&usType,
m_ParseContext.SourceFile);
}
}
IFW32FALSE_EXIT(
::SxspGetAssemblyIdentityAttributeValue(
SXSP_GET_ASSEMBLY_IDENTITY_ATTRIBUTE_VALUE_FLAG_NOT_FOUND_RETURNS_NULL,
AssemblyIdentity,
&s_IdentityAttribute_name,
&pszTemp,
&cchTemp));
if (cchTemp == 0)
{
::FusionpDbgPrintEx(
FUSION_DBG_LEVEL_ERROR,
"SXS.DLL: Manifest \"%ls\" (line %d) is missing name attribute; report to owner of \"%ls\"\n",
m_ParseContext.SourceFile,
m_ParseContext.LineNumber,
m_ParseContext.SourceFile);
fError = true;
}
IFW32FALSE_EXIT(
::SxspGetAssemblyIdentityAttributeValue(
SXSP_GET_ASSEMBLY_IDENTITY_ATTRIBUTE_VALUE_FLAG_NOT_FOUND_RETURNS_NULL,
AssemblyIdentity,
&s_IdentityAttribute_processorArchitecture,
&pszTemp,
&cchTemp));
IFW32FALSE_EXIT(
::SxspGetAssemblyIdentityAttributeValue(
SXSP_GET_ASSEMBLY_IDENTITY_ATTRIBUTE_VALUE_FLAG_NOT_FOUND_RETURNS_NULL,
AssemblyIdentity,
&s_IdentityAttribute_version,
&pszTemp,
&cchTemp));
if (cchTemp != 0)
{
ASSEMBLY_VERSION av;
IFW32FALSE_EXIT(CFusionParser::ParseVersion(av, pszTemp, cchTemp, fSyntaxValid));
if (!fSyntaxValid)
{
::FusionpLogInvalidAttributeValueParseError(
m_ParseContext.SourceFile,
m_ParseContext.SourceFileCch,
m_ParseContext.LineNumber,
m_ParseContext.ElementName,
m_ParseContext.ElementNameCch,
s_IdentityAttribute_version);
ORIGINATE_WIN32_FAILURE_AND_EXIT(InvalidVersionNumber, ERROR_SXS_MANIFEST_PARSE_ERROR);
}
}
if ((Flags & (eValidateIdentity_VersionNotAllowed | eValidateIdentity_VersionRequired)) != 0)
{
if ((Flags & eValidateIdentity_VersionNotAllowed) != 0 && cchTemp != 0)
{
fError = true;
::FusionpDbgPrintEx(
FUSION_DBG_LEVEL_ERROR,
"SXS.DLL: Manifest \"%ls\" (line %d) has a version attribute where it may not appear; report to owner of \"%ls\"\n",
m_ParseContext.SourceFile,
m_ParseContext.LineNumber,
m_ParseContext.SourceFile);
}
else if ((Flags & eValidateIdentity_VersionRequired) != 0 && cchTemp == 0)
{
fError = true;
::FusionpDbgPrintEx(
FUSION_DBG_LEVEL_ERROR,
"SXS.DLL: Manifest \"%ls\" (line %d) is missing version attribute; report to owner of \"%ls\"\n",
m_ParseContext.SourceFile,
m_ParseContext.LineNumber,
m_ParseContext.SourceFile);
}
}
if (fError)
{
::FusionpDbgPrintEx(
FUSION_DBG_LEVEL_ERROR,
"SXS.DLL: Manifest \"%ls\" is missing required attribute or contains disallowed attribute; report to owner of \"%ls\"\n",
m_ParseContext.SourceFile,
m_ParseContext.SourceFile);
ORIGINATE_WIN32_FAILURE_AND_EXIT(InvalidIdentity, ERROR_SXS_MANIFEST_PARSE_ERROR);
}
FN_EPILOG
}
BOOL
CNodeFactory::ValidateElementAttributes(
PCSXS_NODE_INFO prgNodes,
SIZE_T cNodes,
PCELEMENT_LEGAL_ATTRIBUTE prgAttributes,
UCHAR cAttributes
)
{
FN_PROLOG_WIN32
SIZE_T i;
UCHAR j;
UCHAR cRequiredAttributes, cRequiredAttributesFound;
UCHAR rgRequiredAttributeFoundBitMask[8]; // 8 * 32 = 256
BOOL fParseFailed = FALSE;
PARAMETER_CHECK((cNodes == 0) || (prgNodes != NULL));
PARAMETER_CHECK((cAttributes == 0) || (prgAttributes != NULL));
cRequiredAttributes = 0;
cRequiredAttributesFound = 0;
for (i=0; i<cAttributes; i++)
if (prgAttributes[i].m_dwFlags & ELEMENT_LEGAL_ATTRIBUTE_FLAG_REQUIRED)
cRequiredAttributes++;
rgRequiredAttributeFoundBitMask[0] = 0;
rgRequiredAttributeFoundBitMask[1] = 0;
rgRequiredAttributeFoundBitMask[2] = 0;
rgRequiredAttributeFoundBitMask[3] = 0;
rgRequiredAttributeFoundBitMask[4] = 0;
rgRequiredAttributeFoundBitMask[5] = 0;
rgRequiredAttributeFoundBitMask[6] = 0;
rgRequiredAttributeFoundBitMask[7] = 0;
for (i=0; i<cNodes; i++)
{
if (prgNodes[i].Type == SXS_ATTRIBUTE)
{
const SIZE_T cchText = prgNodes[i].cchText;
const SIZE_T cchNamespace = prgNodes[i].NamespaceStringBuf.Cch();
const PCWSTR pszText = prgNodes[i].pszText;
// Ignore any attributes that start with xml
if ((cchText >= 3) &&
((pszText[0] == L'x') || (pszText[0] == L'X')) &&
((pszText[1] == L'm') || (pszText[1] == L'M')) &&
((pszText[2] == L'l') || (pszText[2] == L'L')))
{
continue;
}
if (cchNamespace != 0 )
{
continue;
}
for (j=0; j<cAttributes; j++)
{
if ((prgAttributes[j].m_pName != NULL) &&
::FusionpEqualStrings(prgNodes[i].NamespaceStringBuf, cchNamespace, prgAttributes[j].m_pName->Namespace, prgAttributes[j].m_pName->NamespaceCch, false) &&
::FusionpEqualStrings(pszText, cchText, prgAttributes[j].m_pName->Name, prgAttributes[j].m_pName->NameCch, false))
{
if (prgAttributes[j].m_pfnValidator != NULL)
{
CSmallStringBuffer buffValue;
bool fValid = false;
SIZE_T cb;
SIZE_T i2;
for (i2=i+1; i2<cNodes; i2++)
{
if (prgNodes[i2].Type == SXS_PCDATA)
IFW32FALSE_EXIT(buffValue.Win32Append(prgNodes[i2].pszText, prgNodes[i2].cchText));
else
break;
}
IFW32FALSE_EXIT(
(*prgAttributes[j].m_pfnValidator)(
prgAttributes[j].m_dwValidatorFlags,
buffValue,
fValid,
0,
NULL,
cb));
if (!fValid)
{
::FusionpLogInvalidAttributeValueParseError(
m_ParseContext.SourceFile,
m_ParseContext.SourceFileCch,
m_ParseContext.LineNumber,
m_ParseContext.ElementName,
m_ParseContext.ElementNameCch,
prgAttributes[j].m_pName->Name,
prgAttributes[j].m_pName->NameCch);
ORIGINATE_WIN32_FAILURE_AND_EXIT(InvalidAttributeValue, ERROR_SXS_MANIFEST_PARSE_ERROR);
}
}
if (prgAttributes[j].m_dwFlags & ELEMENT_LEGAL_ATTRIBUTE_FLAG_REQUIRED)
{
rgRequiredAttributeFoundBitMask[(j / 32)] |= (1 << (j % 32));
cRequiredAttributesFound++;
}
break;
}
}
if (j == cAttributes)
{
// We found an illegal attribute!!
::FusionpLogAttributeNotAllowedParseError(
m_ParseContext.SourceFile,
m_ParseContext.SourceFileCch,
m_ParseContext.LineNumber,
prgNodes[0].pszText,
prgNodes[0].cchText,
prgNodes[i].pszText,
prgNodes[i].cchText);
// We don't just go to exit here because we want to report all the bad attributes and missing attributes...
fParseFailed = TRUE;
}
}
}
if (cRequiredAttributesFound != cRequiredAttributes)
{
for (j=0; j<cAttributes; j++)
{
if (prgAttributes[j].m_dwFlags & ELEMENT_LEGAL_ATTRIBUTE_FLAG_REQUIRED)
{
if ((rgRequiredAttributeFoundBitMask[(j / 32)] & (1 << (j % 32))) == 0)
{
::FusionpLogRequiredAttributeMissingParseError(
m_ParseContext.SourceFile,
m_ParseContext.SourceFileCch,
m_ParseContext.LineNumber,
prgNodes[0].pszText,
prgNodes[0].cchText,
prgAttributes[j].m_pName->Name,
prgAttributes[j].m_pName->NameCch);
fParseFailed = TRUE;
}
}
}
}
if (fParseFailed)
ORIGINATE_WIN32_FAILURE_AND_EXIT(ParseError, ERROR_SXS_MANIFEST_PARSE_ERROR);
FN_EPILOG
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.