code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QtAws is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "deletefunctiondefinitionrequest.h"
#include "deletefunctiondefinitionrequest_p.h"
#include "deletefunctiondefinitionresponse.h"
#include "greengrassrequest_p.h"
namespace QtAws {
namespace Greengrass {
/*!
* \class QtAws::Greengrass::DeleteFunctionDefinitionRequest
* \brief The DeleteFunctionDefinitionRequest class provides an interface for Greengrass DeleteFunctionDefinition requests.
*
* \inmodule QtAwsGreengrass
*
* AWS IoT Greengrass seamlessly extends AWS onto physical devices so they can act locally on the data they generate, while
* still using the cloud for management, analytics, and durable storage. AWS IoT Greengrass ensures your devices can
* respond quickly to local events and operate with intermittent connectivity. AWS IoT Greengrass minimizes the cost of
*
* \sa GreengrassClient::deleteFunctionDefinition
*/
/*!
* Constructs a copy of \a other.
*/
DeleteFunctionDefinitionRequest::DeleteFunctionDefinitionRequest(const DeleteFunctionDefinitionRequest &other)
: GreengrassRequest(new DeleteFunctionDefinitionRequestPrivate(*other.d_func(), this))
{
}
/*!
* Constructs a DeleteFunctionDefinitionRequest object.
*/
DeleteFunctionDefinitionRequest::DeleteFunctionDefinitionRequest()
: GreengrassRequest(new DeleteFunctionDefinitionRequestPrivate(GreengrassRequest::DeleteFunctionDefinitionAction, this))
{
}
/*!
* \reimp
*/
bool DeleteFunctionDefinitionRequest::isValid() const
{
return false;
}
/*!
* Returns a DeleteFunctionDefinitionResponse object to process \a reply.
*
* \sa QtAws::Core::AwsAbstractClient::send
*/
QtAws::Core::AwsAbstractResponse * DeleteFunctionDefinitionRequest::response(QNetworkReply * const reply) const
{
return new DeleteFunctionDefinitionResponse(*this, reply);
}
/*!
* \class QtAws::Greengrass::DeleteFunctionDefinitionRequestPrivate
* \brief The DeleteFunctionDefinitionRequestPrivate class provides private implementation for DeleteFunctionDefinitionRequest.
* \internal
*
* \inmodule QtAwsGreengrass
*/
/*!
* Constructs a DeleteFunctionDefinitionRequestPrivate object for Greengrass \a action,
* with public implementation \a q.
*/
DeleteFunctionDefinitionRequestPrivate::DeleteFunctionDefinitionRequestPrivate(
const GreengrassRequest::Action action, DeleteFunctionDefinitionRequest * const q)
: GreengrassRequestPrivate(action, q)
{
}
/*!
* Constructs a copy of \a other, with public implementation \a q.
*
* This copy-like constructor exists for the benefit of the DeleteFunctionDefinitionRequest
* class' copy constructor.
*/
DeleteFunctionDefinitionRequestPrivate::DeleteFunctionDefinitionRequestPrivate(
const DeleteFunctionDefinitionRequestPrivate &other, DeleteFunctionDefinitionRequest * const q)
: GreengrassRequestPrivate(other, q)
{
}
} // namespace Greengrass
} // namespace QtAws
|
pcolby/libqtaws
|
src/greengrass/deletefunctiondefinitionrequest.cpp
|
C++
|
lgpl-3.0
| 3,578 |
/**
* This file is part of topicmodeling.io.
*
* topicmodeling.io is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* topicmodeling.io is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with topicmodeling.io. If not, see <http://www.gnu.org/licenses/>.
*/
package org.dice_research.topicmodeling.io.xml;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import org.dice_research.topicmodeling.utils.doc.Document;
import org.dice_research.topicmodeling.utils.doc.DocumentMultipleCategories;
import org.dice_research.topicmodeling.utils.doc.DocumentText;
import org.dice_research.topicmodeling.utils.doc.ParseableDocumentProperty;
import org.dice_research.topicmodeling.utils.doc.ner.NamedEntitiesInText;
import org.dice_research.topicmodeling.utils.doc.ner.NamedEntityInText;
import org.dice_research.topicmodeling.utils.doc.ner.SignedNamedEntityInText;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractDocumentXmlReader implements XMLParserObserver {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractDocumentXmlReader.class);
private Document currentDocument;
private NamedEntityInText currentNamedEntity;
private List<NamedEntityInText> namedEntities = new ArrayList<NamedEntityInText>();
private List<String> categories = new ArrayList<String>();
private StringBuilder textBuffer = new StringBuilder();
private String data;
public AbstractDocumentXmlReader() {
}
@Override
public void handleOpeningTag(String tagString) {
// SHOULDN'T THIS METHOD SET data=""? Otherwise it is possible that a
// closing tag gets data that was set
// before its starting tag has been seen (in most cases this is "\n").
data = "";
// Ok, this is done and the JUnit test is green. This comment will
// remain here if another problem should
// arose.
int pos = tagString.indexOf(' ');
String tagName;
if (pos == -1) {
tagName = tagString;
} else {
tagName = tagString.substring(0, pos);
}
if (tagName.equals(CorpusXmlTagHelper.DOCUMENT_TAG_NAME)) {
currentDocument = new Document();
pos = tagString.indexOf(" id=\"");
if (pos > 0) {
pos += 5;
int tmp = tagString.indexOf('"', pos + 1);
if (tmp > 0) {
try {
tmp = Integer.parseInt(tagString.substring(pos, tmp));
currentDocument.setDocumentId(tmp);
} catch (NumberFormatException e) {
LOGGER.warn("Coudln't parse the document id from the document tag.", e);
}
} else {
LOGGER.warn("Found a document tag without a document id attribute.");
}
}
} else if (tagName.equals(CorpusXmlTagHelper.NAMED_ENTITY_IN_TEXT_TAG_NAME)
|| tagName.equals(CorpusXmlTagHelper.SIGNED_NAMED_ENTITY_IN_TEXT_TAG_NAME)) {
currentNamedEntity = parseNamedEntityInText(tagString);
currentNamedEntity.setStartPos(textBuffer.length());
}
}
@Override
public void handleClosingTag(String tagString) {
if (tagString.equals(CorpusXmlTagHelper.DOCUMENT_TAG_NAME)) {
finishedDocument(currentDocument);
currentDocument = null;
} else
if (tagString.equals(CorpusXmlTagHelper.TEXT_WITH_NAMED_ENTITIES_TAG_NAME) && (currentDocument != null)) {
currentDocument.addProperty(new DocumentText(textBuffer.toString()));
textBuffer.delete(0, textBuffer.length());
NamedEntitiesInText nes = new NamedEntitiesInText(namedEntities);
currentDocument.addProperty(nes);
namedEntities.clear();
} else if (tagString.equals(CorpusXmlTagHelper.TEXT_PART_TAG_NAME)) {
textBuffer.append(data);
data = "";
} else if (tagString.equals(CorpusXmlTagHelper.NAMED_ENTITY_IN_TEXT_TAG_NAME)
|| tagString.equals(CorpusXmlTagHelper.SIGNED_NAMED_ENTITY_IN_TEXT_TAG_NAME)) {
if (currentNamedEntity != null) {
currentNamedEntity.setLength(data.length());
namedEntities.add(currentNamedEntity);
textBuffer.append(data);
currentNamedEntity = null;
data = "";
}
} else if (tagString.equals(CorpusXmlTagHelper.DOCUMENT_CATEGORIES_TAG_NAME)) {
currentDocument
.addProperty(new DocumentMultipleCategories(categories.toArray(new String[categories.size()])));
categories.clear();
} else if (tagString.equals(CorpusXmlTagHelper.DOCUMENT_CATEGORIES_SINGLE_CATEGORY_TAG_NAME)) {
categories.add(data);
data = "";
} else {
if (currentDocument != null) {
Class<? extends ParseableDocumentProperty> propertyClazz = CorpusXmlTagHelper
.getParseableDocumentPropertyClassForTagName(tagString);
if (propertyClazz != null) {
try {
ParseableDocumentProperty property;
Constructor<? extends ParseableDocumentProperty> constructor;
try {
constructor = propertyClazz.getConstructor(String.class);
property = constructor.newInstance(data);
} catch (NoSuchMethodException e) {
// Couldn't get a constructor accepting a single
// String. Lets try the normal constructor.
constructor = propertyClazz.getConstructor();
property = constructor.newInstance();
property.parseValue(data);
}
currentDocument.addProperty(property);
} catch (Exception e) {
LOGGER.error("Couldn't parse property " + propertyClazz + " from the String \"" + data + "\".",
e);
}
}
data = "";
}
}
}
@Override
public void handleData(String data) {
this.data = data;
}
@Override
public void handleEmptyTag(String tagString) {
// nothing to do
}
protected NamedEntityInText parseNamedEntityInText(String tag) {
String namedEntityUri = null;
String namedEntitySource = null;
int startPos = -1;
int length = -1;
int start = 0, end = 0;
try {
start = tag.indexOf(' ') + 1;
end = tag.indexOf('=', start);
String key, value;
while (end > 0) {
key = tag.substring(start, end).trim();
end = tag.indexOf('"', end);
start = tag.indexOf('"', end + 1);
value = tag.substring(end + 1, start);
if (key.equals(CorpusXmlTagHelper.URI_ATTRIBUTE_NAME)) {
namedEntityUri = value;
} else if (key.equals(CorpusXmlTagHelper.SOURCE_ATTRIBUTE_NAME)) {
namedEntitySource = value;
}
/*
* else if (key.equals("start")) { startPos =
* Integer.parseInt(value); } else if (key.equals("length")) {
* length = Integer.parseInt(value); }
*/
++start;
end = tag.indexOf('=', start);
}
if (namedEntitySource != null) {
return new SignedNamedEntityInText(startPos, length, namedEntityUri, namedEntitySource);
} else {
return new NamedEntityInText(startPos, length, namedEntityUri);
}
} catch (Exception e) {
LOGGER.error("Couldn't parse NamedEntityInText tag (" + tag + "). Returning null.", e);
}
return null;
}
public static void registerParseableDocumentProperty(Class<? extends ParseableDocumentProperty> clazz) {
CorpusXmlTagHelper.registerParseableDocumentProperty(clazz);
}
protected abstract void finishedDocument(Document document);
}
|
AKSW/topicmodeling
|
topicmodeling.io/src/main/java/org/dice_research/topicmodeling/io/xml/AbstractDocumentXmlReader.java
|
Java
|
lgpl-3.0
| 9,108 |
/*******************************************************************************
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package com.jaspersoft.studio.components.chart.property.widget;
import java.util.List;
import net.sf.jasperreports.charts.JRDataRange;
import net.sf.jasperreports.charts.design.JRDesignDataRange;
import net.sf.jasperreports.charts.util.JRMeterInterval;
import net.sf.jasperreports.eclipse.ui.util.UIUtils;
import net.sf.jasperreports.engine.JRExpression;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ICellModifier;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.views.properties.IPropertyDescriptor;
import com.jaspersoft.studio.components.chart.messages.Messages;
import com.jaspersoft.studio.editor.expression.ExpressionContext;
import com.jaspersoft.studio.model.APropertyNode;
import com.jaspersoft.studio.property.descriptor.NullEnum;
import com.jaspersoft.studio.property.descriptor.color.ColorCellEditor;
import com.jaspersoft.studio.property.descriptor.color.ColorLabelProvider;
import com.jaspersoft.studio.property.descriptor.expression.JRExpressionCellEditor;
import com.jaspersoft.studio.property.section.AbstractSection;
import com.jaspersoft.studio.swt.widgets.table.DeleteButton;
import com.jaspersoft.studio.swt.widgets.table.INewElement;
import com.jaspersoft.studio.swt.widgets.table.ListContentProvider;
import com.jaspersoft.studio.swt.widgets.table.ListOrderButtons;
import com.jaspersoft.studio.swt.widgets.table.NewButton;
import com.jaspersoft.studio.utils.AlfaRGB;
import com.jaspersoft.studio.utils.Colors;
import com.jaspersoft.studio.utils.Misc;
/**
* Dialog with a table that show all the meter intervals defined, and allow to edit, move
* delete and add them
*
* @author Orlandin Marco
*
*/
public class MeterIntervalsDialog extends Dialog {
/**
* Section used to get the selected element
*/
private AbstractSection section;
/**
* Descriptor of the property
*/
private IPropertyDescriptor pDescriptor;
/**
* List of the intervals actually shown in the table
*/
private List<JRMeterInterval> intervalsList;
/**
* Table where the intervals are shown
*/
private Table table;
/**
* Table viewer
*/
private TableViewer tableViewer;
/**
* Composite where the table is placed
*/
private Composite sectioncmp;
/**
* Cell editor for the low expression
*/
private JRExpressionCellEditor lowExp;
/**
* Cell editor for the high expression
*/
private JRExpressionCellEditor highExp;
/**
* Create the dialog
*
* @param parentShell parent shell
* @param section section of the element
* @param pDescriptor descriptor of the intervals property
* @param intervalsList list of the intervals already inside the meter chart
*/
public MeterIntervalsDialog(Shell parentShell, AbstractSection section, IPropertyDescriptor pDescriptor, List<JRMeterInterval> intervalsList) {
super(parentShell);
this.pDescriptor = pDescriptor;
this.intervalsList = intervalsList;
this.section = section;
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText(Messages.MeterIntervalsDialog_dialogTitle);
}
/**
*
* Custom label provider for the table
*
*/
private final class TLabelProvider extends LabelProvider implements ITableLabelProvider {
private ColorLabelProvider colorLabel = new ColorLabelProvider(NullEnum.NULL);
/**
* Return an image only on the second column of the table, the one with the color. The
* image show a sample of the color
*/
public Image getColumnImage(Object element, int columnIndex) {
JRMeterInterval mi = (JRMeterInterval) element;
switch (columnIndex) {
case 1:
AlfaRGB color = Colors.getSWTRGB4AWTGBColor(mi.getBackgroundColor());
Double alfa = mi.getAlphaDouble();
color.setAlfa(alfa != null ? alfa : 1.0d);
return colorLabel.getImage(color);
}
return null;
}
/**
* Return an appropriate string for every column of the table
*/
public String getColumnText(Object element, int columnIndex) {
JRMeterInterval mi = (JRMeterInterval) element;
JRDataRange dataRange = mi.getDataRange();
switch (columnIndex) {
case 0:
return Misc.nvl(mi.getLabel(), ""); //$NON-NLS-1$
case 1:
AlfaRGB color = Colors.getSWTRGB4AWTGBColor(mi.getBackgroundColor());
Double alfa = mi.getAlphaDouble();
color.setAlfa(alfa != null ? alfa : 1.0d);
RGB rgb = color.getRgb();
return "RGBA (" + rgb.red + "," + rgb.green + "," + rgb.blue + "," + color.getAlfa()+")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
case 2:
if (dataRange != null) {
JRExpression lowe = dataRange.getLowExpression();
return lowe != null ? lowe.getText() : ""; //$NON-NLS-1$
}
break;
case 3:
if (dataRange != null) {
JRExpression highe = dataRange.getHighExpression();
return highe != null ? highe.getText() : ""; //$NON-NLS-1$
}
break;
}
return ""; //$NON-NLS-1$
}
}
@Override
protected Control createDialogArea(Composite parent) {
sectioncmp = (Composite)super.createDialogArea(parent);
sectioncmp = new Composite(sectioncmp, SWT.NONE);
sectioncmp.setLayout(new GridLayout(2,false));
sectioncmp.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite bGroup = new Composite(sectioncmp, SWT.NONE);
bGroup.setLayout(new GridLayout(1, false));
bGroup.setLayoutData(new GridData(GridData.FILL_VERTICAL));
buildTable(sectioncmp);
new NewButton().createNewButtons(bGroup, tableViewer, new INewElement() {
public Object newElement(List<?> input, int pos) {
NewMeterIntervalWizard wizard = new NewMeterIntervalWizard();
WizardDialog dialog = new WizardDialog(UIUtils.getShell(), wizard);
if (dialog.open() == WizardDialog.OK){
return wizard.getMeterInterval();
} else return null;
}
});
new DeleteButton().createDeleteButton(bGroup, tableViewer);
new ListOrderButtons().createOrderButtons(bGroup, tableViewer);
table.setToolTipText(pDescriptor.getDescription());
//Set the content of the table
APropertyNode selctedNode = section.getElement();
if (selctedNode != null) {
ExpressionContext expContext = new ExpressionContext(selctedNode.getJasperConfiguration());
lowExp.setExpressionContext(expContext);
highExp.setExpressionContext(expContext);
}
tableViewer.setInput(intervalsList);
return sectioncmp;
}
/**
* Create the table element with all the cell editors
*
* @param composite parent of the table
*/
private void buildTable(Composite composite) {
table = new Table(composite, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION);
GridData gd = new GridData(GridData.FILL_BOTH);
gd.heightHint = 200;
gd.widthHint = 580;
table.setLayoutData(gd);
table.setHeaderVisible(true);
table.setLinesVisible(true);
tableViewer = new TableViewer(table);
tableViewer.setContentProvider(new ListContentProvider());
tableViewer.setLabelProvider(new TLabelProvider());
attachCellEditors(tableViewer, table);
TableLayout tlayout = new TableLayout();
tlayout.addColumnData(new ColumnWeightData(25));
tlayout.addColumnData(new ColumnWeightData(25));
tlayout.addColumnData(new ColumnWeightData(25));
tlayout.addColumnData(new ColumnWeightData(25));
table.setLayout(tlayout);
TableColumn[] column = new TableColumn[4];
column[0] = new TableColumn(table, SWT.NONE);
column[0].setText(Messages.MeterIntervalsDialog_label);
column[1] = new TableColumn(table, SWT.NONE);
column[1].setText(Messages.MeterIntervalsDialog_background);
column[2] = new TableColumn(table, SWT.NONE);
column[2].setText(Messages.MeterIntervalsDialog_lowExpression);
column[3] = new TableColumn(table, SWT.NONE);
column[3].setText(Messages.MeterIntervalsDialog_highExpression);
for (int i = 0, n = column.length; i < n; i++)
column[i].pack();
}
/**
* Attach the cell editor to the table
*
* @param viewer viewer of the table
* @param parent the table
*/
private void attachCellEditors(final TableViewer viewer, Composite parent) {
viewer.setCellModifier(new ICellModifier() {
//Every column can be modfied
public boolean canModify(Object element, String property) {
if (property.equals("LABEL")) //$NON-NLS-1$
return true;
if (property.equals("COLOR")) //$NON-NLS-1$
return true;
if (property.equals("HIGH")) //$NON-NLS-1$
return true;
if (property.equals("LOW")) //$NON-NLS-1$
return true;
return false;
}
public Object getValue(Object element, String property) {
JRMeterInterval mi = (JRMeterInterval) element;
if (property.equals("LABEL"))//$NON-NLS-1$
return mi.getLabel();
if (property.equals("COLOR")){//$NON-NLS-1$
AlfaRGB color = Colors.getSWTRGB4AWTGBColor(mi.getBackgroundColor());
Double alfa = mi.getAlphaDouble();
color.setAlfa(alfa != null ? alfa : 1.0d);
return color;
}
if (property.equals("HIGH"))//$NON-NLS-1$
return mi.getDataRange().getHighExpression();
if (property.equals("LOW"))//$NON-NLS-1$
return mi.getDataRange().getLowExpression();
return null;
}
public void modify(Object element, String property, Object value) {
TableItem ti = (TableItem) element;
JRMeterInterval mi = (JRMeterInterval) ti.getData();
if (property.equals("LABEL")) {//$NON-NLS-1$
mi.setLabel((String) value);
}
if (property.equals("COLOR")) {//$NON-NLS-1$
AlfaRGB argb = (AlfaRGB) value;
mi.setBackgroundColor(Colors.getAWT4SWTRGBColor(argb));
mi.setAlpha(argb.getAlfa() / 255.0d);
}
if (property.equals("HIGH")) {//$NON-NLS-1$
((JRDesignDataRange) mi.getDataRange()).setHighExpression((JRExpression) value);
}
if (property.equals("LOW")) {//$NON-NLS-1$
((JRDesignDataRange) mi.getDataRange()).setLowExpression((JRExpression) value);
}
tableViewer.update(element, new String[] { property });
tableViewer.refresh();
propertyChange();
}
});
lowExp = new JRExpressionCellEditor(parent, null);
highExp = new JRExpressionCellEditor(parent, null);
ColorCellEditor argbColor = new ColorCellEditor(parent){
@Override
protected void updateContents(Object value) {
AlfaRGB argb = (AlfaRGB) value;
if (argb == null) {
rgbLabel.setText(""); //$NON-NLS-1$
} else {
RGB rgb = argb.getRgb();
rgbLabel.setText("RGBA (" + rgb.red + "," + rgb.green + "," + rgb.blue + "," + argb.getAlfa()+")");//$NON-NLS-4$ //$NON-NLS-5$//$NON-NLS-3$//$NON-NLS-2$//$NON-NLS-1$
}
}
};
viewer.setCellEditors(new CellEditor[] { new TextCellEditor(parent), argbColor, lowExp, highExp });
viewer.setColumnProperties(new String[] { "LABEL", "COLOR", "LOW", "HIGH" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
}
/**
* When something in the table change, the list of the element inside the table is update as well
*/
@SuppressWarnings("unchecked")
private void propertyChange() {
intervalsList = (List<JRMeterInterval>)tableViewer.getInput();
}
/**
* Return the list of the intervals actually shown in the table
*
* @return a list of intervals, can be null
*/
public List<JRMeterInterval> getIntervalsList(){
return intervalsList;
}
}
|
OpenSoftwareSolutions/PDFReporter-Studio
|
com.jaspersoft.studio.components/src/com/jaspersoft/studio/components/chart/property/widget/MeterIntervalsDialog.java
|
Java
|
lgpl-3.0
| 12,609 |
//
// This file is part of the Tioga software library
//
// Tioga is a tool for overset grid assembly on parallel distributed systems
// Copyright (C) 2015 Jay Sitaraman
//
// This library is TIOGA_FREE software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "codetypes.h"
#include "MeshBlock.h"
#include <cstring>
#include <stdexcept>
extern "C" {
void findOBB(double *x,double xc[3],double dxc[3],double vec[3][3],int nnodes);
double computeCellVolume(double xv[8][3],int nvert);
void deallocateLinkList(DONORLIST *temp);
void deallocateLinkList2(INTEGERLIST *temp);
double tdot_product(double a[3],double b[3],double c[3]);
void getobbcoords(double xc[3],double dxc[3],double vec[3][3],double xv[8][3]);
void transform2OBB(double xv[3],double xc[3],double vec[3][3],double xd[3]);
void writebbox(OBB *obb,int bid);
void writebboxdiv(OBB *obb,int bid);
}
void MeshBlock::setData(int btag,int nnodesi,double *xyzi, int *ibli,int nwbci, int nobci,
int *wbcnodei,int *obcnodei,
int ntypesi,int *nvi,int *nci,int **vconni,
uint64_t* cell_gid, uint64_t* node_gid)
{
int i;
//
// set internal pointers
//
meshtag=btag;
nnodes=nnodesi;
x=xyzi;
iblank=ibli;
nwbc=nwbci;
nobc=nobci;
wbcnode=wbcnodei;
obcnode=obcnodei;
//
ntypes=ntypesi;
//
nv=nvi;
nc=nci;
vconn=vconni;
cellGID = cell_gid;
nodeGID = node_gid;
//
//TRACEI(nnodes);
//for(i=0;i<ntypes;i++) TRACEI(nc[i]);
ncells=0;
for(i=0;i<ntypes;i++) ncells+=nc[i];
#ifdef TIOGA_HAS_NODEGID
if (nodeGID == NULL)
throw std::runtime_error("#tioga: global IDs for nodes not provided");
#endif
}
void MeshBlock::preprocess(void)
{
int i;
//
// set all iblanks = 1
//
for(i=0;i<nnodes;i++) iblank[i]=1;
//
// find oriented bounding boxes
//
if (check_uniform_hex_flag) {
check_for_uniform_hex();
if (uniform_hex) create_hex_cell_map();
}
if (obb) TIOGA_FREE(obb);
obb=(OBB *) malloc(sizeof(OBB));
findOBB(x,obb->xc,obb->dxc,obb->vec,nnodes);
tagBoundary();
}
void MeshBlock::tagBoundary(void)
{
int i,j,k,n,m,ii;
int itag;
int inode[8];
double xv[8][3];
double vol;
int *iflag;
int nvert,i3;
FILE *fp;
char intstring[7];
char fname[80];
int *iextmp,*iextmp1;
int iex;
//
// do this only once
// i.e. when the meshblock is first
// initialized, cellRes would be NULL in this case
//
if(cellRes) TIOGA_FREE(cellRes);
if(nodeRes) TIOGA_FREE(nodeRes);
//
cellRes=(double *) malloc(sizeof(double)*ncells);
nodeRes=(double *) malloc(sizeof(double)*nnodes);
//
// this is a local array
//
iflag=(int *)malloc(sizeof(int)*nnodes);
iextmp=(int *) malloc(sizeof(double)*nnodes);
iextmp1=(int *) malloc(sizeof(double)*nnodes);
//
for(i=0;i<nnodes;i++) iflag[i]=0;
//
if (userSpecifiedNodeRes ==NULL && userSpecifiedCellRes ==NULL)
{
for(i=0;i<nnodes;i++) iflag[i]=0;
for(i=0;i<nnodes;i++) nodeRes[i]=0.0;
//
k=0;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
for(m=0;m<nvert;m++)
{
inode[m]=vconn[n][nvert*i+m]-BASE;
i3=3*inode[m];
for(j=0;j<3;j++)
xv[m][j]=x[i3+j];
}
vol=computeCellVolume(xv,nvert);
cellRes[k++]=(vol*resolutionScale);
for(m=0;m<nvert;m++)
{
iflag[inode[m]]++;
nodeRes[inode[m]]+=(vol*resolutionScale);
}
}
}
}
else
{
k=0;
for(n=0;n<ntypes;n++)
{
for(i=0;i<nc[n];i++)
{
cellRes[k]=userSpecifiedCellRes[k];
k++;
}
}
for(k=0;k<nnodes;k++) nodeRes[k]=userSpecifiedNodeRes[k];
}
for(int j=0;j<3;j++)
{
mapdims[j]=10;
mapdx[j]=2*obb->dxc[j]/mapdims[j];
}
//
// compute nodal resolution as the average of
// all the cells associated with it. This takes care
// of partition boundaries as well.
//
// Also create the inverse map of nodes
//
if (icft) TIOGA_FREE(icft);
icft=(int *)malloc(sizeof(int)*(mapdims[2]*mapdims[1]*mapdims[0]+1));
if (invmap) TIOGA_FREE(invmap);
invmap=(int *)malloc(sizeof(int)*nnodes);
for(int i=0;i<mapdims[2]*mapdims[1]*mapdims[0]+1;i++) icft[i]=-1;
icft[0]=0;
int *iptr;
iptr=(int *)malloc(sizeof(int)*nnodes);
//
for(i=0;i<nnodes;i++)
{
double xd[3];
int idx[3];
if (iflag[i]!=0) nodeRes[i]/=iflag[i];
iflag[i]=0;
iextmp[i]=iextmp1[i]=0;
for(int j=0;j<3;j++)
{
xd[j]=obb->dxc[j];
for(int k=0;k<3;k++)
xd[j]+=(x[3*i+k]-obb->xc[k])*obb->vec[j][k];
idx[j]=xd[j]/mapdx[j];
}
int indx=idx[2]*mapdims[1]*mapdims[0]+idx[1]*mapdims[0]+idx[0];
iptr[i]=icft[indx+1];
icft[indx+1]=i;
}
int kc=0;
for(int i=0;i<mapdims[2]*mapdims[1]*mapdims[0];i++)
{
int ip=icft[i+1];
int m=0;
while(ip != -1)
{
invmap[kc++]=ip;
ip=iptr[ip];
m++;
}
icft[i+1]=icft[i]+m;
}
TIOGA_FREE(iptr);
//
// now tag the boundary nodes
// reuse the iflag array
//
//TRACEI(nobc);
for(i=0;i<nobc;i++)
{
ii=(obcnode[i]-BASE);
iflag[(obcnode[i]-BASE)]=1;
}
//
// now tag all the nodes of boundary cells
// to be mandatory receptors
// also make the inverse map mask
if (mapmask) TIOGA_FREE(mapmask);
mapmask=(int *)malloc(sizeof(int)*mapdims[2]*mapdims[1]*mapdims[0]);
for(int i=0;i<mapdims[2]*mapdims[1]*mapdims[0];i++) mapmask[i]=0;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
double xd[3],xc[3],xmin[3],xmax[3];
int idx[3];
itag=0;
for(int j=0;j<3;j++) { xmin[j]=BIGVALUE;xmax[j]=-BIGVALUE;}
for(m=0;m<nvert;m++)
{
inode[m]=vconn[n][nvert*i+m]-BASE;
if (iflag[inode[m]]) itag=1;
for(int j=0;j<3;j++)
{
xd[j]=obb->dxc[j];
for(int k=0;k<3;k++)
xd[j]+=(x[3*inode[m]+k]-obb->xc[k])*obb->vec[j][k];
xmin[j]=TIOGA_MIN(xd[j],xmin[j]);
xmax[j]=TIOGA_MAX(xd[j],xmax[j]);
}
}
for(int j=0;j<3;j++) { xmin[j]-=TOL; xmax[j]+=TOL;}
for(int j=xmin[0]/mapdx[0];j<=xmax[0]/mapdx[0];j++)
for(int k=xmin[1]/mapdx[1];k<=xmax[1]/mapdx[1];k++)
for(int l=xmin[2]/mapdx[2];l<=xmax[2]/mapdx[2];l++)
{
idx[0]=TIOGA_MAX(TIOGA_MIN(j,mapdims[0]-1),0);
idx[1]=TIOGA_MAX(TIOGA_MIN(k,mapdims[1]-1),0);
idx[2]=TIOGA_MAX(TIOGA_MIN(l,mapdims[2]-1),0);
mapmask[idx[2]*mapdims[1]*mapdims[0]+idx[1]*mapdims[0]+idx[0]]=1;
}
if (itag)
{
for(m=0;m<nvert;m++)
{
//iflag[inode[m]]=1;
nodeRes[inode[m]]=BIGVALUE;
iextmp[inode[m]]=iextmp1[inode[m]]=1;
}
}
}
}
/*
sprintf(intstring,"%d",100000+myid);
sprintf(fname,"nodeRes%s.dat",&(intstring[1]));
fp=fopen(fname,"w");
for(i=0;i<nnodes;i++)
{
if (nodeRes[i]==BIGVALUE) {
fprintf(fp,"%e %e %e\n",x[3*i],x[3*i+1],x[3*i+2]);
}
}
fclose(fp);
*/
//
// now tag all the cells which have
// mandatory receptors as nodes as not acceptable
// donors
//
for(iex=0;iex<mexclude;iex++)
{
k=0;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
for(m=0;m<nvert;m++)
{
inode[m]=vconn[n][nvert*i+m]-BASE;
if (iextmp[inode[m]]==1) //(iflag[inode[m]])
{
cellRes[k]=BIGVALUE;
break;
}
}
if (cellRes[k]==BIGVALUE)
{
for(m=0;m<nvert;m++) {
inode[m]=vconn[n][nvert*i+m]-BASE;
if (iextmp[inode[m]]!=1) iextmp1[inode[m]]=1;
}
}
k++;
}
}
for(i=0;i<nnodes;i++) iextmp[i]=iextmp1[i];
}
TIOGA_FREE(iflag);
TIOGA_FREE(iextmp);
TIOGA_FREE(iextmp1);
}
void MeshBlock::writeGridFile(int bid)
{
char fname[80];
char intstring[7];
char hash,c;
int i,n,j;
int bodytag;
FILE *fp;
int ba;
int nvert;
sprintf(intstring,"%d",100000+bid);
sprintf(fname,"part%s.dat",&(intstring[1]));
fp=fopen(fname,"w");
fprintf(fp,"TITLE =\"Tioga output\"\n");
fprintf(fp,"VARIABLES=\"X\",\"Y\",\"Z\",\"IBLANK\"\n");
fprintf(fp,"ZONE T=\"VOL_MIXED\",N=%d E=%d ET=BRICK, F=FEPOINT\n",nnodes,
ncells);
for(i=0;i<nnodes;i++)
{
fprintf(fp,"%.14e %.14e %.14e %d\n",x[3*i],x[3*i+1],x[3*i+2],iblank[i]);
}
ba=1-BASE;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
if (nvert==4)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba);
}
else if (nvert==5)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba);
}
else if (nvert==6)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+5]+ba,
vconn[n][nvert*i+5]+ba);
}
else if (nvert==8)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+5]+ba,
vconn[n][nvert*i+6]+ba,
vconn[n][nvert*i+7]+ba);
}
}
}
fclose(fp);
return;
}
void MeshBlock::writeCellFile(int bid)
{
char fname[80];
char qstr[3];
char intstring[7];
char hash,c;
int i,n,j;
int bodytag;
FILE *fp;
int ba;
int nvert;
sprintf(intstring,"%d",100000+bid);
sprintf(fname,"cell%s.dat",&(intstring[1]));
fp=fopen(fname,"w");
fprintf(fp, "TITLE =\"Tioga output\"\n");
fprintf(fp, "VARIABLES = \"X\"\n");
fprintf(fp, "\"Y\"\n");
fprintf(fp, "\"Z\"\n");
fprintf(fp, "\"IBLANK\"\n");
fprintf(fp, "\"IBLANK_CELL\"\n");
fprintf(fp, "ZONE T=\"VOL_MIXED\"\n");
fprintf(fp, " Nodes=%d, Elements=%d, ZONETYPE=FEBrick\n", nnodes, ncells);
fprintf(fp, " DATAPACKING=BLOCK\n");
fprintf(fp, " VARLOCATION=([5]=CELLCENTERED)\n");
fprintf(fp, " DT=(SINGLE SINGLE SINGLE SINGLE SINGLE)\n");
for(i=0;i<nnodes;i++) fprintf(fp,"%lf\n",x[3*i]);
for(i=0;i<nnodes;i++) fprintf(fp,"%lf\n",x[3*i+1]);
for(i=0;i<nnodes;i++) fprintf(fp,"%lf\n",x[3*i+2]);
for(i=0;i<nnodes;i++) fprintf(fp,"%d.0\n",iblank[i]);
for(i=0;i<ncells;i++) fprintf(fp,"%d.0\n",iblank_cell[i]);
ba=1-BASE;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
if (nvert==4)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba);
}
else if (nvert==5)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba);
}
else if (nvert==6)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+5]+ba,
vconn[n][nvert*i+5]+ba);
}
else if (nvert==8)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+5]+ba,
vconn[n][nvert*i+6]+ba,
vconn[n][nvert*i+7]+ba);
}
}
}
fclose(fp);
return;
}
void MeshBlock::writeFlowFile(int bid,double *q,int nvar,int type)
{
char fname[80];
char qstr[3];
char intstring[7];
char hash,c;
int i,n,j;
int bodytag;
FILE *fp;
int ba;
int nvert;
int *ibl;
//
// if fringes were reduced use
// iblank_reduced
//
if (iblank_reduced)
{
ibl=iblank_reduced;
}
else
{
ibl=iblank;
}
//
sprintf(intstring,"%d",100000+bid);
sprintf(fname,"flow%s.dat",&(intstring[1]));
fp=fopen(fname,"w");
fprintf(fp,"TITLE =\"Tioga output\"\n");
fprintf(fp,"VARIABLES=\"X\",\"Y\",\"Z\",\"IBLANK\",\"BTAG\" ");
for(i=0;i<nvar;i++)
{
sprintf(qstr,"Q%d",i);
fprintf(fp,"\"%s\",",qstr);
}
fprintf(fp,"\n");
fprintf(fp,"ZONE T=\"VOL_MIXED\",N=%d E=%d ET=BRICK, F=FEPOINT\n",nnodes,
ncells);
if (type==0)
{
for(i=0;i<nnodes;i++)
{
fprintf(fp,"%lf %lf %lf %d %d ",x[3*i],x[3*i+1],x[3*i+2],ibl[i],meshtag);
for(j=0;j<nvar;j++)
fprintf(fp,"%lf ",q[i*nvar+j]);
//for(j=0;j<nvar;j++)
// fprintf(fp,"%lf ", x[3*i]+x[3*i+1]+x[3*i+2]);
fprintf(fp,"\n");
}
}
else
{
for(i=0;i<nnodes;i++)
{
fprintf(fp,"%lf %lf %lf %d %d ",x[3*i],x[3*i+1],x[3*i+2],ibl[i],meshtag);
for(j=0;j<nvar;j++)
fprintf(fp,"%lf ",q[j*nnodes+i]);
fprintf(fp,"\n");
}
}
ba=1-BASE;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
if (nvert==4)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+3]+ba);
}
else if (nvert==5)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+4]+ba);
}
else if (nvert==6)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+5]+ba,
vconn[n][nvert*i+5]+ba);
}
else if (nvert==8)
{
fprintf(fp,"%d %d %d %d %d %d %d %d\n",
vconn[n][nvert*i]+ba,
vconn[n][nvert*i+1]+ba,
vconn[n][nvert*i+2]+ba,
vconn[n][nvert*i+3]+ba,
vconn[n][nvert*i+4]+ba,
vconn[n][nvert*i+5]+ba,
vconn[n][nvert*i+6]+ba,
vconn[n][nvert*i+7]+ba);
}
}
}
fprintf(fp,"%d\n",nwbc);
for(i=0;i<nwbc;i++)
fprintf(fp,"%d\n",wbcnode[i]);
fprintf(fp,"%d\n",nobc);
for(i=0;i<nobc;i++)
fprintf(fp,"%d\n",obcnode[i]);
fclose(fp);
return;
}
void MeshBlock::getWallBounds(int *mtag,int *existWall, double wbox[6])
{
int i,j,i3;
int inode;
*mtag=meshtag+(1-BASE);
if (nwbc <=0) {
*existWall=0;
for(i=0;i<6;i++) wbox[i]=0;
return;
}
*existWall=1;
wbox[0]=wbox[1]=wbox[2]=BIGVALUE;
wbox[3]=wbox[4]=wbox[5]=-BIGVALUE;
for(i=0;i<nwbc;i++)
{
inode=wbcnode[i]-BASE;
i3=3*inode;
for(j=0;j<3;j++)
{
wbox[j]=TIOGA_MIN(wbox[j],x[i3+j]);
wbox[j+3]=TIOGA_MAX(wbox[j+3],x[i3+j]);
}
}
}
void MeshBlock::markWallBoundary(int *sam,int nx[3],double extents[6])
{
int i,j,k,m,n;
int nvert;
int ii,jj,kk,mm;
int i3,iv;
int *iflag;
int *inode;
char intstring[7];
char fname[80];
double ds[3];
double xv;
int imin[3];
int imax[3];
FILE *fp;
//
iflag=(int *)malloc(sizeof(int)*ncells);
inode=(int *) malloc(sizeof(int)*nnodes);
///
//sprintf(intstring,"%d",100000+myid);
//sprintf(fname,"wbc%s.dat",&(intstring[1]));
//fp=fopen(fname,"w");
for(i=0;i<ncells;i++) iflag[i]=0;
for(i=0;i<nnodes;i++) inode[i]=0;
//
for(i=0;i<nwbc;i++)
{
ii=wbcnode[i]-BASE;
//fprintf(fp,"%e %e %e\n",x[3*ii],x[3*ii+1],x[3*ii+2]);
inode[ii]=1;
}
//fclose(fp);
//
// mark wall boundary cells
//
m=0;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
for(j=0;j<nvert;j++)
{
ii=vconn[n][nvert*i+j]-BASE;
if (inode[ii]==1)
{
iflag[m]=1;
break;
}
}
m++;
}
}
//
// find delta's in each directions
//
for(k=0;k<3;k++) ds[k]=(extents[k+3]-extents[k])/nx[k];
//
// mark sam cells with wall boundary cells now
//
m=0;
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
if (iflag[m]==1)
{
//
// find the index bounds of each wall boundary cell
// bounding box
//
imin[0]=imin[1]=imin[2]=BIGINT;
imax[0]=imax[1]=imax[2]=-BIGINT;
for(j=0;j<nvert;j++)
{
i3=3*(vconn[n][nvert*i+j]-BASE);
for(k=0;k<3;k++)
{
xv=x[i3+k];
iv=floor((xv-extents[k])/ds[k]);
imin[k]=TIOGA_MIN(imin[k],iv);
imax[k]=TIOGA_MAX(imax[k],iv);
}
}
for(j=0;j<3;j++)
{
imin[j]=TIOGA_MAX(imin[j],0);
imax[j]=TIOGA_MIN(imax[j],nx[j]-1);
}
//
// mark sam to 1
//
for(kk=imin[2];kk<imax[2]+1;kk++)
for(jj=imin[1];jj<imax[1]+1;jj++)
for (ii=imin[0];ii<imax[0]+1;ii++)
{
mm=kk*nx[1]*nx[0]+jj*nx[0]+ii;
sam[mm]=2;
}
}
m++;
}
}
TIOGA_FREE(iflag);
TIOGA_FREE(inode);
}
void MeshBlock::getReducedOBB(OBB *obc,double *realData)
{
int i,j,k,m,n,i3;
int nvert;
bool iflag;
double bbox[6],xd[3];
/*
for(j=0;j<3;j++)
{
realData[j]=obb->xc[j];
realData[j+3]=obb->dxc[j];
}
return;
*/
for(j=0;j<3;j++)
{
realData[j]=BIGVALUE;
realData[j+3]=-BIGVALUE;
}
for(n=0;n<ntypes;n++)
{
nvert=nv[n];
for(i=0;i<nc[n];i++)
{
bbox[0]=bbox[1]=bbox[2]=BIGVALUE;
bbox[3]=bbox[4]=bbox[5]=-BIGVALUE;
for(m=0;m<nvert;m++)
{
i3=3*(vconn[n][nvert*i+m]-BASE);
for(j=0;j<3;j++) xd[j]=0;
for(j=0;j<3;j++)
for(k=0;k<3;k++)
xd[j]+=(x[i3+k]-obc->xc[k])*obc->vec[j][k];
for(j=0;j<3;j++) bbox[j]=TIOGA_MIN(bbox[j],xd[j]);
for(j=0;j<3;j++) bbox[j+3]=TIOGA_MAX(bbox[j+3],xd[j]);
}
iflag=0;
for(j=0;j<3;j++) iflag=(iflag || (bbox[j] > obc->dxc[j]));
if (iflag) continue;
iflag=0;
for(j=0;j<3;j++) iflag=(iflag || (bbox[j+3] < -obc->dxc[j]));
if (iflag) continue;
for (m=0;m<nvert;m++)
{
i3=3*(vconn[n][nvert*i+m]-BASE);
for(j=0;j<3;j++) xd[j]=0;
for(j=0;j<3;j++)
for(k=0;k<3;k++)
xd[j]+=(x[i3+k]-obb->xc[k])*obb->vec[j][k];
for(j=0;j<3;j++) realData[j]=TIOGA_MIN(realData[j],xd[j]);
for(j=0;j<3;j++) realData[j+3]=TIOGA_MAX(realData[j+3],xd[j]);
}
}
}
for(j=0;j<6;j++) bbox[j]=realData[j];
for(j=0;j<3;j++)
{
realData[j]=obb->xc[j];
for(k=0;k<3;k++)
realData[j]+=((bbox[k]+bbox[k+3])*0.5)*obb->vec[k][j];
realData[j+3]=(bbox[j+3]-bbox[j])*0.51;
}
return;
}
void MeshBlock::getReducedOBB2(OBB *obc,double *realData)
{
int i,j,k,l,m,n,i3,jmin,kmin,lmin,jmax,kmax,lmax,indx;
double bbox[6],xd[3];
double xmin[3],xmax[3],xv[8][3];
double delta;
int imin[3],imax[3];
getobbcoords(obc->xc,obc->dxc,obc->vec,xv);
for(j=0;j<3;j++) {xmin[j]=BIGVALUE;xmax[j]=-BIGVALUE;};
for(n=0;n<8;n++)
{
transform2OBB(xv[n],obb->xc,obb->vec,xd);
for(j=0;j<3;j++)
{
xmin[j]=TIOGA_MIN(xmin[j],xd[j]+obb->dxc[j]);
xmax[j]=TIOGA_MAX(xmax[j],xd[j]+obb->dxc[j]);
}
}
for(j=0;j<3;j++)
{
delta=0.01*(xmax[j]-xmin[j]);
xmin[j]-=delta;
xmax[j]+=delta;
imin[j]=TIOGA_MAX(xmin[j]/mapdx[j],0);
imax[j]=TIOGA_MIN(xmax[j]/mapdx[j],mapdims[j]-1);
}
lmin=mapdims[2]-1;
kmin=mapdims[1]-1;
jmin=mapdims[0]-1;
lmax=kmax=jmax=0;
for(l=imin[2];l<=imax[2];l++)
for(k=imin[1];k<=imax[1];k++)
for(j=imin[0];j<=imax[0];j++)
{
indx=l*mapdims[1]*mapdims[0]+k*mapdims[0]+j;
if (mapmask[indx]) {
lmin=TIOGA_MIN(lmin,l);
kmin=TIOGA_MIN(kmin,k);
jmin=TIOGA_MIN(jmin,j);
lmax=TIOGA_MAX(lmax,l);
kmax=TIOGA_MAX(kmax,k);
jmax=TIOGA_MAX(jmax,j);
}
}
bbox[0]=-obb->dxc[0]+jmin*mapdx[0];
bbox[1]=-obb->dxc[1]+kmin*mapdx[1];
bbox[2]=-obb->dxc[2]+lmin*mapdx[2];
bbox[3]=-obb->dxc[0]+(jmax+1)*mapdx[0];
bbox[4]=-obb->dxc[1]+(kmax+1)*mapdx[1];
bbox[5]=-obb->dxc[2]+(lmax+1)*mapdx[2];
for(j=0;j<3;j++)
{
realData[j]=obb->xc[j];
for(k=0;k<3;k++)
realData[j]+=((bbox[k]+bbox[k+3])*0.5)*obb->vec[k][j];
realData[j+3]=(bbox[j+3]-bbox[j])*0.5;
}
return;
}
void MeshBlock::getQueryPoints(OBB *obc,
int *nints,int **intData,
int *nreals, double **realData)
{
int i,j,k;
int i3;
double xd[3];
int *inode;
int iptr;
int m;
inode=(int *)malloc(sizeof(int)*nnodes);
*nints=*nreals=0;
for(i=0;i<nnodes;i++)
{
i3=3*i;
for(j=0;j<3;j++) xd[j]=0;
for(j=0;j<3;j++)
for(k=0;k<3;k++)
xd[j]+=(x[i3+k]-obc->xc[k])*obc->vec[j][k];
if (fabs(xd[0]) <= obc->dxc[0] &&
fabs(xd[1]) <= obc->dxc[1] &&
fabs(xd[2]) <= obc->dxc[2])
{
inode[*nints]=i;
(*nints)++;
(*nreals)+=4;
}
}
if (myid==0 && meshtag==1) {TRACEI(*nints);}
(*intData)=(int *)malloc(sizeof(int)*(*nints));
(*realData)=(double *)malloc(sizeof(double)*(*nreals));
//
m=0;
for(i=0;i<*nints;i++)
{
i3=3*inode[i];
(*intData)[i]=inode[i];
(*realData)[m++]=x[i3];
(*realData)[m++]=x[i3+1];
(*realData)[m++]=x[i3+2];
(*realData)[m++]=nodeRes[inode[i]];
}
//
TIOGA_FREE(inode);
}
void MeshBlock::getQueryPoints2(OBB *obc,
int *nints,int **intData,
int *nreals, double **realData)
{
int i,j,k,l,il,ik,ij,n,m,i3,iflag;
int indx,iptr;
int *inode;
double delta;
double xv[8][3],mdx[3],xd[3],xc[3];
double xmax[3],xmin[3];
int imin[3],imax[3];
//
inode=(int *)malloc(sizeof(int)*nnodes);
*nints=*nreals=0;
getobbcoords(obc->xc,obc->dxc,obc->vec,xv);
for(j=0;j<3;j++) {xmin[j]=BIGVALUE;xmax[j]=-BIGVALUE;};
//writebbox(obc,1);
//writebbox(obb,2);
//writebboxdiv(obb,1);
//
for(n=0;n<8;n++)
{
transform2OBB(xv[n],obb->xc,obb->vec,xd);
for(j=0;j<3;j++)
{
xmin[j]=TIOGA_MIN(xmin[j],xd[j]+obb->dxc[j]);
xmax[j]=TIOGA_MAX(xmax[j],xd[j]+obb->dxc[j]);
}
}
for(j=0;j<3;j++)
{
delta=0.01*(xmax[j]-xmin[j]);
xmin[j]-=delta;
xmax[j]+=delta;
imin[j]=TIOGA_MAX(xmin[j]/mapdx[j],0);
imax[j]=TIOGA_MIN(xmax[j]/mapdx[j],mapdims[j]-1);
mdx[j]=0.5*mapdx[j];
}
//
// find min/max extends of a single sub-block
// in OBC axes
//
getobbcoords(obc->xc,mdx,obb->vec,xv);
for(j=0;j<3;j++) {xmin[j]=BIGVALUE;xmax[j]=-BIGVALUE;}
for(m=0;m<8;m++)
{
transform2OBB(xv[m],obc->xc,obc->vec,xd);
for(j=0;j<3;j++)
{
xmin[j]=TIOGA_MIN(xmin[j],xd[j]);
xmax[j]=TIOGA_MAX(xmax[j],xd[j]);
}
}
//printf("xmin :%f %f %f\n",xmin[0],xmin[1],xmin[2]);
//printf("xmax :%f %f %f\n",xmax[0],xmax[1],xmax[2]);
//
// now find the actual number of points
// that are within OBC using only the
// sub-blocks with potential bbox overlap
//
//FILE *fp,*fp2,*fp3,*fp4;
//fp=fopen("v.dat","w");
//fp2=fopen("v2.dat","w");
//fp3=fopen("v3.dat","w");
//fp4=fopen("v4.dat","w");
for(l=imin[2];l<=imax[2];l++)
for(k=imin[1];k<=imax[1];k++)
for(j=imin[0];j<=imax[0];j++)
{
//
// centroid of each sub-block
// in OBC axes
//
xd[0]=-obb->dxc[0]+j*mapdx[0]+mapdx[0]*0.5;
xd[1]=-obb->dxc[1]+k*mapdx[1]+mapdx[1]*0.5;
xd[2]=-obb->dxc[2]+l*mapdx[2]+mapdx[2]*0.5;
for(n=0;n<3;n++)
{
xc[n]=obb->xc[n];
for(ij=0;ij<3;ij++)
xc[n]+=(xd[ij]*obb->vec[ij][n]);
}
//if (j==0 && k==0 & l==0) {
//printf("%f %f %f\n",obc->vec[0][0],obc->vec[1][0],obc->vec[2][0]);
//printf("%f %f %f\n",obc->vec[0][1],obc->vec[1][1],obc->vec[2][1]);
//printf("%f %f %f\n",obc->vec[0][2],obc->vec[1][2],obc->vec[2][2]);
//printf("%f %f %f\n",obc->xc[0],obc->xc[1],obc->xc[2]);
//}
//fprintf(fp,"%f %f %f\n",xc[0],xc[1],xc[2]);
transform2OBB(xc,obc->xc,obc->vec,xd);
//fprintf(fp2,"%f %f %f\n",xd[0],xd[1],xd[2]);
//if (fabs(xd[0]) <= obc->dxc[0] &&
// fabs(xd[1]) <= obc->dxc[1] &&
// fabs(xd[2]) <= obc->dxc[2])
// {
// fprintf(fp3,"%f %f %f\n",xc[0],xc[1],xc[2]);
// }
//
// check if this sub-block overlaps OBC
//
iflag=0;
for(ij=0;ij<3 && !iflag;ij++) iflag=(iflag || (xmin[ij]+xd[ij] > obc->dxc[ij]));
if (iflag) continue;
iflag=0;
for(ij=0;ij<3 && !iflag;ij++) iflag=(iflag || (xmax[ij]+xd[ij] < -obc->dxc[ij]));
if (iflag) continue;
//fprintf(fp4,"%f %f %f\n",xc[0],xc[1],xc[2]);
//
// if there overlap
// go through points within the sub-block
// to figure out what needs to be send
//
indx=l*mapdims[1]*mapdims[0]+k*mapdims[0]+j;
for(m=icft[indx];m<icft[indx+1];m++)
{
i3=3*invmap[m];
for(ik=0;ik<3;ik++) xc[ik]=x[i3+ik];
transform2OBB(xc,obc->xc,obc->vec,xd);
if (fabs(xd[0]) <= obc->dxc[0] &&
fabs(xd[1]) <= obc->dxc[1] &&
fabs(xd[2]) <= obc->dxc[2])
{
inode[*nints]=invmap[m];
(*nints)++;
(*nreals)+=4;
}
}
}
// TRACEI(*nints);
// fclose(fp);
// fclose(fp2);
// fclose(fp3);
// fclose(fp4);
// int ierr;
// MPI_Abort(MPI_COMM_WORLD,ierr);
//
#ifdef TIOGA_HAS_NODEGID
int nintsPerNode = 3;
#else
int nintsPerNode = 1;
#endif
(*intData)=(int *)malloc(sizeof(int)*(*nints) * nintsPerNode);
(*realData)=(double *)malloc(sizeof(double)*(*nreals));
//
m=0;
int iidx = 0;
for(i=0;i<*nints;i++) {
i3=3*inode[i];
(*intData)[iidx++]=inode[i];
#ifdef TIOGA_HAS_NODEGID
std::memcpy(&(*intData)[iidx],&nodeGID[inode[i]], sizeof(uint64_t));
iidx += 2;
#endif
(*realData)[m++]=x[i3];
(*realData)[m++]=x[i3+1];
(*realData)[m++]=x[i3+2];
(*realData)[m++]=nodeRes[inode[i]];
}
// Adjust nints to the proper array size
*nints *= nintsPerNode;
//
TIOGA_FREE(inode);
}
void MeshBlock::writeOBB(int bid)
{
FILE *fp;
char intstring[7];
char fname[80];
int l,k,j,m,il,ik,ij;
REAL xx[3];
sprintf(intstring,"%d",100000+bid);
sprintf(fname,"box%s.dat",&(intstring[1]));
fp=fopen(fname,"w");
fprintf(fp,"TITLE =\"Box file\"\n");
fprintf(fp,"VARIABLES=\"X\",\"Y\",\"Z\"\n");
fprintf(fp,"ZONE T=\"VOL_MIXED\",N=%d E=%d ET=BRICK, F=FEPOINT\n",8,
1);
for(l=0;l<2;l++)
{
il=2*(l%2)-1;
for(k=0;k<2;k++)
{
ik=2*(k%2)-1;
for(j=0;j<2;j++)
{
ij=2*(j%2)-1;
xx[0]=xx[1]=xx[2]=0;
for(m=0;m<3;m++)
xx[m]=obb->xc[m]+ij*obb->vec[0][m]*obb->dxc[0]
+ik*obb->vec[1][m]*obb->dxc[1]
+il*obb->vec[2][m]*obb->dxc[2];
fprintf(fp,"%f %f %f\n",xx[0],xx[1],xx[2]);
}
}
}
fprintf(fp,"1 2 4 3 5 6 8 7\n");
fprintf(fp,"%e %e %e\n",obb->xc[0],obb->xc[1],obb->xc[2]);
for(k=0;k<3;k++)
fprintf(fp,"%e %e %e\n",obb->vec[0][k],obb->vec[1][k],obb->vec[2][k]);
fprintf(fp,"%e %e %e\n",obb->dxc[0],obb->dxc[1],obb->dxc[2]);
fclose(fp);
}
//
// destructor that deallocates all the
// the dynamic objects inside
//
MeshBlock::~MeshBlock()
{
int i;
//
// TIOGA_FREE all data that is owned by this MeshBlock
// i.e not the pointers of the external code.
//
if (cellRes) TIOGA_FREE(cellRes);
if (nodeRes) TIOGA_FREE(nodeRes);
if (elementBbox) TIOGA_FREE(elementBbox);
if (elementList) TIOGA_FREE(elementList);
if (adt) delete[] adt;
if (donorList) {
for(i=0;i<nnodes;i++) deallocateLinkList(donorList[i]);
TIOGA_FREE(donorList);
}
if (interpList) {
for(i=0;i<interpListSize;i++)
{
if (interpList[i].inode) TIOGA_FREE(interpList[i].inode);
if (interpList[i].weights) TIOGA_FREE(interpList[i].weights);
}
TIOGA_FREE(interpList);
}
if (interpList2) {
for(i=0;i<interp2ListSize;i++)
{
if (interpList2[i].inode) TIOGA_FREE(interpList2[i].inode);
if (interpList2[i].weights) TIOGA_FREE(interpList2[i].weights);
}
TIOGA_FREE(interpList2);
}
if (interpListCart) {
for(i=0;i<interpListCartSize;i++)
{
if (interpListCart[i].inode) TIOGA_FREE(interpListCart[i].inode);
if (interpListCart[i].weights) TIOGA_FREE(interpListCart[i].weights);
}
TIOGA_FREE(interpListCart);
}
// For nalu-wind API the iblank_cell array is managed on the nalu side
// if (!ihigh) {
// if (iblank_cell) TIOGA_FREE(iblank_cell);
// }
if (obb) TIOGA_FREE(obb);
if (obh) TIOGA_FREE(obh);
if (isearch) TIOGA_FREE(isearch);
if (xsearch) TIOGA_FREE(xsearch);
if (res_search) TIOGA_FREE(res_search);
if (xtag) TIOGA_FREE(xtag);
if (rst) TIOGA_FREE(rst);
if (interp2donor) TIOGA_FREE(interp2donor);
if (cancelList) deallocateLinkList2(cancelList);
if (ctag) TIOGA_FREE(ctag);
if (pointsPerCell) TIOGA_FREE(pointsPerCell);
if (rxyz) TIOGA_FREE(rxyz);
if (picked) TIOGA_FREE(picked);
if (rxyzCart) TIOGA_FREE(rxyzCart);
if (donorIdCart) TIOGA_FREE(donorIdCart);
if (pickedCart) TIOGA_FREE(pickedCart);
if (ctag_cart) TIOGA_FREE(ctag_cart);
if (tagsearch) TIOGA_FREE(tagsearch);
if (donorId) TIOGA_FREE(donorId);
if (receptorIdCart) TIOGA_FREE(receptorIdCart);
if (icft) TIOGA_FREE(icft);
if (mapmask) TIOGA_FREE(mapmask);
if (uindx) TIOGA_FREE(uindx);
if (invmap) TIOGA_FREE(invmap);
// need to add code here for other objects as and
// when they become part of MeshBlock object
};
//
// set user specified node and cell resolutions
//
void MeshBlock::setResolutions(double *nres,double *cres)
{
userSpecifiedNodeRes=nres;
userSpecifiedCellRes=cres;
}
//
// detect if a given meshblock is a uniform hex
// and create a data structure that will enable faster
// searching
//
void MeshBlock::check_for_uniform_hex(void)
{
double xv[8][3];
int hex_present=0;
if (ntypes > 1) return;
for(int n=0;n<ntypes;n++)
{
int nvert=nv[n];
if (nvert==8) {
hex_present=1;
for(int i=0;i<nc[n];i++)
{
int vold=-1;
for(int m=0;m<nvert;m++)
{
if (vconn[n][nvert*i+m]==vold) return; // degenerated hex are not uniform
vold=vconn[n][nvert*i+m];
int i3=3*(vconn[n][nvert*i+m]-BASE);
for(int k=0;k<3;k++)
xv[m][k]=x[i3+k];
}
//
// check angles to see if sides are
// rectangles
//
// z=0 side
//
if (fabs(tdot_product(xv[1],xv[3],xv[0])) > TOL) return;
if (fabs(tdot_product(xv[1],xv[3],xv[2])) > TOL) return;
//
// x=0 side
//
if (fabs(tdot_product(xv[3],xv[4],xv[0])) > TOL) return;
if (fabs(tdot_product(xv[3],xv[4],xv[7])) > TOL) return;
//
// y=0 side
//
if (fabs(tdot_product(xv[4],xv[1],xv[0])) > TOL) return;
if (fabs(tdot_product(xv[4],xv[1],xv[5])) > TOL) return;
//
// need to check just one more angle on
// on the corner against 0 (6)
//
if (fabs(tdot_product(xv[5],xv[7],xv[6])) > TOL) return;
//
// so this is a hex
// check if it has the same size as the previous hex
// if not return
//
if (i==0){
dx[0]=tdot_product(xv[1],xv[1],xv[0]);
dx[1]=tdot_product(xv[3],xv[3],xv[0]);
dx[2]=tdot_product(xv[4],xv[4],xv[0]);
}
else {
if (fabs(dx[0]-tdot_product(xv[1],xv[1],xv[0])) > TOL) return;
if (fabs(dx[1]-tdot_product(xv[3],xv[3],xv[0])) > TOL) return;
if (fabs(dx[2]-tdot_product(xv[4],xv[4],xv[0])) > TOL) return;
}
}
}
}
if (hex_present) {
for(int j=0;j<3;j++) dx[j]=sqrt(dx[j]);
uniform_hex=1;
if (obh) TIOGA_FREE(obh);
obh=(OBB *) malloc(sizeof(OBB));
for(int j=0;j<3;j++)
for(int k=0;k<3;k++)
obh->vec[j][k]=0;
for(int k=0;k<3;k++)
obh->vec[0][k]=(xv[1][k]-xv[0][k])/dx[0];
for(int k=0;k<3;k++)
obh->vec[1][k]=(xv[3][k]-xv[0][k])/dx[1];
for(int k=0;k<3;k++)
obh->vec[2][k]=(xv[4][k]-xv[0][k])/dx[2];
//obh->vec[0][0]=obh->vec[1][1]=obh->vec[2][2]=1;
//
double xd[3];
double xmax[3];
double xmin[3];
xmax[0]=xmax[1]=xmax[2]=-BIGVALUE;
xmin[0]=xmin[1]=xmin[2]=BIGVALUE;
//
for(int i=0;i<nnodes;i++)
{
int i3=3*i;
for(int j=0;j<3;j++) xd[j]=0;
//
for(int j=0;j<3;j++)
for(int k=0;k<3;k++)
xd[j]+=x[i3+k]*obh->vec[j][k];
//
for(int j=0;j<3;j++)
{
xmax[j]=TIOGA_MAX(xmax[j],xd[j]);
xmin[j]=TIOGA_MIN(xmin[j],xd[j]);
}
}
//
// find the extents of the box
// and coordinates of the center w.r.t. xc
// increase extents by 1% for tolerance
//
for(int j=0;j<3;j++)
{
xmax[j]+=TOL;
xmin[j]-=TOL;
obh->dxc[j]=(xmax[j]-xmin[j])*0.5;
xd[j]=(xmax[j]+xmin[j])*0.5;
}
//
// find the center of the box in
// actual cartesian coordinates
//
for(int j=0;j<3;j++)
{
obh->xc[j]=0.0;
for(int k=0;k<3;k++)
obh->xc[j]+=(xd[k]*obh->vec[k][j]);
}
}
return;
}
void MeshBlock::create_hex_cell_map(void)
{
for(int j=0;j<3;j++)
{
xlow[j]=obh->xc[j];
for (int k=0;k<3;k++)
xlow[j]-=(obh->dxc[k]*obh->vec[k][j]);
idims[j]=round(2*obh->dxc[j]/dx[j]);
dx[j]=(2*obh->dxc[j])/idims[j];
}
//
if (uindx) TIOGA_FREE(uindx);
uindx=(int *)malloc(sizeof(int)*idims[0]*idims[1]*idims[2]);
for(int i=0;i<idims[0]*idims[1]*idims[2];uindx[i++]=-1);
//
for(int i=0;i<nc[0];i++)
{
double xc[3];
double xd[3];
int idx[3];
for(int j=0;j<3;j++)
{
int lnode=vconn[0][8*i]-BASE;
int tnode=vconn[0][8*i+6]-BASE;
xc[j]=0.5*(x[3*lnode+j]+x[3*tnode+j]);
}
for(int j=0;j<3;j++)
{
xd[j]=0;
for(int k=0;k<3;k++)
xd[j]+=(xc[k]-xlow[k])*obh->vec[j][k];
idx[j]=xd[j]/dx[j];
}
uindx[idx[2]*idims[1]*idims[0]+idx[1]*idims[0]+idx[0]]=i;
}
}
|
jsitaraman/tioga
|
src/MeshBlock.C
|
C++
|
lgpl-3.0
| 35,409 |
#include <algorithm>
#include <descriptor.hpp>
namespace gemini
{
descriptor::
descriptor(unsigned short bus,
unsigned short port,
unsigned short product_id,
unsigned short vendor_id,
unsigned short interface_class) :
info_(std::array<unsigned short,DESCRIPTOR_SIZE>
{bus,port,vendor_id,product_id,interface_class})
{}
descriptor::
descriptor(std::array<unsigned short,DESCRIPTOR_SIZE> const& info) :
info_(info)
{}
bool descriptor::relevant(descriptor const& descriptor) const
{
bool relevant = true;
for(unsigned short index = BUS ; index != UNDEFINED ; ++index)
{
if(info_[index] != MASKED && info_[index] != descriptor[index])
{
relevant = false;
}
}
return relevant;
}
void descriptor::
read_device_address(libusb_device * device)
{
info_[BUS] = libusb_get_bus_number(device);
info_[PORT] = libusb_get_port_number(device);
}
void descriptor::
read_device_descriptor(libusb_device_descriptor const& dev_desc)
{
info_[VENDOR_ID] = dev_desc.idVendor;
info_[PRODUCT_ID] = dev_desc.idProduct;
}
void descriptor::
read_interface_descriptor(libusb_interface_descriptor const& intf_desc)
{
info_[INTERFACE_CLASS] = intf_desc.bInterfaceClass;
}
std::string const descriptor::info(bool readable) const
{
std::string descriptor_info;
for(unsigned short index = BUS ; index != UNDEFINED ; ++index)
{
if(index > 0) descriptor_info += " ";
if(readable)
{
switch(index)
{
case BUS : descriptor_info += "[BUS:"; break;
case PORT : descriptor_info += "[PORT:"; break;
case VENDOR_ID : descriptor_info += "[VENDOR ID:"; break;
case PRODUCT_ID : descriptor_info += "[PRODUCT ID:"; break;
case INTERFACE_CLASS : descriptor_info += "[INTERFACE CLASS:"; break;
}
}
descriptor_info += std::to_string(info_[index])
+ "]";
}
return descriptor_info;
}
std::string const descriptor::device_info() const
{
std::string device_info;
for(unsigned short index = BUS ; index != INTERFACE_CLASS ; ++index)
{
device_info += " ";
device_info += std::to_string(info_[index]);
}
return device_info;
}
unsigned short descriptor::operator [] (unsigned short index) const
{
return info_[index];
}
unsigned short & descriptor::operator [] (unsigned short index)
{
return info_[index];
}
bool operator == (descriptor const& i1,descriptor const& i2)
{
bool equal = true;
for(unsigned short index = BUS ; index != UNDEFINED ; ++index)
{
if(i1[index] != i2[index]) equal = false;
}
return equal;
}
// stream operator
std::ostream & operator << (std::ostream & out,descriptor const& intf_info)
{
// write descriptor informations readable in stream
out << intf_info.info(true);
return out;
}
} // end namespace gemini
|
tgrochow/gemini
|
daemon/descriptor.cpp
|
C++
|
lgpl-3.0
| 2,965 |
#!/usr/bin/env python
# -*- coding: utf-8 -*
import clutter
from clutter import cogl
import math
class Clock(clutter.Actor):
__gtype_name__ = 'Clock'
"""
A clock widget
"""
def __init__(self, date=None, texture=None):
clutter.Actor.__init__(self)
self._date = date
self._texture = texture
self._color = clutter.color_from_string('Black')
def set_color(self, color):
self._color = clutter.color_from_string(color)
self.queue_redraw()
def set_texture(self, texture):
self._texture = texture
self.queue_redraw()
def set_date(self, date=None):
self._date = date
if date is not None:
self.queue_redraw()
def do_paint(self):
#clutter.Texture.do_paint(self)
(x1, y1, x2, y2) = self.get_allocation_box()
width = x2 - x1
height = y2 - y1
hw = width / 2
hh = height / 2
center_x = hw
center_y = hh
# texture
if self._texture is not None:
cogl.path_rectangle(0, 0, width, height)
cogl.path_close()
cogl.set_source_texture(self._texture)
cogl.path_fill()
# clock hands
if self._date is not None:
hour = self._date.hour
minute = self._date.minute
# hour
angle = (60 * hour + minute) / 2 + 270
left = angle - 14
right = angle + 14
angle = angle * (math.pi / 180)
left = left * (math.pi / 180)
right = right * (math.pi / 180)
cogl.path_move_to(center_x, center_y)
cogl.path_line_to(center_x + (hw/4) * math.cos(left), center_y + (hh/4) * math.sin(left))
cogl.path_line_to(center_x + (2*hw/3) * math.cos(angle), center_y + (2*hh/3) * math.sin(angle))
cogl.path_line_to(center_x + (hw/4) * math.cos(right), center_y + (hh/4) * math.sin(right))
cogl.path_line_to(center_x, center_y)
cogl.path_close()
cogl.set_source_color(self._color)
cogl.path_fill()
# minute
angle = 6 * minute + 270
left = angle - 10
right = angle + 10
angle = angle * (math.pi / 180)
left = left * (math.pi / 180)
right = right * (math.pi / 180)
cogl.path_move_to(center_x, center_y)
cogl.path_line_to(center_x + (hw/3) * math.cos(left), center_y + (hh/3) * math.sin(left))
cogl.path_line_to(center_x + hw * math.cos(angle), center_y + hh * math.sin(angle))
cogl.path_line_to(center_x + (hw/3) * math.cos(right), center_y + (hh/3) * math.sin(right))
cogl.path_line_to(center_x, center_y)
cogl.path_close()
cogl.set_source_color(self._color)
cogl.path_fill()
#main to test
if __name__ == '__main__':
stage = clutter.Stage()
stage.connect('destroy',clutter.main_quit)
import gobject, datetime
t = cogl.texture_new_from_file('clock.png', clutter.cogl.TEXTURE_NO_SLICING, clutter.cogl.PIXEL_FORMAT_ANY)
c = Clock()
c.set_texture(t)
c.set_size(400, 400)
c.set_position(50, 50)
stage.add(c)
def update():
today = datetime.datetime.today()
#self.actor.set_text(today.strftime('%H:%M\n%d / %m'))
c.set_date(today)
return True
gobject.timeout_add_seconds(60, update)
stage.show()
clutter.main()
|
UbiCastTeam/candies
|
candies2/clock.py
|
Python
|
lgpl-3.0
| 3,642 |
#ifndef QACCESSIBLEBRIDGE
#define QACCESSIBLEBRIDGE
class DummyQAccessibleBridge {
// Q_OBJECT;
public:
knh_RawPtr_t *self;
std::map<std::string, knh_Func_t *> *event_map;
std::map<std::string, knh_Func_t *> *slot_map;
DummyQAccessibleBridge();
virtual ~DummyQAccessibleBridge();
void setSelf(knh_RawPtr_t *ptr);
bool eventDispatcher(QEvent *event);
bool addEvent(knh_Func_t *callback_func, std::string str);
bool signalConnect(knh_Func_t *callback_func, std::string str);
knh_Object_t** reftrace(CTX ctx, knh_RawPtr_t *p FTRARG);
void connection(QObject *o);
};
class KQAccessibleBridge : public QAccessibleBridge {
// Q_OBJECT;
public:
int magic_num;
knh_RawPtr_t *self;
DummyQAccessibleBridge *dummy;
~KQAccessibleBridge();
void setSelf(knh_RawPtr_t *ptr);
};
#endif //QACCESSIBLEBRIDGE
|
imasahiro/konohascript
|
package/konoha.qt4/include/KQAccessibleBridge.hpp
|
C++
|
lgpl-3.0
| 810 |
package org.onebeartoe.filesystem;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
/**
* @author Roberto Marquez
*/
public class FileSystemSearcher
{
File dir;
List<FileType> targets;
FileType type;
boolean recursive;
public FileSystemSearcher(File dir, List<FileType> targets)
{
this(dir, targets, false);
}
public FileSystemSearcher(File dir, List<FileType> targets, boolean recursive)
{
if (dir == null)
{
throw new NullPointerException("search directory can't have a null value");
}
if (targets == null)
{
throw new NullPointerException("target list can't have a null value");
}
this.dir = dir;
this.targets = targets;
this.recursive = recursive;
}
public List<File> findTargetDirectories()
{
ArrayList<File> targetDirs = new ArrayList<File>();
Vector<File> directories = new Vector<File>();
directories.add(dir);
while (!directories.isEmpty())
{
File currentDir = directories.remove(0);
boolean currentContainsTargets = findTargetDirectoriesOneLevel(currentDir, directories);
if (currentContainsTargets)
{
targetDirs.add(currentDir);
}
}
return targetDirs;
}
private boolean findTargetDirectoriesOneLevel(File currentDir, Vector<File> directories)
{
boolean currentContainsTargets = false;
File[] dirContents = currentDir.listFiles();
if (dirContents != null)
{
currentContainsTargets = findTargetDirectoriesOneLevelExecute(dirContents, directories);
}
return currentContainsTargets;
}
private boolean findTargetDirectoriesOneLevelExecute(File[] dirContents, Vector<File> directories)
{
boolean currentContainsTargets = false;
boolean targetNotFoundYet = true;
for (File file : dirContents)
{
if (file.isDirectory() && recursive)
{
directories.add(file);
}
else
{
if (targetNotFoundYet)
{
// Only come here if a target has not been found.
FileType type = determinFileType(file);
if (targets.contains(type))
{
currentContainsTargets = true;
// If a target has been found in the current dir, we can skip the next file check
targetNotFoundYet = false;
}
}
}
}
return currentContainsTargets;
}
public List<File> findTargetFiles()
{
List<File> targetFiles = new ArrayList<File>();
Vector<File> directories = new Vector<File>();
directories.add(dir);
while (!directories.isEmpty())
{
findTargetFilesOneLevel(directories, targetFiles);
}
return targetFiles;
}
private void findTargetFilesOneLevel(Vector<File> directories, List<File> targetFiles)
{
File currentDir = directories.remove(0);
File[] dirContents = currentDir.listFiles();
if (dirContents != null)
{
for (File file : dirContents)
{
if (file.isDirectory() && recursive)
{
directories.add(file);
}
else
{
FileType type = determinFileType(file);
if (targets.contains(type))
{
targetFiles.add(file);
}
}
}
}
}
private FileType determinFileType(File file)
{
FileType type = FileType.UNKNOWN;
String name = file.getName();
if (FileHelper.isAudioFile(name))
{
type = FileType.AUDIO;
}
if (FileHelper.isZipFormatFile(name))
{
type = FileType.ZIP;
}
if (FileHelper.isMultimediaFile(name))
{
type = FileType.MULTIMEDIA;
}
if (FileHelper.isImageFile(name))
{
type = FileType.IMAGE;
}
if (FileHelper.isTextFile(name))
{
type = FileType.TEXT;
}
return type;
}
}
|
onebeartoe/java-libraries
|
system/src/main/java/org/onebeartoe/filesystem/FileSystemSearcher.java
|
Java
|
lgpl-3.0
| 4,892 |
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2021 Live Networks, Inc. All rights reserved.
// A filter that breaks up a H.265 Video Elementary Stream into NAL units.
// C++ header
#ifndef _H265_VIDEO_STREAM_FRAMER_HH
#define _H265_VIDEO_STREAM_FRAMER_HH
#ifndef _H264_OR_5_VIDEO_STREAM_FRAMER_HH
#include "H264or5VideoStreamFramer.hh"
#endif
class H265VideoStreamFramer: public H264or5VideoStreamFramer {
public:
static H265VideoStreamFramer* createNew(UsageEnvironment& env, FramedSource* inputSource,
Boolean includeStartCodeInOutput = False,
Boolean insertAccessUnitDelimiters = False);
protected:
H265VideoStreamFramer(UsageEnvironment& env, FramedSource* inputSource,
Boolean createParser,
Boolean includeStartCodeInOutput, Boolean insertAccessUnitDelimiters);
// called only by "createNew()"
virtual ~H265VideoStreamFramer();
// redefined virtual functions:
virtual Boolean isH265VideoStreamFramer() const;
};
#endif
|
k0zmo/live555
|
liveMedia/include/H265VideoStreamFramer.hh
|
C++
|
lgpl-3.0
| 1,732 |
/*
Copyright 2007-2011 B3Partners BV.
This program is distributed under the terms
of the GNU General Public License.
You should have received a copy of the GNU General Public License
along with this software. If not, see http://www.gnu.org/licenses/gpl.html
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.
*/
/*Hulp functions*/
//contains on array function
function arrayContains(array,element) {
for (var i = 0; i < array.length; i++) {
if (array[i] == element) {
return true;
}
}
return false;
}
// jQuery gives problems with DWR - util.js, so noConflict mode. Usage for jQuery selecter becomes $j() instead of $()
$j = jQuery.noConflict();
// Trim polyfill
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
attachOnload = function(onloadfunction) {
if(typeof(onloadfunction) == 'function') {
var oldonload=window.onload;
if(typeof(oldonload) == 'function') {
window.onload = function() {
oldonload();
onloadfunction();
}
} else {
window.onload = function() {
onloadfunction();
}
}
}
}
var resizeFunctions = new Array();
resizeFunction = function() {
for(i in resizeFunctions) {
resizeFunctions[i]();
}
}
window.onresize = resizeFunction;
attachOnresize = function(onresizefunction) {
if(typeof(onresizefunction) == 'function') {
resizeFunctions[resizeFunctions.length] = onresizefunction;
}
}
checkLocation = function() {
if (top.location != self.location)
top.location = self.location;
}
checkLocationPopup = function() {
if(!usePopup) {
if (top.location == self.location) {
top.location = '/gisviewerconfig/index.do';
}
}
}
getIEVersionNumber = function() {
var ua = navigator.userAgent;
var MSIEOffset = ua.indexOf("MSIE ");
if (MSIEOffset == -1) {
return -1;
} else {
return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
}
}
var ieVersion = getIEVersionNumber();
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return [curleft,curtop];
}
function showHelpDialog(divid) {
$j("#" + divid).dialog({
resizable: true,
draggable: true,
show: 'slide',
hide: 'slide',
autoOpen: false
});
$j("#" + divid).dialog('open');
return false;
}
(function(B3PConfig) {
B3PConfig.cookie = {
createCookie: function(name,value,days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
},
readCookie: function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
}
return null;
},
eraseCookie: function(name) {
this.createCookie(name,"",-1);
}
};
})(window.B3PConfig || (window.B3PConfig = {}));
(function(B3PConfig, $) {
B3PConfig.advancedToggle = {
config: {
advancedclass: '.configadvanced',
advancedtoggle: '#advancedToggle',
cookiename: 'advancedtoggle'
},
advancedToggle: null,
advancedItems: [],
init: function() {
var me = this, useAdvancedToggle = false;
me.advancedToggle = $(me.config.advancedtoggle);
me.advancedItems = $(me.config.advancedclass);
me.advancedItems.each(function() {
if($(this).html().trim() !== '') useAdvancedToggle = true;
});
if(B3PConfig.cookie.readCookie(me.getCookiename()) !== null) {
me.advancedToggle[0].checked = B3PConfig.cookie.readCookie(me.getCookiename()) === 'on';
}
if(useAdvancedToggle) {
me.advancedToggle.click(function(){
me.showHideAdvanced();
});
me.showHideAdvanced();
} else {
me.advancedToggle.parent().hide();
}
},
showHideAdvanced: function () {
var showAdvancedOptions = this.advancedToggle.is(':checked');
B3PConfig.cookie.createCookie(this.getCookiename(), showAdvancedOptions ? 'on' : 'off', 7);
showAdvancedOptions ? this.advancedItems.show() : this.advancedItems.hide();
},
getCookiename: function() {
return this.config.cookiename + (this.advancedToggle.data('cookie-key') ? '-' + this.advancedToggle.data('cookie-key') : '');
}
};
})(window.B3PConfig || (window.B3PConfig = {}), jQuery);
var prevTab = null;
var fbLbl;
function labelClick($lbl) {
if(prevTab != null) prevTab.hide();
prevTab = $j(".content_"+$lbl.attr("id").replace("label_", ""));
prevTab.show();
$j(".tablabel").removeClass("active");
$lbl.addClass("active");
}
var showAdvancedOptions = false;
var contentMinHeight = 300;
$j(document).ready(function() {
contentMinHeight = $j(".tablabels").outerHeight(true)+20;
if($j("#treedivContainer").length > 0) contentMinHeight = $j("#treedivContainer").outerHeight(true)+20;
$j(".tabcontent").each(function (){
var counter = 0;
$j(this).find(".configrow").each(function() {
var $this = $j(this);
if(counter%2==1) $this.addClass("odd");
counter++;
$this.find(".helpLink").each(function (){
if($j(this).attr("id") && $j(this).attr("id") != 'undefined')
{
var $helpContentDiv = $j("#" + $j(this).attr("id").replace("helpLink_", ""));
var helpContent = $helpContentDiv.html();
var helpTitle = $helpContentDiv.attr("title");
$j(this).qtip({
content: {
text: helpContent,
title: helpTitle
},
hide: {
event: 'mouseout'
},
show: {
event: 'click mouseenter'
},
position: {
my: 'right top',
at: 'left middle',
target: $j(this),
viewport: $j(window),
adjust: {
x: -10
}
}
});
}
});
});
if(!$j(this).hasClass("defaulttab")) $j(this).hide();
});
$j(".tablabel").each(function() {
$j(this).click(function() {
labelClick($j(this));
});
});
B3PConfig.advancedToggle.init();
$j(".tabcontent").css("min-height", contentMinHeight);
if($j(".tablabel").length != 0) labelClick($j(".tablabel").first());
// Datatables
var tables = [];
jQuery('.dataTable').each(function() {
tables.push(new B3PDataTable(this));
});
jQuery('.postCheckboxTable').click(function() {
for(var x in tables) {
tables[x].showAllRows();
}
});
});
/**
* B3P wrapper for the jQuery DataTables plugin
* @requires jQuery
* @requires jQuery.dataTables
* @param {HTMLElement} table
* @returns {B3PDataTable}
*/
function B3PDataTable(table) {
/**
* Setting to preserve table height even when there are less items
* @type boolean
*/
this.preserveHeight = true;
/**
* The jQuery object of the table
* @type jQuery
*/
this.table = jQuery(table);
/**
* Container for the creation of the DataTable object
* @type DataTable
*/
this.dataTableObj = null;
/**
* Container for the column settings
* @type Array
*/
this.columnSettings = [];
/**
* Widths for each column
* @type Array
*/
this.columnWidths = [];
/**
* Header row to hold the filters
* @type jQuery
*/
this.filters = jQuery('<tr class="filter"></tr>');
/**
* The selected row object
* @type jQuery
*/
this.selectedRow = this.table.find('.row_selected');
/**
* Container for the DataTable settings
* @type Object
*/
this.tableSettings = null;
/**
* Initializes a B3PDataTable object to create a sortable, filterable DataTable
* @returns {Boolean}
*/
this.init = function() {
// We compute the column widths as soon as possible
this.columnWidths = this.getColumnWidths();
var filterCount = this.initHeaders();
if(this.preserveHeight) var tableHeight = this.calculatePageHeight(filterCount);
var tableSettings = this.initDataTable();
// If there is no saved state (first time view) go to selected row
if(tableSettings.oLoadedState === null) {
this.showSelectedRow();
}
this.appendSelectedRowButton();
if(filterCount !== 0) {
this.appendFilters();
}
this.initRowClick();
if(this.preserveHeight) this.setWrapperHeight(tableHeight);
this.showTable();
return true;
};
/**
* Calculate the height of the table header and first 10 rows (first page)
* @param {int} number of filters
* @returns {int}
*/
this.calculatePageHeight = function(filterCount) {
// Border margin of table
var borderMargin = 2;
// Calc header height
var headerHeight = this.table.find('thead').outerHeight(true) + borderMargin;
// If there are filters, multiply headerheight by 2
if(filterCount !== 0) headerHeight = headerHeight * 2;
// Calc content height
var contentHeight = 0;
// Use first 10 rows
var count = 1;
this.table.find('tbody').children().slice(0, 10).each(function() {
contentHeight += jQuery(this).outerHeight(true) + borderMargin;
});
var tableHeight = headerHeight + contentHeight + 16; // margin;
return tableHeight;
};
/**
* Sets the minimum height of the wrapper, causing the table to preserve height
* @param {int} tableHeight
* @returns {Boolean}
*/
this.setWrapperHeight = function(tableHeight) {
var wrapper = this.table.parent();
// Calculate height of search box and pagination
var childHeight = 0;
wrapper.find('.dataTables_filter, .dataTables_paginate').each(function() {
childHeight += jQuery(this).outerHeight(true);
});
// Move info and pagination to the bottom
jQuery('.dataTables_info, .dataTables_paginate').each(function() {
var obj = jQuery(this);
obj.css({
'position': 'absolute',
'bottom': '0px'
});
if(obj.hasClass('dataTables_paginate')) obj.css('right', '15px');
});
// Set wrapper min-height
wrapper.css({
'min-height': (childHeight + tableHeight - 19 + 'px') // Subtract 19 pixels for wrapper margin
});
return true;
};
/**
* Initializes the headers: create column settings and append a filter.
* Returns the amount of filters created.
* @returns {int}
*/
this.initHeaders = function() {
var me = this, filterCount = 0;
this.table.find('thead tr').first().find('th').each(function(index) {
me.columnSettings.push(me.getColumnSettings(this));
var hasFilter = me.createFilter(this, index);
if(hasFilter) filterCount++;
});
return filterCount;
};
/**
* Creates a DataTables column settings object based on some options
* @param {type} the table header object
* @returns {Object}
*/
this.getColumnSettings = function(column) {
var colSetting = {};
var sortType = "string";
if(column.className.match(/sorter\:[ ]?[']?digit[']?/)) {
sortType = "numeric";
}
if(column.className.match(/sorter\:[ ]?[']?dutchdates[']?/)) {
sortType = "dutchdates";
}
if(column.className.match(/sorter\:[ ]?[']?false[']?/)) {
colSetting.bSortable = false;
}
colSetting.sType = sortType;
colSetting.mRender = function(content, type) {
if(type === 'filter') {
// Remove all HTML tags from content to improve filtering
return content.replace(/<\/?[^>]+>/g, '').trim();
}
return content;
};
return colSetting;
};
/**
* Compute the default width of all columns in the table
* @returns {Object}
*/
this.getColumnWidths = function() {
var i = 0, me = this, columnWidths = [];
// Wrap all td's in the body in a .tablespan class (taking care of text-overflow and set width to 1px)
// So we can use the percentages set for the columns as widths
this.table.find('tbody td').wrapInner(jQuery('<span class="tablespan" style="width: 1px;"></span>'));
// Set the table to the maximum width (wrapper - 30px padding)
this.table.css('width', this.table.parent().width() - 30);
// Loop over first row and add width of each td to array
this.table.find('tbody tr:first-child td').each(function() {
columnWidths[i++] = jQuery(this).width();
});
// Reset width of table
this.table.css('width', 'auto');
// Return array with column widths
return columnWidths;
};
/**
* Sets width on each column to prevent large texts from pushing table off screen
* @returns {Boolean}
*/
this.setTablecellWidth = function() {
var me = this;
// Loop over all rows
this.table.find('tbody tr').each(function() {
// Set index var
var i = 0;
// Loop over all cells
jQuery(this).find('td').each(function() {
var td = jQuery(this);
// Add tablespan container when td is empty so widths are consistant
if(td.is(':empty')) {
td.append('<span class="tablespan"></span>');
}
// Set the max width
td.find('.tablespan').css('width', me.columnWidths[i++]);
});
});
return true;
};
/**
* Creates a filter box for a column. Returns true if a filter is created
* @param {type} the table header object
* @param {type} the column index
* @returns {Boolean}
*/
this.createFilter = function(column, index) {
var me = this, col = jQuery(column);
if(col.hasClass('no-filter')) {
// Column has no-filter class, so create empty header
this.filters.append('<th> </th>');
return false;
} else {
var filter = jQuery('<input type="text" name="filter" title="' + col.text() + '" value="" />').keyup(function(e) {
me.filterColumn(this.value, index);
});
var header = jQuery('<th></th>').append(filter);
this.filters.append(header);
}
return true;
};
/**
* Initializes the DataTables plugin and returns the creation settings
* @returns {Object}
*/
this.initDataTable = function() {
var me = this;
this.dataTableObj = this.table.dataTable({
"iDisplayLength": 10,
"bSortClasses": false,
"aoColumns": this.columnSettings,
"aaSorting": [],
"bStateSave": true,
"sPaginationType": "full_numbers",
"oLanguage": {
"sLengthMenu": "_MENU_ items per pagina",
"sSearch": "Zoeken:",
"oPaginate": {
"sFirst": "Begin",
"sNext": "Volgende",
"sPrevious": "Vorige",
"sLast": "Einde"
},
"sInfo": "Items _START_ tot _END_ van _TOTAL_ getoond",
"sInfoEmpty": "Geen items gevonden",
"sInfoFiltered": " - gefilterd (in totaal _MAX_ items)",
"sEmptyTable": "Geen items gevonden",
"sZeroRecords": "Geen items gevonden"
},
"fnDrawCallback": function() {
me.setTablecellWidth();
}
});
this.tableSettings = this.dataTableObj.fnSettings();
return this.tableSettings;
};
/**
* Append the button to go to the selected row to the paginiation
* @returns {Boolean}
*/
this.appendSelectedRowButton = function() {
var me = this;
me.table.parent().find('.dataTables_paginate').append(jQuery('<a>Geselecteerd</a>').addClass('paginate_button').click(function(e){
e.preventDefault();
me.showSelectedRow();
}));
return true;
};
/**
* Append the filter boxes to the table header
* @returns {Boolean}
*/
this.appendFilters = function() {
var me = this;
// Get saved searches to repopulate field with search value
me.filters.find('th').each(function(index) {
var searchCol = me.tableSettings.aoPreSearchCols[index];
if(searchCol.hasOwnProperty('sSearch') && searchCol.sSearch.length !== 0) {
jQuery('input', this).val(searchCol.sSearch);
}
});
// Add filters to table
me.table.find('thead').append(me.filters);
return true;
};
/**
* Attach handlers for clicking a row in the table
* @returns {Boolean}
*/
this.initRowClick = function() {
this.table.find('tbody').delegate("td", "click", function() {
var row = jQuery(this);
// Check if there is a link or input (button, checkbox, etc.) present
if(row.find('a, input').length === 0) {
// No link or input so navigate to the attached URL
var link = row.parent().attr('data-link');
if(link) window.location.href = link;
}
});
return true;
};
/**
* Search a single column for a string
* @param {String} the string to search on
* @param {int} the index of the columns that needs to be filtered
* @returns {Boolean}
*/
this.filterColumn = function(filter, colindex) {
if(this.dataTableObj === null) return;
this.dataTableObj.fnFilter( filter, colindex );
return true;
};
/**
* Shows the currently selected row
* @returns {Boolean}
*/
this.showSelectedRow = function() {
if(this.dataTableObj === null) return false;
this.dataTableObj.fnDisplayRow( this.selectedRow[0] );
return true;
};
/**
* Makes the table visible (table is hidden using CSS and positioning to prevent flicker)
* @returns {Boolean}
*/
this.showTable = function() {
this.table.css({
'position': 'static',
'left': '0px'
});
return true;
};
/**
* Function to show all rows (remove pagination).
* This is mainly used to post all input fields in a tables
* @returns {Boolean}
*/
this.showAllRows = function() {
var wrapper = this.table.parent(), wrapperHeight = wrapper.height();
wrapper.css({
'height': wrapperHeight + 'px',
'overflow': 'hidden'
});
this.table.css({
'position': 'absolute',
'left': '-99999px'
});
jQuery('<div>Bezig met opslaan...</div>')
.css({ 'clear': 'both', 'margin-top': '15px;' })
.insertAfter(jQuery('.dataTables_filter', wrapper));
jQuery('tbody', this.table).append( this.dataTableObj.fnGetHiddenNodes() );
};
/**
* Install dataTable extensions, needed for some functionality
*/
(function() {
if(typeof jQuery.fn.dataTableExt.oSort['dutchdates-asc'] === "undefined") {
/**
* Extension to support sorting of dutch formatted dates (dd-mm-yyyy)
*/
jQuery.fn.dataTableExt.oSort['dutchdates-asc'] = function(a,b) {
var x = parseDutchDate(jQuery(a)), y = parseDutchDate(jQuery(b));
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['dutchdates-desc'] = function(a,b) {
var x = parseDutchDate(jQuery(a)), y = parseDutchDate(jQuery(b));
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
var parseDutchDate = function(obj) {
var s = obj.text();
var hit = s.match(/(\d{2})-(\d{2})-(\d{4})/);
if (hit && hit.length === 4) return new Date(hit[3], hit[2], hit[1]);
return new Date(s);
};
}
if(typeof jQuery.fn.dataTableExt.oApi.fnDisplayRow === "undefined") {
/**
* Extension to go to the page containing a specific row
* We use this extension to go to the selected row
*/
jQuery.fn.dataTableExt.oApi.fnDisplayRow = function ( oSettings, nRow ) {
// Account for the "display" all case - row is already displayed
if ( oSettings._iDisplayLength === -1 ) return;
// Find the node in the table
var iPos = -1, iLen=oSettings.aiDisplay.length;
for( var i=0; i < iLen; i++ ) {
if( oSettings.aoData[ oSettings.aiDisplay[i] ].nTr === nRow ) {
iPos = i;
break;
}
}
// Alter the start point of the paging display
if( iPos >= 0 ) {
oSettings._iDisplayStart = ( Math.floor(i / oSettings._iDisplayLength) ) * oSettings._iDisplayLength;
this.oApi._fnCalculateEnd( oSettings );
}
this.oApi._fnDraw( oSettings );
};
}
if(typeof jQuery.fn.dataTableExt.oApi.fnGetHiddenNodes === "undefined") {
jQuery.fn.dataTableExt.oApi.fnGetHiddenNodes = function ( oSettings ) {
/* Note the use of a DataTables 'private' function thought the 'oApi' object */
var anNodes = this.oApi._fnGetTrNodes( oSettings );
var anDisplay = jQuery('tbody tr', oSettings.nTable);
/* Remove nodes which are being displayed */
for ( var i=0 ; i<anDisplay.length ; i++ )
{
var iIndex = jQuery.inArray( anDisplay[i], anNodes );
if ( iIndex != -1 )
{
anNodes.splice( iIndex, 1 );
}
}
/* Fire back the array to the caller */
return anNodes;
};
}
})();
/**
* Execute initialize function
*/
this.init();
}
|
B3Partners/gisviewerConfig
|
src/main/webapp/scripts/commonfunctions.js
|
JavaScript
|
lgpl-3.0
| 24,486 |
/**
* Copyright (C) 2010-2016 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* EvoSuite is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.graphs.ccfg;
public class CCFGFrameEdge extends CCFGEdge {
private static final long serialVersionUID = 8223049010545407697L;
/** {@inheritDoc} */
@Override
public String toString() {
return "";
}
}
|
claudejin/evosuite
|
client/src/main/java/org/evosuite/graphs/ccfg/CCFGFrameEdge.java
|
Java
|
lgpl-3.0
| 1,011 |
/*
This file is part of Advanced Input.
Advanced Input is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Advanced Input is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Advanced Input. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
namespace AdvancedInput.ButtonBindings {
public class AI_BB_TranslateBack: IButtonBinding
{
public string name { get { return "TranslateBack"; } }
public ControlTypes lockMask { get { return ControlTypes.LINEAR; } }
public bool locked { get; set; }
public void Update (int state, bool edge)
{
if (state > 0) {
FlightInputHandler.state.Z = 1;
}
}
public AI_BB_TranslateBack (ConfigNode node)
{
}
}
}
|
taniwha/AdvancedInput
|
Source/ButtonBindings/TranslateBack.cs
|
C#
|
lgpl-3.0
| 1,131 |
import { ipcRenderer } from 'electron';
import * as normalizeUrl from 'normalize-url';
$(document).ready(() => {
ipcRenderer.send('ready');
});
ipcRenderer.on('open-url', (e: any, msg: any) => {
const url = normalizeUrl(msg);
(document.querySelector('webview.active') as any).loadURL(url);
});
|
Perolize/MyBrowser
|
app/src/js/urlLoad.ts
|
TypeScript
|
lgpl-3.0
| 307 |
########################################################################
# File:: presenters.rb
# (C):: Loyalty New Zealand 2014
#
# Purpose:: Include the schema based data validation and rendering code.
# ----------------------------------------------------------------------
# 26-Jan-2015 (ADH): Split from top-level inclusion file.
########################################################################
module Hoodoo
# Module providing a namespace for schema-based data rendering and
# validation code.
#
module Presenters
end
end
# Dependencies
require 'hoodoo/utilities'
# Presenters
require 'hoodoo/presenters/base'
require 'hoodoo/presenters/base_dsl'
require 'hoodoo/presenters/embedding'
require 'hoodoo/presenters/types/field'
require 'hoodoo/presenters/types/object'
require 'hoodoo/presenters/types/array'
require 'hoodoo/presenters/types/hash'
require 'hoodoo/presenters/types/string'
require 'hoodoo/presenters/types/text'
require 'hoodoo/presenters/types/enum'
require 'hoodoo/presenters/types/boolean'
require 'hoodoo/presenters/types/float'
require 'hoodoo/presenters/types/integer'
require 'hoodoo/presenters/types/decimal'
require 'hoodoo/presenters/types/date'
require 'hoodoo/presenters/types/date_time'
require 'hoodoo/presenters/types/tags'
require 'hoodoo/presenters/types/uuid'
require 'hoodoo/presenters/common_resource_fields'
|
LoyaltyNZ/hoodoo
|
lib/hoodoo/presenters.rb
|
Ruby
|
lgpl-3.0
| 1,391 |
import itertools
import re
import random
import time
import urllib2
from bs4 import BeautifulSoup
import csv
import os
import os.path
import string
import pg
from collections import OrderedDict
import tweepy
import sys
# lint_ignore=E302,E501
_dir = os.path.dirname(os.path.abspath(__file__))
_cur = pg.connect(host="127.0.0.1")
_topHashtagsDir = "%s/dissertationData/topHashtags" % (_dir)
def getTweepyAPI():
consumer_key = "vKbz24SqytZnYO33FNkR7w"
consumer_secret = "jjobro8Chy9aKMzo8szYMz9tHftONLRkjNnrxk0"
access_key = "363361813-FKSdmwSbzuUzHWg326fTGJM7Bu2hTviqEetjMgu8"
access_secret = "VKgzDnTvDUWR1csliUR3BiMOI2oqO9NzocNKX1jPd4"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
return tweepy.API(auth)
_api = getTweepyAPI()
def isRetweet(tweet):
return hasattr(tweet, 'retweeted_status')
def write2csv(res, file):
print "writing %s results to file: %s" % (len(res), file)
with open(file, 'wb') as f:
writer = csv.writer(f, quoting=csv.QUOTE_ALL)
writer.writerows(res)
def myQuery(query):
print "running query: %s" % (query)
res = _cur.query(query)
print "finished running query"
return(res)
def getTweetObj(tweet):
tweetObj = [tweet.id_str, tweet.user.id, tweet.user.screen_name.lower(), tweet.created_at, isRetweet(tweet), tweet.in_reply_to_status_id_str,
tweet.lang, tweet.truncated, tweet.text.encode("utf-8")]
return tweetObj
class CustomStreamListener(tweepy.StreamListener):
def __init__(self, group):
self.group = group
self.curTweets = []
# http://stackoverflow.com/questions/576169/understanding-python-super-and-init-methods
super(CustomStreamListener, self).__init__()
def addTweet(self, tweet):
tweetObj = getTweetObj(tweet)
tweetObj.append(self.group)
self.curTweets.append(tweetObj)
if len(self.curTweets) == 1000:
self.saveResults()
self.curTweets = []
def saveResults(self):
sys.stdout.write('\n')
file = '/tmp/topHashtags.csv' % ()
ids = [tweet[0] for tweet in self.curTweets]
ids = list(OrderedDict.fromkeys(ids))
ids = [[id] for id in ids]
myQuery('truncate temp_tweets_id')
write2csv(ids, file)
myQuery("copy temp_tweets_id (id) from '%s' delimiters ',' csv" % (file))
newIds = myQuery("select id from temp_tweets_id as t where t.id not in (select id from top_hashtag_tweets where top_hashtag_tweets.id >= (select min(id) from temp_tweets_id))").getresult()
newIds = [id[0] for id in newIds]
newIds = [str(id) for id in newIds]
newTweets = [tweet for tweet in self.curTweets if tweet[0] in newIds]
newTweets = dict((tweet[0], tweet) for tweet in newTweets).values()
write2csv(newTweets, file)
myQuery("copy top_hashtag_tweets (id, user_id, user_screen_name, created_at, retweeted, in_reply_to_status_id, lang, truncated, text, hashtag_group) from '%s' delimiters ',' csv" % (file))
def on_status(self, status):
sys.stdout.write('.')
sys.stdout.flush()
self.addTweet(status)
def on_error(self, status_code):
print >> sys.stderr, 'error: %s' % (repr(status_code))
return True
def on_timeout(self):
print >> sys.stderr, 'Timeout...'
return True
def scrapeTrendsmap():
baseUrl = 'http://trendsmap.com'
url = baseUrl + '/local'
soup = BeautifulSoup(urllib2.urlopen(url).read())
#res = soup.findAll('div', {'class': 'location'})
res = soup.findAll('a', {'href': re.compile('^\/local\/us')})
cityUrls = [baseUrl + item['href'] for item in res]
allHashtags = []
for rank, url in enumerate(cityUrls):
print "working url %s, %s/%s" % (url, rank, len(cityUrls))
soup = BeautifulSoup(urllib2.urlopen(url).read())
res = soup.findAll('a', {'class': 'obscure-text', 'title': re.compile('^#')})
hashtags = [item['title'].encode('utf-8') for item in res]
allHashtags.extend(hashtags)
time.sleep(2 + random.random())
allHashtags = list(OrderedDict.fromkeys(allHashtags))
random.shuffle(allHashtags)
return allHashtags
def generateTopHashtagsTrendsmap():
res = scrapeTrendsmap()
return res
def scrapeStatweestics():
url = 'http://statweestics.com/stats/hashtags/day'
soup = BeautifulSoup(urllib2.urlopen(url).read())
res = []
for hrefEl in soup.findAll('a', {'href': re.compile('^\/stats\/show')}):
res.append(hrefEl.contents[0].encode('utf-8'))
return res
def generateTopHashtagsStatweestics():
res = scrapeStatweestics()
return res
def generateTopHashtagsCSV(scrapeFun, group):
res = []
for rank, item in enumerate(scrapeFun()):
res.append([item, rank, group])
file = "%s/%s.csv" % (_topHashtagsDir, group)
write2csv(res, file)
def storeTopHashtags(topHashtagsFile):
cmd = "copy top_hashtag_hashtags (hashtag, rank, hashtag_group) from '%s/%s.csv' delimiters ',' csv" % (_topHashtagsDir, topHashtagsFile)
myQuery(cmd)
def generateTopHashtags(scrapeFun=generateTopHashtagsTrendsmap, groupID='trendsmap'):
hashtagGroup = '%s %s' % (time.strftime("%Y-%m-%d %H:%M:%S"), groupID)
generateTopHashtagsCSV(scrapeFun, hashtagGroup)
storeTopHashtags(hashtagGroup)
def getHashtagsFrom(group):
res = myQuery("select hashtag from top_hashtag_hashtags where hashtag_group = '%s' order by rank asc" % (group)).getresult()
res = [item[0] for item in res]
res = [hashtag for hashtag in res if sys.getsizeof(hashtag) <= 60]
res = res[-400:]
return res
def streamHashtags(hashtagGroup):
while True:
try:
sapi = tweepy.streaming.Stream(_api.auth, CustomStreamListener(hashtagGroup))
sapi.filter(languages=['en'], track=getHashtagsFrom('%s' % (hashtagGroup)))
except Exception as e:
print "couldn't do it for %s:" % (e)
time.sleep(1)
pass
def streamHashtagsCurrent():
#hashtagGroup = '2014-02-27 17:13:30 initial'
#hashtagGroup = '2014-03-17 11:28:15 trendsmap'
#hashtagGroup = '2014-03-24 13:06:19 trendsmap'
hashtagGroup = '2014-04-04 15:03:59 trendsmap'
streamHashtags(hashtagGroup)
def scrape_socialbakers(url):
soup = BeautifulSoup(urllib2.urlopen(url).read())
res = []
for div in soup.findAll('div', {'id': 'snippet-bookmarkToggle-bookmarkToggle'}):
res.append(div.findAll('div')[0]['id'].split('-')[-1])
print "grabbed %s results from url %s" % (len(res), url)
return res
def scrape_twitaholic(url):
soup = BeautifulSoup(urllib2.urlopen(url).read())
res = []
for tr in soup.findAll('tr', {'style': 'border-top:1px solid black;'}):
temp = tr.find('td', {'class': 'statcol_name'})
res.append(temp.a['title'].split('(')[1][4:-1])
return res
def generateTopUsersTwitaholic():
res = []
for i in range(10):
i = i + 1
url = 'http://twitaholic.com/top' + str(i) + '00/followers/'
res.append(scrape_twitaholic(url))
return res
def generateTopUsersSocialBakers(numUsers=10000):
res = []
for i in range(numUsers / 50):
url = 'http://socialbakers.com/twitter/page-' + str(i + 1) + '/'
res.append(scrape_socialbakers(url))
return res
_topUsersDir = "%s/dissertationData/topRankedUsers" % (_dir)
def generateTopUsersCSV(scrapeFun, topUsersFile):
res = scrapeFun()
res = list(itertools.chain(*res))
res = [x.lower() for x in res]
res = OrderedDict.fromkeys(res)
res = filter(None, res)
with open("%s/%s" % (_topUsersDir, topUsersFile), 'wb') as csvfile:
csvWriter = csv.writer(csvfile, quoting=csv.QUOTE_ALL)
rank = 0
for item in res:
rank = rank + 1
csvWriter.writerow([item, rank])
def storeTopUsers(topUsersFile):
topUsersDir = _topUsersDir
cmd = "copy topUsers (user_screen_name, rank) from '${topUsersDir}/${topUsersFile}' delimiters ',' csv"
cmd = string.Template(cmd).substitute(locals())
myQuery(cmd)
def generateTopUsers(scrapeFun=generateTopUsersTwitaholic, topUsersFile='top1000Twitaholic.csv'):
generateTopUsersCSV(scrapeFun=scrapeFun, topUsersFile=topUsersFile)
storeTopUsers(topUsersFile=topUsersFile)
def storeTagSynonyms(synonymsFile):
cmd = "copy tag_synonyms (%s) from '%s/dissertationData/tagSynonyms/%s' delimiters ',' csv header" % (
"id, Source_Tag_Name, Target_Tag_Name, Creation_Date, Owner_User_Id, Auto_Rename_Count, Last_Auto_Rename, Score, Approved_By_User_Id, Approval_Date",
_dir, synonymsFile)
myQuery(cmd)
def storeCurTagSynonyms():
storeTagSynonyms('synonyms-2014-01-30.csv')
def backupTables(tableNames=['topUsers', 'tweets', 'top_hashtag_hashtags', 'top_hashtag_tweets', 'post_subsets', 'top_hashtag_subsets',
'post_tokenized', 'top_hashtag_tokenized', 'post_filtered', 'twitter_users', 'tag_synonyms', 'users', 'posts',
'post_tokenized_type_types', 'top_hashtag_tokenized_type_types', 'post_tokenized_chunk_types', 'top_hashtag_tokenized_chunk_types',
'tweets_tokenized', 'tweets_tokenized_chunk_types', 'tweets_tokenized_type_types']):
for tableName in tableNames:
file = "%s/dissertationData/tables/%s.csv" % (_dir, tableName)
cmd = string.Template("copy ${tableName} to '${file}' delimiter ',' csv header").substitute(locals())
myQuery(cmd)
def getRemainingHitsUserTimeline():
stat = _api.rate_limit_status()
return stat['resources']['statuses']['/statuses/user_timeline']['remaining']
def getRemainingHitsGetUser():
stat = _api.rate_limit_status()
return stat['resources']['users']['/users/lookup']['remaining']
def getTweets(screen_name, **kwargs):
# w.r.t include_rts: ref: https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
# When set to false, the timeline will strip any native retweets (though they
# will still count toward both the maximal length of the timeline and the slice
# selected by the count parameter).
return _api.user_timeline(screen_name=screen_name, include_rts=True, **kwargs)
def getInfoForUser(screenNames):
users = _api.lookup_users(screen_names=screenNames)
res = [[user.id, user.created_at, user.description.encode('utf-8'), user.followers_count, user.friends_count,
user.lang, user.location.encode('utf-8'), user.name.encode('utf-8'), user.screen_name.lower(), user.verified, user.statuses_count] for user in users]
file = '/tmp/%s..%s_user.csv' % (screenNames[0], screenNames[-1])
write2csv(res, file)
myQuery("copy twitter_users (id,created_at,description,followers_count,friends_count,lang,location,name,user_screen_name,verified,statuses_count) from '%s' delimiters ',' csv" % (file))
def getAllTweets(screenNames):
def getTweetsBetween(greaterThanID, lessThanID):
alltweets = []
while True:
print "getting tweets from %s that are later than %s but before %s" % (screen_name, greaterThanID, lessThanID)
newTweets = getTweets(screen_name, count=200, max_id=lessThanID - 1, since_id=greaterThanID + 1)
if len(newTweets) == 0:
break
alltweets.extend(newTweets)
lessThanID = alltweets[-1].id
print "...%s tweets downloaded so far" % (len(alltweets))
return alltweets
assert len(screenNames) == 1, "Passed more than one screen name into function"
screen_name = screenNames[0]
print "getting tweets for %s" % (screen_name)
alltweets = []
lessThanID = getTweets(screen_name, count=1)[-1].id + 1
cmd = string.Template("select id from tweets where user_screen_name = '${screen_name}' order by id desc").substitute(locals())
res = myQuery(cmd).getresult()
if len(res) == 0:
newestGrabbed = 0
else:
newestGrabbed = int(res[0][0])
res = getTweetsBetween(newestGrabbed, lessThanID)
alltweets.extend(res)
cmd = string.Template("select id from tweets where user_screen_name = '${screen_name}' order by id asc").substitute(locals())
res = myQuery(cmd).getresult()
if len(res) == 0:
lessThanID = 0
else:
lessThanID = int(res[0][0])
alltweets.extend(getTweetsBetween(0, lessThanID))
outTweets = [getTweetObj(tweet) for tweet in alltweets]
file = '/tmp/%s_tweets.csv' % screen_name
write2csv(outTweets, file)
myQuery("copy tweets (id, user_id, user_screen_name, created_at, retweeted, in_reply_to_status_id, lang, truncated,text) from '%s' delimiters ',' csv" % (file))
def userAlreadyCollected(user_screen_name):
res = myQuery(string.Template("select * from tweets where user_screen_name='${user_screen_name}' limit 1").substitute(locals())).getresult()
return len(res) > 0
def userInfoAlreadyCollected(user_screen_name):
res = myQuery(string.Template("select * from twitter_users where user_screen_name='${user_screen_name}' limit 1").substitute(locals())).getresult()
return len(res) > 0
# ref: http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks/434411#434411
def chunker(seq, size):
return (seq[pos:pos + size] for pos in xrange(0, len(seq), size))
def getForTopUsers(alreadyCollectedFun, getForUserFun, getRemainingHitsFun, hitsAlwaysGreaterThan, userQuery, groupFun=lambda x: chunker(x, 1)):
res = myQuery(userQuery).getresult()
screenNames = [[user[0]] for user in res]
screenNames = list(itertools.chain(*screenNames))
print "getting tweets for %s users" % len(screenNames)
screenNameGroups = groupFun(screenNames)
for screenNameGroup in screenNameGroups:
newScreenNames = []
for screenName in screenNameGroup:
if alreadyCollectedFun(screenName):
print "already collected tweets for %s; moving to next user" % (screenName)
continue
newScreenNames.append(screenName)
if len(newScreenNames) == 0:
continue
try:
while True:
remainingHits = getRemainingHitsFun()
if remainingHits > hitsAlwaysGreaterThan:
break
print "only %s remaining hits; waiting until greater than %s" % (remainingHits, hitsAlwaysGreaterThan)
time.sleep(60)
print "calling %s with %s at %s remaining hits" % (getForUserFun, newScreenNames, remainingHits)
getForUserFun(newScreenNames)
except Exception as e:
print "couldn't do it for %s: %s" % (newScreenNames, e)
time.sleep(1)
pass
def getAllTweetsDefault(userQuery):
return getForTopUsers(alreadyCollectedFun=userAlreadyCollected, getForUserFun=getAllTweets, getRemainingHitsFun=getRemainingHitsUserTimeline, hitsAlwaysGreaterThan=30, userQuery=userQuery)
def makeUserQuery(val, col):
return 'select user_screen_name from twitter_users where %s > %d order by %s asc limit 1000' % (col, val, col)
def makeUserQueryFollowers(val):
return makeUserQuery(val, 'followers_count')
def makeUserQueryTweets(val):
return makeUserQuery(val, 'statuses_count')
def getAllTweetsFor10MUsers():
return getAllTweetsDefault(makeUserQueryFollowers(10000000))
def getAllTweetsFor1MUsers():
return getAllTweetsDefault(makeUserQueryFollowers(1000000))
def getAllTweetsFor100kUsers():
return getAllTweetsDefault(makeUserQueryFollowers(100000))
def getAllTweetsFor10kUsers():
return getAllTweetsDefault(makeUserQueryFollowers(10000))
def getAllTweetsFor5kUsers():
return getAllTweetsDefault(makeUserQueryFollowers(5000))
def getAllTweetsFor1kUsers():
return getAllTweetsDefault(makeUserQueryFollowers(1000))
def getAllTweetsForS1e2Users():
return getAllTweetsDefault(makeUserQueryTweets(100))
def getAllTweetsForS5e2Users():
return getAllTweetsDefault(makeUserQueryTweets(500))
def getAllTweetsForS1e3Users():
return getAllTweetsDefault(makeUserQueryTweets(1000))
def getAllTweetsForS5e3Users():
return getAllTweetsDefault(makeUserQueryTweets(5000))
def getAllTweetsForS1e4Users():
return getAllTweetsDefault(makeUserQueryTweets(10000))
def getAllTweetsForS5e4Users():
return getAllTweetsDefault(makeUserQueryTweets(50000))
def getAllTweetsForTopUsersByFollowers():
getAllTweetsFor10MUsers()
getAllTweetsFor1MUsers()
getAllTweetsFor100kUsers()
getAllTweetsFor10kUsers()
getAllTweetsFor1kUsers()
getAllTweetsFor5kUsers()
def getAllTweetsForTopUsersByTweets():
getAllTweetsForS1e2Users()
getAllTweetsForS5e2Users()
getAllTweetsForS1e3Users()
getAllTweetsForS5e3Users()
getAllTweetsForS1e4Users()
getAllTweetsForS5e4Users()
def getUserInfoForTopUsers():
getForTopUsers(alreadyCollectedFun=userInfoAlreadyCollected, getForUserFun=getInfoForUser, getRemainingHitsFun=getRemainingHitsGetUser, hitsAlwaysGreaterThan=30, groupFun=lambda x: chunker(x, 100),
userQuery='select (user_screen_name) from topUsers order by rank asc limit 100000')
def generateTopUsers100k():
generateTopUsers(scrapeFun=lambda: generateTopUsersSocialBakers(numUsers=100000), topUsersFile='top100000SocialBakers.csv')
def backupTopHashtags():
backupTables(tableNames=['top_hashtag_hashtags',
'top_hashtag_subsets',
'top_hashtag_tokenized',
'top_hashtag_tokenized_chunk_types',
'top_hashtag_tokenized_type_types',
'top_hashtag_tweets'])
def backupTweets():
backupTables(tableNames=['tweets',
'tweets_tokenized',
'tweets_tokenized_chunk_types',
'tweets_tokenized_type_types'])
# Current run selections
#generateTopUsers100k()
#getAllTweetsForTopUsersByFollowers()
#getAllTweetsForTopUsersByTweets()
#getUserInfoForTopUsers()
#storeCurTagSynonyms()
#backupTopHashtags()
#backupTables()
#generateTopHashtags()
#streamHashtagsCurrent()
if __name__ == "__main__":
command = " ".join(sys.argv[1:])
print('running command %s') % (command)
eval(command)
|
claytontstanley/dissertation
|
dissProject/scrapeUsers.py
|
Python
|
lgpl-3.0
| 18,399 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package parallelismanalysis.util;
/*************************************************************************
* Compilation: javac Permutations.java
* Execution: java Permutations N
*
* Enumerates all permutations on N elements.
*
* % java Permutations 3
* bca
* cba
* cab
* acb
* bac
* abc
*
* % java Permutations 3 | sort
* abc
* acb
* bac
* bca
* cab
* cba
*
* http://www.comscigate.com/cs/IntroSedgewick/20elements/27recursion/Permutations.java
*************************************************************************/
public class Permutations {
// swap the characters at indices i and j
public static void swap(char[] a, int i, int j) {
char c;
c = a[i];
a[i] = a[j];
a[j] = c;
}
// print n! permutation of the characters of a
public static void enumerate(char[] a, int n) {
if (n == 1) {
System.out.println(a);
return;
}
for (int i = 0; i < n; i++) {
swap(a, i, n - 1);
enumerate(a, n - 1);
swap(a, i, n - 1);
}
}
public static void main(String[] args) {
int N = 6; // Integer.parseInt(args[0]);
String elements = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// initialize a[i] to ith letter, starting at 'a'
char[] a = new char[N];
for (int i = 0; i < N; i++) {
a[i] = elements.charAt(i);
}
enumerate(a, N);
}
}
|
parmerasa-uau/parallelism-optimization
|
ParallelismAnalysisJMetal/src/parallelismanalysis/util/Permutations.java
|
Java
|
lgpl-3.0
| 1,677 |
namespace StockSharp.Algo.Testing
{
using System;
using Ecng.Common;
using StockSharp.Messages;
/// <summary>
/// Адаптер, исполняющий сообщения в <see cref="IMarketEmulator"/>.
/// </summary>
public class EmulationMessageAdapter : MessageAdapter<IMessageSessionHolder>
{
/// <summary>
/// Создать <see cref="EmulationMessageAdapter"/>.
/// </summary>
/// <param name="sessionHolder">Контейнер для сессии.</param>
public EmulationMessageAdapter(IMessageSessionHolder sessionHolder)
: this(new MarketEmulator(), sessionHolder)
{
}
/// <summary>
/// Создать <see cref="EmulationMessageAdapter"/>.
/// </summary>
/// <param name="emulator">Эмулятор торгов.</param>
/// <param name="sessionHolder">Контейнер для сессии.</param>
public EmulationMessageAdapter(IMarketEmulator emulator, IMessageSessionHolder sessionHolder)
: base(MessageAdapterTypes.Transaction, sessionHolder)
{
Emulator = emulator;
}
private IMarketEmulator _emulator;
/// <summary>
/// Эмулятор торгов.
/// </summary>
public IMarketEmulator Emulator
{
get { return _emulator; }
set
{
if (value == null)
throw new ArgumentNullException("value");
if (value == _emulator)
return;
if (_emulator != null)
{
_emulator.NewOutMessage -= SendOutMessage;
_emulator.Parent = null;
}
_emulator = value;
_emulator.Parent = SessionHolder;
_emulator.NewOutMessage += SendOutMessage;
}
}
/// <summary>
/// Запустить таймер генерации с интервалом <see cref="MessageSessionHolder.MarketTimeChangedInterval"/> сообщений <see cref="TimeMessage"/>.
/// </summary>
protected override void StartMarketTimer()
{
}
/// <summary>
/// Отправить сообщение.
/// </summary>
/// <param name="message">Сообщение.</param>
protected override void OnSendInMessage(Message message)
{
SessionHolder.DoIf<IMessageSessionHolder, HistorySessionHolder>(s => s.UpdateCurrentTime(message.GetServerTime()));
switch (message.Type)
{
case MessageTypes.Connect:
_emulator.SendInMessage(new ResetMessage());
SendOutMessage(new ConnectMessage());
return;
case MessageTypes.Disconnect:
SendOutMessage(new DisconnectMessage());
return;
case ExtendedMessageTypes.EmulationState:
SendOutMessage(message.Clone());
return;
}
_emulator.SendInMessage(message);
}
}
}
|
Enterprize-1701/robot
|
Algo/Testing/EmulationMessageAdapter.cs
|
C#
|
lgpl-3.0
| 2,581 |
<?php
/*
* This file is part of facturacion_base
* Copyright (C) 2013-2017 Carlos Garcia Gomez neorazorx@gmail.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace FacturaScripts\model;
require_model('asiento.php');
require_model('ejercicio.php');
require_model('linea_iva_factura_proveedor.php');
require_model('linea_factura_proveedor.php');
require_model('regularizacion_iva.php');
require_model('secuencia.php');
require_model('serie.php');
/**
* Factura de un proveedor.
*
* @author Carlos García Gómez <neorazorx@gmail.com>
*/
class factura_proveedor extends \fs_model
{
/**
* Clave primaria.
* @var type
*/
public $idfactura;
/**
* ID de la factura a la que rectifica.
* @var type
*/
public $idfacturarect;
/**
* ID del asiento relacionado, si lo hay.
* @var type
*/
public $idasiento;
/**
* ID del asiento de pago relacionado, si lo hay.
* @var type
*/
public $idasientop;
public $cifnif;
/**
* Empleado que ha creado la factura.
* Modelo agente.
* @var type
*/
public $codagente;
/**
* Almacén en el que entra la mercancía.
* @var type
*/
public $codalmacen;
/**
* Divisa de la factura.
* @var type
*/
public $coddivisa;
/**
* Ejercicio relacionado. El que corresponde a la fecha.
* @var type
*/
public $codejercicio;
/**
* Código único de la factura. Para humanos.
* @var type
*/
public $codigo;
/**
* Código de la factura a la que rectifica.
* @var type
*/
public $codigorect;
/**
* Forma d epago usada.
* @var type
*/
public $codpago;
/**
* Proveedor de la factura.
* @var type
*/
public $codproveedor;
/**
* Serie de la factura.
* @var type
*/
public $codserie;
public $fecha;
public $hora;
/**
* % de retención IRPF de la factura.
* Cada línea puede tener uno distinto.
* @var type
*/
public $irpf;
/**
* Suma total antes de impuestos.
* @var type
*/
public $neto;
/**
* Nombre del proveedor.
* @var type
*/
public $nombre;
/**
* Número de la factura.
* Único dentro de serie+ejercicio.
* @var type
*/
public $numero;
/**
* Número de factura del proveedor, si lo hay.
* @var type
*/
public $numproveedor;
public $observaciones;
public $pagada;
/**
* Tasa de conversión a Euros de la divisa de la factura.
* @var type
*/
public $tasaconv;
/**
* Importe total de la factura, con impuestos.
* @var type
*/
public $total;
/**
* Total expresado en euros, por si no fuese la divisa de la factura.
* totaleuros = total/tasaconv
* No hace falta rellenarlo, al hacer save() se calcula el valor.
* @var type
*/
public $totaleuros;
/**
* Suma total de retenciones IRPF de las líneas.
* @var type
*/
public $totalirpf;
/**
* Suma total del IVA de las líneas.
* @var type
*/
public $totaliva;
/**
* Suma del recargo de equivalencia de las líneas.
* @var type
*/
public $totalrecargo;
public $anulada;
/**
* Número de documentos adjuntos.
* @var integer
*/
public $numdocs;
public function __construct($f = FALSE)
{
parent::__construct('facturasprov');
if($f)
{
$this->anulada = $this->str2bool($f['anulada']);
$this->cifnif = $f['cifnif'];
$this->codagente = $f['codagente'];
$this->codalmacen = $f['codalmacen'];
$this->coddivisa = $f['coddivisa'];
$this->codejercicio = $f['codejercicio'];
$this->codigo = $f['codigo'];
$this->codigorect = $f['codigorect'];
$this->codpago = $f['codpago'];
$this->codproveedor = $f['codproveedor'];
$this->codserie = $f['codserie'];
$this->fecha = Date('d-m-Y', strtotime($f['fecha']));
$this->hora = '00:00:00';
if( !is_null($f['hora']) )
{
$this->hora = date('H:i:s', strtotime($f['hora']));
}
$this->idasiento = $this->intval($f['idasiento']);
$this->idasientop = $this->intval($f['idasientop']);
$this->idfactura = $this->intval($f['idfactura']);
$this->idfacturarect = $this->intval($f['idfacturarect']);
$this->irpf = floatval($f['irpf']);
$this->neto = floatval($f['neto']);
$this->nombre = $f['nombre'];
$this->numero = $f['numero'];
$this->numproveedor = $f['numproveedor'];
$this->observaciones = $this->no_html($f['observaciones']);
$this->pagada = $this->str2bool($f['pagada']);
$this->tasaconv = floatval($f['tasaconv']);
$this->total = floatval($f['total']);
$this->totaleuros = floatval($f['totaleuros']);
$this->totalirpf = floatval($f['totalirpf']);
$this->totaliva = floatval($f['totaliva']);
$this->totalrecargo = floatval($f['totalrecargo']);
$this->numdocs = intval($f['numdocs']);
}
else
{
$this->anulada = FALSE;
$this->cifnif = '';
$this->codagente = NULL;
$this->codalmacen = $this->default_items->codalmacen();
$this->coddivisa = NULL;
$this->codejercicio = NULL;
$this->codigo = NULL;
$this->codigorect = NULL;
$this->codpago = $this->default_items->codpago();
$this->codproveedor = NULL;
$this->codserie = $this->default_items->codserie();
$this->fecha = Date('d-m-Y');
$this->hora = Date('H:i:s');
$this->idasiento = NULL;
$this->idasientop = NULL;
$this->idfactura = NULL;
$this->idfacturarect = NULL;
$this->irpf = 0;
$this->neto = 0;
$this->nombre = '';
$this->numero = NULL;
$this->numproveedor = NULL;
$this->observaciones = NULL;
$this->pagada = FALSE;
$this->tasaconv = 1;
$this->total = 0;
$this->totaleuros = 0;
$this->totalirpf = 0;
$this->totaliva = 0;
$this->totalrecargo = 0;
$this->numdocs = 0;
}
}
protected function install()
{
new \serie();
new \asiento();
return '';
}
public function observaciones_resume()
{
if($this->observaciones == '')
{
return '-';
}
else if( strlen($this->observaciones) < 60 )
{
return $this->observaciones;
}
else
return substr($this->observaciones, 0, 50).'...';
}
/**
* Establece la fecha y la hora, pero respetando el ejercicio y las
* regularizaciones de IVA.
* Devuelve TRUE si se asigna una fecha u hora distinta a los solicitados.
* @param type $fecha
* @param type $hora
* @return boolean
*/
public function set_fecha_hora($fecha, $hora)
{
$cambio = FALSE;
if( is_null($this->numero) ) /// nueva factura
{
$this->fecha = $fecha;
$this->hora = $hora;
}
else if($fecha != $this->fecha) /// factura existente y cambiamos fecha
{
$cambio = TRUE;
$eje0 = new \ejercicio();
$ejercicio = $eje0->get($this->codejercicio);
if($ejercicio)
{
/// ¿El ejercicio actual está abierto?
if( $ejercicio->abierto() )
{
$eje2 = $eje0->get_by_fecha($fecha);
if($eje2)
{
if( $eje2->abierto() )
{
/// ¿La factura está dentro de alguna regularización?
$regiva0 = new \regularizacion_iva();
if( $regiva0->get_fecha_inside($this->fecha) )
{
$this->new_error_msg('La factura se encuentra dentro de una regularización de '
.FS_IVA.'. No se puede modificar la fecha.');
}
else if( $regiva0->get_fecha_inside($fecha) )
{
$this->new_error_msg('No se puede asignar la fecha '.$fecha.' porque ya hay'
. ' una regularización de '.FS_IVA.' para ese periodo.');
}
else
{
$cambio = FALSE;
$this->fecha = $fecha;
$this->hora = $hora;
/// ¿El ejercicio es distinto?
if($this->codejercicio != $eje2->codejercicio)
{
$this->codejercicio = $eje2->codejercicio;
$this->new_codigo();
}
}
}
else
{
$this->new_error_msg('El ejercicio '.$eje2->nombre.' está cerrado. No se puede modificar la fecha.');
}
}
}
else
{
$this->new_error_msg('El ejercicio '.$ejercicio->nombre.' está cerrado. No se puede modificar la fecha.');
}
}
else
{
$this->new_error_msg('Ejercicio no encontrado.');
}
}
else if($hora != $this->hora) /// factura existente y cambiamos hora
{
$this->hora = $hora;
}
return $cambio;
}
public function url()
{
if( is_null($this->idfactura) )
{
return 'index.php?page=compras_facturas';
}
else
return 'index.php?page=compras_factura&id='.$this->idfactura;
}
public function asiento_url()
{
if( is_null($this->idasiento) )
{
return 'index.php?page=contabilidad_asientos';
}
else
return 'index.php?page=contabilidad_asiento&id='.$this->idasiento;
}
public function asiento_pago_url()
{
if( is_null($this->idasientop) )
{
return 'index.php?page=contabilidad_asientos';
}
else
return 'index.php?page=contabilidad_asiento&id='.$this->idasientop;
}
public function agente_url()
{
if( is_null($this->codagente) )
{
return "index.php?page=admin_agentes";
}
else
return "index.php?page=admin_agente&cod=".$this->codagente;
}
public function proveedor_url()
{
if( is_null($this->codproveedor) )
{
return "index.php?page=compras_proveedores";
}
else
return "index.php?page=compras_proveedor&cod=".$this->codproveedor;
}
/**
* Devuelve las líneas de la factura.
* @return line_factura_proveedor
*/
public function get_lineas()
{
$linea = new \linea_factura_proveedor();
return $linea->all_from_factura($this->idfactura);
}
/**
* Devuelve las líneas de IVA de la factura.
* Si no hay, las crea.
* @return \linea_iva_factura_proveedor
*/
public function get_lineas_iva()
{
$linea_iva = new \linea_iva_factura_proveedor();
$lineasi = $linea_iva->all_from_factura($this->idfactura);
/// si no hay lineas de IVA las generamos
if( !$lineasi )
{
$lineas = $this->get_lineas();
if($lineas)
{
foreach($lineas as $l)
{
$i = 0;
$encontrada = FALSE;
while($i < count($lineasi))
{
if($l->iva == $lineasi[$i]->iva AND $l->recargo == $lineasi[$i]->recargo)
{
$encontrada = TRUE;
$lineasi[$i]->neto += $l->pvptotal;
$lineasi[$i]->totaliva += ($l->pvptotal*$l->iva)/100;
$lineasi[$i]->totalrecargo += ($l->pvptotal*$l->recargo)/100;
}
$i++;
}
if( !$encontrada )
{
$lineasi[$i] = new \linea_iva_factura_proveedor();
$lineasi[$i]->idfactura = $this->idfactura;
$lineasi[$i]->codimpuesto = $l->codimpuesto;
$lineasi[$i]->iva = $l->iva;
$lineasi[$i]->recargo = $l->recargo;
$lineasi[$i]->neto = $l->pvptotal;
$lineasi[$i]->totaliva = ($l->pvptotal*$l->iva)/100;
$lineasi[$i]->totalrecargo = ($l->pvptotal*$l->recargo)/100;
}
}
/// redondeamos y guardamos
if( count($lineasi) == 1 )
{
$lineasi[0]->neto = round($lineasi[0]->neto, FS_NF0);
$lineasi[0]->totaliva = round($lineasi[0]->totaliva, FS_NF0);
$lineasi[0]->totalrecargo = round($lineasi[0]->totalrecargo, FS_NF0);
$lineasi[0]->totallinea = $lineasi[0]->neto + $lineasi[0]->totaliva + $lineasi[0]->totalrecargo;
$lineasi[0]->save();
}
else
{
/*
* Como el neto y el iva se redondean en la factura, al dividirlo
* en líneas de iva podemos encontrarnos con un descuadre que
* hay que calcular y solucionar.
*/
$t_neto = 0;
$t_iva = 0;
foreach($lineasi as $li)
{
$li->neto = bround($li->neto, FS_NF0);
$li->totaliva = bround($li->totaliva, FS_NF0);
$li->totallinea = $li->neto + $li->totaliva + $li->totalrecargo;
$t_neto += $li->neto;
$t_iva += $li->totaliva;
}
if( !$this->floatcmp($this->neto, $t_neto) )
{
/*
* Sumamos o restamos un céntimo a los netos más altos
* hasta que desaparezca el descuadre
*/
$diferencia = round( ($this->neto-$t_neto) * 100 );
usort($lineasi, function($a, $b) {
if($a->totallinea == $b->totallinea)
{
return 0;
}
else if($this->total < 0)
{
return ($a->totallinea < $b->totallinea) ? -1 : 1;
}
else
{
return ($a->totallinea < $b->totallinea) ? 1 : -1;
}
});
foreach($lineasi as $i => $value)
{
if($diferencia > 0)
{
$lineasi[$i]->neto += .01;
$diferencia--;
}
else if($diferencia < 0)
{
$lineasi[$i]->neto -= .01;
$diferencia++;
}
else
break;
}
}
if( !$this->floatcmp($this->totaliva, $t_iva) )
{
/*
* Sumamos o restamos un céntimo a los importes más altos
* hasta que desaparezca el descuadre
*/
$diferencia = round( ($this->totaliva-$t_iva) * 100 );
usort($lineasi, function($a, $b) {
if($a->totaliva == $b->totaliva)
{
return 0;
}
else if($this->total < 0)
{
return ($a->totaliva < $b->totaliva) ? -1 : 1;
}
else
{
return ($a->totaliva < $b->totaliva) ? 1 : -1;
}
});
foreach($lineasi as $i => $value)
{
if($diferencia > 0)
{
$lineasi[$i]->totaliva += .01;
$diferencia--;
}
else if($diferencia < 0)
{
$lineasi[$i]->totaliva -= .01;
$diferencia++;
}
else
break;
}
}
foreach($lineasi as $i => $value)
{
$lineasi[$i]->totallinea = $value->neto + $value->totaliva + $value->totalrecargo;
$lineasi[$i]->save();
}
}
}
}
return $lineasi;
}
public function get_asiento()
{
$asiento = new \asiento();
return $asiento->get($this->idasiento);
}
public function get_asiento_pago()
{
$asiento = new \asiento();
return $asiento->get($this->idasientop);
}
/**
* Devuelve un array con todas las facturas rectificativas de esta factura.
* @return \factura_proveedor
*/
public function get_rectificativas()
{
$devoluciones = array();
$data = $this->db->select("SELECT * FROM ".$this->table_name." WHERE idfacturarect = ".$this->var2str($this->idfactura).";");
if($data)
{
foreach($data as $d)
{
$devoluciones[] = new \factura_proveedor($d);
}
}
return $devoluciones;
}
/**
* Devuelve la factura de compra con el id proporcionado.
* @param type $id
* @return boolean|\factura_proveedor
*/
public function get($id)
{
$fact = $this->db->select("SELECT * FROM ".$this->table_name." WHERE idfactura = ".$this->var2str($id).";");
if($fact)
{
return new \factura_proveedor($fact[0]);
}
else
return FALSE;
}
public function get_by_codigo($cod)
{
$fact = $this->db->select("SELECT * FROM ".$this->table_name." WHERE codigo = ".$this->var2str($cod).";");
if($fact)
{
return new \factura_proveedor($fact[0]);
}
else
return FALSE;
}
public function exists()
{
if( is_null($this->idfactura) )
{
return FALSE;
}
else
return $this->db->select("SELECT * FROM ".$this->table_name." WHERE idfactura = ".$this->var2str($this->idfactura).";");
}
/**
* Genera el número y código de la factura.
*/
public function new_codigo()
{
/// buscamos un hueco o el siguiente número disponible
$encontrado = FALSE;
$num = 1;
$sql = "SELECT ".$this->db->sql_to_int('numero')." as numero,fecha,hora FROM ".$this->table_name
." WHERE codejercicio = ".$this->var2str($this->codejercicio)
." AND codserie = ".$this->var2str($this->codserie)
." ORDER BY numero ASC;";
$data = $this->db->select($sql);
if($data)
{
foreach($data as $d)
{
if( intval($d['numero']) < $num )
{
/**
* El número de la factura es menor que el inicial.
* El usuario ha cambiado el número inicial después de hacer
* facturas.
*/
}
else if( intval($d['numero']) == $num )
{
/// el número es correcto, avanzamos
$num++;
}
else
{
/// Hemos encontrado un hueco
$encontrado = TRUE;
break;
}
}
}
if($encontrado)
{
$this->numero = $num;
}
else
{
$this->numero = $num;
/// nos guardamos la secuencia para abanq/eneboo
$sec = new \secuencia();
$sec = $sec->get_by_params2($this->codejercicio, $this->codserie, 'nfacturaprov');
if($sec)
{
if($sec->valorout <= $this->numero)
{
$sec->valorout = 1 + $this->numero;
$sec->save();
}
}
}
if(FS_NEW_CODIGO == 'eneboo')
{
$this->codigo = $this->codejercicio.sprintf('%02s', $this->codserie).sprintf('%06s', $this->numero);
}
else
{
$this->codigo = 'FAC'.$this->codejercicio.$this->codserie.$this->numero.'C';
}
}
/**
* Comprueba los datos de la factura, devuelve TRUE si está todo correcto
* @return boolean
*/
public function test()
{
$this->nombre = $this->no_html($this->nombre);
if($this->nombre == '')
{
$this->nombre = '-';
}
$this->numproveedor = $this->no_html($this->numproveedor);
$this->observaciones = $this->no_html($this->observaciones);
/**
* Usamos el euro como divisa puente a la hora de sumar, comparar
* o convertir cantidades en varias divisas. Por este motivo necesimos
* muchos decimales.
*/
$this->totaleuros = round($this->total / $this->tasaconv, 5);
if( $this->floatcmp($this->total, $this->neto+$this->totaliva-$this->totalirpf+$this->totalrecargo, FS_NF0, TRUE) )
{
return TRUE;
}
else
{
$this->new_error_msg("Error grave: El total está mal calculado. ¡Informa del error!");
return FALSE;
}
}
public function full_test($duplicados = TRUE)
{
$status = TRUE;
/// comprobamos la fecha de la factura
$ejercicio = new \ejercicio();
$eje0 = $ejercicio->get($this->codejercicio);
if($eje0)
{
if( strtotime($this->fecha) < strtotime($eje0->fechainicio) OR strtotime($this->fecha) > strtotime($eje0->fechafin) )
{
$status = FALSE;
$this->new_error_msg("La fecha de esta factura está fuera del rango del"
. " <a target='_blank' href='".$eje0->url()."'>ejercicio</a>.");
}
}
/// comprobamos las líneas
$neto = 0;
$iva = 0;
$irpf = 0;
$recargo = 0;
foreach($this->get_lineas() as $l)
{
if( !$l->test() )
{
$status = FALSE;
}
$neto += $l->pvptotal;
$iva += $l->pvptotal * $l->iva / 100;
$irpf += $l->pvptotal * $l->irpf / 100;
$recargo += $l->pvptotal * $l->recargo / 100;
}
$neto = round($neto, FS_NF0);
$iva = round($iva, FS_NF0);
$irpf = round($irpf, FS_NF0);
$recargo = round($recargo, FS_NF0);
$total = $neto + $iva - $irpf + $recargo;
if( !$this->floatcmp($this->neto, $neto, FS_NF0, TRUE) )
{
$this->new_error_msg("Valor neto de la factura ".$this->codigo." incorrecto. Valor correcto: ".$neto);
$status = FALSE;
}
else if( !$this->floatcmp($this->totaliva, $iva, FS_NF0, TRUE) )
{
$this->new_error_msg("Valor totaliva de la factura ".$this->codigo." incorrecto. Valor correcto: ".$iva);
$status = FALSE;
}
else if( !$this->floatcmp($this->totalirpf, $irpf, FS_NF0, TRUE) )
{
$this->new_error_msg("Valor totalirpf de la factura ".$this->codigo." incorrecto. Valor correcto: ".$irpf);
$status = FALSE;
}
else if( !$this->floatcmp($this->totalrecargo, $recargo, FS_NF0, TRUE) )
{
$this->new_error_msg("Valor totalrecargo de la factura ".$this->codigo." incorrecto. Valor correcto: ".$recargo);
$status = FALSE;
}
else if( !$this->floatcmp($this->total, $total, FS_NF0, TRUE) )
{
$this->new_error_msg("Valor total de la factura ".$this->codigo." incorrecto. Valor correcto: ".$total);
$status = FALSE;
}
/// comprobamos las líneas de IVA
$this->get_lineas_iva();
$linea_iva = new \linea_iva_factura_proveedor();
if( !$linea_iva->factura_test($this->idfactura, $neto, $iva, $recargo) )
{
$status = FALSE;
}
/// comprobamos el asiento
if( isset($this->idasiento) )
{
$asiento = $this->get_asiento();
if($asiento)
{
if($asiento->tipodocumento != 'Factura de proveedor' OR $asiento->documento != $this->codigo)
{
$this->new_error_msg("Esta factura apunta a un <a href='".$this->asiento_url()."'>asiento incorrecto</a>.");
$status = FALSE;
}
else if($this->coddivisa == $this->default_items->coddivisa() AND (abs($asiento->importe) - abs($this->total+$this->totalirpf) >= .02) )
{
$this->new_error_msg("El importe del asiento es distinto al de la factura.");
$status = FALSE;
}
else
{
$asientop = $this->get_asiento_pago();
if($asientop)
{
if($this->totalirpf != 0)
{
/// excluimos la comprobación si la factura tiene IRPF
}
else if( !$this->floatcmp($asiento->importe, $asientop->importe) )
{
$this->new_error_msg('No coinciden los importes de los asientos.');
$status = FALSE;
}
}
}
}
else
{
$this->new_error_msg("Asiento no encontrado.");
$status = FALSE;
}
}
if($status AND $duplicados)
{
/// comprobamos si es un duplicado
$facturas = $this->db->select("SELECT * FROM ".$this->table_name." WHERE fecha = ".$this->var2str($this->fecha)
." AND codproveedor = ".$this->var2str($this->codproveedor)
." AND total = ".$this->var2str($this->total)
." AND codagente = ".$this->var2str($this->codagente)
." AND numproveedor = ".$this->var2str($this->numproveedor)
." AND observaciones = ".$this->var2str($this->observaciones)
." AND idfactura != ".$this->var2str($this->idfactura).";");
if($facturas)
{
foreach($facturas as $fac)
{
/// comprobamos las líneas
$aux = $this->db->select("SELECT referencia FROM lineasfacturasprov WHERE
idfactura = ".$this->var2str($this->idfactura)."
AND referencia NOT IN (SELECT referencia FROM lineasfacturasprov
WHERE idfactura = ".$this->var2str($fac['idfactura']).");");
if( !$aux )
{
$this->new_error_msg("Esta factura es un posible duplicado de
<a href='index.php?page=compras_factura&id=".$fac['idfactura']."'>esta otra</a>.
Si no lo es, para evitar este mensaje, simplemente modifica las observaciones.");
$status = FALSE;
}
}
}
}
return $status;
}
public function save()
{
if( $this->test() )
{
if( $this->exists() )
{
$sql = "UPDATE ".$this->table_name." SET codigo = ".$this->var2str($this->codigo)
.", total = ".$this->var2str($this->total)
.", neto = ".$this->var2str($this->neto)
.", cifnif = ".$this->var2str($this->cifnif)
.", pagada = ".$this->var2str($this->pagada)
.", anulada = ".$this->var2str($this->anulada)
.", observaciones = ".$this->var2str($this->observaciones)
.", codagente = ".$this->var2str($this->codagente)
.", codalmacen = ".$this->var2str($this->codalmacen)
.", irpf = ".$this->var2str($this->irpf)
.", totaleuros = ".$this->var2str($this->totaleuros)
.", nombre = ".$this->var2str($this->nombre)
.", codpago = ".$this->var2str($this->codpago)
.", codproveedor = ".$this->var2str($this->codproveedor)
.", idfacturarect = ".$this->var2str($this->idfacturarect)
.", numproveedor = ".$this->var2str($this->numproveedor)
.", codigorect = ".$this->var2str($this->codigorect)
.", codserie = ".$this->var2str($this->codserie)
.", idasiento = ".$this->var2str($this->idasiento)
.", idasientop = ".$this->var2str($this->idasientop)
.", totalirpf = ".$this->var2str($this->totalirpf)
.", totaliva = ".$this->var2str($this->totaliva)
.", coddivisa = ".$this->var2str($this->coddivisa)
.", numero = ".$this->var2str($this->numero)
.", codejercicio = ".$this->var2str($this->codejercicio)
.", tasaconv = ".$this->var2str($this->tasaconv)
.", totalrecargo = ".$this->var2str($this->totalrecargo)
.", fecha = ".$this->var2str($this->fecha)
.", hora = ".$this->var2str($this->hora)
.", numdocs = ".$this->var2str($this->numdocs)
." WHERE idfactura = ".$this->var2str($this->idfactura).";";
return $this->db->exec($sql);
}
else
{
$this->new_codigo();
$sql = "INSERT INTO ".$this->table_name." (codigo,total,neto,cifnif,pagada,anulada,observaciones,
codagente,codalmacen,irpf,totaleuros,nombre,codpago,codproveedor,idfacturarect,numproveedor,
codigorect,codserie,idasiento,idasientop,totalirpf,totaliva,coddivisa,numero,codejercicio,tasaconv,
totalrecargo,fecha,hora,numdocs) VALUES (".$this->var2str($this->codigo)
.",".$this->var2str($this->total)
.",".$this->var2str($this->neto)
.",".$this->var2str($this->cifnif)
.",".$this->var2str($this->pagada)
.",".$this->var2str($this->anulada)
.",".$this->var2str($this->observaciones)
.",".$this->var2str($this->codagente)
.",".$this->var2str($this->codalmacen)
.",".$this->var2str($this->irpf)
.",".$this->var2str($this->totaleuros)
.",".$this->var2str($this->nombre)
.",".$this->var2str($this->codpago)
.",".$this->var2str($this->codproveedor)
.",".$this->var2str($this->idfacturarect)
.",".$this->var2str($this->numproveedor)
.",".$this->var2str($this->codigorect)
.",".$this->var2str($this->codserie)
.",".$this->var2str($this->idasiento)
.",".$this->var2str($this->idasientop)
.",".$this->var2str($this->totalirpf)
.",".$this->var2str($this->totaliva)
.",".$this->var2str($this->coddivisa)
.",".$this->var2str($this->numero)
.",".$this->var2str($this->codejercicio)
.",".$this->var2str($this->tasaconv)
.",".$this->var2str($this->totalrecargo)
.",".$this->var2str($this->fecha)
.",".$this->var2str($this->hora)
.",".$this->var2str($this->numdocs).");";
if( $this->db->exec($sql) )
{
$this->idfactura = $this->db->lastval();
return TRUE;
}
else
return FALSE;
}
}
else
return FALSE;
}
/**
* Elimina la factura de la base de datos.
* @return boolean
*/
public function delete()
{
$bloquear = FALSE;
$eje0 = new \ejercicio();
$ejercicio = $eje0->get($this->codejercicio);
if($ejercicio)
{
if( $ejercicio->abierto() )
{
$reg0 = new \regularizacion_iva();
if( $reg0->get_fecha_inside($this->fecha) )
{
$this->new_error_msg('La factura se encuentra dentro de una regularización de '
.FS_IVA.'. No se puede eliminar.');
$bloquear = TRUE;
}
else
{
foreach($this->get_rectificativas() as $rect)
{
$this->new_error_msg('La factura ya tiene una rectificativa. No se puede eliminar.');
$bloquear = TRUE;
break;
}
}
}
else
{
$this->new_error_msg('El ejercicio '.$ejercicio->nombre.' está cerrado.');
$bloquear = TRUE;
}
}
/// desvincular albaranes asociados y eliminar factura
$sql = "UPDATE albaranesprov SET idfactura = NULL, ptefactura = TRUE WHERE idfactura = ".$this->var2str($this->idfactura).";"
. "DELETE FROM ".$this->table_name." WHERE idfactura = ".$this->var2str($this->idfactura).";";
if($bloquear)
{
return FALSE;
}
else if( $this->db->exec($sql) )
{
if($this->idasiento)
{
/**
* Delegamos la eliminación del asiento en la clase correspondiente.
*/
$asiento = new \asiento();
$asi0 = $asiento->get($this->idasiento);
if($asi0)
{
$asi0->delete();
}
$asi1 = $asiento->get($this->idasientop);
if($asi1)
{
$asi1->delete();
}
}
$this->new_message(ucfirst(FS_FACTURA)." de compra ".$this->codigo." eliminada correctamente.");
return TRUE;
}
else
return FALSE;
}
/**
* Devuelve un array con las últimas facturas
* @param type $offset
* @param type $limit
* @param type $order
* @return \factura_proveedor
*/
public function all($offset = 0, $limit = FS_ITEM_LIMIT, $order = 'fecha DESC, codigo DESC')
{
$faclist = array();
$sql = "SELECT * FROM ".$this->table_name." ORDER BY ".$order;
$data = $this->db->select_limit($sql, $limit, $offset);
if($data)
{
foreach($data as $f)
{
$faclist[] = new \factura_proveedor($f);
}
}
return $faclist;
}
/**
* Devuelve un array con las facturas sin pagar.
* @param type $offset
* @param type $limit
* @param type $order
* @return \factura_proveedor
*/
public function all_sin_pagar($offset = 0, $limit = FS_ITEM_LIMIT, $order = 'fecha ASC, codigo ASC')
{
$faclist = array();
$sql = "SELECT * FROM ".$this->table_name." WHERE pagada = false ORDER BY ".$order;
$data = $this->db->select_limit($sql, $limit, $offset);
if($data)
{
foreach($data as $f)
{
$faclist[] = new \factura_proveedor($f);
}
}
return $faclist;
}
/**
* Devuelve un array con las facturas del agente/empleado
* @param type $codagente
* @param type $offset
* @return \factura_proveedor
*/
public function all_from_agente($codagente, $offset = 0)
{
$faclist = array();
$sql = "SELECT * FROM ".$this->table_name.
" WHERE codagente = ".$this->var2str($codagente).
" ORDER BY fecha DESC, codigo DESC";
$data = $this->db->select_limit($sql, FS_ITEM_LIMIT, $offset);
if($data)
{
foreach($data as $f)
{
$faclist[] = new \factura_proveedor($f);
}
}
return $faclist;
}
/**
* Devuelve un array con las facturas del proveedor
* @param type $codproveedor
* @param type $offset
* @return \factura_proveedor
*/
public function all_from_proveedor($codproveedor, $offset = 0)
{
$faclist = array();
$sql = "SELECT * FROM ".$this->table_name.
" WHERE codproveedor = ".$this->var2str($codproveedor).
" ORDER BY fecha DESC, codigo DESC";
$data = $this->db->select_limit($sql, FS_ITEM_LIMIT, $offset);
if($data)
{
foreach($data as $f)
{
$faclist[] = new \factura_proveedor($f);
}
}
return $faclist;
}
/**
* Devuelve un array con las facturas comprendidas entre $desde y $hasta
* @param type $desde
* @param type $hasta
* @param type $codserie
* @param type $codagente
* @param type $codproveedor
* @param type $estado
* @return \factura_proveedor
*/
public function all_desde($desde, $hasta, $codserie = FALSE, $codagente = FALSE, $codproveedor = FALSE, $estado = FALSE, $forma_pago = FALSE)
{
$faclist = array();
$sql = "SELECT * FROM ".$this->table_name." WHERE fecha >= ".$this->var2str($desde)." AND fecha <= ".$this->var2str($hasta);
if($codserie)
{
$sql .= " AND codserie = ".$this->var2str($codserie);
}
if($codagente)
{
$sql .= " AND codagente = ".$this->var2str($codagente);
}
if($codproveedor)
{
$sql .= " AND codproveedor = ".$this->var2str($codproveedor);
}
if($estado)
{
if($estado == 'pagada')
{
$sql .= " AND pagada = true";
}
else
{
$sql .= " AND pagada = false";
}
}
if($forma_pago)
{
$sql .= " AND codpago = ".$this->var2str($forma_pago);
}
$sql .= " ORDER BY fecha ASC, codigo ASC;";
$data = $this->db->select($sql);
if($data)
{
foreach($data as $f)
{
$faclist[] = new \factura_proveedor($f);
}
}
return $faclist;
}
/**
* Devuelve un array con las facturas coincidentes con $query
* @param type $query
* @param type $offset
* @return \factura_proveedor
*/
public function search($query, $offset = 0)
{
$faclist = array();
$query = mb_strtolower( $this->no_html($query), 'UTF8' );
$consulta = "SELECT * FROM ".$this->table_name." WHERE ";
if( is_numeric($query) )
{
$consulta .= "codigo LIKE '%".$query."%' OR numproveedor LIKE '%".$query
."%' OR observaciones LIKE '%".$query."%'";
}
else
{
$consulta .= "lower(codigo) LIKE '%".$query."%' OR lower(numproveedor) LIKE '%".$query."%' "
. "OR lower(observaciones) LIKE '%".str_replace(' ', '%', $query)."%'";
}
$consulta .= " ORDER BY fecha DESC, codigo DESC";
$data = $this->db->select_limit($consulta, FS_ITEM_LIMIT, $offset);
if($data)
{
foreach($data as $f)
{
$faclist[] = new \factura_proveedor($f);
}
}
return $faclist;
}
public function cron_job()
{
}
}
|
KalimochoAz/facturacion_base
|
model/core/factura_proveedor.php
|
PHP
|
lgpl-3.0
| 40,486 |
//QPen QPen.new();
KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
KQPen *ret_v = new KQPen();
knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL);
ret_v->setSelf(rptr);
RETURN_(rptr);
}
/*
//QPen QPen.new(int style);
KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
Qt::PenStyle style = Int_to(Qt::PenStyle, sfp[1]);
KQPen *ret_v = new KQPen(style);
knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL);
ret_v->setSelf(rptr);
RETURN_(rptr);
}
*/
/*
//QPen QPen.new(QColor color);
KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
const QColor color = *RawPtr_to(const QColor *, sfp[1]);
KQPen *ret_v = new KQPen(color);
knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL);
ret_v->setSelf(rptr);
RETURN_(rptr);
}
*/
/*
//QPen QPen.new(QBrush brush, float width, int style, int cap, int join);
KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
const QBrush brush = *RawPtr_to(const QBrush *, sfp[1]);
qreal width = Float_to(qreal, sfp[2]);
Qt::PenStyle style = Int_to(Qt::PenStyle, sfp[3]);
Qt::PenCapStyle cap = Int_to(Qt::PenCapStyle, sfp[4]);
Qt::PenJoinStyle join = Int_to(Qt::PenJoinStyle, sfp[5]);
KQPen *ret_v = new KQPen(brush, width, style, cap, join);
knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL);
ret_v->setSelf(rptr);
RETURN_(rptr);
}
*/
/*
//QPen QPen.new(QPen pen);
KMETHOD QPen_new(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
const QPen pen = *RawPtr_to(const QPen *, sfp[1]);
KQPen *ret_v = new KQPen(pen);
knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL);
ret_v->setSelf(rptr);
RETURN_(rptr);
}
*/
//QBrush QPen.getBrush();
KMETHOD QPen_getBrush(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
QBrush ret_v = qp->brush();
QBrush *ret_v_ = new QBrush(ret_v);
knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v_, NULL);
RETURN_(rptr);
} else {
RETURN_(KNH_NULL);
}
}
//int QPen.getCapStyle();
KMETHOD QPen_getCapStyle(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
Qt::PenCapStyle ret_v = qp->capStyle();
RETURNi_(ret_v);
} else {
RETURNi_(0);
}
}
//QColor QPen.getColor();
KMETHOD QPen_getColor(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
QColor ret_v = qp->color();
QColor *ret_v_ = new QColor(ret_v);
knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v_, NULL);
RETURN_(rptr);
} else {
RETURN_(KNH_NULL);
}
}
//float QPen.dashOffset();
KMETHOD QPen_dashOffset(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
qreal ret_v = qp->dashOffset();
RETURNf_(ret_v);
} else {
RETURNf_(0.0f);
}
}
//boolean QPen.isCosmetic();
KMETHOD QPen_isCosmetic(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
bool ret_v = qp->isCosmetic();
RETURNb_(ret_v);
} else {
RETURNb_(false);
}
}
//boolean QPen.isSolid();
KMETHOD QPen_isSolid(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
bool ret_v = qp->isSolid();
RETURNb_(ret_v);
} else {
RETURNb_(false);
}
}
//int QPen.getJoinStyle();
KMETHOD QPen_getJoinStyle(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
Qt::PenJoinStyle ret_v = qp->joinStyle();
RETURNi_(ret_v);
} else {
RETURNi_(0);
}
}
//float QPen.getMiterLimit();
KMETHOD QPen_getMiterLimit(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
qreal ret_v = qp->miterLimit();
RETURNf_(ret_v);
} else {
RETURNf_(0.0f);
}
}
//void QPen.setBrush(QBrush brush);
KMETHOD QPen_setBrush(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
const QBrush brush = *RawPtr_to(const QBrush *, sfp[1]);
qp->setBrush(brush);
}
RETURNvoid_();
}
//void QPen.setCapStyle(int style);
KMETHOD QPen_setCapStyle(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
Qt::PenCapStyle style = Int_to(Qt::PenCapStyle, sfp[1]);
qp->setCapStyle(style);
}
RETURNvoid_();
}
//void QPen.setColor(QColor color);
KMETHOD QPen_setColor(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
const QColor color = *RawPtr_to(const QColor *, sfp[1]);
qp->setColor(color);
}
RETURNvoid_();
}
//void QPen.setCosmetic(boolean cosmetic);
KMETHOD QPen_setCosmetic(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
bool cosmetic = Boolean_to(bool, sfp[1]);
qp->setCosmetic(cosmetic);
}
RETURNvoid_();
}
//void QPen.setDashOffset(float offset);
KMETHOD QPen_setDashOffset(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
qreal offset = Float_to(qreal, sfp[1]);
qp->setDashOffset(offset);
}
RETURNvoid_();
}
//void QPen.setJoinStyle(int style);
KMETHOD QPen_setJoinStyle(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
Qt::PenJoinStyle style = Int_to(Qt::PenJoinStyle, sfp[1]);
qp->setJoinStyle(style);
}
RETURNvoid_();
}
//void QPen.setMiterLimit(float limit);
KMETHOD QPen_setMiterLimit(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
qreal limit = Float_to(qreal, sfp[1]);
qp->setMiterLimit(limit);
}
RETURNvoid_();
}
//void QPen.setStyle(int style);
KMETHOD QPen_setStyle(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
Qt::PenStyle style = Int_to(Qt::PenStyle, sfp[1]);
qp->setStyle(style);
}
RETURNvoid_();
}
//void QPen.setWidth(int width);
KMETHOD QPen_setWidth(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
int width = Int_to(int, sfp[1]);
qp->setWidth(width);
}
RETURNvoid_();
}
//void QPen.setWidthF(float width);
KMETHOD QPen_setWidthF(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
qreal width = Float_to(qreal, sfp[1]);
qp->setWidthF(width);
}
RETURNvoid_();
}
//int QPen.getStyle();
KMETHOD QPen_getStyle(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
Qt::PenStyle ret_v = qp->style();
RETURNi_(ret_v);
} else {
RETURNi_(0);
}
}
//int QPen.getWidth();
KMETHOD QPen_getWidth(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
int ret_v = qp->width();
RETURNi_(ret_v);
} else {
RETURNi_(0);
}
}
//float QPen.getWidthF();
KMETHOD QPen_getWidthF(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen * qp = RawPtr_to(QPen *, sfp[0]);
if (qp) {
qreal ret_v = qp->widthF();
RETURNf_(ret_v);
} else {
RETURNf_(0.0f);
}
}
//Array<String> QPen.parents();
KMETHOD QPen_parents(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
QPen *qp = RawPtr_to(QPen*, sfp[0]);
if (qp != NULL) {
int size = 10;
knh_Array_t *a = new_Array0(ctx, size);
const knh_ClassTBL_t *ct = sfp[0].p->h.cTBL;
while(ct->supcid != CLASS_Object) {
ct = ct->supTBL;
knh_Array_add(ctx, a, (knh_Object_t *)ct->lname);
}
RETURN_(a);
} else {
RETURN_(KNH_NULL);
}
}
DummyQPen::DummyQPen()
{
CTX lctx = knh_getCurrentContext();
(void)lctx;
self = NULL;
event_map = new map<string, knh_Func_t *>();
slot_map = new map<string, knh_Func_t *>();
}
DummyQPen::~DummyQPen()
{
delete event_map;
delete slot_map;
event_map = NULL;
slot_map = NULL;
}
void DummyQPen::setSelf(knh_RawPtr_t *ptr)
{
DummyQPen::self = ptr;
}
bool DummyQPen::eventDispatcher(QEvent *event)
{
bool ret = true;
switch (event->type()) {
default:
ret = false;
break;
}
return ret;
}
bool DummyQPen::addEvent(knh_Func_t *callback_func, string str)
{
std::map<string, knh_Func_t*>::iterator itr;// = DummyQPen::event_map->bigin();
if ((itr = DummyQPen::event_map->find(str)) == DummyQPen::event_map->end()) {
bool ret = false;
return ret;
} else {
KNH_INITv((*event_map)[str], callback_func);
return true;
}
}
bool DummyQPen::signalConnect(knh_Func_t *callback_func, string str)
{
std::map<string, knh_Func_t*>::iterator itr;// = DummyQPen::slot_map->bigin();
if ((itr = DummyQPen::slot_map->find(str)) == DummyQPen::slot_map->end()) {
bool ret = false;
return ret;
} else {
KNH_INITv((*slot_map)[str], callback_func);
return true;
}
}
knh_Object_t** DummyQPen::reftrace(CTX ctx, knh_RawPtr_t *p FTRARG)
{
(void)ctx; (void)p; (void)tail_;
// fprintf(stderr, "DummyQPen::reftrace p->rawptr=[%p]\n", p->rawptr);
return tail_;
}
void DummyQPen::connection(QObject *o)
{
QPen *p = dynamic_cast<QPen*>(o);
if (p != NULL) {
}
}
KQPen::KQPen() : QPen()
{
magic_num = G_MAGIC_NUM;
self = NULL;
dummy = new DummyQPen();
}
KQPen::~KQPen()
{
delete dummy;
dummy = NULL;
}
KMETHOD QPen_addEvent(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
KQPen *qp = RawPtr_to(KQPen *, sfp[0]);
const char *event_name = String_to(const char *, sfp[1]);
knh_Func_t *callback_func = sfp[2].fo;
if (qp != NULL) {
// if (qp->event_map->find(event_name) == qp->event_map->end()) {
// fprintf(stderr, "WARNING:[QPen]unknown event name [%s]\n", event_name);
// return;
// }
string str = string(event_name);
// KNH_INITv((*(qp->event_map))[event_name], callback_func);
if (!qp->dummy->addEvent(callback_func, str)) {
fprintf(stderr, "WARNING:[QPen]unknown event name [%s]\n", event_name);
return;
}
}
RETURNvoid_();
}
KMETHOD QPen_signalConnect(CTX ctx, knh_sfp_t *sfp _RIX)
{
(void)ctx;
KQPen *qp = RawPtr_to(KQPen *, sfp[0]);
const char *signal_name = String_to(const char *, sfp[1]);
knh_Func_t *callback_func = sfp[2].fo;
if (qp != NULL) {
// if (qp->slot_map->find(signal_name) == qp->slot_map->end()) {
// fprintf(stderr, "WARNING:[QPen]unknown signal name [%s]\n", signal_name);
// return;
// }
string str = string(signal_name);
// KNH_INITv((*(qp->slot_map))[signal_name], callback_func);
if (!qp->dummy->signalConnect(callback_func, str)) {
fprintf(stderr, "WARNING:[QPen]unknown signal name [%s]\n", signal_name);
return;
}
}
RETURNvoid_();
}
static void QPen_free(CTX ctx, knh_RawPtr_t *p)
{
(void)ctx;
if (!exec_flag) return;
if (p->rawptr != NULL) {
KQPen *qp = (KQPen *)p->rawptr;
if (qp->magic_num == G_MAGIC_NUM) {
delete qp;
p->rawptr = NULL;
} else {
delete (QPen*)qp;
p->rawptr = NULL;
}
}
}
static void QPen_reftrace(CTX ctx, knh_RawPtr_t *p FTRARG)
{
if (p->rawptr != NULL) {
// KQPen *qp = (KQPen *)p->rawptr;
KQPen *qp = static_cast<KQPen*>(p->rawptr);
qp->dummy->reftrace(ctx, p, tail_);
}
}
static int QPen_compareTo(knh_RawPtr_t *p1, knh_RawPtr_t *p2)
{
return (*static_cast<QPen*>(p1->rawptr) == *static_cast<QPen*>(p2->rawptr) ? 0 : 1);
}
void KQPen::setSelf(knh_RawPtr_t *ptr)
{
self = ptr;
dummy->setSelf(ptr);
}
DEFAPI(void) defQPen(CTX ctx, knh_class_t cid, knh_ClassDef_t *cdef)
{
(void)ctx; (void) cid;
cdef->name = "QPen";
cdef->free = QPen_free;
cdef->reftrace = QPen_reftrace;
cdef->compareTo = QPen_compareTo;
}
|
imasahiro/konohascript
|
package/konoha.qt4/src/KQPen.cpp
|
C++
|
lgpl-3.0
| 11,262 |
namespace TireDataAnalyzer.UserControls.FittingWizard
{
partial class FittingWizard
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// FittingWizard
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1023, 684);
this.Name = "FittingWizard";
this.Text = "FittingWizard";
this.Load += new System.EventHandler(this.FittingWizard_Load);
this.ResumeLayout(false);
}
#endregion
}
}
|
GRAM-shuzo/TireDataAnalyzer
|
TireDataAnalyzer/TireDataAnalyzer/UserControls/FittingWizard/FittingWizard.Designer.cs
|
C#
|
lgpl-3.0
| 1,503 |
/*
* HA-JDBC: High-Availability JDBC
* Copyright (C) 2013 Paul Ferraro
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.hajdbc.sql;
import java.sql.Ref;
import java.sql.SQLException;
import java.util.Map;
import net.sf.hajdbc.Database;
import net.sf.hajdbc.invocation.Invoker;
/**
*
* @author Paul Ferraro
*/
public class RefProxyFactoryFactory<Z, D extends Database<Z>, P> implements ProxyFactoryFactory<Z, D, P, SQLException, Ref, SQLException>
{
private final boolean locatorsUpdateCopy;
public RefProxyFactoryFactory(boolean locatorsUpdateCopy)
{
this.locatorsUpdateCopy = locatorsUpdateCopy;
}
@Override
public ProxyFactory<Z, D, Ref, SQLException> createProxyFactory(P parentProxy, ProxyFactory<Z, D, P, SQLException> parent, Invoker<Z, D, P, Ref, SQLException> invoker, Map<D, Ref> structs)
{
return new RefProxyFactory<>(parentProxy, parent, invoker, structs, this.locatorsUpdateCopy);
}
}
|
ha-jdbc/ha-jdbc
|
core/src/main/java/net/sf/hajdbc/sql/RefProxyFactoryFactory.java
|
Java
|
lgpl-3.0
| 1,563 |
<?php
namespace Polygen\Grammar;
use Polygen\Grammar\Interfaces\DeclarationInterface;
use Polygen\Grammar\Interfaces\Node;
use Polygen\Language\AbstractSyntaxWalker;
use Webmozart\Assert\Assert;
/**
* Definition Polygen node
*/
class Definition implements DeclarationInterface, Node
{
/**
* @var string
*/
private $name;
/**
* @var ProductionCollection
*/
private $productions;
/**
* @param string $name
*/
public function __construct($name, ProductionCollection $productions)
{
Assert::string($name);
$this->name = $name;
$this->productions = $productions;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Allows a node to pass itself back to the walker using the method most appropriate to walk on it.
*
* @param mixed|null $context Data that you want to be passed back to the walker.
* @return mixed|null
*/
public function traverse(AbstractSyntaxWalker $walker, $context = null)
{
return $walker->walkDefinition($this, $context);
}
/**
* @deprecated
* @return Production[]
*/
public function getProductions()
{
return $this->productions->getProductions();
}
/**
* @return \Polygen\Grammar\ProductionCollection
*/
public function getProductionSet()
{
return $this->productions;
}
/**
* Returns a new instance of this object with the same properties, but with the specified productions.
*
* @return static
*/
public function withProductions(ProductionCollection $productions)
{
return new static($this->name, $productions);
}
}
|
RBastianini/polygen-php
|
src/Grammar/Definition.php
|
PHP
|
lgpl-3.0
| 1,761 |
#!/usr/bin/env python
#
# Copyright (C) 2015 Jonathan Racicot
#
# 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/>.
#
# You are free to use and modify this code for your own software
# as long as you retain information about the original author
# in your code as shown below.
#
# <author>Jonathan Racicot</author>
# <email>infectedpacket@gmail.com</email>
# <date>2015-03-26</date>
# <url>https://github.com/infectedpacket</url>
#//////////////////////////////////////////////////////////
# Program Information
#
PROGRAM_NAME = "vmfcat"
PROGRAM_DESC = ""
PROGRAM_USAGE = "%(prog)s [-i] [-h|--help] (OPTIONS)"
__version_info__ = ('0','1','0')
__version__ = '.'.join(__version_info__)
#//////////////////////////////////////////////////////////
#//////////////////////////////////////////////////////////
# Imports Statements
import re
import sys
import json
import argparse
import traceback
from Factory import *
from Logger import *
from bitstring import *
#//////////////////////////////////////////////////////////
# =============================================================================
# Parameter information
class Params:
parameters = {
"debug" : {
"cmd" : "debug",
"help" : "Enables debug mode.",
"choices" : [True, False]
},
"data" : {
"cmd" : "data",
"help" : "Specifies a file containing data to be included in the VMF message.",
"choices" : []
},
"vmfversion" : {
"cmd" : "vmfversion",
"help" :
"""Field representing the version of the MIL-STD-2045-47001 header being used for the message.""",
"choices" : ["std47001", "std47001b","std47001c","std47001d","std47001d_change"]
},
"compress" : {
"cmd" : "compress",
"help" :
"""This field represents whether the message or messages contained in the User Data portion of the Application PDU have been UNIX compressed or compressed using GZIP.""",
"choices" : ["unix", "gzip"]
},
"headersize" : {
"cmd" : "headersize",
"help" :
"""Indicates the size in octets of the header""",
"choices" : []
},
"originator_urn" : {
"cmd" : "originator_urn",
"help" : """24-bit code used to uniquely identify friendly military units, broadcast networks and multicast groups.""",
"choices" : []
},
"originator_unitname" : {
"cmd" : "originator_unitname",
"help" : """Specify the name of the unit sending the message.""",
"choices" : []
},
"rcpt_urns" : {
"cmd" : "rcpt_urns",
"help" : """List of 24-bit codes used to uniquely identify friendly units.""",
"choices" : []
},
"rcpt_unitnames" : {
"cmd" : "rcpt_unitnames",
"help" : """ List of variable size fields of character-coded identifiers for friendly units. """,
"choices" : []
},
"info_urns" : {
"cmd" : "info_urns",
"help" : """List of 24-bit codes used to uniquely identify friendly units.""",
"choices" : []
},
"info_unitnames" : {
"cmd" : "info_unitnames",
"help" : """ List of variable size fields of character-coded identifiers for friendly units. """,
"choices" : []
},
"umf" : {
"cmd" : "umf",
"choices" : ["link16", "binary", "vmf", "nitfs", "rdm", "usmtf", "doi103", "xml-mtf", "xml-vmf"],
"help" : """ Indicates the format of the message contained in the user data field."""
},
"messagevers" : {
"cmd" : "messagevers",
"choices" : [],
"help" : """Represents the version of the message standard contained in the user data field."""
},
"fad" : {
"cmd" : "fad",
"choices" : ["netcon", "geninfo", "firesp", "airops", "intops", "landops","marops", "css", "specialops", "jtfopsctl", "airdef"],
"help" : "Identifies the functional area of a specific VMF message using code words."
},
"msgnumber" : {
"cmd" : "msgnumber",
"choices" : [],
"help" : """Represents the number that identifies a specific VMF message within a functional area."""
},
"msgsubtype" : {
"cmd" : "msgsubtype",
"choices" : [],
"help" : """Represents a specific case within a VMF message, which depends on the UMF, FAD and message number."""
},
"filename" : {
"cmd" : "filename",
"choices" : [],
"help" : """Indicates the name of the computer file or data block contained in the User Data portion of the application PDU."""
},
"msgsize" : {
"cmd" : "msgsize",
"choices" : [],
"help" : """Indicates the size(in bytes) of the associated message within the User Data field."""
},
"opind" : {
"cmd" : "opind",
"choices" : ["op", "ex", "sim", "test"],
"help" : "Indicates the operational function of the message."
},
"retransmission" : {
"cmd" : "retransmission",
"choices" : [1, 0],
"help" : """Indicates whether a message is a retransmission."""
},
"msgprecedence" : {
"cmd" : "msgprecedence",
"choices" : ["reserved", "critic", "flashover", "flash", "imm", "pri", "routine"],
"help" : """Indicates relative precedence of a message."""
},
"classification" : {
"cmd" : "classification",
"choices" : ["unclass", "conf", "secret", "topsecret"],
"help" : """Security classification of the message."""
},
"releasemark" : {
"cmd" : "releasemark",
"choices" : [],
"help" : """Support the exchange of a list of up to 16 country codes with which the message can be release."""
},
"originatordtg" : {
"cmd" : "originatordtg",
"choices" : [],
"help" : """ Contains the date and time in Zulu Time that the message was prepared."""
},
"perishdtg" : {
"cmd" : "perishdtg",
"choices" : [],
"help" : """Provides the latest time the message is still of value."""
},
"ackmachine" : {
"cmd" : "ackmachine",
"choices" : [1, 0],
"help" : """Indicates whether the originator of a machine requires a machine acknowledgement for the message."""
},
"ackop" : {
"cmd" : "ackop",
"choices" : [1, 0],
"help" : """Indicates whether the originator of the message requires an acknowledgement for the message from the recipient."""
},
"ackdtg" : {
"cmd" : "ackdtg",
"choices" : [],
"help" : """Provides the date and time of the original message that is being acknowledged."""
},
"rc" : {
"cmd" : "rc",
"choices" : ["mr", "cantpro", "oprack", "wilco", "havco", "cantco", "undef"],
"help" : """Codeword representing the Receipt/Compliance answer to the acknowledgement request."""
},
"cantpro" : {
"cmd" : "cantpro",
"choices" : [],
"help" : """Indicates the reason that a particular message cannot be processed by a recipient or information address."""
},
"reply" : {
"cmd" : "reply",
"choices" : [1, 0],
"help" : """Indicates whether the originator of the message requires an operator reply to the message."""
},
"cantco" : {
"cmd" : "cantco",
"choices" : ["comm", "ammo", "pers", "fuel", "env", "equip", "tac", "other"],
"help" : """Indicates the reason that a particular recipient cannot comply with a particular message."""
},
"replyamp" : {
"cmd" : "replyamp",
"choices" : [],
"help" : """Provide textual data an amplification of the recipient's reply to a message."""
},
"ref_urn" : {
"cmd" : "ref_urn",
"choices" : [],
"help" : """URN of the reference message."""
},
"ref_unitname" : {
"cmd" : "ref_unitname",
"choices" : [],
"help" : """Name of the unit of the reference message."""
},
"refdtg" : {
"cmd" : "refdtg",
"choices" : [],
"help" : """Date time group of the reference message."""
},
"secparam" : {
"cmd" : "secparam",
"choices" : ['auth', 'undef'],
"help" : """Indicate the identities of the parameters and algorithms that enable security processing."""
},
"keymatlen" : {
"cmd" : "keymatlen",
"choices" : [],
"help" : """Defines the size in octets of the Keying Material ID field."""
},
"keymatid" : {
"cmd" : "keymatid",
"choices" : [],
"help" : """Identifies the key which was used for encryption."""
},
"crypto_init_len" : {
"cmd" : "crypto_init_len",
"choices" : [],
"help" : """Defines the size, in 64-bit blocks, of the Crypto Initialization field."""
},
"crypto_init" : {
"cmd" : "crypto_init",
"choices" : [],
"help" : """Sequence of bits used by the originator and recipient to initialize the encryption/decryption process."""
},
"keytok_len" : {
"cmd" : "keytok_len",
"choices" : [],
"help" : """Defines the size, in 64-bit blocks, of the Key Token field."""
},
"keytok" : {
"cmd" : "keytok",
"choices" : [],
"help" : """Contains information enabling each member of each address group to decrypt the user data associated with this message header."""
},
"autha-len" : {
"cmd" : "autha-len",
"choices" : [],
"help" : """Defines the size, in 64-bit blocks, of the Authentification Data (A) field."""
},
"authb-len" : {
"cmd" : "authb-len",
"choices" : [],
"help" : """Defines the size, in 64-bit blocks, of the Authentification Data (B) field."""
},
"autha" : {
"cmd" : "autha",
"choices" : [],
"help" : """Data created by the originator to provide both connectionless integrity and data origin authentication (A)."""
},
"authb" : {
"cmd" : "authb",
"choices" : [],
"help" : """Data created by the originator to provide both connectionless integrity and data origin authentication (B)."""
},
"acksigned" : {
"cmd" : "acksigned",
"choices" : [],
"help" : """Indicates whether the originator of a message requires a signed response from the recipient."""
},
"pad_len" : {
"cmd" : "pad_len",
"choices" : [],
"help" : """Defines the size, in octets, of the message security padding field."""
},
"padding" : {
"cmd" : "padding",
"choices" : [],
"help" : """Necessary for a block encryption algorithm so the content of the message is a multiple of the encryption block length."""
},
}
#//////////////////////////////////////////////////////////////////////////////
# Argument Parser Declaration
#
usage = "%(prog)s [options] data"
parser = argparse.ArgumentParser(usage=usage,
prog="vmfcat",
version="%(prog)s "+__version__,
description="Allows crafting of Variable Message Format (VMF) messages.")
io_options = parser.add_argument_group(
"Input/Output Options", "Types of I/O supported.")
io_options.add_argument("-d", "--debug",
dest=Params.parameters['debug']['cmd'],
action="store_true",
help=Params.parameters['debug']['help'])
io_options.add_argument("-i", "--interactive",
dest="interactive",
action="store_true",
help="Create and send VMF messages interactively.")
io_options.add_argument("-of", "--ofile",
dest="outputfile",
nargs="?",
type=argparse.FileType('w'),
default=sys.stdout,
help="File to output the results. STDOUT by default.")
io_options.add_argument("--data",
dest=Params.parameters['data']['cmd'],
help=Params.parameters['data']['help'])
# =============================================================================
# Application Header Arguments
header_options = parser.add_argument_group(
"Application Header", "Flags and Fields of the application header.")
header_options.add_argument("--vmf-version",
dest=Params.parameters["vmfversion"]["cmd"],
action="store",
choices=Params.parameters["vmfversion"]["choices"],
default="std47001c",
help=Params.parameters["vmfversion"]["help"])
header_options.add_argument("--compress",
dest=Params.parameters["compress"]["cmd"],
action="store",
choices=Params.parameters["compress"]["choices"],
help=Params.parameters["compress"]["help"])
header_options.add_argument("--header-size",
dest=Params.parameters["headersize"]["cmd"],
action="store",
type=int,
help=Params.parameters["headersize"]["help"])
# =============================================================================
# Originator Address Group Arguments
orig_addr_options = parser.add_argument_group(
"Originator Address Group", "Fields of the originator address group.")
orig_addr_options.add_argument("--orig-urn",
dest=Params.parameters["originator_urn"]["cmd"],
metavar="URN",
type=int,
action="store",
help=Params.parameters["originator_urn"]["help"])
orig_addr_options.add_argument("--orig-unit",
dest=Params.parameters["originator_unitname"]["cmd"],
metavar="STRING",
action="store",
help=Params.parameters["originator_unitname"]["help"])
# =============================================================================
# =============================================================================
# Recipient Address Group Arguments
recp_addr_options = parser.add_argument_group(
"Recipient Address Group", "Fields of the recipient address group.")
recp_addr_options.add_argument("--rcpt-urns",
nargs="+",
dest=Params.parameters['rcpt_urns']['cmd'],
metavar="URNs",
help=Params.parameters['rcpt_urns']['help'])
recp_addr_options.add_argument("--rcpt-unitnames",
nargs="+",
dest=Params.parameters['rcpt_unitnames']['cmd'],
metavar="UNITNAMES",
help=Params.parameters['rcpt_unitnames']['help'])
# =============================================================================
# =============================================================================
# Information Address Group Arguments
info_addr_options = parser.add_argument_group(
"Information Address Group", "Fields of the information address group.")
info_addr_options.add_argument("--info-urns",
dest=Params.parameters["info_urns"]["cmd"],
metavar="URNs",
nargs="+",
action="store",
help=Params.parameters["info_urns"]["help"])
info_addr_options.add_argument("--info-units",
dest="info_unitnames",
metavar="UNITNAMES",
action="store",
help="Specify the name of the unit of the reference message.")
# =============================================================================
# =============================================================================
# Message Handling Group Arguments
msg_handling_options = parser.add_argument_group(
"Message Handling Group", "Fields of the message handling group.")
msg_handling_options.add_argument("--umf",
dest=Params.parameters["umf"]["cmd"],
action="store",
choices=Params.parameters["umf"]["choices"],
help=Params.parameters["umf"]["help"])
msg_handling_options.add_argument("--msg-version",
dest=Params.parameters["messagevers"]["cmd"],
action="store",
metavar="VERSION",
type=int,
help=Params.parameters["messagevers"]["help"])
msg_handling_options.add_argument("--fad",
dest=Params.parameters["fad"]["cmd"],
action="store",
choices=Params.parameters["fad"]["choices"],
help=Params.parameters["fad"]["help"])
msg_handling_options.add_argument("--msg-number",
dest=Params.parameters["msgnumber"]["cmd"],
action="store",
type=int,
metavar="1-127",
help=Params.parameters["msgnumber"]["help"])
msg_handling_options.add_argument("--msg-subtype",
dest=Params.parameters["msgsubtype"]["cmd"],
action="store",
type=int,
metavar="1-127",
help=Params.parameters["msgsubtype"]["help"])
msg_handling_options.add_argument("--filename",
dest=Params.parameters["filename"]["cmd"],
action="store",
help=Params.parameters["filename"]["help"])
msg_handling_options.add_argument("--msg-size",
dest=Params.parameters["msgsize"]["cmd"],
action="store",
type=int,
metavar="SIZE",
help=Params.parameters["msgsize"]["help"])
msg_handling_options.add_argument("--opind",
dest=Params.parameters["opind"]["cmd"],
action="store",
choices=Params.parameters["opind"]["choices"],
help=Params.parameters["opind"]["help"])
msg_handling_options.add_argument("--retrans",
dest=Params.parameters["retransmission"]["cmd"],
action="store_true",
help=Params.parameters["retransmission"]["help"])
msg_handling_options.add_argument("--msg-prec",
dest=Params.parameters["msgprecedence"]["cmd"],
action="store",
choices=Params.parameters["msgprecedence"]["choices"],
help=Params.parameters["msgprecedence"]["help"])
msg_handling_options.add_argument("--class",
dest=Params.parameters["classification"]["cmd"],
action="store",
nargs="+",
choices=Params.parameters["classification"]["choices"],
help=Params.parameters["classification"]["cmd"])
msg_handling_options.add_argument("--release",
dest=Params.parameters["releasemark"]["cmd"],
action="store",
metavar="COUNTRIES",
help=Params.parameters["releasemark"]["help"])
msg_handling_options.add_argument("--orig-dtg",
dest=Params.parameters["originatordtg"]["cmd"],
action="store",
metavar="YYYY-MM-DD HH:mm[:ss] [extension]",
help=Params.parameters["originatordtg"]["cmd"])
msg_handling_options.add_argument("--perish-dtg",
dest=Params.parameters["perishdtg"]["cmd"],
action="store",
metavar="YYYY-MM-DD HH:mm[:ss]",
help=Params.parameters["perishdtg"]["cmd"])
# =====================================================================================
# =====================================================================================
# Acknowledge Request Group Arguments
ack_options = parser.add_argument_group(
"Acknowledgement Request Group", "Options to request acknowledgement and replies.")
ack_options.add_argument("--ack-machine",
dest=Params.parameters["ackmachine"]["cmd"],
action="store_true",
help=Params.parameters["ackmachine"]["help"])
ack_options.add_argument("--ack-op",
dest=Params.parameters["ackop"]["cmd"],
action="store_true",
help=Params.parameters["ackop"]["help"])
ack_options.add_argument("--reply",
dest=Params.parameters["reply"]["cmd"],
action="store_true",
help=Params.parameters["reply"]["help"])
# =====================================================================================
# =====================================================================================
# Response Data Group Arguments
#
resp_options = parser.add_argument_group(
"Response Data Options", "Fields for the response data group.")
resp_options.add_argument("--ack-dtg",
dest=Params.parameters["ackdtg"]["cmd"],
help=Params.parameters["ackdtg"]["help"],
action="store",
metavar="YYYY-MM-DD HH:mm[:ss] [extension]")
resp_options.add_argument("--rc",
dest=Params.parameters["rc"]["cmd"],
help=Params.parameters["rc"]["help"],
choices=Params.parameters["rc"]["choices"],
action="store")
resp_options.add_argument("--cantpro",
dest=Params.parameters["cantpro"]["cmd"],
help=Params.parameters["cantpro"]["help"],
action="store",
type=int,
metavar="1-32")
resp_options.add_argument("--cantco",
dest=Params.parameters["cantco"]["cmd"],
help=Params.parameters["cantco"]["help"],
choices=Params.parameters["cantco"]["choices"],
action="store")
resp_options.add_argument("--reply-amp",
dest=Params.parameters["replyamp"]["cmd"],
help=Params.parameters["replyamp"]["help"],
action="store")
# =====================================================================================
# =====================================================================================
# Reference Message Data Group Arguments
#
ref_msg_options = parser.add_argument_group(
"Reference Message Data Group", "Fields of the reference message data group.")
ref_msg_options.add_argument("--ref-urn",
dest=Params.parameters["ref_urn"]["cmd"],
help=Params.parameters["ref_urn"]["help"],
metavar="URN",
action="store")
ref_msg_options.add_argument("--ref-unit",
dest=Params.parameters["ref_unitname"]["cmd"],
help=Params.parameters["ref_unitname"]["help"],
metavar="STRING",
action="store")
ref_msg_options.add_argument("--ref-dtg",
dest=Params.parameters["refdtg"]["cmd"],
help=Params.parameters["refdtg"]["help"],
action="store",
metavar="YYYY-MM-DD HH:mm[:ss] [extension]")
# =====================================================================================
# =====================================================================================
# Message Security Data Group Arguments
#
msg_sec_grp = parser.add_argument_group(
"Message Security Group", "Fields of the message security group.")
msg_sec_grp.add_argument("--sec-param",
dest=Params.parameters["secparam"]["cmd"],
help=Params.parameters["secparam"]["help"],
choices=Params.parameters["secparam"]["choices"],
action="store")
msg_sec_grp.add_argument("--keymat-len",
dest=Params.parameters["keymatlen"]["cmd"],
help=Params.parameters["keymatlen"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--keymat-id",
dest=Params.parameters["keymatid"]["cmd"],
help=Params.parameters["keymatid"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--crypto-init-len",
dest=Params.parameters["crypto_init_len"]["cmd"],
help=Params.parameters["crypto_init_len"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--crypto-init",
dest=Params.parameters["crypto_init"]["cmd"],
help=Params.parameters["crypto_init"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--keytok-len",
dest=Params.parameters["keytok_len"]["cmd"],
help=Params.parameters["keytok_len"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--keytok",
dest=Params.parameters["keytok"]["cmd"],
help=Params.parameters["keytok"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--autha-len",
dest=Params.parameters["autha-len"]["cmd"],
help=Params.parameters["autha-len"]["help"],
action="store",
type=int,
metavar="LENGTH")
msg_sec_grp.add_argument("--authb-len",
dest=Params.parameters["authb-len"]["cmd"],
help=Params.parameters["authb-len"]["help"],
action="store",
type=int,
metavar="LENGTH")
msg_sec_grp.add_argument("--autha",
dest=Params.parameters["autha"]["cmd"],
help=Params.parameters["autha"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--authb",
dest=Params.parameters["authb"]["cmd"],
help=Params.parameters["authb"]["help"],
action="store",
type=int)
msg_sec_grp.add_argument("--ack-signed",
dest=Params.parameters["acksigned"]["cmd"],
help=Params.parameters["acksigned"]["help"],
action="store_true")
msg_sec_grp.add_argument("--pad-len",
dest=Params.parameters["pad_len"]["cmd"],
help=Params.parameters["pad_len"]["help"],
action="store",
type=int,
metavar="LENGTH")
msg_sec_grp.add_argument("--padding",
dest=Params.parameters["padding"]["cmd"],
help=Params.parameters["padding"]["help"],
action="store",
type=int)
# =============================================================================
#//////////////////////////////////////////////////////////////////////////////
class VmfShell(object):
"""
Interative shell to Vmfcat. The shell can be use to build a VMF message.
"""
CMD_SAVE = 'save'
CMD_LOAD = 'load'
CMD_SEARCH = 'search'
CMD_SET = 'set'
CMD_SHOW = 'show'
CMD_HEADER = 'header'
CMD_HELP = 'help'
CMD_QUIT = 'quit'
PROMPT = "<<< "
def __init__(self, _output=sys.stdout):
"""
Initializes the user interface by defining a Logger object
and defining the standard output.
"""
self.output = _output
self.logger = Logger(_output, _debug=True)
def start(self):
"""
Starts the main loop of the interactive shell.
"""
# Command entered by the user
cmd = ""
self.logger.print_info("Type 'help' to show a list of available commands.")
while (cmd.lower() != VmfShell.CMD_QUIT):
try:
self.output.write(VmfShell.PROMPT)
user_input = sys.stdin.readline()
tokens = user_input.rstrip().split()
cmd = tokens[0]
if (cmd.lower() == VmfShell.CMD_QUIT):
pass
elif (cmd.lower() == VmfShell.CMD_HELP):
if (len(tokens) == 1):
self.logger.print_info("{:s} <field>|all".format(VmfShell.CMD_SHOW))
self.logger.print_info("{:s} <field> <value>".format(VmfShell.CMD_SET))
self.logger.print_info("{:s} [field] {{bin, hex}}".format(VmfShell.CMD_HEADER))
self.logger.print_info("{:s} <field>".format(VmfShell.CMD_HELP))
self.logger.print_info("{:s} <field>".format(VmfShell.CMD_SEARCH))
self.logger.print_info("{:s} <file>".format(VmfShell.CMD_SAVE))
self.logger.print_info("{:s} <file>".format(VmfShell.CMD_LOAD))
self.logger.print_info("{:s}".format(VmfShell.CMD_QUIT))
else:
param = tokens[1]
if (param in Params.__dict__.keys()):
help_msg = Params.parameters[param]['help']
self.logger.print_info(help_msg)
if (len(Params.parameters[param]['choices']) > 0):
choices_msg = ', '.join([ choice for choice in Params.parameters[param]['choices']])
self.logger.print_info("Available values: {:s}".format(choices_msg))
else:
self.logger.print_error("Unknown parameter/option: {:s}.".format(param))
elif (cmd.lower() == VmfShell.CMD_SHOW):
#
# Displays the value of the given field
#
if (len(tokens) == 2):
param = tokens[1]
if (param in Params.parameters.keys()):
value = Params.__dict__[param]
if (isinstance(value, int)):
value = "0x{:02x}".format(value)
self.logger.print_info("{} = {}".format(param, value))
elif param.lower() == "all":
for p in Params.parameters.keys():
value = Params.__dict__[p]
self.logger.print_info("{} = {}".format(p, value))
else:
self.logger.print_error("Unknown parameter/option {:s}.".format(param))
else:
self.logger.print_error("Usage: {s} <field>".format(VmfShell.CMD_SHOW))
elif (cmd.lower() == VmfShell.CMD_SET):
#
# Sets a field with the given value
#
# TODO: Issues with parameters with boolean values
if (len(tokens) >= 3):
param = tokens[1]
value = ' '.join(tokens[2:])
if (param in Params.__dict__.keys()):
if (Params.parameters[param]["choices"]):
if (value in Params.parameters[param]["choices"]):
Params.__dict__[param] = value
new_value = Params.__dict__[param]
self.logger.print_success("{:s} = {:s}".format(param, new_value))
else:
self.logger.print_error("Invalid value ({:s}) for field {:s}.".format(value, param))
self.logger.print_info("Values for field are : {:s}.".format(','.join(str(Params.parameters[param]["choices"]))))
else:
Params.__dict__[param] = value
new_value = Params.__dict__[param]
self.logger.print_success("{:s} = {:s}".format(param, new_value))
else:
self.logger.print_error("Unknown parameter {:s}.".format(param))
else:
self.logger.print_error("Usage: {:s} <field> <value>".format(VmfShell.CMD_SET))
elif (cmd.lower() == VmfShell.CMD_HEADER):
field = "vmfversion"
fmt = "bin"
if (len(tokens) >= 2):
field = tokens[1]
if (len(tokens) == 3):
fmt = tokens[2]
vmf_factory = Factory(_logger=self.logger)
vmf_message = vmf_factory.new_message(Params)
vmf_elem = vmf_message.header.elements[field]
if (isinstance(vmf_elem, Field)):
vmf_value = vmf_elem.value
elif (isinstance(vmf_elem, Group)):
vmf_value = "n/a"
else:
raise Exception("Unknown type for element '{:s}'.".format(field))
vmf_bits = vmf_elem.get_bit_array()
output = vmf_bits
if (fmt == "bin"):
output = vmf_bits.bin
if (fmt == "hex"):
output = vmf_bits.hex
self.logger.print_success("{}\t{}\t{}".format(field, vmf_value, output))
elif (cmd.lower() == VmfShell.CMD_SEARCH):
keyword = ' '.join(tokens[1:]).lower()
for p in Params.parameters.keys():
help = Params.parameters[p]['help']
if (p.lower() == keyword or keyword in help.lower()):
self.logger.print_success("{:s}: {:s}".format(p, help))
elif (cmd.lower() == VmfShell.CMD_SAVE):
if len(tokens) == 2:
file = tokens[1]
tmpdict = {}
for param in Params.parameters.keys():
value = Params.__dict__[param]
tmpdict[param] = value
with open(file, 'w') as f:
json.dump(tmpdict, f)
self.logger.print_success("Saved VMF message to {:s}.".format(file))
else:
self.logger.print_error("Specify a file to save the configuration to.")
elif (cmd.lower() == "test"):
if (len(tokens) == 2):
vmf_params = tokens[1]
else:
vmf_params = '0x4023'
s = BitStream(vmf_params)
bstream = BitStream('0x4023')
vmf_factory = Factory(_logger=self.logger)
vmf_message = vmf_factory.read_message(bstream)
elif (cmd.lower() == VmfShell.CMD_LOAD):
if len(tokens) == 2:
file = tokens[1]
with open(file, 'r') as f:
param_dict = json.load(f)
for (param, value) in param_dict.iteritems():
Params.__dict__[param] = value
self.logger.print_success("Loaded VMF message from {:s}.".format(file))
else:
self.logger.print_error("Specify a file to load the configuration from.")
else:
self.logger.print_error("Unknown command {:s}.".format(cmd))
except Exception as e:
self.logger.print_error("An exception as occured: {:s}".format(e.message))
traceback.print_exc(file=sys.stdout)
|
InfectedPacket/TerrorCat
|
UI.py
|
Python
|
lgpl-3.0
| 32,143 |
/*
* Copyright (c) 2011 for Jacek Bzdak
*
* This file is part of query builder.
*
* Query builder is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Query builder is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Query builder. If not, see <http://www.gnu.org/licenses/>.
*/
package cx.ath.jbzdak.sqlbuilder.expression;
import fakeEnum.FakeEnum;
import java.util.Collection;
/**
* Created by: Jacek Bzdak
*/
public class BinaryExpressionType {
public static final String LIKE = "LIKE";
public static final String EQUALS = "=";
public static final String NE = "<>";
public static final String LT = "<";
public static final String GT = ">";
public static final String LTE = "<=";
public static final String GTE = ">=";
public static final String IN = "IN";
public static final String MINUS = "-";
public static final String DIVIDE = "/";
public static final FakeEnum<String> FAKE_ENUM = new FakeEnum<String>(BinaryExpressionType.class, String.class);
public static String nameOf(String value) {
return FAKE_ENUM.nameOf(value);
}
public static Collection<? extends String> values() {
return FAKE_ENUM.values();
}
public static String valueOf(String s) {
return FAKE_ENUM.valueOf(s);
}
}
|
jbzdak/query-builder
|
sql-builder-api/src/main/java/cx/ath/jbzdak/sqlbuilder/expression/BinaryExpressionType.java
|
Java
|
lgpl-3.0
| 1,760 |
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; version 3 of the License.
//
// 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 Lesser General Public License
// for more details.
//
// You should have received a copy of the GNU Lesser General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
using NUnit.Framework;
using System.Web.Security;
using System.Collections.Specialized;
using System.Data;
using System;
using System.Configuration.Provider;
using MariaDB.Web.Security;
using MariaDB.Data.MySqlClient;
namespace MariaDB.Web.Tests
{
[TestFixture]
public class UserManagement : BaseWebTest
{
private MySQLMembershipProvider provider;
[SetUp]
public override void Setup()
{
base.Setup();
execSQL("DROP TABLE IF EXISTS mysql_membership");
}
private void CreateUserWithFormat(MembershipPasswordFormat format)
{
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("applicationName", "/");
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", format.ToString());
provider.Initialize(null, config);
// create the user
MembershipCreateStatus status;
provider.CreateUser("foo", "barbar!", "foo@bar.com", null, null, true, null, out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
// verify that the password format is hashed.
DataTable table = FillTable("SELECT * FROM my_aspnet_Membership");
MembershipPasswordFormat rowFormat =
(MembershipPasswordFormat)Convert.ToInt32(table.Rows[0]["PasswordFormat"]);
Assert.AreEqual(format, rowFormat);
// then attempt to verify the user
Assert.IsTrue(provider.ValidateUser("foo", "barbar!"));
}
[Test]
public void CreateUserWithHashedPassword()
{
CreateUserWithFormat(MembershipPasswordFormat.Hashed);
}
[Test]
public void CreateUserWithEncryptedPasswordWithAutoGenKeys()
{
try
{
CreateUserWithFormat(MembershipPasswordFormat.Encrypted);
}
catch (ProviderException)
{
}
}
[Test]
public void CreateUserWithClearPassword()
{
CreateUserWithFormat(MembershipPasswordFormat.Clear);
}
/// <summary>
/// Bug #34792 New User/Changing Password Validation Not working.
/// </summary>
[Test]
public void ChangePassword()
{
CreateUserWithHashedPassword();
try
{
provider.ChangePassword("foo", "barbar!", "bar2");
Assert.Fail();
}
catch (ArgumentException ae1)
{
Assert.AreEqual("newPassword", ae1.ParamName);
Assert.IsTrue(ae1.Message.Contains("length of parameter"));
}
try
{
provider.ChangePassword("foo", "barbar!", "barbar2");
Assert.Fail();
}
catch (ArgumentException ae1)
{
Assert.AreEqual("newPassword", ae1.ParamName);
Assert.IsTrue(ae1.Message.Contains("alpha numeric"));
}
// now test regex strength testing
bool result = provider.ChangePassword("foo", "barbar!", "zzzxxx!");
Assert.IsFalse(result);
// now do one that should work
result = provider.ChangePassword("foo", "barbar!", "barfoo!");
Assert.IsTrue(result);
provider.ValidateUser("foo", "barfoo!");
}
/// <summary>
/// Bug #34792 New User/Changing Password Validation Not working.
/// </summary>
[Test]
public void CreateUserWithErrors()
{
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("applicationName", "/");
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", "Hashed");
provider.Initialize(null, config);
// first try to create a user with a password not long enough
MembershipCreateStatus status;
MembershipUser user = provider.CreateUser("foo", "xyz",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status);
// now with not enough non-alphas
user = provider.CreateUser("foo", "xyz1234",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status);
// now one that doesn't pass the regex test
user = provider.CreateUser("foo", "xyzxyz!",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNull(user);
Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status);
// now one that works
user = provider.CreateUser("foo", "barbar!",
"foo@bar.com", null, null, true, null, out status);
Assert.IsNotNull(user);
Assert.AreEqual(MembershipCreateStatus.Success, status);
}
[Test]
public void DeleteUser()
{
CreateUserWithHashedPassword();
Assert.IsTrue(provider.DeleteUser("foo", true));
DataTable table = FillTable("SELECT * FROM my_aspnet_Membership");
Assert.AreEqual(0, table.Rows.Count);
table = FillTable("SELECT * FROM my_aspnet_Users");
Assert.AreEqual(0, table.Rows.Count);
CreateUserWithHashedPassword();
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("applicationName", "/");
provider.Initialize(null, config);
Assert.IsTrue(Membership.DeleteUser("foo", false));
table = FillTable("SELECT * FROM my_aspnet_Membership");
Assert.AreEqual(0, table.Rows.Count);
table = FillTable("SELECT * FROM my_aspnet_Users");
Assert.AreEqual(1, table.Rows.Count);
}
[Test]
public void FindUsersByName()
{
CreateUserWithHashedPassword();
int records;
MembershipUserCollection users = provider.FindUsersByName("F%", 0, 10, out records);
Assert.AreEqual(1, records);
Assert.AreEqual("foo", users["foo"].UserName);
}
[Test]
public void FindUsersByEmail()
{
CreateUserWithHashedPassword();
int records;
MembershipUserCollection users = provider.FindUsersByEmail("foo@bar.com", 0, 10, out records);
Assert.AreEqual(1, records);
Assert.AreEqual("foo", users["foo"].UserName);
}
[Test]
public void TestCreateUserOverrides()
{
try
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status);
int records;
MembershipUserCollection users = Membership.FindUsersByName("F%", 0, 10, out records);
Assert.AreEqual(1, records);
Assert.AreEqual("foo", users["foo"].UserName);
Membership.CreateUser("test", "barbar!", "myemail@host.com",
"question", "answer", true, out status);
users = Membership.FindUsersByName("T%", 0, 10, out records);
Assert.AreEqual(1, records);
Assert.AreEqual("test", users["test"].UserName);
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
}
[Test]
public void NumberOfUsersOnline()
{
int numOnline = Membership.GetNumberOfUsersOnline();
Assert.AreEqual(0, numOnline);
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status);
Membership.CreateUser("foo2", "barbar!", null, "question", "answer", true, out status);
numOnline = Membership.GetNumberOfUsersOnline();
Assert.AreEqual(2, numOnline);
}
[Test]
public void UnlockUser()
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status);
Assert.IsFalse(Membership.ValidateUser("foo", "bar2"));
Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
Assert.IsFalse(Membership.ValidateUser("foo", "bar3"));
// the user should be locked now so the right password should fail
Assert.IsFalse(Membership.ValidateUser("foo", "barbar!"));
MembershipUser user = Membership.GetUser("foo");
Assert.IsTrue(user.IsLockedOut);
Assert.IsTrue(user.UnlockUser());
user = Membership.GetUser("foo");
Assert.IsFalse(user.IsLockedOut);
Assert.IsTrue(Membership.ValidateUser("foo", "barbar!"));
}
[Test]
public void GetUsernameByEmail()
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", "foo@bar.com", "question", "answer", true, out status);
string username = Membership.GetUserNameByEmail("foo@bar.com");
Assert.AreEqual("foo", username);
username = Membership.GetUserNameByEmail("foo@b.com");
Assert.IsNull(username);
username = Membership.GetUserNameByEmail(" foo@bar.com ");
Assert.AreEqual("foo", username);
}
[Test]
public void UpdateUser()
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
MembershipUser user = Membership.GetUser("foo");
user.Comment = "my comment";
user.Email = "my email";
user.IsApproved = false;
user.LastActivityDate = new DateTime(2008, 1, 1);
user.LastLoginDate = new DateTime(2008, 2, 1);
Membership.UpdateUser(user);
MembershipUser newUser = Membership.GetUser("foo");
Assert.AreEqual(user.Comment, newUser.Comment);
Assert.AreEqual(user.Email, newUser.Email);
Assert.AreEqual(user.IsApproved, newUser.IsApproved);
Assert.AreEqual(user.LastActivityDate, newUser.LastActivityDate);
Assert.AreEqual(user.LastLoginDate, newUser.LastLoginDate);
}
private void ChangePasswordQAHelper(MembershipUser user, string pw, string newQ, string newA)
{
try
{
user.ChangePasswordQuestionAndAnswer(pw, newQ, newA);
Assert.Fail("This should not work.");
}
catch (ArgumentNullException ane)
{
Assert.AreEqual("password", ane.ParamName);
}
catch (ArgumentException)
{
Assert.IsNotNull(pw);
}
}
[Test]
public void ChangePasswordQuestionAndAnswer()
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, out status);
Assert.AreEqual(MembershipCreateStatus.Success, status);
MembershipUser user = Membership.GetUser("foo");
ChangePasswordQAHelper(user, "", "newQ", "newA");
ChangePasswordQAHelper(user, "barbar!", "", "newA");
ChangePasswordQAHelper(user, "barbar!", "newQ", "");
ChangePasswordQAHelper(user, null, "newQ", "newA");
bool result = user.ChangePasswordQuestionAndAnswer("barbar!", "newQ", "newA");
Assert.IsTrue(result);
user = Membership.GetUser("foo");
Assert.AreEqual("newQ", user.PasswordQuestion);
}
[Test]
public void GetAllUsers()
{
MembershipCreateStatus status;
// first create a bunch of users
for (int i=0; i < 100; i++)
Membership.CreateUser(String.Format("foo{0}", i), "barbar!", null,
"question", "answer", true, out status);
MembershipUserCollection users = Membership.GetAllUsers();
Assert.AreEqual(100, users.Count);
int index = 0;
foreach (MembershipUser user in users)
Assert.AreEqual(String.Format("foo{0}", index++), user.UserName);
int total;
users = Membership.GetAllUsers(2, 10, out total);
Assert.AreEqual(10, users.Count);
Assert.AreEqual(100, total);
index = 0;
foreach (MembershipUser user in users)
Assert.AreEqual(String.Format("foo2{0}", index++), user.UserName);
}
private void GetPasswordHelper(bool requireQA, bool enablePasswordRetrieval, string answer)
{
MembershipCreateStatus status;
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("requiresQuestionAndAnswer", requireQA ? "true" : "false");
config.Add("enablePasswordRetrieval", enablePasswordRetrieval ? "true" : "false");
config.Add("passwordFormat", "clear");
config.Add("applicationName", "/");
config.Add("writeExceptionsToEventLog", "false");
provider.Initialize(null, config);
provider.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, null, out status);
try
{
string password = provider.GetPassword("foo", answer);
if (!enablePasswordRetrieval)
Assert.Fail("This should have thrown an exception");
Assert.AreEqual("barbar!", password);
}
catch (MembershipPasswordException)
{
if (requireQA && answer != null)
Assert.Fail("This should not have thrown an exception");
}
catch (ProviderException)
{
if (requireQA && answer != null)
Assert.Fail("This should not have thrown an exception");
}
}
[Test]
public void GetPassword()
{
GetPasswordHelper(false, false, null);
GetPasswordHelper(false, true, null);
GetPasswordHelper(true, true, null);
GetPasswordHelper(true, true, "blue");
}
/// <summary>
/// Bug #38939 MembershipUser.GetPassword(string answer) fails when incorrect answer is passed.
/// </summary>
[Test]
public void GetPasswordWithWrongAnswer()
{
MembershipCreateStatus status;
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("requiresQuestionAndAnswer", "true");
config.Add("enablePasswordRetrieval", "true");
config.Add("passwordFormat", "Encrypted");
config.Add("applicationName", "/");
provider.Initialize(null, config);
provider.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, null, out status);
MySQLMembershipProvider provider2 = new MySQLMembershipProvider();
NameValueCollection config2 = new NameValueCollection();
config2.Add("connectionStringName", "LocalMySqlServer");
config2.Add("requiresQuestionAndAnswer", "true");
config2.Add("enablePasswordRetrieval", "true");
config2.Add("passwordFormat", "Encrypted");
config2.Add("applicationName", "/");
provider2.Initialize(null, config2);
try
{
string pw = provider2.GetPassword("foo", "wrong");
Assert.Fail("Should have failed");
}
catch (MembershipPasswordException)
{
}
}
[Test]
public void GetUser()
{
MembershipCreateStatus status;
Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status);
MembershipUser user = Membership.GetUser(1);
Assert.AreEqual("foo", user.UserName);
// now move the activity date back outside the login
// window
user.LastActivityDate = new DateTime(2008, 1, 1);
Membership.UpdateUser(user);
user = Membership.GetUser("foo");
Assert.IsFalse(user.IsOnline);
user = Membership.GetUser("foo", true);
Assert.IsTrue(user.IsOnline);
// now move the activity date back outside the login
// window again
user.LastActivityDate = new DateTime(2008, 1, 1);
Membership.UpdateUser(user);
user = Membership.GetUser(1);
Assert.IsFalse(user.IsOnline);
user = Membership.GetUser(1, true);
Assert.IsTrue(user.IsOnline);
}
[Test]
public void FindUsers()
{
MembershipCreateStatus status;
for (int i=0; i < 100; i++)
Membership.CreateUser(String.Format("boo{0}", i), "barbar!", null,
"question", "answer", true, out status);
for (int i=0; i < 100; i++)
Membership.CreateUser(String.Format("foo{0}", i), "barbar!", null,
"question", "answer", true, out status);
for (int i=0; i < 100; i++)
Membership.CreateUser(String.Format("schmoo{0}", i), "barbar!", null,
"question", "answer", true, out status);
MembershipUserCollection users = Membership.FindUsersByName("fo%");
Assert.AreEqual(100, users.Count);
int total;
users = Membership.FindUsersByName("fo%", 2, 10, out total);
Assert.AreEqual(10, users.Count);
Assert.AreEqual(100, total);
int index = 0;
foreach (MembershipUser user in users)
Assert.AreEqual(String.Format("foo2{0}", index++), user.UserName);
}
[Test]
public void CreateUserWithNoQA()
{
MembershipCreateStatus status;
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("requiresQuestionAndAnswer", "true");
config.Add("passwordFormat", "clear");
config.Add("applicationName", "/");
provider.Initialize(null, config);
try
{
provider.CreateUser("foo", "barbar!", "foo@bar.com", "color", null, true, null, out status);
Assert.Fail();
}
catch (Exception ex)
{
Assert.IsTrue(ex.Message.StartsWith("Password answer supplied is invalid"));
}
try
{
provider.CreateUser("foo", "barbar!", "foo@bar.com", "", "blue", true, null, out status);
Assert.Fail();
}
catch (Exception ex)
{
Assert.IsTrue(ex.Message.StartsWith("Password question supplied is invalid"));
}
}
[Test]
public void MinRequiredAlpha()
{
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("applicationName", "/");
config.Add("minRequiredNonalphanumericCharacters", "3");
provider.Initialize(null, config);
MembershipCreateStatus status;
MembershipUser user = provider.CreateUser("foo", "pw!pass", "email", null, null, true, null, out status);
Assert.IsNull(user);
user = provider.CreateUser("foo", "pw!pa!!", "email", null, null, true, null, out status);
Assert.IsNotNull(user);
}
/// <summary>
/// Bug #35332 GetPassword() don't working (when PasswordAnswer is NULL)
/// </summary>
[Test]
public void GetPasswordWithNullValues()
{
MembershipCreateStatus status;
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("requiresQuestionAndAnswer", "false");
config.Add("enablePasswordRetrieval", "true");
config.Add("passwordFormat", "clear");
config.Add("applicationName", "/");
provider.Initialize(null, config);
MembershipUser user = provider.CreateUser("foo", "barbar!", "foo@bar.com", null, null, true, null, out status);
Assert.IsNotNull(user);
string pw = provider.GetPassword("foo", null);
Assert.AreEqual("barbar!", pw);
}
/// <summary>
/// Bug #35336 GetPassword() return wrong password (when format is encrypted)
/// </summary>
[Test]
public void GetEncryptedPassword()
{
MembershipCreateStatus status;
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("requiresQuestionAndAnswer", "false");
config.Add("enablePasswordRetrieval", "true");
config.Add("passwordFormat", "encrypted");
config.Add("applicationName", "/");
provider.Initialize(null, config);
MembershipUser user = provider.CreateUser("foo", "barbar!", "foo@bar.com", null, null, true, null, out status);
Assert.IsNotNull(user);
string pw = provider.GetPassword("foo", null);
Assert.AreEqual("barbar!", pw);
}
/// <summary>
/// Bug #42574 ValidateUser does not use the application id, allowing cross application login
/// </summary>
[Test]
public void CrossAppLogin()
{
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("applicationName", "/");
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", "Clear");
provider.Initialize(null, config);
MembershipCreateStatus status;
provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status);
MySQLMembershipProvider provider2 = new MySQLMembershipProvider();
NameValueCollection config2 = new NameValueCollection();
config2.Add("connectionStringName", "LocalMySqlServer");
config2.Add("applicationName", "/myapp");
config2.Add("passwordStrengthRegularExpression", ".*");
config2.Add("passwordFormat", "Clear");
provider2.Initialize(null, config2);
bool worked = provider2.ValidateUser("foo", "bar!bar");
Assert.AreEqual(false, worked);
}
/// <summary>
/// Bug #41408 PasswordReset not possible when requiresQuestionAndAnswer="false"
/// </summary>
[Test]
public void ResetPassword()
{
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("applicationName", "/");
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", "Clear");
config.Add("requiresQuestionAndAnswer", "false");
provider.Initialize(null, config);
MembershipCreateStatus status;
provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status);
MembershipUser u = provider.GetUser("foo", false);
string newpw = provider.ResetPassword("foo", null);
}
/// <summary>
/// Bug #59438 setting Membership.ApplicationName has no effect
/// </summary>
[Test]
public void ChangeAppName()
{
provider = new MySQLMembershipProvider();
NameValueCollection config = new NameValueCollection();
config.Add("connectionStringName", "LocalMySqlServer");
config.Add("applicationName", "/");
config.Add("passwordStrengthRegularExpression", "bar.*");
config.Add("passwordFormat", "Clear");
provider.Initialize(null, config);
MembershipCreateStatus status;
provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status);
Assert.IsTrue(status == MembershipCreateStatus.Success);
MySQLMembershipProvider provider2 = new MySQLMembershipProvider();
NameValueCollection config2 = new NameValueCollection();
config2.Add("connectionStringName", "LocalMySqlServer");
config2.Add("applicationName", "/myapp");
config2.Add("passwordStrengthRegularExpression", "foo.*");
config2.Add("passwordFormat", "Clear");
provider2.Initialize(null, config2);
provider2.CreateUser("foo2", "foo!foo", null, null, null, true, null, out status);
Assert.IsTrue(status == MembershipCreateStatus.Success);
provider.ApplicationName = "/myapp";
Assert.IsFalse(provider.ValidateUser("foo", "bar!bar"));
Assert.IsTrue(provider.ValidateUser("foo2", "foo!foo"));
}
[Test]
public void GetUserLooksForExactUsername()
{
MembershipCreateStatus status;
Membership.CreateUser("code", "thecode!", null, "question", "answer", true, out status);
MembershipUser user = Membership.GetUser("code");
Assert.AreEqual("code", user.UserName);
user = Membership.GetUser("co_e");
Assert.IsNull(user);
}
[Test]
public void GetUserNameByEmailLooksForExactEmail()
{
MembershipCreateStatus status;
Membership.CreateUser("code", "thecode!", "code@mysql.com", "question", "answer", true, out status);
string username = Membership.GetUserNameByEmail("code@mysql.com");
Assert.AreEqual("code", username);
username = Membership.GetUserNameByEmail("co_e@mysql.com");
Assert.IsNull(username);
}
}
}
|
noahvans/mariadb-connector-net
|
Legacy/Tests/MariaDB.Web.Tests/UserManagement.cs
|
C#
|
lgpl-3.0
| 23,494 |
package com.sirma.itt.seip.definition;
import java.lang.invoke.MethodHandles;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.enterprise.context.ContextNotActiveException;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sirma.itt.seip.domain.definition.DefinitionModel;
import com.sirma.itt.seip.domain.definition.PropertyDefinition;
import com.sirma.itt.seip.domain.instance.Instance;
import com.sirma.itt.seip.domain.instance.InstancePropertyNameResolver;
/**
* Default implementation of the {@link InstancePropertyNameResolver} that uses a request scoped cache to store already
* resolved definitions for an instance in order to provide better performance. If request context is not available
* then the resolver will fall back to on demand definition lookup.
*
* @author <a href="mailto:borislav.bonev@sirma.bg">Borislav Bonev</a>
* @since 19/07/2018
*/
public class InstancePropertyNameResolverImpl implements InstancePropertyNameResolver {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
@Inject
private DefinitionService definitionService;
@Inject
private InstancePropertyNameResolverCache cache;
@Override
public String resolve(Instance instance, String fieldUri) {
return getOrResolveModel(instance)
.getField(fieldUri)
.map(PropertyDefinition::getName)
.orElse(fieldUri);
}
private DefinitionModel getOrResolveModel(Instance instance) {
try {
return cache.getOrResolveModel(instance.getId(), resolveDefinition(instance));
} catch (ContextNotActiveException e) {
// for the cases when this is used outside of a transaction like parallel stream processing
return resolveDefinition(instance).get();
}
}
@Override
public Function<String, String> resolverFor(Instance instance) {
DefinitionModel model = getOrResolveModel(instance);
return property -> model.getField(property)
.map(PropertyDefinition::getName)
.orElse(property);
}
private Supplier<DefinitionModel> resolveDefinition(Instance instance) {
return () -> {
LOGGER.trace("Resolving model for {}", instance.getId());
return definitionService.getInstanceDefinition(instance);
};
}
}
|
SirmaITT/conservation-space-1.7.0
|
docker/sirma-platform/platform/seip-parent/model-management/definition-core/src/main/java/com/sirma/itt/seip/definition/InstancePropertyNameResolverImpl.java
|
Java
|
lgpl-3.0
| 2,269 |
/**
* \file components/gpp/stack/CoordinatorMobility/CoordinatorMobilityComponent.cpp
* \version 1.0
*
* \section COPYRIGHT
*
* Copyright 2012 The Iris Project Developers. See the
* COPYRIGHT file at the top-level directory of this distribution
* and at http://www.softwareradiosystems.com/iris/copyright.html.
*
* \section LICENSE
*
* This file is part of the Iris Project.
*
* Iris 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.
*
* Iris 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.
*
* A copy of the GNU General Public License can be found in
* the LICENSE file in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/.
*
* \section DESCRIPTION
*
* Implementation of a mobility protocol that has a coordinator that
* determines a backup channel for a set of follower nodes.
*
*/
#include "irisapi/LibraryDefs.h"
#include "irisapi/Version.h"
#include "CoordinatorMobilityComponent.h"
using namespace std;
using namespace boost;
namespace iris
{
// export library symbols
IRIS_COMPONENT_EXPORTS(StackComponent, CoordinatorMobilityComponent);
CoordinatorMobilityComponent::CoordinatorMobilityComponent(std::string name)
: FllStackComponent(name,
"coordinatorcstackcomponent",
"A very simple mobility protocol with coordinator/follower roles",
"Andre Puschmann",
"0.1")
{
//Format: registerParameter(name, description, default, dynamic?, parameter, allowed values);
registerParameter("role", "Role of node", "coordinator", false, role_x);
registerParameter("updateinterval", "Interval between BC updates", "1000", true, updateInterval_x);
registerParameter("querydrm", "Whether to use DRM to determine backupchannel", "false", true, queryDrm_x);
//Format: registerEvent(name, description, data type);
registerEvent("EvGetAvailableChannelsRequest", "Retrieve list of available channels from FllController", TypeInfo< int32_t >::identifier);
registerEvent("EvGetOperatingChannelRequest", "Retrieve current operating channel from FllController", TypeInfo< int32_t >::identifier);
registerEvent("EvUpdateBackupChannel", "Set new backup channel", TypeInfo< int32_t >::identifier);
}
CoordinatorMobilityComponent::~CoordinatorMobilityComponent()
{
}
void CoordinatorMobilityComponent::initialize()
{
// turn off logging to file, system will take care of closing file handle
//LoggingPolicy::getPolicyInstance()->setFileStream(NULL);
}
void CoordinatorMobilityComponent::processMessageFromAbove(boost::shared_ptr<StackDataSet> incomingFrame)
{
//StackHelper::printDataset(incomingFrame, "vanilla from above");
}
void CoordinatorMobilityComponent::processMessageFromBelow(boost::shared_ptr<StackDataSet> incomingFrame)
{
//StackHelper::printDataset(incomingFrame, "vanilla from below");
MobilityPacket updatePacket;
StackHelper::deserializeAndStripDataset(incomingFrame, updatePacket);
switch(updatePacket.type()) {
case MobilityPacket::UPDATE_BC:
{
if (updatePacket.source() == MobilityPacket::COORDINATOR) {
// take first channel in update packet as backup channel
if (updatePacket.channelmap_size() > 0) {
MobilityChannel *mobilityChannel = updatePacket.mutable_channelmap(0);
FllChannel fllChannel = MobilityChannelToFllChannel(mobilityChannel);
LOG(LINFO) << "Received new backup channel from coordinator: " << fllChannel.getFreq() << "Hz.";
setBackupChannel(fllChannel);
}
}
break;
}
default:
LOG(LERROR) << "Undefined packet type.";
break;
} // switch
}
void CoordinatorMobilityComponent::start()
{
// start beaconing thread in coordinator mode
LOG(LINFO) << "I am a " << role_x << " node.";
if (role_x == "coordinator") {
LOG(LINFO) << "Start beaconing thread ..";
beaconingThread_.reset(new boost::thread(boost::bind( &CoordinatorMobilityComponent::beaconingThreadFunction, this)));
} else
if (role_x == "follower") {
LOG(LINFO) << "I am waiting for beacons ..";
} else {
LOG(LERROR) << "Mode is not defined: " << role_x;
}
FllChannelVector channels = getAvailableChannels();
LOG(LINFO) << "No of channels: " << channels.size();
}
void CoordinatorMobilityComponent::stop()
{
// stop threads
if (beaconingThread_) {
beaconingThread_->interrupt();
beaconingThread_->join();
}
}
void CoordinatorMobilityComponent::beaconingThreadFunction()
{
boost::this_thread::sleep(boost::posix_time::seconds(1));
LOG(LINFO) << "Beaconing thread started.";
try
{
while(true)
{
boost::this_thread::interruption_point();
// determine backup channel and transmit beacon
FllChannel bc;
if (findBackupChannel(bc) == true) {
setBackupChannel(bc);
sendUpdateBackupChannelPacket(bc);
}
// sleep until next beacon
boost::this_thread::sleep(boost::posix_time::milliseconds(updateInterval_x));
} // while
}
catch(IrisException& ex)
{
LOG(LFATAL) << "Error in CoordinatorMobility component: " << ex.what() << " - Beaconing thread exiting.";
}
catch(boost::thread_interrupted)
{
LOG(LINFO) << "Thread " << boost::this_thread::get_id() << " in stack component interrupted.";
}
}
void CoordinatorMobilityComponent::sendUpdateBackupChannelPacket(FllChannel backupChannel)
{
MobilityPacket updatePacket;
updatePacket.set_source(MobilityPacket::COORDINATOR);
updatePacket.set_destination(MobilityPacket::FOLLOWER);
updatePacket.set_type(MobilityPacket::UPDATE_BC);
MobilityChannel *channel = updatePacket.add_channelmap();
FllChannelToMobilityChannel(backupChannel, channel);
shared_ptr<StackDataSet> buffer(new StackDataSet);
StackHelper::mergeAndSerializeDataset(buffer, updatePacket);
//StackHelper::printDataset(buffer, "UpdateBC packet Tx");
sendDownwards(buffer);
LOG(LINFO) << "Tx UpdateBC packet ";
}
void CoordinatorMobilityComponent::FllChannelToMobilityChannel(const FllChannel fllchannel, MobilityChannel *mobilityChannel)
{
mobilityChannel->set_f_center(fllchannel.getFreq());
mobilityChannel->set_bandwidth(fllchannel.getBandwidth());
switch (fllchannel.getState()) {
case FREE: mobilityChannel->set_status(MobilityChannel_Status_FREE); break;
case BUSY_SU: mobilityChannel->set_status(MobilityChannel_Status_BUSY_SU); break;
case BUSY_PU: mobilityChannel->set_status(MobilityChannel_Status_BUSY_PU); break;
default: LOG(LERROR) << "Unknown channel state.";
}
}
FllChannel CoordinatorMobilityComponent::MobilityChannelToFllChannel(MobilityChannel *mobilityChannel)
{
FllChannel channel;
channel.setFreq(mobilityChannel->f_center());
channel.setBandwidth(mobilityChannel->bandwidth());
switch (mobilityChannel->status()) {
case MobilityChannel_Status_FREE: channel.setState(FREE); break;
case MobilityChannel_Status_BUSY_SU: channel.setState(BUSY_SU); break;
case MobilityChannel_Status_BUSY_PU: channel.setState(BUSY_PU); break;
default: LOG(LERROR) << "Unknown channel state.";
}
return channel;
}
bool CoordinatorMobilityComponent::findBackupChannel(FllChannel& bc)
{
FllChannelVector channels = getAvailableChannels();
FllChannel operatingChannel = getOperatingChannel(0); // get operating channel of primary receiver, i.e. trx 0
#if OSPECORR
if (queryDrm_x) {
bool ret = FllDrmHelper::getChannel(bc);
if (ret == true && bc != operatingChannel) {
// success, got valid backup channel from DRM
LOG(LINFO) << "Got backup channel at " << bc.getFreq() << " from DRM.";
return true;
} else {
return false;
}
}
#endif
// find free channel other than operating channel in set of available channels
FllChannelVector::iterator it;
bool channelFound = false;
for (it = channels.begin(); it != channels.end(); ++it) {
if (it->getState() == FREE && *it != operatingChannel) {
LOG(LINFO) << "Free channel found: " << it->getFreq() << "Hz.";
bc = *it;
channelFound = true;
break;
}
}
if (not channelFound) {
LOG(LERROR) << "No free backup channel found. Skip update.";
}
return channelFound;
}
} /* namespace iris */
|
andrepuschmann/iris_fll_modules
|
components/gpp/stack/CoordinatorMobility/CoordinatorMobilityComponent.cpp
|
C++
|
lgpl-3.0
| 9,079 |
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
Plot cost evolution
@author: verlaanm
"""
# ex1
#load numpy and matplotlib if needed
import matplotlib.pyplot as plt
#load data
import dud_results as dud
# create plot of cost and parameter
plt.close("all")
f,ax = plt.subplots(2,1)
ax[0].plot(dud.costTotal);
ax[0].set_xlabel("model run");
ax[0].set_ylabel("cost function");
ax[1].plot(dud.evaluatedParameters);
ax[1].set_xlabel('model run');
ax[1].set_ylabel('change of reaction\_time [seconds]');
|
OpenDA-Association/OpenDA
|
course/exercise_black_box_calibration_polution_NOT_WORKING/plot_cost.py
|
Python
|
lgpl-3.0
| 504 |
// Copyright 2019 The Swarm Authors
// This file is part of the Swarm library.
//
// The Swarm library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The Swarm library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the Swarm library. If not, see <http://www.gnu.org/licenses/>.
package stream
import (
"bytes"
"context"
"encoding/hex"
"fmt"
"io/ioutil"
"os"
"runtime"
"sync"
"testing"
"time"
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethersphere/swarm/chunk"
"github.com/ethersphere/swarm/log"
"github.com/ethersphere/swarm/network"
"github.com/ethersphere/swarm/network/simulation"
"github.com/ethersphere/swarm/p2p/protocols"
"github.com/ethersphere/swarm/pot"
"github.com/ethersphere/swarm/storage"
"github.com/ethersphere/swarm/storage/localstore"
"github.com/ethersphere/swarm/testutil"
)
var timeout = 90 * time.Second
// TestTwoNodesSyncWithGaps tests that syncing works with gaps in the localstore intervals
func TestTwoNodesSyncWithGaps(t *testing.T) {
// construct a pauser before simulation is started and reset it to nil after all streams are closed
// to avoid the need for protecting handleMsgPauser with a lock in production code.
handleMsgPauser = new(syncPauser)
defer func() { handleMsgPauser = nil }()
removeChunks := func(t *testing.T, ctx context.Context, store chunk.Store, gaps [][2]uint64, chunks []chunk.Address) (removedCount uint64) {
t.Helper()
for _, gap := range gaps {
for i := gap[0]; i < gap[1]; i++ {
c := chunks[i]
if err := store.Set(ctx, chunk.ModeSetRemove, c); err != nil {
t.Fatal(err)
}
removedCount++
}
}
return removedCount
}
for _, tc := range []struct {
name string
chunkCount uint64
gaps [][2]uint64
liveChunkCount uint64
liveGaps [][2]uint64
}{
{
name: "no gaps",
chunkCount: 100,
gaps: nil,
},
{
name: "first chunk removed",
chunkCount: 100,
gaps: [][2]uint64{{0, 1}},
},
{
name: "one chunk removed",
chunkCount: 100,
gaps: [][2]uint64{{60, 61}},
},
{
name: "single gap at start",
chunkCount: 100,
gaps: [][2]uint64{{0, 5}},
},
{
name: "single gap",
chunkCount: 100,
gaps: [][2]uint64{{5, 10}},
},
{
name: "multiple gaps",
chunkCount: 100,
gaps: [][2]uint64{{0, 1}, {10, 21}},
},
{
name: "big gaps",
chunkCount: 100,
gaps: [][2]uint64{{0, 1}, {10, 21}, {50, 91}},
},
{
name: "remove all",
chunkCount: 100,
gaps: [][2]uint64{{0, 100}},
},
{
name: "large db",
chunkCount: 4000,
},
{
name: "large db with gap",
chunkCount: 4000,
gaps: [][2]uint64{{1000, 3000}},
},
{
name: "live",
liveChunkCount: 100,
},
{
name: "live and history",
chunkCount: 100,
liveChunkCount: 100,
},
{
name: "live and history with history gap",
chunkCount: 100,
gaps: [][2]uint64{{5, 10}},
liveChunkCount: 100,
},
{
name: "live and history with live gap",
chunkCount: 100,
liveChunkCount: 100,
liveGaps: [][2]uint64{{105, 110}},
},
{
name: "live and history with gaps",
chunkCount: 100,
gaps: [][2]uint64{{5, 10}},
liveChunkCount: 100,
liveGaps: [][2]uint64{{105, 110}},
},
} {
t.Run(tc.name, func(t *testing.T) {
sim := simulation.NewBzzInProc(map[string]simulation.ServiceFunc{
"bzz-sync": newSyncSimServiceFunc(&SyncSimServiceOptions{Autostart: true}),
}, false)
defer sim.Close()
defer catchDuplicateChunkSync(t)()
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
uploadNode, err := sim.AddNode()
if err != nil {
t.Fatal(err)
}
uploadStore := sim.MustNodeItem(uploadNode, bucketKeyFileStore).(chunk.Store)
chunks := mustUploadChunks(ctx, t, uploadStore, tc.chunkCount)
totalChunkCount, err := getChunkCount(uploadStore)
if err != nil {
t.Fatal(err)
}
if totalChunkCount != tc.chunkCount {
t.Errorf("uploaded %v chunks, want %v", totalChunkCount, tc.chunkCount)
}
removedCount := removeChunks(t, ctx, uploadStore, tc.gaps, chunks)
syncNode, err := sim.AddNode()
if err != nil {
t.Fatal(err)
}
err = sim.Net.Connect(uploadNode, syncNode)
if err != nil {
t.Fatal(err)
}
syncStore := sim.MustNodeItem(syncNode, bucketKeyFileStore).(chunk.Store)
err = waitChunks(syncStore, totalChunkCount-removedCount, 10*time.Second)
if err != nil {
t.Fatal(err)
}
if tc.liveChunkCount > 0 {
// pause syncing so that the chunks in the live gap
// are not synced before they are removed
handleMsgPauser.Pause()
chunks = append(chunks, mustUploadChunks(ctx, t, uploadStore, tc.liveChunkCount)...)
removedCount += removeChunks(t, ctx, uploadStore, tc.liveGaps, chunks)
// resume syncing
handleMsgPauser.Resume()
err = waitChunks(syncStore, tc.chunkCount+tc.liveChunkCount-removedCount, time.Minute)
if err != nil {
t.Fatal(err)
}
}
})
}
}
// TestTheeNodesUnionHistoricalSync brings up three nodes, uploads content too all of them and then
// asserts that all of them have the union of all 3 local stores (depth is assumed to be 0)
func TestThreeNodesUnionHistoricalSync(t *testing.T) {
nodes := 3
chunkCount := 1000
sim := simulation.NewBzzInProc(map[string]simulation.ServiceFunc{
"bzz-sync": newSyncSimServiceFunc(&SyncSimServiceOptions{Autostart: true}),
}, false)
defer sim.Close()
union := make(map[string]struct{})
nodeIDs := []enode.ID{}
for i := 0; i < nodes; i++ {
node, err := sim.AddNode()
if err != nil {
t.Fatal(err)
}
nodeIDs = append(nodeIDs, node)
nodeStore := sim.MustNodeItem(node, bucketKeyFileStore).(*storage.FileStore)
mustUploadChunks(context.Background(), t, nodeStore, uint64(chunkCount))
uploadedChunks, err := getChunks(nodeStore.ChunkStore)
if err != nil {
t.Fatal(err)
}
for k := range uploadedChunks {
if _, ok := union[k]; ok {
t.Fatal("chunk already exists in union")
}
union[k] = struct{}{}
}
}
err := sim.Net.ConnectNodesFull(nodeIDs)
if err != nil {
t.Fatal(err)
}
for _, n := range nodeIDs {
nodeStore := sim.MustNodeItem(n, bucketKeyFileStore).(*storage.FileStore)
if err := waitChunks(nodeStore, uint64(len(union)), 10*time.Second); err != nil {
t.Fatal(err)
}
}
}
// TestFullSync performs a series of subtests where a number of nodes are
// connected to the single (chunk uploading) node.
func TestFullSync(t *testing.T) {
for _, tc := range []struct {
name string
chunkCount uint64
syncNodeCount int
history bool
live bool
}{
{
name: "sync to two nodes history",
chunkCount: 5000,
syncNodeCount: 2,
history: true,
},
{
name: "sync to two nodes live",
chunkCount: 5000,
syncNodeCount: 2,
live: true,
},
{
name: "sync to two nodes history and live",
chunkCount: 2500,
syncNodeCount: 2,
history: true,
live: true,
},
{
name: "sync to 50 nodes history",
chunkCount: 500,
syncNodeCount: 50,
history: true,
},
{
name: "sync to 50 nodes live",
chunkCount: 500,
syncNodeCount: 50,
live: true,
},
{
name: "sync to 50 nodes history and live",
chunkCount: 250,
syncNodeCount: 50,
history: true,
live: true,
},
} {
t.Run(tc.name, func(t *testing.T) {
if tc.syncNodeCount > 2 && runtime.GOARCH == "386" {
t.Skip("skipping larger simulation on low memory architecture")
}
sim := simulation.NewInProc(map[string]simulation.ServiceFunc{
"bzz-sync": newSyncSimServiceFunc(&SyncSimServiceOptions{Autostart: true}),
})
defer sim.Close()
defer catchDuplicateChunkSync(t)()
uploaderNode, err := sim.AddNode()
if err != nil {
t.Fatal(err)
}
uploaderNodeStore := sim.MustNodeItem(uploaderNode, bucketKeyFileStore).(*storage.FileStore)
if tc.history {
mustUploadChunks(context.Background(), t, uploaderNodeStore, tc.chunkCount)
}
// add nodes to sync to
ids, err := sim.AddNodes(tc.syncNodeCount)
if err != nil {
t.Fatal(err)
}
// connect every new node to the uploading one, so
// every node will have depth 0 as only uploading node
// will be in their kademlia tables
err = sim.Net.ConnectNodesStar(ids, uploaderNode)
if err != nil {
t.Fatal(err)
}
// count the content in the bins again
uploadedChunks, err := getChunks(uploaderNodeStore.ChunkStore)
if err != nil {
t.Fatal(err)
}
if tc.history && len(uploadedChunks) == 0 {
t.Errorf("got empty uploader chunk store")
}
if !tc.history && len(uploadedChunks) != 0 {
t.Errorf("got non empty uploader chunk store")
}
historicalChunks := make(map[enode.ID]map[string]struct{})
for _, id := range ids {
wantChunks := make(map[string]struct{}, len(uploadedChunks))
for k, v := range uploadedChunks {
wantChunks[k] = v
}
// wait for all chunks to be synced
store := sim.MustNodeItem(id, bucketKeyFileStore).(chunk.Store)
if err := waitChunks(store, uint64(len(wantChunks)), 10*time.Second); err != nil {
t.Fatal(err)
}
// validate that all and only all chunks are synced
syncedChunks, err := getChunks(store)
if err != nil {
t.Fatal(err)
}
historicalChunks[id] = make(map[string]struct{})
for c := range wantChunks {
if _, ok := syncedChunks[c]; !ok {
t.Errorf("missing chunk %v", c)
}
delete(wantChunks, c)
delete(syncedChunks, c)
historicalChunks[id][c] = struct{}{}
}
if len(wantChunks) != 0 {
t.Errorf("some of the uploaded chunks are not synced")
}
if len(syncedChunks) != 0 {
t.Errorf("some of the synced chunks are not of uploaded ones")
}
}
if tc.live {
mustUploadChunks(context.Background(), t, uploaderNodeStore, tc.chunkCount)
}
uploadedChunks, err = getChunks(uploaderNodeStore.ChunkStore)
if err != nil {
t.Fatal(err)
}
for _, id := range ids {
wantChunks := make(map[string]struct{}, len(uploadedChunks))
for k, v := range uploadedChunks {
wantChunks[k] = v
}
store := sim.MustNodeItem(id, bucketKeyFileStore).(chunk.Store)
// wait for all chunks to be synced
if err := waitChunks(store, uint64(len(wantChunks)), 10*time.Second); err != nil {
t.Fatal(err)
}
// get all chunks from the syncing node
syncedChunks, err := getChunks(store)
if err != nil {
t.Fatal(err)
}
// remove historical chunks from total uploaded and synced chunks
for c := range historicalChunks[id] {
if _, ok := wantChunks[c]; !ok {
t.Errorf("missing uploaded historical chunk: %s", c)
}
delete(wantChunks, c)
if _, ok := syncedChunks[c]; !ok {
t.Errorf("missing synced historical chunk: %s", c)
}
delete(syncedChunks, c)
}
// validate that all and only all live chunks are synced
for c := range wantChunks {
if _, ok := syncedChunks[c]; !ok {
t.Errorf("missing chunk %v", c)
}
delete(wantChunks, c)
delete(syncedChunks, c)
}
if len(wantChunks) != 0 {
t.Errorf("some of the uploaded live chunks are not synced")
}
if len(syncedChunks) != 0 {
t.Errorf("some of the synced live chunks are not of uploaded ones")
}
}
})
}
}
func waitChunks(store chunk.Store, want uint64, staledTimeout time.Duration) (err error) {
start := time.Now()
var (
count uint64 // total number of chunks
prev uint64 // total number of chunks in previous check
sleep time.Duration // duration until the next check
staled time.Duration // duration for when the number of chunks is the same
)
for staled < staledTimeout { // wait for some time while staled
count, err = getChunkCount(store)
if err != nil {
return err
}
if count >= want {
break
}
if count == prev {
staled += sleep
} else {
staled = 0
}
prev = count
if count > 0 {
// Calculate sleep time only if there is at least 1% of chunks available,
// less may produce unreliable result.
if count > want/100 {
// Calculate the time required to pass for missing chunks to be available,
// and divide it by half to perform a check earlier.
sleep = time.Duration(float64(time.Since(start)) * float64(want-count) / float64(count) / 2)
log.Debug("expecting all chunks", "in", sleep*2, "want", want, "have", count)
}
}
switch {
case sleep > time.Minute:
// next check and speed calculation in some shorter time
sleep = 500 * time.Millisecond
case sleep > 5*time.Second:
// upper limit for the check, do not check too slow
sleep = 5 * time.Second
case sleep < 50*time.Millisecond:
// lower limit for the check, do not check too frequently
sleep = 50 * time.Millisecond
if staled > 0 {
// slow down if chunks are stuck near the want value
sleep *= 10
}
}
time.Sleep(sleep)
}
if count != want {
return fmt.Errorf("got synced chunks %d, want %d", count, want)
}
return nil
}
func getChunkCount(store chunk.Store) (c uint64, err error) {
for po := 0; po <= chunk.MaxPO; po++ {
last, err := store.LastPullSubscriptionBinID(uint8(po))
if err != nil {
return 0, err
}
c += last
}
return c, nil
}
func getChunks(store chunk.Store) (chunks map[string]struct{}, err error) {
chunks = make(map[string]struct{})
for po := uint8(0); po <= chunk.MaxPO; po++ {
last, err := store.LastPullSubscriptionBinID(po)
if err != nil {
return nil, err
}
if last == 0 {
continue
}
ch, _ := store.SubscribePull(context.Background(), po, 0, last)
for c := range ch {
addr := c.Address.Hex()
if _, ok := chunks[addr]; ok {
return nil, fmt.Errorf("duplicate chunk %s", addr)
}
chunks[addr] = struct{}{}
}
}
return chunks, nil
}
/*
BenchmarkHistoricalStream measures syncing time after two nodes connect.
go test -v github.com/ethersphere/swarm/network/stream/v2 -run="^$" -bench BenchmarkHistoricalStream -benchmem -loglevel 0
goos: darwin
goarch: amd64
pkg: github.com/ethersphere/swarm/network/stream/v2
BenchmarkHistoricalStream/1000-chunks-8 10 133564663 ns/op 148289188 B/op 233646 allocs/op
BenchmarkHistoricalStream/2000-chunks-8 5 290056259 ns/op 316599452 B/op 541507 allocs/op
BenchmarkHistoricalStream/10000-chunks-8 1 1714618578 ns/op 1791108672 B/op 4133564 allocs/op
BenchmarkHistoricalStream/20000-chunks-8 1 4724760666 ns/op 4133092720 B/op 11347504 allocs/op
PASS
*/
func BenchmarkHistoricalStream(b *testing.B) {
for _, c := range []uint64{
1000,
2000,
10000,
20000,
} {
b.Run(fmt.Sprintf("%v-chunks", c), func(b *testing.B) {
benchmarkHistoricalStream(b, c)
})
}
}
func benchmarkHistoricalStream(b *testing.B, chunks uint64) {
b.StopTimer()
for i := 0; i < b.N; i++ {
sim := simulation.NewBzzInProc(map[string]simulation.ServiceFunc{
"bzz-sync": newSyncSimServiceFunc(&SyncSimServiceOptions{Autostart: true}),
}, false)
uploaderNode, err := sim.AddNode()
if err != nil {
b.Fatal(err)
}
uploaderNodeStore := nodeFileStore(sim, uploaderNode)
mustUploadChunks(context.Background(), b, uploaderNodeStore, chunks)
uploadedChunks, err := getChunks(uploaderNodeStore.ChunkStore)
if err != nil {
b.Fatal(err)
}
syncingNode, err := sim.AddNode()
if err != nil {
b.Fatal(err)
}
b.StartTimer()
err = sim.Net.Connect(syncingNode, uploaderNode)
if err != nil {
b.Fatal(err)
}
syncingNodeStore := sim.MustNodeItem(syncingNode, bucketKeyFileStore).(chunk.Store)
if err := waitChunks(syncingNodeStore, uint64(len(uploadedChunks)), 10*time.Second); err != nil {
b.Fatal(err)
}
b.StopTimer()
err = sim.Net.Stop(syncingNode)
if err != nil {
b.Fatal(err)
}
sim.Close()
}
}
// Function that uses putSeenTestHook to record and report
// if there were duplicate chunk synced between Node id
func catchDuplicateChunkSync(t *testing.T) (validate func()) {
m := make(map[enode.ID]map[string]int)
var mu sync.Mutex
putSeenTestHook = func(addr chunk.Address, id enode.ID) {
mu.Lock()
defer mu.Unlock()
if _, ok := m[id]; !ok {
m[id] = make(map[string]int)
}
m[id][addr.Hex()]++
}
return func() {
// reset the test hook
putSeenTestHook = nil
// do the validation
mu.Lock()
defer mu.Unlock()
for nodeID, addrs := range m {
for addr, count := range addrs {
t.Errorf("chunk synced %v times to node %s: %v", count, nodeID, addr)
}
}
}
}
// TestStarNetworkSyncWithBogusNodes ests that syncing works on a more elaborate network topology
// the test creates three real nodes in a star topology, then adds bogus nodes to the pivot (instead of using real nodes
// this is in order to make the simulation be more CI friendly)
// the pivot node will have neighbourhood depth > 0, which in turn means that from each
// connected node, the pivot node should have only part of its chunks
// The test checks that EVERY chunk that exists a node which is not the pivot, according to
// its PO, and kademlia table of the pivot - exists on the pivot node and does not exist on other nodes
func TestStarNetworkSyncWithBogusNodes(t *testing.T) {
var (
chunkCount = 500
nodeCount = 12
minPivotDepth = 1
chunkSize = 4096
simTimeout = 60 * time.Second
syncTime = 4 * time.Second
filesize = chunkCount * chunkSize
opts = &SyncSimServiceOptions{SyncOnlyWithinDepth: false, Autostart: true}
)
sim := simulation.NewBzzInProc(map[string]simulation.ServiceFunc{
"bzz-sync": newSyncSimServiceFunc(opts),
}, false)
defer sim.Close()
ctx, cancel := context.WithTimeout(context.Background(), simTimeout)
defer cancel()
pivot, err := sim.AddNode()
if err != nil {
t.Fatal(err)
}
pivotKad := sim.MustNodeItem(pivot, simulation.BucketKeyKademlia).(*network.Kademlia)
pivotBase := pivotKad.BaseAddr()
log.Debug("started pivot node", "addr", hex.EncodeToString(pivotBase))
newNode, err := sim.AddNode()
if err != nil {
t.Fatal(err)
}
err = sim.Net.Connect(pivot, newNode)
if err != nil {
t.Fatal(err)
}
newNode2, err := sim.AddNode()
if err != nil {
t.Fatal(err)
}
err = sim.Net.Connect(pivot, newNode2)
if err != nil {
t.Fatal(err)
}
time.Sleep(50 * time.Millisecond)
log.Trace(sim.MustNodeItem(newNode, simulation.BucketKeyKademlia).(*network.Kademlia).String())
pivotKad = sim.MustNodeItem(pivot, simulation.BucketKeyKademlia).(*network.Kademlia)
pivotAddr := pot.NewAddressFromBytes(pivotBase)
// add a few fictional nodes at higher POs to uploader so that uploader depth goes > 0
for i := 0; i < nodeCount; i++ {
rw := &p2p.MsgPipeRW{}
ptpPeer := p2p.NewPeer(enode.ID{}, "im just a lazy hobo", []p2p.Cap{})
protoPeer := protocols.NewPeer(ptpPeer, rw, &protocols.Spec{})
peerAddr := pot.RandomAddressAt(pivotAddr, i)
bzzPeer := &network.BzzPeer{
Peer: protoPeer,
BzzAddr: network.NewBzzAddr(peerAddr.Bytes(), nil),
}
peer := network.NewPeer(bzzPeer, pivotKad)
pivotKad.On(peer)
}
time.Sleep(50 * time.Millisecond)
log.Trace(pivotKad.String())
if d := pivotKad.NeighbourhoodDepth(); d < minPivotDepth {
t.Skipf("too shallow. depth %d want %d", d, minPivotDepth)
}
pivotDepth := pivotKad.NeighbourhoodDepth()
chunkProx := make(map[string]chunkProxData)
result := sim.Run(ctx, func(ctx context.Context, sim *simulation.Simulation) (err error) {
nodeIDs := sim.UpNodeIDs()
for _, node := range nodeIDs {
node := node
if bytes.Equal(pivot.Bytes(), node.Bytes()) {
continue
}
nodeKad := sim.MustNodeItem(node, simulation.BucketKeyKademlia).(*network.Kademlia)
nodePo := chunk.Proximity(nodeKad.BaseAddr(), pivotKad.BaseAddr())
seed := int(time.Now().UnixNano())
randomBytes := testutil.RandomBytes(seed, filesize)
log.Debug("putting chunks to ephemeral localstore")
chunkAddrs, err := getAllRefs(randomBytes[:])
if err != nil {
return err
}
log.Debug("done getting all refs")
for _, c := range chunkAddrs {
proxData := chunkProxData{
addr: c,
uploaderNodeToPivotNodePO: nodePo,
chunkToUploaderPO: chunk.Proximity(nodeKad.BaseAddr(), c),
pivotPO: chunk.Proximity(c, pivotKad.BaseAddr()),
uploaderNode: node,
}
log.Debug("test putting chunk", "node", node, "addr", hex.EncodeToString(c), "uploaderToPivotPO", proxData.uploaderNodeToPivotNodePO, "c2uploaderPO", proxData.chunkToUploaderPO, "pivotDepth", pivotDepth)
if _, ok := chunkProx[hex.EncodeToString(c)]; ok {
return fmt.Errorf("chunk already found on another node %s", hex.EncodeToString(c))
}
chunkProx[hex.EncodeToString(c)] = proxData
}
fs := sim.MustNodeItem(node, bucketKeyFileStore).(*storage.FileStore)
reader := bytes.NewReader(randomBytes[:])
_, wait1, err := fs.Store(ctx, reader, int64(len(randomBytes)), false)
if err != nil {
return fmt.Errorf("fileStore.Store: %v", err)
}
if err := wait1(ctx); err != nil {
return err
}
}
//according to old pull sync - if the node is outside of depth - it should have all chunks where po(chunk)==po(node)
time.Sleep(syncTime)
pivotLs := sim.MustNodeItem(pivot, bucketKeyLocalStore).(*localstore.DB)
verifyCorrectChunksOnPivot(t, chunkProx, pivotDepth, pivotLs)
return nil
})
if result.Error != nil {
t.Fatal(result.Error)
}
}
// verifyCorrectChunksOnPivot checks which chunks should be present on the
// pivot node from the perspective of the pivot node. All streams established
// should be presumed from the point of view of the pivot and presence of
// chunks should be assumed by po(chunk,uploader)
// for example, if the pivot has depth==1 and the po(pivot,uploader)==1, then
// all chunks that have po(chunk,uploader)==1 should be synced to the pivot
func verifyCorrectChunksOnPivot(t *testing.T, chunkProx map[string]chunkProxData, pivotDepth int, pivotLs *localstore.DB) {
t.Helper()
for _, v := range chunkProx {
// outside of depth
if v.uploaderNodeToPivotNodePO < pivotDepth {
// chunk PO to uploader == uploader node PO to pivot (i.e. chunk should be synced) - inclusive test
if v.chunkToUploaderPO == v.uploaderNodeToPivotNodePO {
//check that the chunk exists on the pivot when the chunkPo == uploaderPo
_, err := pivotLs.Get(context.Background(), chunk.ModeGetRequest, v.addr)
if err != nil {
t.Errorf("chunk errored. err %v uploaderNode %s poUploader %d uploaderToPivotPo %d chunk %s", err, v.uploaderNode.String(), v.chunkToUploaderPO, v.uploaderNodeToPivotNodePO, hex.EncodeToString(v.addr))
}
} else {
//chunk should not be synced - exclusion test
_, err := pivotLs.Get(context.Background(), chunk.ModeGetRequest, v.addr)
if err == nil {
t.Errorf("chunk did not error but should have. uploaderNode %s poUploader %d uploaderToPivotPo %d chunk %s", v.uploaderNode.String(), v.chunkToUploaderPO, v.uploaderNodeToPivotNodePO, hex.EncodeToString(v.addr))
}
}
}
}
}
type chunkProxData struct {
addr chunk.Address
uploaderNodeToPivotNodePO int
chunkToUploaderPO int
uploaderNode enode.ID
pivotPO int
}
func getAllRefs(testData []byte) (storage.AddressCollection, error) {
datadir, err := ioutil.TempDir("", "chunk-debug")
if err != nil {
return nil, fmt.Errorf("unable to create temp dir: %v", err)
}
defer os.RemoveAll(datadir)
fileStore, cleanup, err := storage.NewLocalFileStore(datadir, make([]byte, 32), chunk.NewTags())
if err != nil {
return nil, err
}
defer cleanup()
reader := bytes.NewReader(testData)
return fileStore.GetAllReferences(context.Background(), reader)
}
|
ethersphere/go-ethereum
|
network/stream/syncing_test.go
|
GO
|
lgpl-3.0
| 24,602 |
<?php
/**
* @copyright Copyright (c) Metaways Infosystems GmbH, 2011
* @license LGPLv3, http://www.arcavias.com/en/license
* @package MShop
* @subpackage Order
*/
/**
* Default Manager Order service
*
* @package MShop
* @subpackage Order
*/
class MShop_Order_Manager_Base_Service_Default
extends MShop_Common_Manager_Abstract
implements MShop_Order_Manager_Base_Service_Interface
{
private $_searchConfig = array(
'order.base.service.id' => array(
'code' => 'order.base.service.id',
'internalcode' => 'mordbase."id"',
'internaldeps' => array( 'LEFT JOIN "mshop_order_base_service" AS mordbase ON ( mordba."id" = mordbase."baseid" )' ),
'label' => 'Order base service ID',
'type' => 'integer',
'internaltype' => MW_DB_Statement_Abstract::PARAM_INT,
'public' => false,
),
'order.base.service.siteid' => array(
'code' => 'order.base.service.siteid',
'internalcode' => 'mordbase."siteid"',
'label' => 'Order base service site ID',
'type' => 'integer',
'internaltype' => MW_DB_Statement_Abstract::PARAM_INT,
'public' => false,
),
'order.base.service.baseid' => array(
'code' => 'order.base.service.baseid',
'internalcode' => 'mordbase."baseid"',
'label' => 'Order base ID',
'type' => 'integer',
'internaltype' => MW_DB_Statement_Abstract::PARAM_INT,
'public' => false,
),
'order.base.service.serviceid' => array(
'code' => 'order.base.service.serviceid',
'internalcode' => 'mordbase."servid"',
'label' => 'Order base service original service ID',
'type' => 'string',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.type' => array(
'code' => 'order.base.service.type',
'internalcode' => 'mordbase."type"',
'label' => 'Order base service type',
'type' => 'string',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.code' => array(
'code' => 'order.base.service.code',
'internalcode' => 'mordbase."code"',
'label' => 'Order base service code',
'type' => 'string',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.name' => array(
'code' => 'order.base.service.name',
'internalcode' => 'mordbase."name"',
'label' => 'Order base service name',
'type' => 'string',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.mediaurl' => array(
'code'=>'order.base.service.mediaurl',
'internalcode'=>'mordbase."mediaurl"',
'label'=>'Order base service media url',
'type'=> 'string',
'internaltype'=> MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.price' => array(
'code' => 'order.base.service.price',
'internalcode' => 'mordbase."price"',
'label' => 'Order base service price',
'type' => 'decimal',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.costs' => array(
'code' => 'order.base.service.costs',
'internalcode' => 'mordbase."costs"',
'label' => 'Order base service shipping',
'type' => 'decimal',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.rebate' => array(
'code' => 'order.base.service.rebate',
'internalcode' => 'mordbase."rebate"',
'label' => 'Order base service rebate',
'type' => 'decimal',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.taxrate' => array(
'code' => 'order.base.service.taxrate',
'internalcode' => 'mordbase."taxrate"',
'label' => 'Order base service taxrate',
'type' => 'decimal',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.mtime' => array(
'code' => 'order.base.service.mtime',
'internalcode' => 'mordbase."mtime"',
'label' => 'Order base service modification time',
'type' => 'datetime',
'internaltype' => MW_DB_Statement_Abstract::PARAM_STR,
),
'order.base.service.ctime'=> array(
'code'=>'order.base.service.ctime',
'internalcode'=>'mordbase."ctime"',
'label'=>'Order base service create date/time',
'type'=> 'datetime',
'internaltype'=> MW_DB_Statement_Abstract::PARAM_STR
),
'order.base.service.editor'=> array(
'code'=>'order.base.service.editor',
'internalcode'=>'mordbase."editor"',
'label'=>'Order base service editor',
'type'=> 'string',
'internaltype'=> MW_DB_Statement_Abstract::PARAM_STR
),
);
/**
* Initializes the object.
*
* @param MShop_Context_Item_Interface $context Context object
*/
public function __construct( MShop_Context_Item_Interface $context )
{
parent::__construct( $context );
$this->_setResourceName( 'db-order' );
}
/**
* Removes old entries from the storage.
*
* @param integer[] $siteids List of IDs for sites whose entries should be deleted
*/
public function cleanup( array $siteids )
{
$path = 'classes/order/manager/base/service/submanagers';
foreach( $this->_getContext()->getConfig()->get( $path, array( 'attribute' ) ) as $domain ) {
$this->getSubManager( $domain )->cleanup( $siteids );
}
$this->_cleanup( $siteids, 'mshop/order/manager/base/service/default/item/delete' );
}
/**
* Creates new order service item object.
*
* @return MShop_Order_Item_Base_Service_Interface New object
*/
public function createItem()
{
$context = $this->_getContext();
$priceManager = MShop_Factory::createManager( $context, 'price' );
$values = array( 'siteid'=> $context->getLocale()->getSiteId() );
return $this->_createItem( $priceManager->createItem(), $values );
}
/**
* Adds or updates an order base service item to the storage.
*
* @param MShop_Common_Item_Interface $item Order base service object
* @param boolean $fetch True if the new ID should be returned in the item
*/
public function saveItem( MShop_Common_Item_Interface $item, $fetch = true )
{
$iface = 'MShop_Order_Item_Base_Service_Interface';
if( !( $item instanceof $iface ) ) {
throw new MShop_Order_Exception( sprintf( 'Object is not of required type "%1$s"', $iface ) );
}
if( !$item->isModified() ) { return; }
$context = $this->_getContext();
$dbm = $context->getDatabaseManager();
$dbname = $this->_getResourceName();
$conn = $dbm->acquire( $dbname );
try
{
$id = $item->getId();
$price = $item->getPrice();
$path = 'mshop/order/manager/base/service/default/item/';
$path .= ( $id === null ) ? 'insert' : 'update';
$stmt = $this->_getCachedStatement( $conn, $path );
$stmt->bind(1, $item->getBaseId(), MW_DB_Statement_Abstract::PARAM_INT);
$stmt->bind(2, $context->getLocale()->getSiteId(), MW_DB_Statement_Abstract::PARAM_INT);
$stmt->bind(3, $item->getServiceId(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(4, $item->getType(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(5, $item->getCode(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(6, $item->getName(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(7, $item->getMediaUrl(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(8, $price->getValue(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(9, $price->getCosts(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(10, $price->getRebate(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(11, $price->getTaxRate(), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(12, date('Y-m-d H:i:s', time()), MW_DB_Statement_Abstract::PARAM_STR);
$stmt->bind(13, $context->getEditor() );
if ( $id !== null ) {
$stmt->bind(14, $id, MW_DB_Statement_Abstract::PARAM_INT);
} else {
$stmt->bind(14, date( 'Y-m-d H:i:s', time() ), MW_DB_Statement_Abstract::PARAM_STR );// ctime
}
$stmt->execute()->finish();
if( $fetch === true )
{
if( $id === null ) {
$path = 'mshop/order/manager/base/service/default/item/newid';
$item->setId( $this->_newId( $conn, $context->getConfig()->get( $path, $path ) ) );
} else {
$item->setId($id);
}
}
$dbm->release( $conn, $dbname );
}
catch ( Exception $e )
{
$dbm->release( $conn, $dbname );
throw $e;
}
}
/**
* Removes multiple items specified by ids in the array.
*
* @param array $ids List of IDs
*/
public function deleteItems( array $ids )
{
$path = 'mshop/order/manager/base/service/default/item/delete';
$this->_deleteItems( $ids, $this->_getContext()->getConfig()->get( $path, $path ) );
}
/**
* Returns the order service item object for the given ID.
*
* @param integer $id Order service ID
* @param array $ref List of domains to fetch list items and referenced items for
* @return MShop_Order_Item_Base_Service_Interface Returns order base service item of the given id
* @throws MShop_Exception If item couldn't be found
*/
public function getItem( $id, array $ref = array() )
{
return $this->_getItem( 'order.base.service.id', $id, $ref );
}
/**
* Searches for order service items based on the given criteria.
*
* @param MW_Common_Criteria_Interface $search Search object containing the conditions
* @param array $ref Not used
* @param integer &$total Number of items that are available in total
* @return array List of items implementing MShop_Order_Item_Base_Service_Interface
*/
public function searchItems(MW_Common_Criteria_Interface $search, array $ref = array(), &$total = null)
{
$items = array();
$context = $this->_getContext();
$priceManager = MShop_Factory::createManager( $context, 'price' );
$dbm = $context->getDatabaseManager();
$dbname = $this->_getResourceName();
$conn = $dbm->acquire( $dbname );
try
{
$sitelevel = MShop_Locale_Manager_Abstract::SITE_SUBTREE;
$cfgPathSearch = 'mshop/order/manager/base/service/default/item/search';
$cfgPathCount = 'mshop/order/manager/base/service/default/item/count';
$required = array( 'order.base.service' );
$results = $this->_searchItems( $conn, $search, $cfgPathSearch, $cfgPathCount,
$required, $total, $sitelevel );
try
{
while( ( $row = $results->fetch() ) !== false )
{
$price = $priceManager->createItem();
$price->setValue($row['price']);
$price->setRebate($row['rebate']);
$price->setCosts($row['costs']);
$price->setTaxRate($row['taxrate']);
$items[ $row['id'] ] = array( 'price' => $price, 'item' => $row );
}
}
catch( Exception $e )
{
$results->finish();
throw $e;
}
$dbm->release( $conn, $dbname );
}
catch( Exception $e )
{
$dbm->release( $conn, $dbname );
throw $e;
}
$result = array();
$attributes = $this->_getAttributeItems( array_keys( $items ) );
foreach ( $items as $id => $row )
{
$attrList = array();
if( isset( $attributes[$id] ) ) {
$attrList = $attributes[$id];
}
$result[ $id ] = $this->_createItem( $row['price'], $row['item'], $attrList );
}
return $result;
}
/**
* Returns the search attributes that can be used for searching.
*
* @param boolean $withsub Return also attributes of sub-managers if true
* @return array List of attributes implementing MW_Common_Criteria_Attribute_Interface
*/
public function getSearchAttributes($withsub = true)
{
/** classes/order/manager/base/service/submanagers
* List of manager names that can be instantiated by the order base service manager
*
* Managers provide a generic interface to the underlying storage.
* Each manager has or can have sub-managers caring about particular
* aspects. Each of these sub-managers can be instantiated by its
* parent manager using the getSubManager() method.
*
* The search keys from sub-managers can be normally used in the
* manager as well. It allows you to search for items of the manager
* using the search keys of the sub-managers to further limit the
* retrieved list of items.
*
* @param array List of sub-manager names
* @since 2014.03
* @category Developer
*/
$path = 'classes/order/manager/base/service/submanagers';
return $this->_getSearchAttributes( $this->_searchConfig, $path, array( 'attribute' ), $withsub );
}
/**
* Returns a new manager for order service extensions.
*
* @param string $manager Name of the sub manager type in lower case
* @param string|null $name Name of the implementation (from configuration or "Default" if null)
* @return MShop_Common_Manager_Interface Manager for different extensions, e.g attribute
*/
public function getSubManager($manager, $name = null)
{
/** classes/order/manager/base/service/name
* Class name of the used order base service manager implementation
*
* Each default order base service manager can be replaced by an alternative imlementation.
* To use this implementation, you have to set the last part of the class
* name as configuration value so the manager factory knows which class it
* has to instantiate.
*
* For example, if the name of the default class is
*
* MShop_Order_Manager_Base_Service_Default
*
* and you want to replace it with your own version named
*
* MShop_Order_Manager_Base_Service_Myservice
*
* then you have to set the this configuration option:
*
* classes/order/manager/base/service/name = Myservice
*
* The value is the last part of your own class name and it's case sensitive,
* so take care that the configuration value is exactly named like the last
* part of the class name.
*
* The allowed characters of the class name are A-Z, a-z and 0-9. No other
* characters are possible! You should always start the last part of the class
* name with an upper case character and continue only with lower case characters
* or numbers. Avoid chamel case names like "MyService"!
*
* @param string Last part of the class name
* @since 2014.03
* @category Developer
*/
/** mshop/order/manager/base/service/decorators/excludes
* Excludes decorators added by the "common" option from the order base service manager
*
* Decorators extend the functionality of a class by adding new aspects
* (e.g. log what is currently done), executing the methods of the underlying
* class only in certain conditions (e.g. only for logged in users) or
* modify what is returned to the caller.
*
* This option allows you to remove a decorator added via
* "mshop/common/manager/decorators/default" before they are wrapped
* around the order base service manager.
*
* mshop/order/manager/base/service/decorators/excludes = array( 'decorator1' )
*
* This would remove the decorator named "decorator1" from the list of
* common decorators ("MShop_Common_Manager_Decorator_*") added via
* "mshop/common/manager/decorators/default" for the order base service manager.
*
* @param array List of decorator names
* @since 2014.03
* @category Developer
* @see mshop/common/manager/decorators/default
* @see mshop/order/manager/base/service/decorators/global
* @see mshop/order/manager/base/service/decorators/local
*/
/** mshop/order/manager/base/service/decorators/global
* Adds a list of globally available decorators only to the order base service manager
*
* Decorators extend the functionality of a class by adding new aspects
* (e.g. log what is currently done), executing the methods of the underlying
* class only in certain conditions (e.g. only for logged in users) or
* modify what is returned to the caller.
*
* This option allows you to wrap global decorators
* ("MShop_Common_Manager_Decorator_*") around the order base service manager.
*
* mshop/order/manager/base/service/decorators/global = array( 'decorator1' )
*
* This would add the decorator named "decorator1" defined by
* "MShop_Common_Manager_Decorator_Decorator1" only to the order controller.
*
* @param array List of decorator names
* @since 2014.03
* @category Developer
* @see mshop/common/manager/decorators/default
* @see mshop/order/manager/base/service/decorators/excludes
* @see mshop/order/manager/base/service/decorators/local
*/
/** mshop/order/manager/base/service/decorators/local
* Adds a list of local decorators only to the order base service manager
*
* Decorators extend the functionality of a class by adding new aspects
* (e.g. log what is currently done), executing the methods of the underlying
* class only in certain conditions (e.g. only for logged in users) or
* modify what is returned to the caller.
*
* This option allows you to wrap local decorators
* ("MShop_Common_Manager_Decorator_*") around the order base service manager.
*
* mshop/order/manager/base/service/decorators/local = array( 'decorator2' )
*
* This would add the decorator named "decorator2" defined by
* "MShop_Common_Manager_Decorator_Decorator2" only to the order
* controller.
*
* @param array List of decorator names
* @since 2014.03
* @category Developer
* @see mshop/common/manager/decorators/default
* @see mshop/order/manager/base/service/decorators/excludes
* @see mshop/order/manager/base/service/decorators/global
*/
return $this->_getSubManager( 'order', 'base/service/' . $manager, $name );
}
/**
* Creates a new order service item object initialized with given parameters.
*
* @param MShop_Price_Item_Interface $price Price object
* @param array $values Associative list of values from the database
* @param array $attributes List of order service attribute items
* @return MShop_Order_Item_Base_Service_Interface Order item service object
*/
protected function _createItem( MShop_Price_Item_Interface $price,
array $values = array(), array $attributes = array() )
{
return new MShop_Order_Item_Base_Service_Default( $price, $values, $attributes );
}
/**
* Searches for attribute items connected with order service item.
*
* @param string[] $ids List of order service item IDs
* @return array List of items implementing MShop_Order_Item_Base_Service_Attribute_Interface
*/
protected function _getAttributeItems( $ids )
{
$manager = $this->getSubManager( 'attribute' );
$search = $manager->createSearch();
$search->setConditions( $search->compare( '==', 'order.base.service.attribute.serviceid', $ids ) );
$search->setSortations( array( $search->sort( '+', 'order.base.service.attribute.code' ) ) );
$search->setSlice( 0, 0x7fffffff );
$result = array();
foreach ($manager->searchItems( $search ) as $item) {
$result[ $item->getServiceId() ][ $item->getId() ] = $item;
}
return $result;
}
}
|
Arcavias/arcavias-core
|
lib/mshoplib/src/MShop/Order/Manager/Base/Service/Default.php
|
PHP
|
lgpl-3.0
| 18,575 |
//+======================================================================
// $Source$
//
// Project: Tango
//
// Description: java source code for the TANGO client/server API.
//
// $Author: pascal_verdier $
//
// Copyright (C) : 2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,
// European Synchrotron Radiation Facility
// BP 220, Grenoble 38043
// FRANCE
//
// This file is part of Tango.
//
// Tango is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Tango is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Tango. If not, see <http://www.gnu.org/licenses/>.
//
// $Revision: 25297 $
//
//-======================================================================
package fr.esrf.TangoApi;
import fr.esrf.Tango.DevCmdInfo;
import fr.esrf.Tango.DevFailed;
import fr.esrf.TangoDs.Except;
public class DevVarCmdArray
{
/**
* manage an array of CommandInfo objects.
*/
protected CommandInfo[] cmd_info;
/**
* The device name
*/
protected String devname;
//======================================================
//======================================================
public DevVarCmdArray(String devname, DevCmdInfo[] info)
{
this.devname = devname;
cmd_info = new CommandInfo[info.length];
for (int i=0 ; i<info.length ; i++)
cmd_info[i] = new CommandInfo(info[i]);
}
//======================================================
//======================================================
public DevVarCmdArray(String devname, CommandInfo[] info)
{
this.devname = devname;
this.cmd_info = info;
}
//======================================================
//======================================================
public int size()
{
return cmd_info.length;
}
//======================================================
//======================================================
public CommandInfo elementAt(int i)
{
return cmd_info[i];
}
//======================================================
//======================================================
public CommandInfo[] getInfoArray()
{
return cmd_info;
}
//======================================================
//======================================================
public int argoutType(String cmdname) throws DevFailed
{
for (CommandInfo info : cmd_info)
if (cmdname.equals(info.cmd_name))
return info.out_type;
Except.throw_non_supported_exception("TACO_CMD_UNAVAILABLE",
cmdname + " command unknown for device " + devname,
"DevVarCmdArray.argoutType()");
return -1;
}
//======================================================
//======================================================
public int arginType(String cmdname) throws DevFailed
{
for (CommandInfo info : cmd_info)
if (cmdname.equals(info.cmd_name))
return info.in_type;
Except.throw_non_supported_exception("TACO_CMD_UNAVAILABLE",
cmdname + " command unknown for device " + devname,
"DevVarCmdArray.arginType()");
return -1;
}
//======================================================
//======================================================
public String toString()
{
StringBuffer sb = new StringBuffer();
for (CommandInfo info : cmd_info)
{
sb.append(info.cmd_name);
sb.append("(").append(info.in_type);
sb.append(", ").append(info.out_type).append(")\n");
}
return sb.toString();
}
}
|
tango-controls/JTango
|
dao/src/main/java/fr/esrf/TangoApi/DevVarCmdArray.java
|
Java
|
lgpl-3.0
| 3,880 |
/*
* SonarLint for Visual Studio
* Copyright (C) 2016-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
using System;
using System.Collections.Generic;
using EnvDTE;
using FluentAssertions;
using VsShell = Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using SonarLint.VisualStudio.CFamily.Analysis;
using SonarLint.VisualStudio.Core;
using SonarLint.VisualStudio.Core.CFamily;
using SonarLint.VisualStudio.Integration.Vsix.CFamily;
using SonarLint.VisualStudio.Integration.Vsix.CFamily.VcxProject;
using static SonarLint.VisualStudio.Integration.Vsix.CFamily.UnitTests.CFamilyTestUtility;
using System.Threading.Tasks;
using EnvDTE80;
using Microsoft.VisualStudio.Shell.Interop;
namespace SonarLint.VisualStudio.Integration.UnitTests.CFamily
{
[TestClass]
public class VcxRequestFactoryTests
{
private static ProjectItem DummyProjectItem = Mock.Of<ProjectItem>();
private static CFamilyAnalyzerOptions DummyAnalyzerOptions = new CFamilyAnalyzerOptions();
[TestMethod]
public void MefCtor_CheckIsExported()
{
MefTestHelpers.CheckTypeCanBeImported<VcxRequestFactory, IRequestFactory>(null, new[]
{
MefTestHelpers.CreateExport<VsShell.SVsServiceProvider>(Mock.Of<IServiceProvider>()),
MefTestHelpers.CreateExport<ICFamilyRulesConfigProvider>(Mock.Of<ICFamilyRulesConfigProvider>()),
MefTestHelpers.CreateExport<ILogger>(Mock.Of<ILogger>())
});
}
[TestMethod]
public async Task TryGet_RunsOnUIThread()
{
var fileConfigProvider = new Mock<IFileConfigProvider>();
var threadHandling = new Mock<IThreadHandling>();
threadHandling.Setup(x => x.RunOnUIThread(It.IsAny<Action>()))
.Callback<Action>(op =>
{
// Try to check that the product code is executed inside the "RunOnUIThread" call
fileConfigProvider.Invocations.Count.Should().Be(0);
op();
fileConfigProvider.Invocations.Count.Should().Be(1);
});
var testSubject = CreateTestSubject(projectItem: DummyProjectItem,
threadHandling: threadHandling.Object,
fileConfigProvider: fileConfigProvider.Object);
var request = await testSubject.TryCreateAsync("any", new CFamilyAnalyzerOptions());
threadHandling.Verify(x => x.RunOnUIThread(It.IsAny<Action>()), Times.Once);
threadHandling.Verify(x => x.ThrowIfNotOnUIThread(), Times.Once);
}
[TestMethod]
public async Task TryGet_NoProjectItem_Null()
{
var testSubject = CreateTestSubject(projectItem: null);
var request = await testSubject.TryCreateAsync("path", new CFamilyAnalyzerOptions());
request.Should().BeNull();
}
[TestMethod]
public async Task TryGet_NoFileConfig_Null()
{
const string analyzedFilePath = "path";
var fileConfigProvider = SetupFileConfigProvider(DummyProjectItem, DummyAnalyzerOptions, analyzedFilePath, null);
var testSubject = CreateTestSubject(DummyProjectItem, fileConfigProvider: fileConfigProvider.Object);
var request = await testSubject.TryCreateAsync("path", DummyAnalyzerOptions);
request.Should().BeNull();
fileConfigProvider.Verify(x=> x.Get(DummyProjectItem, analyzedFilePath, DummyAnalyzerOptions), Times.Once);
}
[TestMethod]
public async Task TryGet_RequestCreatedWithNoDetectedLanguage_Null()
{
const string analyzedFilePath = "c:\\notCFamilyFile.txt";
var fileConfig = CreateDummyFileConfig(analyzedFilePath);
var fileConfigProvider = SetupFileConfigProvider(DummyProjectItem, DummyAnalyzerOptions, analyzedFilePath, fileConfig.Object);
var cFamilyRulesConfigProvider = new Mock<ICFamilyRulesConfigProvider>();
var testSubject = CreateTestSubject(DummyProjectItem,
fileConfigProvider: fileConfigProvider.Object,
cFamilyRulesConfigProvider: cFamilyRulesConfigProvider.Object);
var request = await testSubject.TryCreateAsync(analyzedFilePath, DummyAnalyzerOptions);
request.Should().BeNull();
fileConfig.VerifyGet(x => x.AbsoluteFilePath, Times.Once);
cFamilyRulesConfigProvider.Invocations.Count.Should().Be(0);
}
[TestMethod]
public async Task TryGet_FailureParsing_NonCriticialException_Null()
{
const string analyzedFilePath = "c:\\test.cpp";
var fileConfig = CreateDummyFileConfig(analyzedFilePath);
var fileConfigProvider = SetupFileConfigProvider(DummyProjectItem, DummyAnalyzerOptions, analyzedFilePath, fileConfig.Object);
var cFamilyRulesConfigProvider = new Mock<ICFamilyRulesConfigProvider>();
cFamilyRulesConfigProvider
.Setup(x => x.GetRulesConfiguration(SonarLanguageKeys.CPlusPlus))
.Throws<NotImplementedException>();
var logger = new TestLogger();
var testSubject = CreateTestSubject(DummyProjectItem,
fileConfigProvider: fileConfigProvider.Object,
cFamilyRulesConfigProvider: cFamilyRulesConfigProvider.Object,
logger: logger);
var request = await testSubject.TryCreateAsync(analyzedFilePath, DummyAnalyzerOptions);
request.Should().BeNull();
logger.AssertPartialOutputStringExists(nameof(NotImplementedException));
}
[TestMethod]
public void TryGet_FailureParsing_CriticalException_ExceptionThrown()
{
const string analyzedFilePath = "c:\\test.cpp";
var fileConfig = CreateDummyFileConfig(analyzedFilePath);
var fileConfigProvider = SetupFileConfigProvider(DummyProjectItem, DummyAnalyzerOptions, analyzedFilePath, fileConfig.Object);
var cFamilyRulesConfigProvider = new Mock<ICFamilyRulesConfigProvider>();
cFamilyRulesConfigProvider
.Setup(x => x.GetRulesConfiguration(SonarLanguageKeys.CPlusPlus))
.Throws<StackOverflowException>();
var testSubject = CreateTestSubject(DummyProjectItem,
fileConfigProvider: fileConfigProvider.Object,
cFamilyRulesConfigProvider: cFamilyRulesConfigProvider.Object);
Func<Task> act = () => testSubject.TryCreateAsync(analyzedFilePath, DummyAnalyzerOptions);
act.Should().ThrowExactly<StackOverflowException>();
}
[TestMethod]
public async Task TryGet_IRequestPropertiesAreSet()
{
var analyzerOptions = new CFamilyAnalyzerOptions();
var rulesConfig = Mock.Of<ICFamilyRulesConfig>();
var request = await GetSuccessfulRequest(analyzerOptions, "d:\\xxx\\fileToAnalyze.cpp", rulesConfig);
request.Should().NotBeNull();
request.Context.File.Should().Be("d:\\xxx\\fileToAnalyze.cpp");
request.Context.PchFile.Should().Be(SubProcessFilePaths.PchFilePath);
request.Context.AnalyzerOptions.Should().BeSameAs(analyzerOptions);
request.Context.RulesConfiguration.Should().BeSameAs(rulesConfig);
}
[TestMethod]
public async Task TryGet_FileConfigIsSet()
{
var request = await GetSuccessfulRequest();
request.Should().NotBeNull();
request.FileConfig.Should().NotBeNull();
}
[TestMethod]
public async Task TryGet_NonHeaderFile_IsSupported()
{
var request = await GetSuccessfulRequest();
request.Should().NotBeNull();
(request.Flags & Request.MainFileIsHeader).Should().Be(0);
}
[TestMethod]
public async Task TryGet_HeaderFile_IsSupported()
{
var projectItemConfig = new ProjectItemConfig { ItemType = "ClInclude" };
var projectItemMock = CreateMockProjectItem("c:\\foo\\xxx.vcxproj", projectItemConfig);
var fileConfig = CreateDummyFileConfig("c:\\dummy\\file.h");
fileConfig.Setup(x => x.CompileAs).Returns("CompileAsCpp");
fileConfig.Setup(x => x.ItemType).Returns("ClInclude");
var request = await GetSuccessfulRequest(fileToAnalyze: "c:\\dummy\\file.h", projectItem: projectItemMock.Object, fileConfig: fileConfig);
request.Should().NotBeNull();
(request.Flags & Request.MainFileIsHeader).Should().NotBe(0);
}
[TestMethod]
public async Task TryGet_NoAnalyzerOptions_RequestCreatedWithoutOptions()
{
var request = await GetSuccessfulRequest(analyzerOptions: null);
request.Should().NotBeNull();
(request.Flags & Request.CreateReproducer).Should().Be(0);
(request.Flags & Request.BuildPreamble).Should().Be(0);
request.Context.AnalyzerOptions.Should().BeNull();
}
[TestMethod]
public async Task TryGet_AnalyzerOptionsWithReproducerEnabled_RequestCreatedWithReproducerFlag()
{
var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreateReproducer = true });
request.Should().NotBeNull();
(request.Flags & Request.CreateReproducer).Should().NotBe(0);
}
[TestMethod]
public async Task TryGet_AnalyzerOptionsWithoutReproducerEnabled_RequestCreatedWithoutReproducerFlag()
{
var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreateReproducer = false });
request.Should().NotBeNull();
(request.Flags & Request.CreateReproducer).Should().Be(0);
}
[TestMethod]
public async Task TryGet_AnalyzerOptionsWithPCH_RequestCreatedWithPCHFlag()
{
var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreatePreCompiledHeaders = true });
request.Should().NotBeNull();
(request.Flags & Request.BuildPreamble).Should().NotBe(0);
}
[TestMethod]
public async Task TryGet_AnalyzerOptionsWithoutPCH_RequestCreatedWithoutPCHFlag()
{
var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreatePreCompiledHeaders = false });
request.Should().NotBeNull();
(request.Flags & Request.BuildPreamble).Should().Be(0);
}
[TestMethod]
public async Task TryGet_AnalyzerOptionsWithPCH_RequestOptionsNotSet()
{
var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreatePreCompiledHeaders = true });
request.Should().NotBeNull();
request.Context.RulesConfiguration.Should().BeNull();
request.Options.Should().BeEmpty();
}
[TestMethod]
public async Task TryGet_AnalyzerOptionsWithoutPCH_RequestOptionsAreSet()
{
var rulesProtocolFormat = new RuleConfigProtocolFormat("some profile", new Dictionary<string, string>
{
{"rule1", "param1"},
{"rule2", "param2"}
});
var request = await GetSuccessfulRequest(new CFamilyAnalyzerOptions { CreatePreCompiledHeaders = false }, protocolFormat: rulesProtocolFormat);
request.Should().NotBeNull();
request.Context.RulesConfiguration.Should().NotBeNull();
request.Options.Should().BeEquivalentTo(
"internal.qualityProfile=some profile",
"rule1=param1",
"rule2=param2");
}
private static Mock<IFileConfigProvider> SetupFileConfigProvider(ProjectItem projectItem,
CFamilyAnalyzerOptions analyzerOptions,
string analyzedFilePath,
IFileConfig fileConfigToReturn)
{
var fileConfigProvider = new Mock<IFileConfigProvider>();
fileConfigProvider
.Setup(x => x.Get(projectItem, analyzedFilePath, analyzerOptions))
.Returns(fileConfigToReturn);
return fileConfigProvider;
}
private VcxRequestFactory CreateTestSubject(ProjectItem projectItem,
ICFamilyRulesConfigProvider cFamilyRulesConfigProvider = null,
IFileConfigProvider fileConfigProvider = null,
IRulesConfigProtocolFormatter rulesConfigProtocolFormatter = null,
IThreadHandling threadHandling = null,
ILogger logger = null)
{
var serviceProvider = CreateServiceProviderReturningProjectItem(projectItem);
cFamilyRulesConfigProvider ??= Mock.Of<ICFamilyRulesConfigProvider>();
rulesConfigProtocolFormatter ??= Mock.Of<IRulesConfigProtocolFormatter>();
fileConfigProvider ??= Mock.Of<IFileConfigProvider>();
threadHandling ??= new NoOpThreadHandler();
logger ??= Mock.Of<ILogger>();
return new VcxRequestFactory(serviceProvider.Object,
cFamilyRulesConfigProvider,
rulesConfigProtocolFormatter,
fileConfigProvider,
logger,
threadHandling);
}
private static Mock<IServiceProvider> CreateServiceProviderReturningProjectItem(ProjectItem projectItemToReturn)
{
var mockSolution = new Mock<Solution>();
mockSolution.Setup(s => s.FindProjectItem(It.IsAny<string>())).Returns(projectItemToReturn);
var mockDTE = new Mock<DTE2>();
mockDTE.Setup(d => d.Solution).Returns(mockSolution.Object);
var mockServiceProvider = new Mock<IServiceProvider>();
mockServiceProvider.Setup(s => s.GetService(typeof(SDTE))).Returns(mockDTE.Object);
return mockServiceProvider;
}
private async Task<Request> GetSuccessfulRequest(CFamilyAnalyzerOptions analyzerOptions = null,
string fileToAnalyze = "c:\\foo\\file.cpp",
ICFamilyRulesConfig rulesConfig = null,
ProjectItem projectItem = null,
Mock<IFileConfig> fileConfig = null,
RuleConfigProtocolFormat protocolFormat = null)
{
rulesConfig ??= Mock.Of<ICFamilyRulesConfig>();
var rulesConfigProviderMock = new Mock<ICFamilyRulesConfigProvider>();
rulesConfigProviderMock
.Setup(x => x.GetRulesConfiguration(It.IsAny<string>()))
.Returns(rulesConfig);
projectItem ??= Mock.Of<ProjectItem>();
fileConfig ??= CreateDummyFileConfig(fileToAnalyze);
var fileConfigProvider = SetupFileConfigProvider(projectItem, analyzerOptions, fileToAnalyze, fileConfig.Object);
protocolFormat ??= new RuleConfigProtocolFormat("qp", new Dictionary<string, string>());
var rulesConfigProtocolFormatter = new Mock<IRulesConfigProtocolFormatter>();
rulesConfigProtocolFormatter
.Setup(x => x.Format(rulesConfig))
.Returns(protocolFormat);
var testSubject = CreateTestSubject(projectItem,
rulesConfigProviderMock.Object,
fileConfigProvider.Object,
rulesConfigProtocolFormatter.Object);
return await testSubject.TryCreateAsync(fileToAnalyze, analyzerOptions) as Request;
}
private Mock<IFileConfig> CreateDummyFileConfig(string filePath)
{
var fileConfig = new Mock<IFileConfig>();
fileConfig.SetupGet(x => x.PlatformName).Returns("Win32");
fileConfig.SetupGet(x => x.AdditionalIncludeDirectories).Returns("");
fileConfig.SetupGet(x => x.ForcedIncludeFiles).Returns("");
fileConfig.SetupGet(x => x.PrecompiledHeader).Returns("");
fileConfig.SetupGet(x => x.UndefinePreprocessorDefinitions).Returns("");
fileConfig.SetupGet(x => x.PreprocessorDefinitions).Returns("");
fileConfig.SetupGet(x => x.CompileAs).Returns("");
fileConfig.SetupGet(x => x.CompileAsManaged).Returns("");
fileConfig.SetupGet(x => x.RuntimeLibrary).Returns("");
fileConfig.SetupGet(x => x.ExceptionHandling).Returns("");
fileConfig.SetupGet(x => x.EnableEnhancedInstructionSet).Returns("");
fileConfig.SetupGet(x => x.BasicRuntimeChecks).Returns("");
fileConfig.SetupGet(x => x.LanguageStandard).Returns("");
fileConfig.SetupGet(x => x.AdditionalOptions).Returns("");
fileConfig.SetupGet(x => x.CompilerVersion).Returns("1.2.3.4");
fileConfig.SetupGet(x => x.AbsoluteProjectPath).Returns("c:\\test.vcxproj");
fileConfig.SetupGet(x => x.AbsoluteFilePath).Returns(filePath);
return fileConfig;
}
}
}
|
SonarSource/sonarlint-visualstudio
|
src/Integration.Vsix.UnitTests/CFamily/VcxRequestFactoryTests.cs
|
C#
|
lgpl-3.0
| 17,901 |
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2019 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.util;
import java.io.IOException;
import java.io.LineNumberReader;
import org.springframework.core.io.support.EncodedResource;
public abstract class DBScriptUtil
{
private static final String DEFAULT_SCRIPT_COMMENT_PREFIX = "--";
/**
* Read a script from the provided EncodedResource and build a String containing
* the lines.
*
* @param resource
* the resource (potentially associated with a specific encoding) to
* load the SQL script from
* @return a String containing the script lines
*/
public static String readScript(EncodedResource resource) throws IOException
{
return readScript(resource, DEFAULT_SCRIPT_COMMENT_PREFIX);
}
/**
* Read a script from the provided EncodedResource, using the supplied line
* comment prefix, and build a String containing the lines.
*
* @param resource
* the resource (potentially associated with a specific encoding) to
* load the SQL script from
* @param lineCommentPrefix
* the prefix that identifies comments in the SQL script (typically
* "--")
* @return a String containing the script lines
*/
private static String readScript(EncodedResource resource, String lineCommentPrefix) throws IOException
{
LineNumberReader lineNumberReader = new LineNumberReader(resource.getReader());
try
{
return readScript(lineNumberReader, lineCommentPrefix);
}
finally
{
lineNumberReader.close();
}
}
/**
* Read a script from the provided LineNumberReader, using the supplied line
* comment prefix, and build a String containing the lines.
*
* @param lineNumberReader
* the LineNumberReader containing the script to be processed
* @param lineCommentPrefix
* the prefix that identifies comments in the SQL script (typically
* "--")
* @return a String containing the script lines
*/
private static String readScript(LineNumberReader lineNumberReader, String lineCommentPrefix) throws IOException
{
String statement = lineNumberReader.readLine();
StringBuilder scriptBuilder = new StringBuilder();
while (statement != null)
{
if (lineCommentPrefix != null && !statement.startsWith(lineCommentPrefix))
{
if (scriptBuilder.length() > 0)
{
scriptBuilder.append('\n');
}
scriptBuilder.append(statement);
}
statement = lineNumberReader.readLine();
}
return scriptBuilder.toString();
}
}
|
Alfresco/alfresco-repository
|
src/main/java/org/alfresco/util/DBScriptUtil.java
|
Java
|
lgpl-3.0
| 3,822 |
#!/usr/bin/env python
from string import punctuation
import argparse
import fnmatch
import os
import shutil
import sys
import json
sys.path.insert(1, '/var/www/bedrock/')
sys.path.insert(0, '/var/www/bedrock/src/')
import analytics.utils
import dataloader.utils
import visualization.utils
from multiprocessing import Queue
#function to determine if the file being checked has the appropriate imports
def find_imports(fileToCheck, desiredInterface):
importedList = []
asterikFound = False
with open(fileToCheck, 'r') as pyFile:
for line in pyFile:
newFront = line.find("import") #finds the first occurence of the word import on the line
if newFront != -1: #an occurence of import has been found
line = line[newFront + 7:] #sets line to now start at the word after import
possibleAs = line.find(" as") #used to find import states that have the structure (from x import y as z)
if possibleAs != -1:
line = line[possibleAs + 4:]
if line.find("*") != -1 and len(line) == 2: #if the import is just the *
importedList.extend(line)
asterikFound = True
line =[word.strip(punctuation) for word in line.split()] #correctly splits the inputs based on puncuation
importedList.extend(line) #creates a single list of all the imports
if desiredInterface == 1:
if "Algorithm" not in importedList:
return "Missing the Algorithm input, can be fixed using 'from ..analytics import Algorithm'.\n"
else:
return ""
elif desiredInterface == 2:
if "*" not in importedList:
return "Missing the * input, can be fixed using 'from visualization.utils import *'.\n"
else:
return ""
elif desiredInterface == 3:
if "*" not in importedList:
return "Missing the * input, can be fixed using 'from dataloader.utils import *'.\n"
else:
return ""
elif desiredInterface == 4:
if "*" not in importedList:
return "Missing the * input, can be fixed using 'from dataloader.utils import *'\n"
else:
return ""
def find_class(fileToCheck, desiredInterface):
classesList = []
with open(fileToCheck, 'r') as pyFile:
for line in pyFile:
newFront = line.find("class")
newEnd = line.find(")")
if newFront == 0:
line = line[newFront + 6: newEnd + 1]
line.split()
classesList.append(line)
return classesList
def find_functions(fileToCheck, desiredInterface):
functionsList_with_inputs = []
with open(fileToCheck, 'r') as pyFile:
for line in pyFile:
newFront = line.find("def")
newEnd = line.find(")")
if newFront != -1:
line = line[newFront + 3: newEnd + 1]
line.split()
functionsList_with_inputs.append(line)
return functionsList_with_inputs
def compare_fuctions(fileToCheck, desiredInterface):
fList = find_functions(fileToCheck, desiredInterface)
if desiredInterface == 1:
if " __init__(self)" not in fList or " compute(self, filepath, **kwargs)" not in fList:
return "Function/s and/or specific input/s missing in this file.\n"
else:
return ""
elif desiredInterface == 2:
if " __init__(self)" not in fList or " initialize(self, inputs)" not in fList or " create(self)" not in fList:
return "Function/s and/or specific inputs/s missing in this file.\n"
else:
return ""
elif desiredInterface == 3:
if " __init__(self)" not in fList or " explore(self, filepath)" not in fList or " ingest(self, posted_data, src)" not in fList:
return "Function/s and/or specific input/s missing in this file.\n"
else:
return ""
elif desiredInterface == 4:
if " __init__(self)" not in fList or (" check(self, name, sample)" not in fList and " check(self, name, col)" not in fList) or " apply(self, conf)" not in fList:
return "Function/s and/or specific input/s missing in this file.\n"
else:
return ""
def inheritance_check(fileToCheck, desiredInterface):
class_name_list = find_class(fileToCheck, desiredInterface)
inhertiance_name = ""
if (len(class_name_list) > 0):
if (desiredInterface == 1 and len(class_name_list) > 1):
inhertiance_name = class_name_list[0]
elif (len(class_name_list) > 1):
inhertiance_name = class_name_list[len(class_name_list) - 1]
else:
inhertiance_name = class_name_list[0]
newFront = inhertiance_name.find("(")
newEnd = inhertiance_name.find(")")
inhertiance_name = inhertiance_name[newFront + 1:newEnd]
if desiredInterface == 1:
if inhertiance_name != "Algorithm":
return "Class must inherit from the Algorithm super class.\n"
else:
return ""
elif desiredInterface == 2:
if inhertiance_name != "Visualization":
return "Class must inherit from the Visualization super class.\n"
else:
return ""
elif desiredInterface == 3:
if inhertiance_name != "Ingest":
return "Class must inherit from the Ingest super class.\n"
else:
return ""
elif desiredInterface == 4:
if inhertiance_name != "Filter":
return "Class must inherit from the Filter super class.\n"
else:
return ""
else:
return "There are no classes in this file.\n"
def validate_file_name(fileToCheck, desiredInterface):
class_name_list = find_class(fileToCheck, desiredInterface)
class_name = ""
if (len(class_name_list) > 0):
if (desiredInterface == 1 and len(class_name_list) > 1):
class_name = class_name_list[0]
elif (len(class_name_list) > 1):
class_name = class_name_list[len(class_name_list) - 1]
else:
class_name = class_name_list[0]
trim = class_name.find("(")
class_name = class_name[:trim]
returnsList = list_returns(fileToCheck, desiredInterface)
superStament = []
with open(fileToCheck, 'r') as pyFile:
for line in pyFile:
newFront = line.find("super")
if newFront != -1:
trimFront = line.find("(")
trimBack = line.find(",")
line = line[trimFront + 1: trimBack]
superStament.append(line)
if class_name not in superStament:
return "File name does not match Class name\n"
else:
return ""
def list_returns(fileToCheck, desiredInterface):
returnsList = []
newLine = ""
with open(fileToCheck, 'r') as pyFile:
for line in pyFile:
if line.find("#") == -1:
newFront = line.find("return")
if newFront != -1:
possibleErrorMessageCheck1 = line.find("'")
bracketBefore = line.find("{")
lastBracket = line.find("}")
newLine = line[possibleErrorMessageCheck1:]
possibleErrorMessageCheck2 = newLine.find(" ")
if possibleErrorMessageCheck2 == -1:
line = line[newFront + 7:]
line.split()
line = [word.strip(punctuation) for word in line.split()]
returnsList.extend(line)
elif possibleErrorMessageCheck1 == bracketBefore + 1:
line = line[newFront + 7:lastBracket + 1]
line.split()
returnsList.append(line)
return returnsList
def check_return_values(fileToCheck, desiredInterface):
listOfReturns = list_returns(fileToCheck, desiredInterface)
listOfClasses = find_class(fileToCheck, desiredInterface)
firstElement = listOfClasses[0]
for elem in listOfClasses:
cutOff = elem.find("(")
if cutOff != -1:
elem = elem[:cutOff]
firstElement = elem
listOfClasses[0] = firstElement
if desiredInterface == 1:
listOfFunctions = find_functions(fileToCheck, desiredInterface)
if len(listOfFunctions) == 2 and len(listOfReturns) > 0:
return "Too many return values in this file.\n"
else:
return ""
elif desiredInterface == 2:
if len(listOfReturns) > 1:
if listOfClasses[0] not in listOfReturns or listOfReturns[1].find("data") == -1 or listOfReturns[1].find("type") == -1 or listOfReturns[1].find("id") == -1:
return "Missing or incorrectly named return values.\n"
else:
return ""
elif listOfReturns[0].find("data") == -1 or listOfReturns[0].find("type") == -1 or listOfReturns[0].find("id") == -1:
return "Missing or incorrectly named return values.\n"
else:
return ""
elif desiredInterface == 3:
if ("schema" not in listOfReturns and "schemas" not in listOfReturns and "collection:ret" not in listOfReturns) or "error" not in listOfReturns or "matrices" not in listOfReturns:
return "Missing or incorrectly named return values.\n"
else:
return ""
elif desiredInterface == 4:
if ("True" not in listOfReturns and "False" not in listOfReturns) or ("matrix" not in listOfReturns and "None" not in listOfReturns):
return "Missing or incorrectly named return values"
else:
return ""
def hard_type_check_return(fileToCheck, desiredInterface, my_dir, output_directory, filter_specs):
specificErrorMessage = ""
queue = Queue()
lastOccurence = fileToCheck.rfind("/")
file_name = fileToCheck[lastOccurence + 1:len(fileToCheck) - 3]
print filter_specs
if desiredInterface == 1:
file_metaData = analytics.utils.get_metadata(file_name)
elif desiredInterface == 2:
file_metaData = visualization.utils.get_metadata(file_name)
elif desiredInterface == 3:
file_metaData = dataloader.utils.get_metadata(file_name, "ingest")
elif desiredInterface == 4:
file_metaData = dataloader.utils.get_metadata(file_name, "filters")
inputList = []
if desiredInterface != 3 and desiredInterface != 4:
for elem in file_metaData['inputs']:
inputList.append(elem)
inputDict = create_input_dict(my_dir, inputList)
if desiredInterface == 1:
count = 0
computeResult = analytics.utils.run_analysis(queue, file_name, file_metaData['parameters'], inputDict, output_directory, "Result")
for file in os.listdir(my_dir):
if fnmatch.fnmatch(file, "*.csv") or fnmatch.fnmatch(file, ".json"):
count += 1
if (count < 1):
specificErrorMessage += "Missing .csv or .json file, the compute function must create a new .csv or .json file."
for file_name in os.listdir(output_directory):
os.remove(os.path.join(output_directory, file_name))
elif desiredInterface == 2:
createResult = visualization.utils.generate_vis(file_name, inputDict, file_metaData['parameters'])
if (type(createResult) != dict):
specificErrorMessage += "Missing a dict return, create function must return a dict item."
elif desiredInterface == 3:
filter_specs_dict = json.loads(str(filter_specs))
exploreResult = dataloader.utils.explore(file_name, my_dir, [])
exploreResultList = list(exploreResult)
count = 0
typeOfMatrix = []
matrix = ""
nameOfSource = ""
filterOfMatrix = []
for elem in exploreResult:
if type(elem) == dict:
for key in elem.keys():
nameOfSource = str(key)
if len(elem.values()) == 1:
for value in elem.values():
while count < len(value):
for item in value[count].keys():
if item == "type":
matrix = str(value[count]['type'])
matrix = matrix[2:len(matrix) - 2]
typeOfMatrix.append(matrix)
if item == "key_usr":
filterOfMatrix.append(str(value[count]['key_usr']))
count += 1
typeListExplore = []
posted_data = {
'matrixFilters':{},
'matrixFeatures':[],
'matrixFeaturesOriginal':[],
'matrixName':"test",
'sourceName':nameOfSource,
'matrixTypes':[]
}
# posted_data['matrixFilters'].update({filterOfMatrix[0]:{"classname":"DocumentLEAN","filter_id":"DocumentLEAN","parameters":[],"stage":"before","type":"extract"}}) #for Text
# posted_data['matrixFilters'].update({filterOfMatrix[0]:{"classname":"TweetDocumentLEAN","filter_id":"TweetDocumentLEAN","parameters":[{"attrname":"include","name":"Include the following keywords","type":"input","value":""},{"attrname":"sent","value":"No"},{"attrname":"exclude","name":"Exclude the following keywords","type":"input","value":""},{"attrname":"lang","name":"Language","type":"input","value":""},{"attrname":"limit","name":"Limit","type":"input","value":"10"},{"attrname":"start","name":"Start time","type":"input","value":""},{"attrname":"end","name":"End time","type":"input","value":""},{"attrname":"geo","name":"Geo","type":"input","value":""}],"stage":"before","type":"extract"}}) #for Mongo
posted_data['matrixFilters'].update({filterOfMatrix[0]:filter_specs_dict})
# posted_data['matrixFilters'].update({filterOfMatrix[0]:{}}) #for spreadsheet
posted_data['matrixFeatures'].append(filterOfMatrix[0])
posted_data['matrixFeaturesOriginal'].append(filterOfMatrix[0])
posted_data['matrixTypes'].append(typeOfMatrix[0])
secondToLastOccurence = my_dir.rfind("/", 0, my_dir.rfind("/"))
my_dir = my_dir[:secondToLastOccurence + 1]
src = {
'created':dataloader.utils.getCurrentTime(),
'host': "127.0.1.1",
'ingest_id':file_name,
'matrices':[],
'name': nameOfSource,
'rootdir':my_dir,
'src_id': "test_files",
'src_type':"file"
}
ingestResult = dataloader.utils.ingest(posted_data, src)
ingestResultList = list(ingestResult)
typeListIngest = []
for i in range(len(exploreResultList)):
typeListExplore.append(type(exploreResultList[i]))
for i in range(len(ingestResultList)):
typeListIngest.append(type(ingestResultList[i]))
for file in os.listdir(my_dir):
if os.path.isdir(my_dir + file) and len(file) > 15:
shutil.rmtree(my_dir + file + "/")
if file.startswith("reduced_"):
os.remove(os.path.join(my_dir, file))
if dict in typeListExplore and int not in typeListExplore:
specificErrorMessage += "Missing a int, explore function must return both a dict and a int."
elif dict not in typeListExplore and int in typeListExplore:
specificErrorMessage += "Missing a dict, explore function must return both a dict and a int."
elif dict not in typeListExplore and int not in typeListExplore:
specificErrorMessage += "Missing a dict and int, explore function must return both a dict and a int."
if bool in typeListIngest and list not in typeListIngest:
specificErrorMessage += " Missing a list, ingest function must return both a boolean and a list."
elif bool not in typeListIngest and list in typeListIngest:
specificErrorMessage += " Missing a boolean value, ingest function must return both a boolean and a list."
elif bool not in typeListIngest and list not in typeListIngest:
specificErrorMessage += " Missing a boolean value and list, ingest function must return both a boolean and a list."
elif desiredInterface == 4:
conf = {
'mat_id':'27651d66d4cf4375a75208d3482476ac',
'storepath':'/home/vagrant/bedrock/bedrock-core/caa1a3105a22477f8f9b4a3124cd41b6/source/',
'src_id':'caa1a3105a22477f8f9b4a3124cd41b6',
'name':'iris'
}
checkResult = dataloader.utils.check(file_name, file_metaData['name'], conf)
if type(checkResult) != bool:
specificErrorMessage += "Missing boolean value, check funtion must return a boolean value."
applyResult = dataloader.utils.apply(file_name, file_metaData['parameters'], conf)
if type(applyResult) != dict:
specificErrorMessage += " Missing a dict object, apply function must return a dict object."
return specificErrorMessage
def create_input_dict(my_dir, inputList):
returnDict = {}
i = 0
j = 1
length = len(inputList)
for file in os.listdir(my_dir):
if file in inputList:
if length == 1 or (length > 1 and file != inputList[length - 1]) or (length > 1 and inputList[i] != inputList[i + 1]):
returnDict.update({file:{'rootdir':my_dir}})
elif length > 1 and inputList[i] == inputList[i + 1]:
firstNewFile = file + "_" + str(j)
j += 1
returnDict.update({firstNewFile:{'rootdir':my_dir}})
if j > 1:
secondNewFile = file + "_" + str(j)
returnDict.update({secondNewFile:{'rootdir':my_dir}})
i += 1
length -= 1
return returnDict
parser = argparse.ArgumentParser(description="Validate files being added to system.")
parser.add_argument('--api', help="The API where the file is trying to be inserted.", action='store', required=True, metavar='api')
parser.add_argument('--filename', help="Name of file inlcuding entire file path.", action='store', required=True, metavar='filename')
parser.add_argument('--input_directory', help="Directory where necessary inputs are stored", action='store', required=True, metavar='input_directory')
parser.add_argument('--filter_specs', help="Specifications for a used filter.", action='store', required=True, metavar='filter_specs')
parser.add_argument('--output_directory', help='Directory where outputs are stored (type NA if there will be no outputs).', action='store', required=True, metavar='output_directory')
args = parser.parse_args()
desiredInterface = 0
fileToCheck = args.filename
if args.api.lower() == "analytics":
desiredInterface = 1
elif args.api.lower() == "visualization":
desiredInterface = 2
elif args.api.lower() == "ingest":
desiredInterface = 3
elif args.api.lower() == "filter":
desiredInterface = 4
my_dir = args.input_directory
output_directory = args.output_directory
filter_specs = args.filter_specs
errorMessage = ""
errorMessage += str(find_imports(fileToCheck, desiredInterface))
errorMessage += str(compare_fuctions(fileToCheck, desiredInterface))
errorMessage += str(inheritance_check(fileToCheck, desiredInterface))
errorMessage += str(validate_file_name(fileToCheck, desiredInterface))
errorMessage += str(check_return_values(fileToCheck, desiredInterface))
if len(errorMessage) == 0:
print("File has been validated and is ready for input")
else:
print("Error Log: ")
print(errorMessage)
print(hard_type_check_return(fileToCheck, desiredInterface, my_dir, output_directory, filter_specs))
|
Bedrock-py/bedrock-core
|
validation/validationScript.py
|
Python
|
lgpl-3.0
| 17,191 |
<?php
namespace Google\AdsApi\Dfp\v201711;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class PackageActionError extends \Google\AdsApi\Dfp\v201711\ApiError
{
/**
* @var string $reason
*/
protected $reason = null;
/**
* @param string $fieldPath
* @param \Google\AdsApi\Dfp\v201711\FieldPathElement[] $fieldPathElements
* @param string $trigger
* @param string $errorString
* @param string $reason
*/
public function __construct($fieldPath = null, array $fieldPathElements = null, $trigger = null, $errorString = null, $reason = null)
{
parent::__construct($fieldPath, $fieldPathElements, $trigger, $errorString);
$this->reason = $reason;
}
/**
* @return string
*/
public function getReason()
{
return $this->reason;
}
/**
* @param string $reason
* @return \Google\AdsApi\Dfp\v201711\PackageActionError
*/
public function setReason($reason)
{
$this->reason = $reason;
return $this;
}
}
|
advanced-online-marketing/AOM
|
vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201711/PackageActionError.php
|
PHP
|
lgpl-3.0
| 1,058 |
/**************************************************************************************************
// file: Engine\Math\CShape.cpp
// A2DE
// Copyright (c) 2013 Blisspoint Softworks and Casey Ugone. All rights reserved.
// Contact cugone@gmail.com for questions or support.
// summary: Implements the shape class
**************************************************************************************************/
#include "CShape.h"
#include "CPoint.h"
#include "CLine.h"
#include "CRectangle.h"
#include "CCircle.h"
#include "CEllipse.h"
#include "CTriangle.h"
#include "CArc.h"
#include "CPolygon.h"
#include "CSpline.h"
#include "CSector.h"
A2DE_BEGIN
Shape::Shape() :
_position(0.0, 0.0),
_half_extents(0.0, 0.0),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(al_map_rgb(0, 0, 0)),
_filled(false) { }
Shape::Shape(double x, double y) :
_position(x, y),
_half_extents(0.0, 0.0),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(al_map_rgb(0, 0, 0)),
_filled(false) { }
Shape::Shape(const Vector2D& position) :
_position(position),
_half_extents(0.0, 0.0),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(al_map_rgb(0, 0, 0)),
_filled(false) { }
Shape::Shape(double x, double y, double half_width, double half_height) :
_position(x, y),
_half_extents(half_width, half_height),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(al_map_rgb(0, 0, 0)),
_filled(false) { }
Shape::Shape(const Vector2D& position, double half_width, double half_height) :
_position(position),
_half_extents(half_width, half_height),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(al_map_rgb(0, 0, 0)),
_filled(false) { }
Shape::Shape(double x, double y, const Vector2D& half_extents) :
_position(x, y),
_half_extents(half_extents),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(al_map_rgb(0, 0, 0)),
_filled(false) { }
Shape::Shape(const Vector2D& position, const Vector2D& half_extents) :
_position(position),
_half_extents(half_extents),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(al_map_rgb(0, 0, 0)),
_filled(false) { }
Shape::Shape(double x, double y, double half_width, double half_height, const ALLEGRO_COLOR& color) :
_position(x, y),
_half_extents(half_width, half_height),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(false) { }
Shape::Shape(const Vector2D& position, double half_width, double half_height, const ALLEGRO_COLOR& color) :
_position(position),
_half_extents(half_width, half_height),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(false) { }
Shape::Shape(double x, double y, const Vector2D& half_extents, const ALLEGRO_COLOR& color) :
_position(x, y),
_half_extents(half_extents),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(false) { }
Shape::Shape(const Vector2D& position, const Vector2D& half_extents, const ALLEGRO_COLOR& color) :
_position(position),
_half_extents(half_extents),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(false) { }
Shape::Shape(double x, double y, double half_width, double half_height, const ALLEGRO_COLOR& color, bool filled) :
_position(x, y),
_half_extents(half_width, half_height),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(filled) { }
Shape::Shape(const Vector2D& position, double half_width, double half_height, const ALLEGRO_COLOR& color, bool filled) :
_position(position),
_half_extents(half_width, half_height),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(filled) { }
Shape::Shape(double x, double y, const Vector2D& half_extents, const ALLEGRO_COLOR& color, bool filled) :
_position(x, y),
_half_extents(half_extents),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(filled) { }
Shape::Shape(const Vector2D& position, const Vector2D& half_extents, const ALLEGRO_COLOR& color, bool filled) :
_position(position),
_half_extents(half_extents),
_area(0.0),
_type(Shape::SHAPETYPE_SHAPE),
_color(color),
_filled(filled) { }
Shape::Shape(const Shape& shape) :
_position(shape._position),
_half_extents(shape._half_extents),
_area(shape._area),
_type(Shape::SHAPETYPE_SHAPE),
_color(shape._color),
_filled(shape._filled) { }
Shape& Shape::operator=(const Shape& rhs) {
if(this == &rhs) return *this;
this->_position = rhs._position;
this->_half_extents = rhs._half_extents;
this->_area = rhs._area;
this->_type = rhs._type;
this->_color = rhs._color;
this->_filled = rhs._filled;
return *this;
}
Shape::~Shape() {
}
const ALLEGRO_COLOR& Shape::GetColor() const {
return _color;
}
ALLEGRO_COLOR& Shape::GetColor() {
return const_cast<ALLEGRO_COLOR&>(static_cast<const Shape&>(*this).GetColor());
}
bool Shape::IsFilled() const {
return _filled;
}
void Shape::SetColor(const ALLEGRO_COLOR& color) {
_color = color;
}
void Shape::SetFill(bool filled) {
_filled = filled;
}
double Shape::GetHalfWidth() const {
return _half_extents.GetX();
}
double Shape::GetHalfWidth(){
return static_cast<const Shape&>(*this).GetHalfWidth();
}
double Shape::GetHalfHeight() const {
return _half_extents.GetY();
}
double Shape::GetHalfHeight() {
return static_cast<const Shape&>(*this).GetHalfHeight();
}
const Vector2D& Shape::GetHalfExtents() const {
return _half_extents;
}
Vector2D& Shape::GetHalfExtents() {
return const_cast<a2de::Vector2D&>(static_cast<const Shape&>(*this).GetHalfExtents());
}
const Vector2D& Shape::GetPosition() const {
return _position;
}
Vector2D& Shape::GetPosition() {
return const_cast<a2de::Vector2D&>(static_cast<const Shape&>(*this).GetPosition());
}
double Shape::GetArea() const {
return _area;
}
double Shape::GetArea() {
return static_cast<const Shape&>(*this).GetArea();
}
double Shape::GetX() const {
return _position.GetX();
}
double Shape::GetX() {
return static_cast<const Shape&>(*this).GetX();
}
double Shape::GetY() const {
return _position.GetY();
}
double Shape::GetY() {
return static_cast<const Shape&>(*this).GetY();
}
void Shape::SetX(double x) {
SetPosition(x, GetY());
}
void Shape::SetY(double y) {
SetPosition(GetX(), y);
}
void Shape::SetPosition(double x, double y) {
SetPosition(Vector2D(x, y));
}
void Shape::SetPosition(const Vector2D& position) {
_position = position;
}
void Shape::SetHalfWidth(double width) {
SetHalfExtents(width, GetHalfHeight());
}
void Shape::SetHalfHeight(double height) {
SetHalfExtents(GetHalfWidth(), height);
}
void Shape::SetHalfExtents(double width, double height) {
SetHalfExtents(Vector2D(width, height));
}
void Shape::SetHalfExtents(const Vector2D& dimensions) {
_half_extents = dimensions;
}
const Shape::SHAPE_TYPE& Shape::GetShapeType() const {
return _type;
}
Shape::SHAPE_TYPE& Shape::GetShapeType() {
return const_cast<Shape::SHAPE_TYPE&>(static_cast<const Shape&>(*this).GetShapeType());
}
Shape* Shape::Clone(Shape* shape) {
if(shape == nullptr) return nullptr;
Shape::SHAPE_TYPE type = shape->GetShapeType();
switch(type) {
case Shape::SHAPETYPE_POINT:
return new Point(*dynamic_cast<Point*>(shape));
case Shape::SHAPETYPE_LINE:
return new Line(*dynamic_cast<Line*>(shape));
case Shape::SHAPETYPE_RECTANGLE:
return new Rectangle(*dynamic_cast<Rectangle*>(shape));
case Shape::SHAPETYPE_CIRCLE:
return new Circle(*dynamic_cast<Circle*>(shape));
case Shape::SHAPETYPE_ELLIPSE:
return new Ellipse(*dynamic_cast<Ellipse*>(shape));
case Shape::SHAPETYPE_TRIANGLE:
return new Triangle(*dynamic_cast<Triangle*>(shape));
case Shape::SHAPETYPE_ARC:
return new Arc(*dynamic_cast<Arc*>(shape));
case Shape::SHAPETYPE_POLYGON:
return new Polygon(*dynamic_cast<Polygon*>(shape));
case Shape::SHAPETYPE_SPLINE:
return new Spline(*dynamic_cast<Spline*>(shape));
case Shape::SHAPETYPE_SECTOR:
return new Sector(*dynamic_cast<Sector*>(shape));
default:
return nullptr;
}
}
bool Shape::Contains(const Shape& shape) const {
Shape::SHAPE_TYPE type = shape.GetShapeType();
switch(type) {
case Shape::SHAPETYPE_POINT:
return this->Contains(dynamic_cast<const Point&>(shape));
case Shape::SHAPETYPE_LINE:
return this->Contains(dynamic_cast<const Line&>(shape));
case Shape::SHAPETYPE_RECTANGLE:
return this->Contains(dynamic_cast<const Rectangle&>(shape));
case Shape::SHAPETYPE_CIRCLE:
return this->Contains(dynamic_cast<const Circle&>(shape));
case Shape::SHAPETYPE_ELLIPSE:
return this->Contains(dynamic_cast<const Ellipse&>(shape));
case Shape::SHAPETYPE_TRIANGLE:
return this->Contains(dynamic_cast<const Triangle&>(shape));
case Shape::SHAPETYPE_ARC:
return this->Contains(dynamic_cast<const Arc&>(shape));
case Shape::SHAPETYPE_POLYGON:
return this->Contains(dynamic_cast<const Polygon&>(shape));
case Shape::SHAPETYPE_SPLINE:
return this->Contains(dynamic_cast<const Spline&>(shape));
case Shape::SHAPETYPE_SECTOR:
return this->Contains(dynamic_cast<const Sector&>(shape));
default:
return false;
}
}
bool Shape::Contains(const Point& point) const {
return this->Intersects(point);
}
bool Shape::Contains(const Line& line) const {
return this->Intersects(line.GetPointOne()) && this->Intersects(line.GetPointTwo());
}
bool Shape::Contains(const Rectangle& rectangle) const {
double rleft = rectangle.GetX();
double rtop = rectangle.GetY();
double rright = rleft + rectangle.GetHalfWidth();
double rbottom = rtop + rectangle.GetHalfHeight();
double tleft = this->GetX();
double ttop = this->GetY();
double tright = tleft + this->GetHalfWidth();
double tbottom = ttop + this->GetHalfHeight();
bool is_exact = a2de::Math::IsEqual(rtop, ttop) && a2de::Math::IsEqual(rleft, tleft) && a2de::Math::IsEqual(rbottom, tbottom) && a2de::Math::IsEqual(rright, tright);
bool is_smaller = (rtop > ttop && rleft > tleft && rbottom < tbottom && rright < tright);
return (is_exact || is_smaller);
}
bool Shape::Contains(const Circle& circle) const {
double cdiameter = circle.GetDiameter();
double twidth = this->GetHalfWidth();
double theight = this->GetHalfHeight();
bool diameter_equal_to_width = a2de::Math::IsEqual(cdiameter, twidth);
bool diameter_equal_to_height = a2de::Math::IsEqual(cdiameter, theight);
bool diameter_less_than_width = cdiameter < twidth;
bool diameter_less_than_height = cdiameter < theight;
bool diameter_less_equal_width = diameter_less_than_width || diameter_equal_to_width;
bool diameter_less_equal_height = diameter_less_than_height || diameter_equal_to_height;
bool center_inside_shape = this->Intersects(Point(circle.GetPosition()));
bool contains = center_inside_shape && diameter_less_equal_width && diameter_less_equal_height;
return contains;
}
bool Shape::Contains(const Ellipse& ellipse) const {
return this->Intersects(Point(ellipse.GetPosition())) && ellipse.GetHalfWidth() <= this->GetHalfWidth() && ellipse.GetHalfHeight() <= this->GetHalfHeight();
}
bool Shape::Contains(const Triangle& triangle) const {
return this->Intersects(Point(triangle.GetPointA())) && this->Intersects(Point(triangle.GetPointB())) && this->Intersects(Point(triangle.GetPointC()));
}
bool Shape::Contains(const Arc& arc) const {
return this->Intersects(arc.GetStartPoint()) && this->Intersects(arc.GetEndPoint());
}
bool Shape::Contains(const Polygon& polygon) const {
int total_points = polygon.GetNumVertices();
for(int i = 0; i < total_points; ++i) {
if(this->Intersects(polygon.GetVertices()[i])) continue;
return false;
}
return true;
}
bool Shape::Contains(const Spline& /*spline*/) const {
return false;
}
bool Shape::Contains(const Sector& sector) const {
return this->Intersects(sector.GetStartPoint()) && this->Intersects(sector.GetEndPoint()) && this->Intersects(Point(sector.GetPosition()));
}
void Shape::Draw(ALLEGRO_BITMAP* dest) {
this->Draw(dest, _color, _filled);
}
A2DE_END
|
cugone/Abrams2012
|
Allegro2DEngine/Engine/Math/CShape.cpp
|
C++
|
lgpl-3.0
| 12,152 |
<?php
/**
* Venne:CMS (version 2.0-dev released on $WCDATE$)
*
* Copyright (c) 2011 Josef Kříž pepakriz@gmail.com
*
* For the full copyright and license information, please view
* the file license.txt that was distributed with this source code.
*/
namespace App\SecurityModule\AdminModule;
/**
* @author Josef Kříž
* @resource AdminModule\SecurityModule\Security
*/
class DefaultPresenter extends BasePresenter
{
public function renderDefault()
{
}
}
|
Venne/Venne-CMS-old
|
App/SecurityModule/AdminModule/presenters/DefaultPresenter.php
|
PHP
|
lgpl-3.0
| 477 |
/**
\author Shestakov Mikhail aka MIKE
\date 12.12.2012 (c)Andrey Korotkov
This file is a part of DGLE project and is distributed
under the terms of the GNU Lesser General Public License.
See "DGLE.h" for more details.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Gtk;
namespace Packer
{
public static class TreeViewExtensions
{
public static IEnumerable<TreeIter> GetSelected(this TreeView tree)
{
return tree.Selection.GetSelectedRows().ToList().Select(path =>
{
TreeIter selectedIter;
if (tree.Model.GetIter(out selectedIter, path))
return selectedIter;
return TreeIter.Zero;
});
}
public static void SelectAndFocus(this TreeView tree, TreeIter iter)
{
tree.Selection.SelectIter(iter);
tree.GrabFocus();
}
public static void SelectAndFocus(this TreeView tree, TreePath path)
{
tree.Selection.SelectPath(path);
tree.GrabFocus();
}
}
}
|
DGLE-HQ/DGLE
|
src/tools/packer/TreeViewExtensions.cs
|
C#
|
lgpl-3.0
| 940 |
<?php declare(strict_types=1);
namespace ju1ius\Pegasus\Parser\Exception;
class ParseError extends \RuntimeException {}
|
ju1ius/pegasus
|
src/Parser/Exception/ParseError.php
|
PHP
|
lgpl-3.0
| 122 |
package broad.core.siphy;
public class UnableToFitException extends Exception {
private static final long serialVersionUID = 285381715807645775L;
public UnableToFitException(String msg) {
super(msg);
}
}
|
mgarber/scriptureV2
|
src/java/broad/core/siphy/UnableToFitException.java
|
Java
|
lgpl-3.0
| 214 |
package org.javlo.component.social;
public class FacebookFriend {
private String name;
private String image;
public FacebookFriend(String name, String image) {
this.name = name;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
|
Javlo/javlo
|
src/main/java/org/javlo/component/social/FacebookFriend.java
|
Java
|
lgpl-3.0
| 427 |
if (typeof ui == 'undefined') var ui = {};
ui.Template = {
reg_vaild_preceding_chars: '(?:[^-\\/"\':!=a-zA-Z0-9_]|^)',
reg_url_path_chars_1: '[a-zA-Z0-9!\\*\';:=\\+\\$/%#\\[\\]\\?\\-_,~\\(\\)&\\.`@]',
reg_url_path_chars_2: '[a-zA-Z0-9!\':=\\+\\$/%#~\\(\\)&`@]',
reg_url_proto_chars: '([a-zA-Z]+:\\/\\/|www\\.)',
reg_user_name_chars: '[@@]([a-zA-Z0-9_]{1,20})',
reg_list_name_template: '[@@]([a-zA-Z0-9_]{1,20}/[a-zA-Z][a-zA-Z0-9_\\-\u0080-\u00ff]{0,24})',
// from https://si0.twimg.com/c/phoenix/en/bundle/t1-hogan-core.f760c184d1eaaf1cf27535473a7306ef.js
reg_hash_tag_latin_chars: '\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u024f\u0253-\u0254\u0256-\u0257\u0259\u025b\u0263\u0268\u026f\u0272\u0289\u028b\u02bb\u1e00-\u1eff',
reg_hash_tag_nonlatin_chars: '\u0400-\u04ff\u0500-\u0527\u2de0-\u2dff\ua640-\ua69f\u0591-\u05bd\u05bf\u05c1-\u05c2\u05c4-\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\ufb12-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufb4f\u0610-\u061a\u0620-\u065f\u066e-\u06d3\u06d5-\u06dc\u06de-\u06e8\u06ea-\u06ef\u06fa-\u06fc\u06ff\u0750-\u077f\u08a0\u08a2-\u08ac\u08e4-\u08fe\ufb50-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\u200c\u0e01-\u0e3a\u0e40-\u0e4e\u1100-\u11ff\u3130-\u3185\ua960-\ua97f\uac00-\ud7af\ud7b0-\ud7ff\uffa1-\uffdc\u30a1-\u30fa\u30fc-\u30fe\uff66-\uff9f\uff70\uff10-\uff19\uff21-\uff3a\uff41-\uff5a\u3041-\u3096\u3099-\u309e\u3400-\u4dbf\u4e00-\u9fff\ua700-\ub73f\ub740-\ub81f\uf800-\ufa1f\u3003\u3005\u303b',
reg_hash_tag_template: '(^|\\s)[##]([a-z0-9_{%LATIN_CHARS%}{%NONLATIN_CHARS%}]*)',
reg_hash_tag: null,
reg_is_rtl: new RegExp('[\u0600-\u06ff]|[\ufe70-\ufeff]|[\ufb50-\ufdff]|[\u0590-\u05ff]'),
tweet_t:
'<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%} {%FAV_CLASS%}" type="tweet" retweet_id="{%RETWEET_ID%}" reply_id="{%REPLY_ID%}" in_thread="{%IN_THREAD%}" reply_name="{%REPLY_NAME%}" screen_name="{%SCREEN_NAME%}" retweetable="{%RETWEETABLE%}" deletable="{%DELETABLE%}" link="{%LINK%}" style="font-family: {%TWEET_FONT%};">\
<div class="tweet_color_label" style="background-color:{%COLOR_LABEL%}"></div>\
<div class="tweet_selected_indicator"></div>\
<div class="tweet_fav_indicator"></div>\
<div class="deleted_mark"></div>\
<div class="tweet_retweet_indicator"></div>\
<div class="profile_img_wrapper" title="{%USER_NAME%}\n\n{%DESCRIPTION%}" style="background-image: url({%PROFILE_IMG%})">\
</div>\
<ul class="tweet_bar">\
<li>\
<a class="tweet_bar_btn tweet_reply_btn" title="Reply this tweet" href="#reply" data-i18n-title="reply"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_fav_btn" title="Fav/Un-fav this tweet" href="#fav" data-i18n-title="fav_or_unfav"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_retweet_btn" title="Official retweet/un-retweet this tweet" href="#retweet" data-i18n-title="retweet"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\
</li>\
</ul>\
<div class="card_body">\
<div class="who {%RETWEET_MARK%}">\
<a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}\n\n{%DESCRIPTION%}">\
{%SCREEN_NAME%}\
</a>\
</div>\
<div class="text" alt="{%ALT%}" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%TEXT%}</div>\
<div class="tweet_meta">\
<div class="tweet_thread_info" style="display:{%IN_REPLY%}">\
<a class="btn_tweet_thread" href="#"></a>\
{%REPLY_TEXT%}\
</div>\
<div class="tweet_source"> \
{%RETWEET_TEXT%} \
<span class="tweet_timestamp">\
<a class="tweet_link tweet_update_timestamp" target="_blank" href="{%TWEET_BASE_URL%}/{%TWEET_ID%}" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</a>\
</span>\
{%TRANS_via%}: {%SOURCE%}</div>\
<div class="status_bar">{%STATUS_INDICATOR%}</div>\
</div>\
</div>\
<span class="shape"></span>\
<span class="shape_mask"></span>\
<div class="tweet_thread_wrapper">\
<div class="tweet_thread_hint">{%TRANS_Loading%}</div>\
<ul class="tweet_thread"></ul>\
<a class="btn_tweet_thread_more">{%TRANS_View_more_conversation%}</a>\
</div>\
</li>',
trending_topic_t:
'<li id="{%ID%}" class="card" type="trending_topic">\
<div class="profile_img_wrapper trend_topic_number">#{%ID%}</div>\
<div class="card_body keep_height">\
<a class="hash_href trending_topic" href="{%NAME%}">{%NAME%}</a>\
</div>\
<span class="shape"></span>\
<span class="shape_mask"></span>\
</li>',
retweeted_by_t:
'<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%} {%FAV_CLASS%}" type="tweet" retweet_id="{%RETWEET_ID%}" reply_id="{%REPLY_ID%}" reply_name="{%REPLY_NAME%}" screen_name="{%SCREEN_NAME%}" retweetable="{%RETWEETABLE%}" deletable="{%DELETABLE%}" style="font-family: {%TWEET_FONT%};">\
<div class="tweet_active_indicator"></div>\
<div class="tweet_selected_indicator"></div>\
<div class="deleted_mark"></div>\
<div class="tweet_fav_indicator"></div>\
<div class="tweet_retweet_indicator"></div>\
<div class="profile_img_wrapper" title="{%USER_NAME%}" style="background-image: url({%PROFILE_IMG%})">\
</div>\
<ul class="tweet_bar">\
<li>\
<a class="tweet_bar_btn tweet_reply_btn" title="Reply this tweet" href="#reply" data-i18n-title="reply"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_fav_btn" title="Fav/Un-fav this tweet" href="#fav" data-i18n-title="fav_or_unfav"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_retweet_btn" title="Official retweet/un-retweet this tweet" href="#retweet" data-i18n-title="retweet"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\
</li>\
</ul>\
<div class="card_body">\
<div class="who {%RETWEET_MARK%}">\
<a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}">\
{%SCREEN_NAME%}\
</a>\
</div>\
<div class="text" alt="{%ALT%}" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%TEXT%}</div>\
<div class="tweet_meta">\
<div class="tweet_thread_info" style="display:{%IN_REPLY%}">\
<a class="btn_tweet_thread" href="#"></a>\
{%REPLY_TEXT%}\
</div>\
<div class="tweet_source"> \
{%RETWEET_TEXT%} \
<span class="tweet_timestamp">\
<a class="tweet_link tweet_update_timestamp" target="_blank" href="{%TWEET_BASE_URL%}/{%TWEET_ID%}" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</a>\
</span>\
{%TRANS_via%}: {%SOURCE%}\
{%TRANS_Retweeted_by%}: <a class="show" href="#" title="{%TRANS_Click_to_show_retweeters%}" tweet_id="{%TWEET_ID%}">{%TRANS_Show_retweeters%}</a>\
</div>\
<div class="tweet_retweeters" tweet_id="{%TWEET_ID%}"></div>\
<div class="status_bar">{%STATUS_INDICATOR%}</div>\
</div>\
</div>\
<span class="shape"></span>\
<span class="shape_mask"></span>\
<div class="tweet_thread_wrapper">\
<div class="tweet_thread_hint">{%TRANS_Loading%}</div>\
<ul class="tweet_thread"></ul>\
<a class="btn_tweet_thread_more">{%TRANS_View_more_conversation%}</a>\
</div>\
</li>',
message_t:
'<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%}" type="message" sender_screen_name="{%SCREEN_NAME%}" style="font-family: {%TWEET_FONT%};">\
<div class="tweet_active_indicator"></div>\
<div class="tweet_selected_indicator"></div>\
<div class="profile_img_wrapper" title="{%USER_NAME%}\n\n{%DESCRIPTION%}" style="background-image: url({%PROFILE_IMG%})">\
</div>\
<ul class="tweet_bar">\
<li>\
<a class="tweet_bar_btn tweet_dm_reply_btn" title="Reply them" href="#reply_dm" data-i18n-title="reply"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\
</li>\
</ul>\
<div class="card_body">\
<div class="who">\
<a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}\n\n{%DESCRIPTION%}">\
{%SCREEN_NAME%}\
</a>\
</div>\
<div class="text" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">@<a class="who_href" href="#{%RECIPIENT_SCREEN_NAME%}">{%RECIPIENT_SCREEN_NAME%}</a> {%TEXT%}</div>\
<div class="tweet_meta">\
<div class="tweet_source"> \
<span class="tweet_timestamp tweet_update_timestamp" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</span>\
</div>\
</div>\
</div>\
<span class="shape"></span>\
<span class="shape_mask"></span>\
</li>',
search_t:
'<li id="{%ID%}" tweet_id="{%TWEET_ID%}" class="card {%SCHEME%}" type="search" screen_name="{%SCREEN_NAME%}" link="{%LINK%}" style="font-family: {%TWEET_FONT%};">\
<div class="tweet_active_indicator"></div>\
<div class="tweet_selected_indicator"></div>\
<div class="deleted_mark"></div>\
<div class="profile_img_wrapper" title="{%USER_NAME%}" style="background-image: url({%PROFILE_IMG%})">\
</div>\
<ul class="tweet_bar">\
<li>\
<a class="tweet_bar_btn tweet_reply_btn" title="Reply this tweet" href="#reply" data-i18n-title="reply"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_fav_btn" title="Fav/Un-fav this tweet" href="#fav" data-i18n-title="fav_or_unfav"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_retweet_btn" title="Official retweet/un-retweet this tweet" href="#retweet" data-i18n-title="retweet"></a>\
</li><li>\
<a class="tweet_bar_btn tweet_more_menu_trigger" href="#more"></a>\
</li>\
</ul>\
<div class="card_body">\
<div class="who">\
<a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}">\
{%SCREEN_NAME%}\
</a>\
</div>\
<div class="text" style="font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%TEXT%}</div>\
<div class="tweet_meta">\
<div class="tweet_source"> \
<span class="tweet_timestamp">\
<a class="tweet_link tweet_update_timestamp" target="_blank" href="{%TWEET_BASE_URL%}/{%TWEET_ID%}" title="{%TIMESTAMP%}">{%SHORT_TIMESTAMP%}</a>\
</span>\
{%TRANS_via%}: {%SOURCE%}</div>\
</div>\
</div>\
<span class="shape"></span>\
<span class="shape_mask"></span>\
</li>',
people_t:
'<li id="{%USER_ID%}" class="people_card card normal" type="people" following={%FOLLOWING%} screen_name={%SCREEN_NAME%} style="font-family: {%TWEET_FONT%};">\
<div class="tweet_active_indicator"></div>\
<div class="tweet_selected_indicator"></div>\
<div class="profile_img_wrapper" title="{%USER_NAME%}" style="background-image: url({%PROFILE_IMG%})">\
</div>\
<ul class="tweet_bar">\
<li style="display:none;">\
<a class="tweet_bar_btn add_to_list_btn" title="Add to list" href="#follow" data-i18n-title="add_to_list"></a>\
</li><li>\
<a class="tweet_bar_btn follow_btn" title="Follow them" href="#follow" data-i18n-title="follow"></a>\
</li><li>\
<a class="tweet_bar_btn unfollow_btn" title="Unfollow them" href="#unfollow" data-i18n-title="unfollow"></a>\
</li>\
</ul>\
<div class="card_body">\
<div id="{%USER_ID%}" class="who">\
<a class="who_href" href="#{%SCREEN_NAME%}" title="{%USER_NAME%}">\
{%SCREEN_NAME%}\
</a>\
</div>\
<div class="text" style="font-style:italic font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%DESCRIPTION%}</div>\
</div>\
<span class="shape"></span>\
<span class="shape_mask"></span>\
</li>',
people_vcard_t_orig:
'<div class="header_frame">\
<div class="people_vcard vcard">\
<a target="_blank" class="profile_img_wrapper"></a>\
<div class="vcard_body">\
<center>\
<ul class="people_vcard_radio_group mochi_button_group"> \
<li><a class="mochi_button_group_item selected" href="#people_vcard_info_page" name="">{%TRANS_info%}</a> \
</li><li><a class="mochi_button_group_item" href="#people_vcard_stat_page">{%TRANS_stat%}</a> \
</li></ul>\
</center>\
<div class="vcard_tabs_pages">\
<table class="people_vcard_info_page vcard_tabs_page radio_group_page" border="0" cellpadding="0" cellspacing="0"> \
<tr><td>{%TRANS_name%}: </td><td> \
<a class="screen_name" target="_blank" href="#"></a> \
(<span class="name"></span>) </td> \
</tr> \
<tr><td>{%TRANS_bio%}: </td> \
<td><span class="bio"></span></td> \
</tr> \
<tr><td>{%TRANS_web%}: </td> \
<td><a class="web" target="_blank" href="#" class="link"></a></td> \
</tr> \
<tr><td>{%TRANS_location%}: </td> \
<td><span class="location"></span></td> \
</tr> \
</table> \
<table class="people_vcard_stat_page vcard_tabs_page radio_group_page"> \
<tr><td>{%TRANS_join%}: </td> \
<td><span class="join"></span></td> \
</tr> \
<tr><td>{%TRANS_tweet_cnt%}: </td> \
<td><span class="tweet_cnt"></span> \
(<span class="tweet_per_day_cnt"></span> per day)</td> \
</tr> \
<tr><td>{%TRANS_follower_cnt%}: </td> \
<td><span class="follower_cnt"></span></td> \
</tr> \
<tr><td>{%TRANS_friend_cnt%}: </td> \
<td><span class="friend_cnt"></span></td> \
</tr> \
<tr><td>{%TRANS_listed_cnt%}: </td> \
<td><span class="listed_cnt"></span></td> \
</tr> \
<tr><td>{%TRANS_relation%}: </td> \
<td><span class="relation"></span></td> \
</tr> \
</table> \
</div><!-- vcard tabs pages --> \
</div> <!-- vcard body --> \
<div class="vcard_ctrl"> \
<ul class="vcard_action_btns"> \
<li><a class="vcard_follow mochi_button blue" \
href="#" >{%TRANS_follow%}</a> \
</li><li> \
<a class="vcard_edit mochi_button" \
href="#" style="display:none;">{%TRANS_edit%}</a>\
</li><li class="people_action_more_trigger"> \
<a class="vcard_more mochi_button" \
href="#">{%TRANS_more_actions%} ▾</a> \
<ul class="people_action_more_memu hotot_menu">\
<li><a class="mention_menu_item" \
title="Mention them"\
href="#">{%TRANS_mention_them%}</a>\
</li><li><a class="message_menu_item" \
title="Send Message to them"\
href="#">{%TRANS_message_them%}</a>\
</li><li><a class="add_to_list_menu_item" \
title="Add them to a list"\
href="#">{%TRANS_add_to_list%}</a>\
</li><li class="separator"><span></span>\
</li><li><a class="block_menu_item" \
title="Block"\
href="#">{%TRANS_block%}</a>\
</li><li><a class="unblock_menu_item"\
href="#" \
title="Unblock">{%TRANS_unblock%}</a>\
</li><li><a class="report_spam_menu_item" \
href="#" \
title="Report Spam">{%TRANS_report_spam%}</a>\
</li>\
</ul>\
</li> \
</ul> \
</div><!-- #people_vcard_ctrl --> \
</div> <!-- vcard --> \
<div class="expand_wrapper"><a href="#" class="expand">…</a></div>\
<div class="people_view_toggle"> \
<ol class="people_view_toggle_btns mochi_button_group"> \
<li><a class="people_view_tweet_btn mochi_button_group_item selected" href="#tweet">{%TRANS_tweets%}</a> \
</li><li> \
<a class="people_view_fav_btn mochi_button_group_item" href="#fav">{%TRANS_favs%}</a> \
</li><li class="people_view_people_trigger"> \
<a class="people_view_people_btn mochi_button_group_item" href="#people">{%TRANS_fellowship%} ▾</a> \
<ul class="people_menu hotot_menu">\
<li><a class="followers_menu_item" \
title="People who follow them."\
href="#">{%TRANS_followers%}</a>\
</li><li><a class="friends_menu_item"\
href="People them is following" \
title="All Lists following Them">{%TRANS_friends%}</a>\
</li>\
</ul>\
</li><li class="people_view_list_trigger"> \
<a class="people_view_list_btn mochi_button_group_item" href="#list">{%TRANS_lists%} ▾\
</a> \
<ul class="lists_menu hotot_menu">\
<li><a class="user_lists_menu_item" \
title="Lists of Them"\
href="#">{%TRANS_lists_of_them%}</a>\
</li><li><a class="listed_lists_menu_item"\
href="#" \
title="All Lists following Them">{%TRANS_lists_following_them%}</a>\
</li><li><a class="create_list_menu_item" \
href="#" \
title="Create A List">{%TRANS_create_a_list%}</a>\
</li>\
</ul>\
</li> \
</ol> \
</div> \
<div class="people_request_hint"> \
<h1 data-i18n-text="he_she_has_protexted_his_her_tweets">He/She has protected his/her tweets.</span></h1> \
<p data-i18n-text="you_need_to_go_to_twitter_com_to_send_a_request_before_you_can_start_following_this_persion">You need to go to twitter.com to send a request before you can start following this person...</p> \
<div style="text-align:center;"> \
<a class="people_request_btn mochi_button" href="#" target="_blank" data-i18n-text="send_request">Send Request</a> \
</div> \
</div></div>',
list_t:
'<li id="{%LIST_ID%}" class="list_card card normal" type="list" following={%FOLLOWING%} screen_name={%SCREEN_NAME%} slug={%SLUG%} style="font-family: {%TWEET_FONT%};">\
<div class="tweet_active_indicator"></div>\
<div class="tweet_selected_indicator"></div>\
<div class="profile_img_wrapper" title="@{%USER_NAME%}/{%SLUG%}" style="background-image: url({%PROFILE_IMG%})">\
</div>\
<ul class="tweet_bar">\
<li>\
<a class="tweet_bar_btn follow_btn" title="Follow them" href="#follow" data-i18n-title="follow"></a>\
</li><li>\
<a class="tweet_bar_btn unfollow_btn" title="Unfollow them" href="#unfollow" data-i18n-title="unfollow"></a>\
</li>\
</ul>\
<div class="card_body">\
<div id="{%USER_ID%}" class="who">\
<a class="list_href" href="#{%SCREEN_NAME%}/{%SLUG%}" title="{%USER_NAME%}/{%SLUG%}">\
@{%SCREEN_NAME%}/{%SLUG%}\
</a>\
</div>\
<div class="text" style="font-style:italic font-size:{%TWEET_FONT_SIZE%}pt;line-height:{%TWEET_LINE_HEIGHT%}">{%DESCRIPTION%}</div>\
</div>\
<span class="shape"></span>\
<span class="shape_mask"></span>\
</li>',
list_vcard_t:
'<div class="header_frame"><div class="list_vcard vcard">\
<a target="_blank" class="profile_img_wrapper"></a>\
<div class="vcard_body">\
<div class="vcard_tabs_pages">\
<table border="0" cellpadding="0" cellspacing="0" class="vcard_tabs_page" style="display:block;"> \
<tr><td data-i18n-text="name">Name: </td><td> \
<a class="name" target="_blank" href="#"></a></td> \
</tr> \
<tr><td>Owner: </td> \
<td><a class="owner" target="_blank" href="#" data-i18n-text="owner"></a></td> \
</tr> \
<tr><td data-i18n-text="description">Description: </td> \
<td><span class="description"></span></td> \
</tr> \
</table> \
</div>\
</div> <!-- vcard body --> \
<div class="vcard_ctrl"> \
<ul class="vcard_action_btns"> \
<li><a class="vcard_follow mochi_button blue" \
href="#" data-i18n-text="follow">Follow</a> \
</li><li> \
<a class="vcard_delete mochi_button red" \
href="#" data-i18n-text="delete">Delete</a> \
</li><li> \
<a class="vcard_edit mochi_button" \
href="#" style="display:none;" data-i18n-text="edit">Edit</a>\
</li> \
</ul> \
</div><!-- #list_vcard_ctrl --> \
</div> <!-- vcard --> \
<div class="expand_wrapper"><a href="#" class="expand">…</a></div>\
<div class="list_view_toggle"> \
<ol class="list_view_toggle_btns mochi_button_group"> \
<li><a class="list_view_tweet_btn mochi_button_group_item selected" href="#tweet" data-i18n-text="tweets">Tweets</a> \
</li><li> \
<a class="list_view_follower_btn mochi_button_group_item" href="#follower" data-i18n-text="followers">Followers</a> \
</li><li> \
<a class="list_view_following_btn mochi_button_group_item" href="#following" data-i18n-text="following">Following</a> \
</li> \
</ol> \
</div> \
<div class="list_lock_hint"> \
<h1 data-i18n-text="he_she_has_protected_his_her_list">He/She has protected his/her list.</span></h1> \
<p data-i18n-text="only_the_owner_can_access_this_list">Only the owner can access this list.</p> \
</div></div>',
search_header_t:
'<div class="header_frame"> \
<div class="search_box"> \
<input class="search_entry mochi_entry" type="text" placeholder="Type and press enter to search." data-i18n-placeholder="type_and_press_enter_to_search"/> \
<a href="#" class="search_entry_clear_btn"></a>\
<div class="search_people_result"> \
<span data-i18n-text="one_user_matched">One user matched: </span> <span class="search_people_inner"></span>\
</div>\
<div class="saved_searches">\
<a id="create_saved_search_btn" class="mochi_button" \
href="#" title="Detach" data-i18n-title="detach"> +\
</a>\
<div id="saved_searches_more_trigger" style="display:none;">\
<a id="saved_searches_btn" class="vcard_more mochi_button" \
href="#"> ▾</a> \
<ul id="saved_searches_more_menu" class="hotot_menu">\
<li><a class="" \
title="Clear ALL"\
href="#" data-i18n-title="clear_all" data-i18n-text="clear_all">Clear All</a>\
</li><li class="separator"><span></span>\
</li><li>\
<a class="saved_search_item" href="#">a</a>\
</li>\
</ul>\
</div>\
</div>\
<div class="search_view_toggle">\
<ol class="search_view_toggle_btns mochi_button_group">\
<li><a class="search_tweet mochi_button_group_item selected" \
href="#tweet" data-i18n-text="tweets">Tweet</a>\
</li><li> \
<a class="search_people mochi_button_group_item"\
href="#people" data-i18n-text="people">People</a>\
</li> \
</ol> \
</div> \
<div class="search_no_result_hint"> \
<p><span data-i18n-text="your_search">Your search</span> - <label class="keywords"></label> - <span data-i18n-text="did_not_match_any_result">did not match any result.</span></p> \
<p><span data-i18n-text="suggestions">Suggestions</span>: <br/> \
- <span data-i18n-text="make_sure_all_words_are_spelled_correctly">Make sure all words are spelled correctly.</span><br/> \
- <span data-i18n-text="try_different_keywords">Try different keywords.</span><br/> \
- <span data-i18n-text="try_more_general_keywords">Try more general keywords.</span><br/></p> \
</div> \
</div> \
</div>',
retweets_header_t:
'<div class="header_frame"><div class="retweets_view_toggle"> \
<ol class="retweets_view_toggle_btns radio_group">\
<li><a class="btn_retweeted_to_me radio_group_btn selected" \
href="#retweeted_to_me" data-i18n-text="by_others">By Others</a>\
</li><li> \
<a class="btn_retweeted_by_me radio_group_btn"\
href="#retweeted_by_me" data-i18n-text="by_me">By Me</a>\
</li><li> \
<a class="btn_retweets_of_me radio_group_btn" \
href="#retweets_of_me" data-i18n-text="my_tweets_retweeted">My Tweets, Retweeted</a> \
</li> \
</ol> \
</div></div>',
common_column_header_t:
'<div class="column_settings"> \
<ul class="mochi_list dark">\
<li class="mochi_list_item dark"> \
<input type="checkbox" href="#use_auto_update" class="mochi_toggle dark widget"/>\
<label class="label" data-i18n-text="auto_update">Auto Update</label>\
</li>\
<li class="mochi_list_item dark"> \
<input type="checkbox" href="#use_notify" class="mochi_toggle dark widget"/>\
<label class="label" data-i18n-text="notify">Notify</label>\
</li>\
<li class="mochi_list_item dark"> \
<input type="checkbox" href="#use_notify_sound" class="mochi_toggle dark widget"/>\
<label class="label" data-i18n-text="sound">Sound</label>\
</li>\
</ul>\
</div>\
',
view_t:
'<div id="{%ID%}" \
name="{%NAME%}" class="listview scrollbar_container {%CLASS%} {%ROLE%}"> \
<div class="scrollbar_track">\
<div class="scrollbar_slot">\
<div class="scrollbar_handle"></div>\
</div>\
</div>\
<div class="scrollbar_content listview_content">\
<div class="listview_header"><div class="header_content">{%HEADER%}</div></div> \
<ul class="listview_body"></ul> \
<div class="listview_footer"> \
<div class="load_more_info"><img src="image/ani_loading_bar.gif"/></div> \
</div> \
</div> \
</div>',
indicator_t:
'<div class="{%STICK%} {%ROLE%}" name="{%TARGET%}" draggable="true"><a class="indicator_btn" href="#{%TARGET%}" title="{%TITLE%}"><img class="icon" src="{%ICON%}"/><div class="icon_alt" style="background-image: url({%ICON%})"></div></a><span class="shape"></span></div>',
kismet_rule_t:
'<li><a class="kismet_rule" name="{%NAME%}" type="{%TYPE%}" method="{%METHOD%}"\
disabled="{%DISABLED%}" field="{%FIELD%}" pattern="{%PATTERN%}" \
actions="{%ACTIONS%}" {%ADDITION%} href="#">{%NAME%}</a></li>',
status_draft_t:
'<li mode="{%MODE%}" reply_to_id="{%REPLY_TO_ID%}" reply_text="{%REPLY_TEXT%}" recipient="{%RECIPIENT%}"><a class="text">{%TEXT%}</a><a class="btn_draft_clear" href="#"></a></li>',
preview_link_reg: {
'img.ly': {
reg: new RegExp('http:\\/\\/img.ly\\/([a-zA-Z0-9_\\-]+)','g'),
base: 'http://img.ly/show/thumb/',
direct_base: 'http://img.ly/show/full/'
},
'twitpic.com': {
reg: new RegExp('http:\\/\\/twitpic.com\\/([a-zA-Z0-9_\\-]+)','g'),
base: 'http://twitpic.com/show/thumb/'
},
'twitgoo.com': {
reg: new RegExp('http:\\/\\/twitgoo.com\\/([a-zA-Z0-9_\\-]+)','g'),
base: 'http://twitgoo.com/show/thumb/',
direct_base: 'http://twitgoo.com/show/img/'
},
'yfrog.com': {
reg: new RegExp('http:\\/\\/yfrog.com\\/([a-zA-Z0-9_\\-]+)','g'),
tail: '.th.jpg'
},
'moby.to': {
reg: new RegExp('http:\\/\\/moby.to\\/([a-zA-Z0-9_\\-]+)','g'),
tail: ':thumbnail'
},
'instagr.am': {
reg: new RegExp('http:\\/\\/instagr.am\\/p\\/([a-zA-Z0-9_\\-]+)\\/?','g'),
tail: 'media?size=m',
direct_tail: 'media?size=l'
},
'plixi.com': {
reg: new RegExp('http:\\/\\/plixi.com\\/p\\/([a-zA-Z0-9_\\-]+)','g'),
base: 'http://api.plixi.com/api/tpapi.svc/imagefromurl?size=thumbnail&url='
},
'picplz.com': {
reg: new RegExp('http:\\/\\/picplz.com\\/([a-zA-Z0-9_\\-]+)','g'),
tail: '/thumb/'
},
'raw': {
reg: new RegExp('[a-zA-Z0-9]+:\\/\\/.+\\/.+\\.(jpg|jpeg|jpe|png|gif)', 'gi')
},
'youtube.com': {
reg: new RegExp('href="(http:\\/\\/(www.)?youtube.com\\/watch\\?v\\=([A-Za-z0-9_\\-]+))','g'),
base: 'http://img.youtube.com/vi/',
tail: '/default.jpg',
}
},
init:
function init() {
ui.Template.reg_url = ''//ui.Template.reg_vaild_preceding_chars
+ '('
+ ui.Template.reg_url_proto_chars
+ ui.Template.reg_url_path_chars_1
+ '*'
+ ui.Template.reg_url_path_chars_2
+ '+)';
ui.Template.reg_user = new RegExp('(^|[^a-zA-Z0-9_!#$%&*@@])'
+ ui.Template.reg_user_name_chars, 'g');
ui.Template.reg_list = new RegExp('(^|[^a-zA-Z0-9_!#$%&*@@])'
+ ui.Template.reg_list_name_template, 'ig');
ui.Template.reg_link = new RegExp(ui.Template.reg_url);
ui.Template.reg_link_g = new RegExp(ui.Template.reg_url, 'g');
ui.Template.reg_hash_tag = new RegExp(ui.Template.reg_hash_tag_template
.replace(new RegExp('{%LATIN_CHARS%}', 'g'), ui.Template.reg_hash_tag_latin_chars)
.replace(new RegExp('{%NONLATIN_CHARS%}', 'g'), ui.Template.reg_hash_tag_nonlatin_chars)
, 'ig');
ui.Template.tweet_m = {
ID:'', TWEET_ID:'', RETWEET_ID:''
, REPLY_ID:'',SCREEN_NAME:'',REPLY_NAME:'', USER_NAME:''
, PROFILE_IMG:'', TEXT:'', SOURCE:'', SCHEME:''
, IN_REPLY:'', RETWEETABLE:'', REPLY_TEXT:'', RETWEET_TEXT:''
, RETWEET_MARK:'', SHORT_TIMESTAMP:'', TIMESTAMP:'', FAV_CLASS:''
, DELETABLE:'', TWEET_FONT_SIZE:'', TWEET_FONT: ''
, TWEET_LINE_HEIGHT:''
, STATUS_INDICATOR:'', TRANS_Delete:''
, TRANS_Official_retweet_this_tweet:'', TRANS_Reply_All:''
, TRANS_Reply_this_tweet:'', TRANS_RT_this_tweet:''
, TRANS_Send_Message:'', TRANS_Send_Message_to_them:''
, TRANS_via:'', TRANS_View_more_conversation:''
, TWEET_BASE_URL: '', IN_THREAD: ''
, COLOR_LABEL: ''
};
ui.Template.trending_topic_m = {
ID:'', NAME:''
};
ui.Template.retweeted_by_m = {
ID:'', TWEET_ID:'', RETWEET_ID:''
, REPLY_ID:'',SCREEN_NAME:'',REPLY_NAME:'', USER_NAME:''
, PROFILE_IMG:'', TEXT:'', SOURCE:'', SCHEME:''
, IN_REPLY:'', RETWEETABLE:'', REPLY_TEXT:'', RETWEET_TEXT:''
, RETWEET_MARK:'', SHORT_TIMESTAMP:'', TIMESTAMP:'', FAV_CLASS:''
, DELETABLE:'', TWEET_FONT_SIZE:'', TWEET_FONT:''
, TWEET_LINE_HEIGHT:''
, STATUS_INDICATOR:'', TRANS_Delete:''
, TRANS_Official_retweet_this_tweet:'', TRANS_Reply_All:''
, TRANS_Reply_this_tweet:'', TRANS_RT_this_tweet:''
, TRANS_Send_Message:'', TRANS_Send_Message_to_them:''
, TRANS_via:'', TRANS_View_more_conversation:''
, TRANS_retweeted_by:'', TRANS_Show_retweeters:''
, TRANS_Click_to_show_retweeters:''
, TWEET_BASE_URL: ''
};
ui.Template.message_m = {
ID:'', TWEET_ID:'', SCREEN_NAME:'', RECIPIENT_SCREEN_NAME:''
, USER_NAME:'', PROFILE_IMG:'', TEXT:''
, SCHEME:'', TIMESTAMP:''
, TWEET_FONT_SIZE:'', TWEET_FONT:''
, TWEET_LINE_HEIGHT:''
, TRANS_Reply_Them:''
};
ui.Template.search_m = {
ID:'', TWEET_ID:'', SCREEN_NAME:''
, USER_NAME:'', PROFILE_IMG:'', TEXT:'', SOURCE:''
, SCHEME:'', SHORT_TIMESTAMP:'', TIMESTAMP:''
, TWEET_FONT_SIZE:'', TWEET_FONT:''
, TWEET_LINE_HEIGHT:''
, TRANS_via:''
, TWEET_BASE_URL: ''
};
ui.Template.people_m = {
USER_ID:'', SCREEN_NAME:'', USER_NAME:'', DESCRIPTION:''
, PROFILE_IMG:'', FOLLOWING:'', TWEET_FONT_SIZE:'', TWEET_FONT:''
, TWEET_LINE_HEIGHT:''
};
ui.Template.list_m = {
LIST_ID:'', SCREEN_NAME:'', SLUG:'', NAME:'', MODE:''
, DESCRIPTION:'', PROFILE_IMG:'', FOLLOWING:''
, TWEET_FONT_SIZE:'', TWEET_FONT:''
, TWEET_LINE_HEIGHT:''
};
ui.Template.view_m = {
ID:'', CLASS:'tweetview', NAME: '', CAN_CLOSE: '', ROLE: ''
};
ui.Template.indicator_m = {
TARGET: '', TITLE: '', ICON: '', ROLE: ''
};
ui.Template.kismet_rule_m = {
TYPE:'', DISABLED:'', FIELD:'', PATTERN:''
, METHOD:'', ACTIONS: '', ADDITION: '', NAME: ''
};
ui.Template.status_draft_m = {
MODE:'', TEXT:'', REPLY_TO_ID: '', REPLY_TEXT: ''
, RECIPIENT: ''
};
ui.Template.update_trans();
},
update_trans:
function update_trans() {
ui.Template.people_vcard_m = {
TRANS_info: _('info'), TRANS_stat: _('stat')
, TRANS_name: _('name'), TRANS_bio: _('bio')
, TRANS_web: _('web'), TRANS_location: _('location')
, TRANS_join: _('join'), TRANS_tweet_cnt: _('tweet_cnt')
, TRANS_tweet_cnt: _('tweet_cnt')
, TRANS_follower_cnt: _('follower_cnt')
, TRANS_friend_cnt: _('friend_cnt')
, TRANS_listed_cnt: _('listed_cnt')
, TRANS_relation: _('relation')
, TRANS_edit: _('edit')
, TRANS_follow: _('follow'), TRANS_more_actions: _('more_actions')
, TRANS_mention_them: _('mention_them')
, TRANS_message_them: _('send_message_to_them')
, TRANS_add_to_list: _('add_to_list')
, TRANS_block: _('block')
, TRANS_unblock: _('unblock')
, TRANS_report_spam: _('report_spam')
, TRANS_tweets: _('tweets'), TRANS_favs: _('favs')
, TRANS_followers: _('followers'), TRANS_friends: _('friends')
, TRANS_fellowship: _('fellowship')
, TRANS_lists: _('lists'), TRANS_lists_of_them: _('lists_of_them')
, TRANS_lists_following_them: _('lists_following_them')
, TRANS_create_a_list: _('create_a_list')
}
ui.Template.people_vcard_t = ui.Template.render(ui.Template.people_vcard_t_orig, ui.Template.people_vcard_m);
},
form_dm:
function form_dm(dm_obj, pagename) {
var timestamp = Date.parse(dm_obj.created_at);
var created_at = new Date();
created_at.setTime(timestamp);
var created_at_str = ui.Template.to_long_time_string(created_at);
var created_at_short_str = ui.Template.to_short_time_string(created_at);
var text = ui.Template.form_text(dm_obj);
var m = ui.Template.message_m;
m.ID = pagename + '-' + dm_obj.id_str;
m.TWEET_ID = dm_obj.id_str;
m.SCREEN_NAME = dm_obj.sender.screen_name;
m.RECIPIENT_SCREEN_NAME = dm_obj.recipient.screen_name;
m.USER_NAME = dm_obj.sender.name;
m.DESCRIPTION = dm_obj.sender.description;
m.PROFILE_IMG = util.big_avatar(dm_obj.sender.profile_image_url_https);
m.TEXT = text;
m.SCHEME = 'message';
m.TIMESTAMP = created_at_str;
m.SHORT_TIMESTAMP = created_at_short_str;
m.TWEET_FONT_SIZE = globals.tweet_font_size;
m.TWEET_LINE_HEIGHT = globals.tweet_line_height;
m.TWEET_FONT = globals.tweet_font;
m.TRANS_Reply_Them = "Reply Them";
return ui.Template.render(ui.Template.message_t, m);
},
// This function returns the html for the given tweet_obj.
form_tweet:
function form_tweet (tweet_obj, pagename, in_thread) {
var retweet_name = '';
var retweet_str = '';
var retweet_id = '';
var id = tweet_obj.id_str;
if (tweet_obj.hasOwnProperty('retweeted_status')) {
retweet_name = tweet_obj['user']['screen_name'];
tweet_obj['retweeted_status'].favorited = tweet_obj.favorited; // The favorite status of the embedded tweet is not reliable, use outer one.
tweet_obj = tweet_obj['retweeted_status'];
retweet_id = tweet_obj.id_str;
}
var reply_name = tweet_obj.in_reply_to_screen_name;
var reply_id = tweet_obj.hasOwnProperty('in_reply_to_status_id_str')
? tweet_obj.in_reply_to_status_id_str:tweet_obj.in_reply_to_status_id;
var reply_str = (reply_id != null) ?
_('reply_to') + ' <a class="who_href" href="#'
+ reply_name + '">'
+ reply_name + '</a>'
: '';
var in_thread = in_thread == true ? true: false;
var timestamp = Date.parse(tweet_obj.created_at);
var created_at = new Date();
created_at.setTime(timestamp);
var created_at_str = ui.Template.to_long_time_string(created_at);
var created_at_short_str = ui.Template.to_short_time_string(created_at);
// choose color scheme
var scheme = 'normal';
if (tweet_obj.entities && tweet_obj.entities.user_mentions) {
for (var i = 0, l = tweet_obj.entities.user_mentions.length; i < l; i+=1)
{
if (tweet_obj.entities.user_mentions[i].screen_name
== globals.myself.screen_name)
{
scheme = 'mention';
}
}
}
if (tweet_obj.user.screen_name == globals.myself.screen_name) {
scheme = 'me';
}
if (retweet_name != '') {
retweet_str = _('retweeted_by') + ' <a class="who_href" href="#'
+ retweet_name + '">'
+ retweet_name + '</a>, ';
}
var alt_text = tweet_obj.text;
var link = '';
if (tweet_obj.entities && tweet_obj.entities.urls) {
var urls = null;
if (tweet_obj.entities.media) {
urls = tweet_obj.entities.urls.concat(tweet_obj.entities.media);
} else {
urls = tweet_obj.entities.urls;
}
for (var i = 0, l = urls.length; i < l; i += 1) {
var url = urls[i];
if (url.url && url.expanded_url) {
tweet_obj.text = tweet_obj.text.replace(url.url, url.expanded_url);
}
}
if (tweet_obj.entities.urls.length > 0) {
link = tweet_obj.entities.urls[0].expanded_url;
}
}
var text = ui.Template.form_text(tweet_obj);
// if the tweet contains user_mentions (which are provided by the Twitter
// API, not by the StatusNet API), it will here replace the
// contents of the 'who_ref'-a-tag by the full name of this user.
if (tweet_obj.entities && tweet_obj.entities.user_mentions) {
for (var i = 0, l = tweet_obj.entities.user_mentions.length; i < l; i+=1)
{
// hotot_log('form_tweet', 'user mention: ' + tweet_obj.entities.user_mentions[i].screen_name);
var screen_name = tweet_obj.entities.user_mentions[i].screen_name;
var name = tweet_obj.entities.user_mentions[i].name.replace(/"/g, '"');
var reg_ulink = new RegExp('>(' + screen_name + ')<', 'ig');
text = text.replace(reg_ulink, ' title="' + name + '">$1<')
}
// If we get here, and there are still <a who_href="...">-tags
// without title attribute, the user name was probably misspelled.
// If I then remove the tag, the incorrect user name is not
// highlighted any more, which fixes #415 for twitter.
// (It does not work for identi.ca, because the identi.ca API
// does not provide user_mentions.)
var re = /\<a class=\"who_href\" href=\"[^"]*\"\>([^<]*)\<\/a\>/gi
text = text.replace(re, '$1');
// hotot_log('form_tweet', 'resulting text: ' + text);
}
var m = ui.Template.tweet_m;
m.ID = pagename+'-'+id;
m.TWEET_ID = id;
m.RETWEET_ID = retweet_id;
m.REPLY_ID = reply_id != null? reply_id:'';
m.IN_THREAD = in_thread;
m.SCREEN_NAME = tweet_obj.user.screen_name;
m.REPLY_NAME = reply_id != null? reply_name: '';
m.USER_NAME = tweet_obj.user.name;
m.DESCRIPTION = tweet_obj.user.description;
m.PROFILE_IMG = util.big_avatar(tweet_obj.user.profile_image_url_https);
m.TEXT = text;
m.ALT = ui.Template.convert_chars(alt_text);
m.SOURCE = tweet_obj.source.replace('href', 'target="_blank" href');
m.SCHEME = scheme;
m.IN_REPLY = (reply_id != null && !in_thread) ? 'block' : 'none';
m.RETWEETABLE = (tweet_obj.user.protected || scheme == 'me' )? 'false':'true';
m.COLOR_LABEL = kismet.get_user_color(tweet_obj.user.screen_name);
m.REPLY_TEXT = reply_str;
m.RETWEET_TEXT = retweet_str;
m.RETWEET_MARK = retweet_name != ''? 'retweet_mark': '';
m.SHORT_TIMESTAMP = created_at_short_str;
m.TIMESTAMP = created_at_str;
m.FAV_CLASS = tweet_obj.favorited? 'faved': '';
m.DELETABLE = scheme == 'me'? 'true': 'false';
m.TWEET_FONT_SIZE = globals.tweet_font_size;
m.TWEET_FONT = globals.tweet_font;
m.TWEET_LINE_HEIGHT = globals.tweet_line_height;
m.STATUS_INDICATOR = ui.Template.form_status_indicators(tweet_obj);
m.TRANS_Delete = _('delete');
m.TRANS_Delete_this_tweet = _('delete_this_tweet');
m.TRANS_Loading = _('loading_dots');
m.TRANS_Official_retweet_this_tweet = _('official_retweet_this_tweet');
m.TRANS_Reply_All = _('reply_all');
m.TRANS_Reply_this_tweet = _('reply_this_tweet');
m.TRANS_RT_this_tweet = _('rt_this_tweet');
m.TRANS_Send_Message = _('send_message');
m.TRANS_Send_Message_to_them = _('send_message_to_them');
m.TRANS_via = _('via');
m.TRANS_View_more_conversation = _('view_more_conversation');
m.TWEET_BASE_URL = conf.current_name.split('@')[1] == 'twitter'?'https://twitter.com/' + tweet_obj.user.screen_name + '/status':'https://identi.ca/notice';
m.LINK = link;
return ui.Template.render(ui.Template.tweet_t, m);
},
form_retweeted_by:
function form_retweeted_by(tweet_obj, pagename) {
var retweet_name = '';
var retweet_str = '';
var retweet_id = '';
var id = tweet_obj.id_str;
if (tweet_obj.hasOwnProperty('retweeted_status')) {
retweet_name = tweet_obj['user']['screen_name'];
tweet_obj['retweeted_status'].favorited = tweet_obj.favorited; // The favorite status of the embedded tweet is not reliable, use outer one.
tweet_obj = tweet_obj['retweeted_status'];
retweet_id = tweet_obj.id_str;
}
var reply_name = tweet_obj.in_reply_to_screen_name;
var reply_id = tweet_obj.hasOwnProperty('in_reply_to_status_id_str')
? tweet_obj.in_reply_to_status_id_str:tweet_obj.in_reply_to_status_id;
var reply_str = (reply_id != null) ?
_('Reply to @') + ' <a class="who_href" href="#'
+ reply_name + '">'
+ reply_name + '</a>: '
: '';
var timestamp = Date.parse(tweet_obj.created_at);
var created_at = new Date();
created_at.setTime(timestamp);
var created_at_str = ui.Template.to_long_time_string(created_at);
var created_at_short_str = ui.Template.to_short_time_string(created_at);
// choose color scheme
var scheme = 'normal';
if (tweet_obj.entities && tweet_obj.entities.user_mentions) {
for (var i = 0, l = tweet_obj.entities.user_mentions.length; i < l; i+=1)
{
if (tweet_obj.entities.user_mentions[i].screen_name
== globals.myself.screen_name)
{
scheme = 'mention';
}
}
}
if (tweet_obj.user.screen_name == globals.myself.screen_name) {
scheme = 'me';
}
if (retweet_name != '') {
retweet_str = _('retweeted_by') + ' <a class="who_href" href="#'
+ retweet_name + '">'
+ retweet_name + '</a>, ';
}
var m = ui.Template.retweeted_by_m;
m.ID = pagename+'-'+id;
m.TWEET_ID = id;
m.RETWEET_ID = retweet_id;
m.REPLY_ID = reply_id != null? reply_id:'';
m.SCREEN_NAME = tweet_obj.user.screen_name;
m.REPLY_NAME = reply_id != null? reply_name: '';
m.USER_NAME = tweet_obj.user.name;
m.PROFILE_IMG = util.big_avatar(tweet_obj.user.profile_image_url_https);
m.TEXT = ui.Template.form_text(tweet_obj);
m.SOURCE = tweet_obj.source.replace('href', 'target="_blank" href');
m.SCHEME = scheme;
m.IN_REPLY = (reply_id != null && pagename.split('-').length < 2) ? 'block' : 'none';
m.RETWEETABLE = (tweet_obj.user.protected || scheme == 'me' )? 'false':'true';
m.REPLY_TEXT = reply_str;
m.RETWEET_TEXT = retweet_str;
m.RETWEET_MARK = retweet_name != ''? 'retweet_mark': '';
m.SHORT_TIMESTAMP = created_at_short_str;
m.TIMESTAMP = created_at_str;
m.FAV_CLASS = tweet_obj.favorited? 'faved': '';
m.DELETABLE = scheme == 'me'? 'true': 'false';
m.TWEET_FONT_SIZE = globals.tweet_font_size;
m.TWEET_FONT = globals.tweet_font;
m.TWEET_LINE_HEIGHT = globals.tweet_line_height;
m.STATUS_INDICATOR = ui.Template.form_status_indicators(tweet_obj);
m.TRANS_Delete = _('delete');
m.TRANS_Delete_this_tweet = _('delete_this_tweet');
m.TRANS_Loading = _('loading_dots');
m.TRANS_Official_retweet_this_tweet = _('official_retweet_this_tweet');
m.TRANS_Reply_All = _('reply_All');
m.TRANS_Reply_this_tweet = _('reply_this_tweet');
m.TRANS_RT_this_tweet = _('rt_this_tweet');
m.TRANS_Send_Message = _('send_message');
m.TRANS_Send_Message_to_them = _('send_message_to_them');
m.TRANS_via = _('via');
m.TRANS_View_more_conversation = _('view_more_conversation');
m.TRANS_Retweeted_by = _('retweeted_by');
m.TRANS_Show_retweeters = _('click_to_show');
m.TRANS_Click_to_show_retweeters = _('click_to_show_retweeters');
m.TWEET_BASE_URL = conf.current_name.split('@')[1] == 'twitter'?'https://twitter.com/' + tweet_obj.user.screen_name + '/status':'https://identi.ca/notice';
return ui.Template.render(ui.Template.retweeted_by_t, m);
},
form_search:
function form_search(tweet_obj, pagename) {
if (tweet_obj.user != undefined) {
// use phoenix_search ... well, in fact, the original parser is totally useless.
return ui.Template.form_tweet(tweet_obj, pagename);
}
var id = tweet_obj.id_str;
var source = tweet_obj.source.replace(/>/g, '>').replace(/</g, '<').replace(/"/g, '');
var timestamp = Date.parse(tweet_obj.created_at);
var created_at = new Date();
created_at.setTime(timestamp);
var created_at_str = ui.Template.to_long_time_string(created_at);
var created_at_short_str = ui.Template.to_short_time_string(created_at);
var text = ui.Template.form_text(tweet_obj);
// choose color scheme
var scheme = 'normal';
if (text.indexOf(globals.myself.screen_name) != -1) {
scheme = 'mention';
}
if (tweet_obj.from_user == globals.myself.screen_name) {
scheme = 'me';
}
var link = '';
if (tweet_obj.entities.urls.length > 0) {
link = tweet_obj.entities.urls[0].expanded_url;
}
var m = ui.Template.search_m;
m.ID = pagename + '-' + id;
m.TWEET_ID = id;
m.SCREEN_NAME = tweet_obj.from_user;
m.USER_NAME = tweet_obj.from_user_name;
m.PROFILE_IMG = util.big_avatar(tweet_obj.profile_image_url_https);
m.TEXT = text;
m.SOURCE = source.replace('href', 'target="_blank" href');
m.SCHEME = scheme;
m.SHORT_TIMESTAMP = created_at_short_str;
m.TIMESTAMP = created_at_str;
m.TWEET_FONT_SIZE = globals.tweet_font_size;
m.TWEET_FONT = globals.tweet_font;
m.TWEET_LINE_HEIGHT = globals.tweet_line_height;
m.TRANS_via = _('via');
m.TWEET_BASE_URL = conf.current_name.split('@')[1] == 'twitter'?'https://twitter.com/' + tweet_obj.from_user + '/status':'https://identi.ca/notice';
m.LINK = link;
return ui.Template.render(ui.Template.search_t, m);
},
form_people:
function form_people(user_obj, pagename) {
var m = ui.Template.people_m;
m.USER_ID = pagename + '-' + user_obj.id_str;
m.SCREEN_NAME = user_obj.screen_name;
m.USER_NAME = user_obj.name;
m.DESCRIPTION = user_obj.description;
m.PROFILE_IMG = util.big_avatar(user_obj.profile_image_url_https);
m.FOLLOWING = user_obj.following;
m.TWEET_FONT_SIZE = globals.tweet_font_size;
m.TWEET_FONT = globals.tweet_font;
m.TWEET_LINE_HEIGHT = globals.tweet_line_height;
return ui.Template.render(ui.Template.people_t, m);
},
form_list:
function form_people(list_obj, pagename) {
var m = ui.Template.list_m;
m.LIST_ID = pagename + '-' + list_obj.id_str;
m.SCREEN_NAME = list_obj.user.screen_name;
m.SLUG = list_obj.slug;
m.NAME = list_obj.name;
m.MODE = list_obj.mode;
m.DESCRIPTION = list_obj.description;
m.PROFILE_IMG = util.big_avatar(list_obj.user.profile_image_url_https);
m.FOLLOWING = list_obj.following;
m.TWEET_FONT_SIZE = globals.tweet_font_size;
m.TWEET_FONT = globals.tweet_font;
m.TWEET_LINE_HEIGHT = globals.tweet_line_height;
return ui.Template.render(ui.Template.list_t, m);
},
form_view:
function form_view(name, title, cls) {
var m = ui.Template.view_m;
m.ID = name + '_tweetview';
m.NAME = name;
m.CLASS = cls;
if (name == 'home') {
m.CAN_CLOSE = 'none';
} else {
m.CAN_CLOSE = 'block';
}
if (ui.Slider.system_views.hasOwnProperty(name)) {
m.ROLE = 'system_view';
} else {
m.ROLE = 'custom_view';
}
return ui.Template.render(ui.Template.view_t, m);
},
form_indicator:
function form_indicator(target, title, icon) {
var m = ui.Template.indicator_m;
m.TARGET = target
m.TITLE = title;
m.ICON = icon;
if (ui.Slider.system_views.hasOwnProperty(target)) {
m.ROLE = 'system_view';
} else {
m.ROLE = 'custom_view';
}
return ui.Template.render(ui.Template.indicator_t, m);
},
form_kismet_rule:
function form_kismet_rule(rule) {
var m = ui.Template.kismet_rule_m;
m.NAME = rule.name;
m.TYPE = rule.type;
m.METHOD = rule.method;
m.PATTERN = rule.pattern;
m.ACTIONS = rule.actions.join(':');
m.ADDITION = rule.actions.indexOf(3)!=-1?'archive_name="'+rule.archive_name+'"':'archive_name=""';
m.FIELD = rule.field;
m.DISABLED = rule.disabled;
return ui.Template.render(ui.Template.kismet_rule_t, m);
},
form_status_draft:
function form_status_draft(draft) {
var m = ui.Template.status_draft_m;
m.MODE = draft.mode;
m.TEXT = draft.text.replace(/</g, "<").replace(/>/g,">");
if (m.MODE == ui.StatusBox.MODE_REPLY) {
m.REPLY_TO_ID = draft.reply_to_id;
m.REPLY_TEXT = draft.reply_text
} else if (m.MODE == ui.StatusBox.MODE_DM) {
m.RECIPIENT = draft.recipient;
} else if (m.MODE == ui.StatusBox.MODE_IMG) {
}
return ui.Template.render(ui.Template.status_draft_t, m);
},
fill_people_vcard:
function fill_people_vcard(user_obj, vcard_container) {
var created_at = new Date(Date.parse(user_obj.created_at));
var now = new Date();
var differ = Math.floor((now-created_at)/(1000 * 60 * 60 * 24));
var created_at_str = ui.Template.to_long_time_string(created_at);
vcard_container.find('.profile_img_wrapper')
.attr('href', user_obj.profile_image_url_https.replace(/_normal/, ''))
.attr('style', 'background-image:url('+util.big_avatar(user_obj.profile_image_url_https)+');');
vcard_container.find('.screen_name')
.attr('href', conf.get_current_profile().preferences.base_url + user_obj.screen_name)
.text(user_obj.screen_name);
vcard_container.find('.name').text(user_obj.name);
vcard_container.find('.tweet_cnt').text(user_obj.statuses_count);
vcard_container.find('.tweet_per_day_cnt').text(
Math.round(user_obj.statuses_count / differ * 100)/ 100);
vcard_container.find('.follower_cnt').text(user_obj.followers_count);
vcard_container.find('.friend_cnt').text(user_obj.friends_count);
vcard_container.find('.listed_cnt').text(user_obj.listed_count);
vcard_container.find('.bio').unbind().empty().html(
ui.Template.form_text_raw(user_obj.description));
ui.Main.bind_tweet_text_action(vcard_container.find('.bio'));
vcard_container.find('.location').text('').text(user_obj.location);
vcard_container.find('.join').text(created_at_str);
if (user_obj.url) {
vcard_container.find('.web').text(user_obj.url)
vcard_container.find('.web').attr('href', user_obj.url);
} else {
vcard_container.find('.web').text('')
vcard_container.find('.web').attr('href', '#');
}
vcard_container.find('.people_vcard_radio_group .mochi_button_group_item').attr('name', 'people_'+user_obj.screen_name+'_vcard')
vcard_container.find('.people_view_toggle .mochi_button_group_item').attr('name', 'people_'+user_obj.screen_name+'_views')
},
fill_list_vcard:
function fill_list_vcard(view, list_obj) {
var vcard_container = view._header;
vcard_container.find('.profile_img_wrapper')
.attr('style', 'background-image:url('
+ util.big_avatar(list_obj.user.profile_image_url_https) + ');');
vcard_container.find('.name')
.attr('href', conf.get_current_profile().preferences.base_url + list_obj.user.screen_name + '/' + list_obj.slug)
.text(list_obj.full_name);
vcard_container.find('.owner')
.attr('href', conf.get_current_profile().preferences.base_url + list_obj.user.screen_name)
.text(list_obj.user.screen_name);
vcard_container.find('.description').text(list_obj.description);
},
convert_chars:
function convert_chars(text) {
text = text.replace(/"/g, '"');
text = text.replace(/'/g, ''');
text = text.replace(/\$/g, '$');
return text;
},
// This function applies some basic replacements to tweet.text, and returns
// the resulting string.
// This is not the final text that will appear in the UI, form_tweet will also do
// some modifications. from_tweet will search for the a-tags added in this
// function, to do the modifications.
form_text:
function form_text(tweet) {
//hotot_log('form_text in', tweet.text);
var text = ui.Template.convert_chars(tweet.text);
text = text.replace(ui.Template.reg_link_g, function replace_url(url) {
if (url.length > 51) url_short = url.substring(0,48) + '...';
else url_short = url;
return ' <a href="'+url+'" target="_blank">' + url_short + '</a>';
});
text = text.replace(/href="www/g, 'href="http://www');
text = text.replace(ui.Template.reg_list
, '$1@<a class="list_href" href="#$2">$2</a>');
text = text.replace(ui.Template.reg_user
, '$1@<a class="who_href" href="#$2">$2</a>');
text = text.replace(ui.Template.reg_hash_tag
, '$1<a class="hash_href" href="#$2">#$2</a>');
text = text.replace(/href="(http:\/\/hotot.in\/(\d+))"/g
, 'full_text_id="$2" href="$1"');
text = text.replace(/[\r\n]\s+[\r\n]/g, '\n\n');
text = text.replace(/\n/g, '<br/>');
if (ui.Template.reg_is_rtl.test(text)) {
text = '<div class="text_inner" align="right" dir="rtl">' + text + '</div>';
} else {
text = '<div class="text_inner">' + text + '</div>';
}
if (conf.get_current_profile().preferences.use_media_preview) {
text += '<div class="preview">'
+ ui.Template.form_preview(tweet)
+ '</div>';
}
//hotot_log('form_text out', text);
return text;
},
form_text_raw:
function form_text_raw(raw_text) {
var text = raw_text;
text = text.replace(/</g, "<");
text = text.replace(/>/g, ">");
text = text.replace(ui.Template.reg_link_g, ' <a href="$1" target="_blank">$1</a>');
text = text.replace(/href="www/g, 'href="http://www');
text = text.replace(ui.Template.reg_list
, '$1@<a class="list_href" href="#$2">$2</a>');
text = text.replace(ui.Template.reg_user
, '$1@<a class="who_href" href="#$2">$2</a>');
text = text.replace(ui.Template.reg_hash_tag
, '$1<a class="hash_href" href="#$2">#$2</a>');
text = text.replace(/href="(http:\/\/hotot.in\/(\d+))"/g
, 'full_text_id="$2" href="$1"');
text = text.replace(/[\r\n]\s+[\r\n]/g, '\n\n');
text = text.replace(/\n/g, '<br/>');
return text;
},
form_media:
function form_media(href, src, direct_url) {
if (direct_url != undefined) {
return '<a direct_url="'+direct_url+'" href="'+href+'"><img src="'+ src +'" /></a>';
} else {
return '<a href="'+href+'" target="_blank"><img src="'+ src +'" /></a>';
}
},
form_preview:
function form_preview(tweet) {
var html_arr = [];
var link_reg = ui.Template.preview_link_reg;
for (var pvd_name in link_reg) {
var match = link_reg[pvd_name].reg.exec(tweet.text);
while (match != null) {
switch (pvd_name) {
case 'img.ly':
case 'twitgoo.com':
html_arr.push(
ui.Template.form_media(
match[0], link_reg[pvd_name].base + match[1],
link_reg[pvd_name].direct_base + match[1]));
break;
case 'twitpic.com':
html_arr.push(
ui.Template.form_media(
match[0], link_reg[pvd_name].base + match[1]));
break;
case 'instagr.am':
html_arr.push(
ui.Template.form_media(
match[0], match[0] + link_reg[pvd_name].tail,
match[0] + link_reg[pvd_name].direct_tail));
break;
case 'yfrog.com':
case 'moby.to':
case 'picplz.com':
html_arr.push(
ui.Template.form_media(
match[0], match[0] + link_reg[pvd_name].tail));
break;
case 'plixi.com':
html_arr.push(
ui.Template.form_media(
match[0], link_reg[pvd_name].base +match[0]));
break;
case 'raw':
html_arr.push(
ui.Template.form_media(
match[0], match[0], match[0]));
break;
case 'youtube.com':
html_arr.push(
ui.Template.form_media(
match[0], link_reg[pvd_name].base + match[2] + link_reg[pvd_name].tail));
break;
}
match = link_reg[pvd_name].reg.exec(tweet.text);
}
}
// twitter official picture service
if (tweet.entities && tweet.entities.media) {
for (var i = 0; i < tweet.entities.media.length; i += 1) {
var media = tweet.entities.media[i];
if (media.expanded_url && media.media_url) {
html_arr.push(
ui.Template.form_media(
tweet.entities.media[i].expanded_url,
tweet.entities.media[i].media_url + ':thumb',
tweet.entities.media[i].media_url + ':large'
));
}
}
}
if (conf.get_current_profile().preferences.filter_nsfw_media && tweet.text.match(/nsfw/ig))
html_arr = ['<i>NSFW image hidden</i>'];
if (html_arr.length != 0) {
return '<p class="media_preview">'+ html_arr.join('')+'</p>';
}
return '';
},
form_status_indicators:
function form_status_indicators(tweet) {
},
render:
function render(tpl, map) {
var text = tpl
var replace = false;
for (var k in map) {
replace = typeof map[k] == 'string' ? map[k] : '';
text = text.replace(new RegExp('{%'+k+'%}', 'g'), replace);
}
return text;
},
to_long_time_string:
function (datetime) {
return moment(datetime).toLocaleString();
},
to_short_time_string:
function (dataObj) {
var is_human = conf.get_current_profile().preferences.show_relative_timestamp,
now = moment(),
mobj = moment(dataObj),
time_str;
if (is_human) {
try {
mobj.lang(i18n.current);
mobj.lang();
} catch (e) {
mobj.lang(false);
}
if(now.diff(mobj, 'hours', true) > 6) {
time_str = mobj.calendar();
} else {
time_str = mobj.fromNow();
}
} else {
if(now.diff(mobj, 'days', true) > 1) {
time_str = mobj.format('YYYY-MM-DD HH:mm:ss');
} else {
time_str = mobj.format('YYYY-MM-DD HH:mm:ss');
}
}
return time_str;
}
}
|
AshKyd/Hotot
|
data/js/ui.template.js
|
JavaScript
|
lgpl-3.0
| 59,989 |
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
declare(strict_types=1);
namespace pocketmine\network\mcpe\protocol\types;
class EntityLink{
public const TYPE_REMOVE = 0;
public const TYPE_RIDER = 1;
public const TYPE_PASSENGER = 2;
/** @var int */
public $fromEntityUniqueId;
/** @var int */
public $toEntityUniqueId;
/** @var int */
public $type;
/** @var bool */
public $immediate; //for dismounting on mount death
public function __construct(int $fromEntityUniqueId = null, int $toEntityUniqueId = null, int $type = null, bool $immediate = false){
$this->fromEntityUniqueId = $fromEntityUniqueId;
$this->toEntityUniqueId = $toEntityUniqueId;
$this->type = $type;
$this->immediate = $immediate;
}
}
|
kabluinc/PocketMine-MP
|
src/pocketmine/network/mcpe/protocol/types/EntityLink.php
|
PHP
|
lgpl-3.0
| 1,388 |
package enhanced.portals.client.gui.elements;
import java.util.List;
import enhanced.base.client.gui.BaseGui;
import enhanced.base.client.gui.elements.BaseElement;
import enhanced.core.Reference.ECMod;
import enhanced.portals.portal.GlyphIdentifier;
import net.minecraft.util.ResourceLocation;
public class ElementGlyphDisplay extends BaseElement {
GlyphIdentifier id;
public ElementGlyphDisplay(BaseGui gui, int x, int y, GlyphIdentifier i) {
super(gui, x, y, 162, 18);
id = i;
}
public void setIdentifier(GlyphIdentifier i) {
id = i;
}
@Override
public void addTooltip(List<String> list) {
}
@Override
protected void drawContent() {
parent.getMinecraft().renderEngine.bindTexture(new ResourceLocation(ECMod.ID, "textures/gui/player_inventory.png"));
drawTexturedModalRect(posX, posY, 7, 7, sizeX, sizeY);
parent.getMinecraft().renderEngine.bindTexture(ElementGlyphSelector.glyphs);
if (id != null && id.size() > 0)
for (int i = 0; i < 9; i++) {
if (i >= id.size())
break;
int glyph = id.get(i), X2 = i % 9 * 18, X = glyph % 9 * 18, Y = glyph / 9 * 18;
drawTexturedModalRect(posX + X2, posY, X, Y, 18, 18);
}
}
@Override
public void update() {
}
}
|
enhancedportals/enhancedportals
|
src/main/java/enhanced/portals/client/gui/elements/ElementGlyphDisplay.java
|
Java
|
lgpl-3.0
| 1,367 |
/**
* Class ReloadRemoteOrder
* Sending remote order for background reload
* Creation: May, 06, 2011
* @author Ludovic APVRILLE
* @see
*/
import java.io.*;
import java.net.*;
public class ReloadRemoteOrder {
public static final int DEFAULT_PORT = 9362;
public static void main(String[] args) throws Exception{
byte[] ipAddr = new byte[]{127, 0, 0, 1};
InetAddress addr = InetAddress.getByAddress(ipAddr);
String sendData = "reload background";
byte [] buf = sendData.getBytes();
DatagramPacket sendPacket = new DatagramPacket(buf, buf.length, addr, ReloadRemoteOrder.DEFAULT_PORT);
DatagramSocket serverSocket = new DatagramSocket(9876);
serverSocket.send(sendPacket);
}
} // End of class ReloadRemoteOrder
|
LudooduL/crocbar
|
src/ReloadRemoteOrder.java
|
Java
|
lgpl-3.0
| 823 |
/*
* Neurpheus - Morfological Analyser
*
* Copyright (C) 2006 Jakub Strychowski
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*/
package org.neurpheus.nlp.morphology.inflection;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import org.neurpheus.core.io.DataOutputStreamPacker;
import org.neurpheus.nlp.morphology.VowelCharacters;
import org.neurpheus.nlp.morphology.VowelCharactersImpl;
/**
* Represents a core pattern which is a common part of some cores covered by this pattern.
*
* @author Jakub Strychowski
*/
public class CorePattern implements Serializable {
/** Unique serialization identifier of this class. */
static final long serialVersionUID = 770608060903220741L;
/** Holds the pattern template. */
private String pattern;
/** Holds the number of cores covered by this pattern. */
private int coveredCoresCount;
/** Holds the weight of this pattern in a morphological analysis process. */
private int weight;
/**
* Creates a new instance of CorePattern.
*/
public CorePattern() {
}
/**
* Returns a template of this pattern.
*
* @return A common fragment of cores.
*/
public String getPattern() {
return pattern;
}
/**
* Sets a new template for this code pattern.
*
* @param newPattern The new value of the template of this core pattern.
*/
public void setPattern(final String newPattern) {
this.pattern = newPattern;
}
/**
* Returns a number of cores covered by this core pattern.
*
* @return The number of covered cores.
*/
public int getCoveredCoresCount() {
return coveredCoresCount;
}
/**
* Sets the number of cores covered by this core pattern.
*
* @param newCoveredCoresCount The new number of covered cores.
*/
public void setCoveredCoresCount(final int newCoveredCoresCount) {
this.coveredCoresCount = newCoveredCoresCount;
}
/**
* Returns the weight value which is used by a morphological analysis process.
*
* @return The weight of this core pattern.
*/
public int getWeight() {
return weight;
}
/**
* Sets the weight value which is used by morphological analysis process.
*
* @param newWeight The new value of this core pattern weight.
*/
public void setWeight(final int newWeight) {
this.weight = newWeight;
}
/**
* Compares twis object with other core pattern.
*
* @param o The core pattern with which compare to.
*
* @return <code>0</code> if core patterns are equal, <code>-1</code> if this core pattern
* is before the given core pattern, and <code>1</code> if this core pattern
* is after the given core pattern.
*/
public int compareTo(final Object o) {
CorePattern p = (CorePattern) o;
return getPattern().compareTo(p.getPattern());
}
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hashtables such as those provided by
* <code>java.util.HashMap</code>.
*
* @return a hash code value for this object.
*/
public int hashCode() {
super.hashCode();
return getPattern().hashCode();
}
/**
* Indicates whether some other object is "equal to" this core pattern.
*
* @param obj The reference object with which to compare.
* @return <code>true</code> if this object is the same as the obj
* argument; <code>false</code> otherwise.
*/
public boolean equals(final Object obj) {
return compareTo(obj) == 0;
}
/**
* Prints this core pattern.
*
* @param out The output stream where this object should be printed.
*/
public void print(final PrintStream out) {
out.print(pattern);
out.print('(');
out.print(weight);
out.print(')');
}
/**
* Checks if a given core matches this core pattern.
*
* @param core The core to check.
* @param vowels The object representing vowels of a language of the core.
*
* @return <code>true</code> if this core pattern covers the given core.
*/
public boolean matches(final String core, final VowelCharacters vowels) {
if (pattern == null) {
return core == null;
}
if (pattern.length() > core.length()) {
return false;
}
char[] ca = core.toCharArray();
char[] pa = pattern.toCharArray();
int cix = ca.length - 1;
for (int pix = pa.length - 1; pix >= 0; pix--, cix--) {
if (ca[cix] != pa[pix]) {
char c = pa[pix];
if (c == vowels.getVowelSign() && Character.isLetter(ca[cix])) {
if (!vowels.isVowel(ca[cix])) {
return false;
}
} else if (c == vowels.getConsonantSign() && Character.isLetter(ca[cix])) {
if (vowels.isVowel(ca[cix])) {
return false;
}
} else {
return false;
}
}
}
return true;
}
/**
* Removes from the given collection all cores covered by this core pattern.
*
* @param cores The collection of cores which should be filtered.
* @param vowels The object representing vowels of a language of cores.
*/
public void removeCoveredCores(final Collection cores, final VowelCharacters vowels) {
boolean containsVowel = false;
boolean containsConsonant = false;
int minCoreLength = Integer.MAX_VALUE;
for (Iterator it = cores.iterator(); it.hasNext();) {
String core = (String) it.next();
if (core.equals("%inn%") && pattern.equals("inn%")) {
core = core + "";
}
if (matches(core, vowels)) {
int clen = core.length();
if (core.startsWith("%")) {
clen--;
}
if (clen < minCoreLength) {
minCoreLength = clen;
}
it.remove();
// check if core contains a vowel or a consonant at the position of
// a character where core pattern starts
if (pattern.length() < core.length()) {
char c = core.charAt(core.length() - pattern.length() - 1);
if (vowels.isVowel(c)) {
containsVowel = true;
} else {
containsConsonant = true;
}
}
}
}
if (pattern.length() < minCoreLength) {
if (containsVowel && !containsConsonant) {
pattern = vowels.getVowelSign() + pattern;
} else if (containsConsonant && !containsVowel) {
pattern = vowels.getConsonantSign() + pattern;
}
}
}
/**
* Reads this object data from the given input stream.
*
* @param in The input stream where this IPB is stored.
*
* @throws IOException if any read error occurred.
* @throws ClassNotFoundException if this object cannot be instantied.
*/
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
pattern = pattern.intern();
}
public void write(final DataOutputStream out) throws IOException {
DataOutputStreamPacker.writeString(pattern, out);
DataOutputStreamPacker.writeInt(coveredCoresCount, out);
DataOutputStreamPacker.writeInt(weight, out);
}
public void read(final DataInputStream in) throws IOException {
pattern = DataOutputStreamPacker.readString(in);
coveredCoresCount = DataOutputStreamPacker.readInt(in);
weight = DataOutputStreamPacker.readInt(in);
}
}
|
Neurpheus/manalyser
|
src/main/java/org/neurpheus/nlp/morphology/inflection/CorePattern.java
|
Java
|
lgpl-3.0
| 8,839 |
package ch.idsia.blip.core.learn.solver.ps;
import ch.idsia.blip.core.utils.ParentSet;
public class NullProvider implements Provider {
@Override
public ParentSet[][] getParentSets() {
return null;
}
}
|
mauro-idsia/blip
|
core/src/main/java/ch/idsia/blip/core/learn/solver/ps/NullProvider.java
|
Java
|
lgpl-3.0
| 226 |
package org.cdisc.ns.odm.v1;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ArchiveLayoutRef complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ArchiveLayoutRef">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <group ref="{http://www.cdisc.org/ns/odm/v1.3}ArchiveLayoutRefElementExtension" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* <attGroup ref="{http://www.cdisc.org/ns/odm/v1.3}ArchiveLayoutRefAttributeExtension"/>
* <attGroup ref="{http://www.cdisc.org/ns/odm/v1.3}ArchiveLayoutRefAttributeDefinition"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArchiveLayoutRef")
public class ArchiveLayoutRef {
@XmlAttribute(name = "ArchiveLayoutOID", required = true)
protected String archiveLayoutOID;
/**
* Gets the value of the archiveLayoutOID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getArchiveLayoutOID() {
return archiveLayoutOID;
}
/**
* Sets the value of the archiveLayoutOID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setArchiveLayoutOID(String value) {
this.archiveLayoutOID = value;
}
}
|
chb/i2b2-ssr
|
data_import/InformClient/src/main/java/org/cdisc/ns/odm/v1/ArchiveLayoutRef.java
|
Java
|
lgpl-3.0
| 1,726 |
<?php
include_once("templates/admin/BeanListPage.php");
include_once("beans/FAQSectionsBean.php");
include_once("beans/FAQItemsBean.php");
class FAQItemsListPage extends BeanListPage
{
public function __construct()
{
parent::__construct();
$sections = new FAQSectionsBean();
$bean = new FAQItemsBean();
$qry = $bean->query();
$qry->select->from.= " fi LEFT JOIN faq_sections fs ON fs.fqsID = fi.fqsID ";
$qry->select->fields()->set("fi.fID", "fs.section_name", "fi.question", "fi.answer");
$this->setIterator($qry);
$this->setListFields(array("section_name"=>"Section", "question"=>"Question", "answer"=>"Answer"));
$this->setBean($bean);
}
protected function initPage()
{
parent::initPage();
$menu = array(new MenuItem("Sections", "sections/list.php"));
$this->getPage()->setPageMenu($menu);
}
}
|
yodor/sparkbox
|
lib/templates/admin/FAQItemsListPage.php
|
PHP
|
lgpl-3.0
| 923 |
package sinhika.bark.handlers;
public interface IThingHelper
{
public abstract void init(); // end init
public abstract String getName(int index);
public abstract String getCapName(int index);
public abstract String getTypeName(int index);
public abstract int getItemID(int index);
public abstract void setItemID(int index, int id);
public abstract String getLocalizationTag(int index);
public abstract String getTexture(int index);
public abstract int size();
}
|
Sinhika/SinhikaSpices
|
common/sinhika/bark/handlers/IThingHelper.java
|
Java
|
lgpl-3.0
| 518 |
/*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.admin.patch.impl;
import org.alfresco.repo.admin.patch.AbstractPatch;
import org.alfresco.service.cmr.admin.PatchException;
/**
* Notifies the user that the patch about to be run is no longer supported and an incremental upgrade
* path must be followed.
*
* @author Derek Hulley
* @since 2.1.5
*/
public class NoLongerSupportedPatch extends AbstractPatch
{
private static final String ERR_USE_INCREMENTAL_UPGRADE = "patch.NoLongerSupportedPatch.err.use_incremental_upgrade";
private String lastSupportedVersion;
public NoLongerSupportedPatch()
{
}
public void setLastSupportedVersion(String lastSupportedVersion)
{
this.lastSupportedVersion = lastSupportedVersion;
}
@Override
protected void checkProperties()
{
super.checkProperties();
checkPropertyNotNull(lastSupportedVersion, "lastSupportedVersion");
}
@Override
protected String applyInternal() throws Exception
{
throw new PatchException(
ERR_USE_INCREMENTAL_UPGRADE,
super.getId(),
lastSupportedVersion,
lastSupportedVersion);
}
}
|
loftuxab/community-edition-old
|
projects/repository/source/java/org/alfresco/repo/admin/patch/impl/NoLongerSupportedPatch.java
|
Java
|
lgpl-3.0
| 2,016 |
package org.ddialliance.ddieditor.ui.view;
import java.util.List;
import org.apache.xmlbeans.XmlObject;
import org.ddialliance.ddieditor.model.conceptual.ConceptualElement;
import org.ddialliance.ddieditor.model.conceptual.ConceptualType;
import org.ddialliance.ddieditor.model.lightxmlobject.CustomType;
import org.ddialliance.ddieditor.model.lightxmlobject.LightXmlObjectType;
import org.ddialliance.ddieditor.model.resource.DDIResourceType;
import org.ddialliance.ddieditor.model.resource.StorageType;
import org.ddialliance.ddieditor.persistenceaccess.maintainablelabel.MaintainableLightLabelQueryResult;
import org.ddialliance.ddieditor.ui.editor.Editor;
import org.ddialliance.ddieditor.ui.util.LanguageUtil;
import org.ddialliance.ddieditor.util.LightXmlObjectUtil;
import org.ddialliance.ddiftp.util.DDIFtpException;
import org.ddialliance.ddiftp.util.Translator;
import org.ddialliance.ddiftp.util.log.Log;
import org.ddialliance.ddiftp.util.log.LogFactory;
import org.ddialliance.ddiftp.util.log.LogType;
import org.ddialliance.ddiftp.util.xml.XmlBeansUtil;
import org.eclipse.jface.viewers.LabelProvider;
/**
* Tree Label Provider
*/
class TreeLabelProvider extends LabelProvider {
private static Log log = LogFactory.getLog(LogType.SYSTEM,
TreeLabelProvider.class);
@Override
public String getText(Object element) {
// LightXmlObjectType
if (element instanceof LightXmlObjectType) {
LightXmlObjectType lightXmlObject = (LightXmlObjectType) element;
if (lightXmlObject.getElement().equals("Variable")) {
StringBuilder result = new StringBuilder();
// name
for (CustomType cus : LightXmlObjectUtil.getCustomListbyType(
lightXmlObject, "Name")) {
result.append(XmlBeansUtil.getTextOnMixedElement(cus));
}
// label
try {
String l = XmlBeansUtil
.getTextOnMixedElement((XmlObject) XmlBeansUtil
.getDefaultLangElement(lightXmlObject
.getLabelList()));
if (l != null && !l.equals("")) {
result.append(" ");
result.append(l);
}
} catch (Exception e) {
Editor.showError(e, getClass().getName());
}
if (result.length() == 0) {
result.append(lightXmlObject.getElement() + ": "
+ lightXmlObject.getId());
}
return result.toString();
}
if (lightXmlObject.getLabelList().size() > 0) {
try {
Object obj = XmlBeansUtil.getLangElement(
LanguageUtil.getDisplayLanguage(),
lightXmlObject.getLabelList());
return XmlBeansUtil.getTextOnMixedElement((XmlObject) obj);
} catch (DDIFtpException e) {
Editor.showError(e, getClass().getName());
}
} else {
// No label specified - use ID instead:
return lightXmlObject.getElement() + ": "
+ lightXmlObject.getId();
}
}
// DDIResourceType
else if (element instanceof DDIResourceType) {
return ((DDIResourceType) element).getOrgName();
}
// StorageType
else if (element instanceof StorageType) {
return ((StorageType) element).getId();
}
// ConceptualType
else if (element instanceof ConceptualType) {
return Translator.trans(((ConceptualType) element).name());
}
// ConceptualElement
else if (element instanceof ConceptualElement) {
List<org.ddialliance.ddieditor.model.lightxmlobject.LabelType> labels = ((ConceptualElement) element)
.getValue().getLabelList();
if (!labels.isEmpty()) {
return XmlBeansUtil
.getTextOnMixedElement(((ConceptualElement) element)
.getValue().getLabelList().get(0));
} else {
return ((ConceptualElement) element).getValue().getId();
}
}
// MaintainableLightLabelQueryResult
else if (element instanceof MaintainableLightLabelQueryResult) {
try {
return ((MaintainableLightLabelQueryResult) element)
.getTargetLabel();
} catch (DDIFtpException e) {
Editor.showError(e, getClass().getName());
}
return "";
}
// java.util.List
else if (element instanceof List<?>) {
if (!((List<?>) element).isEmpty()) {
Object obj = ((List<?>) element).get(0);
// light xml objects
if (obj instanceof LightXmlObjectType) {
String label = ((LightXmlObjectType) obj).getElement();
return label;
}
} else {
DDIFtpException e = new DDIFtpException("Empty list",
new Throwable());
Editor.showError(e, getClass().getName());
}
}
// guard
else {
if (log.isWarnEnabled()) {
DDIFtpException e = new DDIFtpException(element.getClass()
.getName() + "is not supported", new Throwable());
Editor.showError(e, getClass().getName());
}
}
return new String();
}
}
|
DdiEditor/ddieditor-ui
|
src/org/ddialliance/ddieditor/ui/view/TreeLabelProvider.java
|
Java
|
lgpl-3.0
| 4,630 |
// Catalano Imaging Library
// The Catalano Framework
//
// Copyright © Diego Catalano, 2014
// diego.catalano at live.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
package Catalano.Imaging.Filters;
import Catalano.Imaging.FastBitmap;
import Catalano.Imaging.IBaseInPlace;
/**
* Difference of Gaussians is a feature enhancement algorithm that involves the subtraction of one blurred version of an original image from another.
* @author Diego Catalano
*/
public class DifferenceOfGaussian implements IBaseInPlace{
private int windowSize1 = 3, windowSize2 = 5;
private double sigma1 = 1.4D, sigma2 = 1.4D;
/**
* Get first sigma value.
* @return Sigma value.
*/
public double getSigma1() {
return sigma1;
}
/**
* Set first sigma value.
* @param sigma Sigma value.
*/
public void setSigma1(double sigma) {
this.sigma1 = Math.max( 0.5, Math.min( 5.0, sigma ) );
}
/**
* Get second sigma value.
* @return Sigma value.
*/
public double getSigma2() {
return sigma2;
}
/**
* Set second sigma value.
* @param sigma Sigma value.
*/
public void setSigma2(double sigma) {
this.sigma2 = Math.max( 0.5, Math.min( 5.0, sigma ) );
}
/**
* Get first window size.
* @return Window size value.
*/
public int getWindowSize1() {
return windowSize1;
}
/**
* Set first window size.
* @param size Window size value.
*/
public void setWindowSize1(int size) {
this.windowSize1 = Math.max( 3, Math.min( 21, size | 1 ) );
}
/**
* Get second window size.
* @return Window size value.
*/
public int getWindowSize2() {
return windowSize2;
}
/**
* Set second window size.
* @param size Window size value.
*/
public void setWindowSize2(int size) {
this.windowSize2 = Math.max( 3, Math.min( 21, size | 1 ) );
}
/**
* Initialize a new instance of the DifferenceOfGaussian class.
*/
public DifferenceOfGaussian() {}
/**
* Initialize a new instance of the DifferenceOfGaussian class.
* @param windowSize1 First window size.
* @param windowSize2 Second window size.
*/
public DifferenceOfGaussian(int windowSize1, int windowSize2) {
this.windowSize1 = windowSize1;
this.windowSize2 = windowSize2;
}
/**
* Initialize a new instance of the DifferenceOfGaussian class.
* @param windowSize1 First window size.
* @param windowSize2 Second window size.
* @param sigma Sigma value for both images.
*/
public DifferenceOfGaussian(int windowSize1, int windowSize2, double sigma) {
this.windowSize1 = windowSize1;
this.windowSize2 = windowSize2;
this.sigma1 = Math.max( 0.5, Math.min( 5.0, sigma ) );
}
/**
* Initialize a new instance of the DifferenceOfGaussian class.
* @param windowSize1 First window size.
* @param windowSize2 Second window size.
* @param sigma First sigma value.
* @param sigma2 Second sigma value.
*/
public DifferenceOfGaussian(int windowSize1, int windowSize2, double sigma, double sigma2) {
this.windowSize1 = windowSize1;
this.windowSize2 = windowSize2;
this.sigma1 = Math.max( 0.5, Math.min( 5.0, sigma ) );
this.sigma2 = Math.max( 0.5, Math.min( 5.0, sigma2 ) );
}
@Override
public void applyInPlace(FastBitmap fastBitmap) {
FastBitmap b = new FastBitmap(fastBitmap);
GaussianBlur gauss = new GaussianBlur(sigma1, windowSize1);
gauss.applyInPlace(b);
gauss.setSize(windowSize2);
gauss.setSigma(sigma2);
gauss.applyInPlace(fastBitmap);
Subtract sub = new Subtract(b);
sub.applyInPlace(fastBitmap);
b.recycle();
}
}
|
accord-net/java
|
Catalano.Android.Image/src/Catalano/Imaging/Filters/DifferenceOfGaussian.java
|
Java
|
lgpl-3.0
| 4,825 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import { shallow } from 'enzyme';
import * as React from 'react';
import StatPendingTime, { Props } from '../StatPendingTime';
it('should render correctly', () => {
expect(shallowRender()).toMatchSnapshot();
});
it('should not render', () => {
expect(shallowRender({ pendingCount: undefined }).type()).toBeNull();
expect(shallowRender({ pendingCount: 0 }).type()).toBeNull();
expect(shallowRender({ pendingTime: undefined }).type()).toBeNull();
});
it('should not render when pending time is too small', () => {
expect(
shallowRender({ pendingTime: 0 })
.find('.emphasised-measure')
.exists()
).toBe(false);
expect(
shallowRender({ pendingTime: 900 })
.find('.emphasised-measure')
.exists()
).toBe(false);
});
function shallowRender(props: Partial<Props> = {}) {
return shallow(<StatPendingTime pendingCount={5} pendingTime={15420} {...props} />);
}
|
SonarSource/sonarqube
|
server/sonar-web/src/main/js/apps/background-tasks/components/__tests__/StatPendingTime-test.tsx
|
TypeScript
|
lgpl-3.0
| 1,747 |
var default_window_options = {
autoOpen: false,
width: 750,
height: 450,
modal: true,
resizable: false
};
function applyNotificationStyles() {
$('.error').each(function() {
$(this).addClass('ui-state-error ui-corner-all');
$(this).prepend('<span class="ui-icon ui-icon-alert"></span>');
});
$('.notification').each(function() {
$(this).addClass('ui-state-highlight ui-corner-all');
$(this).prepend('<span class="ui-icon ui-icon-info"></span>');
});
}
$(function() {
// Hard-coded paths aren't great... Maybe re-work this in the future
var divider = "url('" + media_url + "img/navigation_divider.png')";
$('#navigation ul.menu li:has(ul.submenu)').hover(function() {
$(this).addClass('has-submenu');
$(this).children('a.menu-link').css('background-image', 'none');
$(this).prev('li').children('a.menu-link').css('background-image', 'none');
$(this).children('ul').show();
}, function() {
$(this).removeClass('has-submenu');
$(this).children('a.menu-link').css('background-image', divider);
$(this).prev('li').children('a.menu-link').css('background-image', divider);
$(this).children('ul').hide();
});
$('#navigation ul.submenu a').click(function() {
$(this).parents('ul.submenu').hide();
});
// Style form buttons
$('input[type=button], input[type=submit], input[type=reset]').button();
// Style error and notification messages
applyNotificationStyles();
});
|
mariajosefrancolugo/osp
|
osp/media/js/base.js
|
JavaScript
|
lgpl-3.0
| 1,553 |
package io.robe.admin.hibernate.entity;
import org.junit.FixMethodOrder;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
/**
* Created by recep on 30/09/16.
*/
@FixMethodOrder
public class MenuTest {
Menu entity = new Menu();
@Test
public void getText() throws Exception {
entity.setText("Text");
assertEquals("Text", entity.getText());
}
@Test
public void getPath() throws Exception {
entity.setPath("Path");
assertEquals("Path", entity.getPath());
}
@Test
public void getIndex() throws Exception {
entity.setIndex(3);
assertEquals(3, entity.getIndex());
}
@Test
public void getParentOid() throws Exception {
entity.setParentOid("12345678901234567890123456789012");
assertEquals("12345678901234567890123456789012", entity.getParentOid());
}
@Test
public void getModule() throws Exception {
entity.setModule("Module");
assertEquals("Module", entity.getModule());
}
@Test
public void getIcon() throws Exception {
entity.setIcon("Icon");
assertEquals("Icon", entity.getIcon());
}
}
|
robeio/robe
|
robe-admin/src/test/java/io/robe/admin/hibernate/entity/MenuTest.java
|
Java
|
lgpl-3.0
| 1,192 |
<?php
/**
* @package wa-apps/photos/api/v1
*/
class photosPhotoRotateMethod extends waAPIMethod
{
protected $method = 'POST';
public function execute()
{
$id = $this->post('id', true);
$photo_model = new photosPhotoModel();
$photo = $photo_model->getById($id);
$clockwise = waRequest::post('clockwise', null, 1);
if (!is_numeric($clockwise)) {
$clockwise = strtolower(trim($clockwise));
$clockwise = $clockwise === 'false' ? 0 : 1;
}
if ($photo) {
try {
$photo_model = new photosPhotoModel();
$photo_model->rotate($id, $clockwise);
} catch (waException $e) {
throw new waAPIException('server_error', $e->getMessage(), 500);
}
$this->response = true;
} else {
throw new waAPIException('invalid_request', 'Photo not found', 404);
}
}
}
|
SergeR/webasyst-framework
|
wa-apps/photos/api/v1/photos.photo.rotate.method.php
|
PHP
|
lgpl-3.0
| 978 |
import math,re,sys,os,time
import random as RD
import time
try:
import netCDF4 as NC
except:
print("You no install netCDF4 for python")
print("So I do not import netCDF4")
try:
import numpy as NP
except:
print("You no install numpy")
print("Do not import numpy")
class GRIDINFORMATER:
"""
This object is the information of the input gridcells/array/map.
Using
.add_an_element to add an element/gridcell
.add_an_geo_element to add an element/gridcell
.create_resample_lat_lon to create a new map of lat and lon for resampling
.create_resample_map to create resample map as ARR_RESAMPLE_MAP
.create_reference_map to create ARR_REFERENCE_MAP to resample target map.
.export_reference_map to export ARR_REFERENCE_MAP into netCDF4 format
"""
STR_VALUE_INIT = "None"
NUM_VALUE_INIT = -9999.9
NUM_NULL = float("NaN")
ARR_RESAMPLE_X_LIM = []
ARR_RESAMPLE_Y_LIM = []
# FROM WRF: module_cam_shr_const_mod.f90
NUM_CONST_EARTH_R = 6.37122E6
NUM_CONST_PI = 3.14159265358979323846
def __init__(self, name="GRID", ARR_LAT=[], ARR_LON=[], NUM_NT=1, DIMENSIONS=2 ):
self.STR_NAME = name
self.NUM_DIMENSIONS = DIMENSIONS
self.NUM_LAST_INDEX = -1
self.ARR_GRID = []
self.NUM_NT = NUM_NT
self.ARR_LAT = ARR_LAT
self.ARR_LON = ARR_LON
self.ARR_RESAMPLE_MAP_PARA = { "EDGE": {"N" :-999, "S":-999, "E":-999, "W":-999 } }
if len(ARR_LAT) != 0 and len(ARR_LON) != 0:
NUM_ARR_NY_T1 = len(ARR_LAT)
NUM_ARR_NY_T2 = len(ARR_LON)
Y_T2 = len(ARR_LON)
NUM_ARR_NX_T1 = len(ARR_LAT[0])
NUM_ARR_NX_T2 = len(ARR_LON[0])
self.NUM_NX = NUM_ARR_NX_T1
self.NUM_NY = NUM_ARR_NY_T1
if NUM_ARR_NY_T1 - NUM_ARR_NY_T2 + NUM_ARR_NX_T1 - NUM_ARR_NX_T2 != 0:
print("The gridcell of LAT is {0:d}&{1:d}, and LON is {2:d}&{3:d} are not match"\
.format(NUM_ARR_NY_T1,NUM_ARR_NY_T2,NUM_ARR_NX_T1,NUM_ARR_NX_T2))
def index_map(self, ARR_IN=[], NUM_IN_NX=0, NUM_IN_NY=0):
if len(ARR_IN) == 0:
self.INDEX_MAP = [[ self.NUM_NULL for i in range(self.NUM_NX)] for j in range(self.NUM_NY)]
NUM_ALL_INDEX = len(self.ARR_GRID)
for n in range(NUM_ALL_INDEX):
self.INDEX_MAP[self.ARR_GRID[n]["INDEX_J"]][self.ARR_GRID[n]["INDEX_I"]] =\
self.ARR_GRID[n]["INDEX"]
else:
MAP_INDEX = [[ self.NUM_NULL for i in range(NUM_IN_NX)] for j in range(NUM_IN_NY)]
NUM_ALL_INDEX = len(ARR_IN)
for n in range(NUM_ALL_INDEX):
MAP_INDEX[ARR_IN[n]["INDEX_J"]][ARR_IN[n]["INDEX_I"]] = ARR_IN[n]["INDEX"]
return MAP_INDEX
def add_an_element(self, ARR_GRID, NUM_INDEX=0, STR_VALUE=STR_VALUE_INIT, NUM_VALUE=NUM_VALUE_INIT ):
""" Adding an element to an empty array """
OBJ_ELEMENT = {"INDEX" : NUM_INDEX, \
STR_VALUE : NUM_VALUE}
ARR_GRID.append(OBJ_ELEMENT)
def add_an_geo_element(self, ARR_GRID, NUM_INDEX=-999, NUM_J=0, NUM_I=0, \
NUM_NX = 0, NUM_NY = 0, NUM_NT=0, \
ARR_VALUE_STR=[], ARR_VALUE_NUM=[] ):
""" Adding an geological element to an empty array
The information for lat and lon of center, edge, and vertex will
be stored for further used.
"""
NUM_NVAR = len(ARR_VALUE_STR)
if NUM_NX == 0 or NUM_NY == 0:
NUM_NX = self.NUM_NX
NUM_NY = self.NUM_NY
if NUM_NT == 0:
NUM_NT = self.NUM_NT
NUM_CENTER_LON = self.ARR_LON[NUM_J][NUM_I]
NUM_CENTER_LAT = self.ARR_LAT[NUM_J][NUM_I]
if NUM_I == 0:
NUM_WE_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I + 1] ) * 0.5
NUM_EW_LON = -1 * ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I + 1] ) * 0.5
elif NUM_I == NUM_NX - 1:
NUM_WE_LON = -1 * ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I - 1] ) * 0.5
NUM_EW_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I - 1] ) * 0.5
else:
NUM_WE_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I + 1] ) * 0.5
NUM_EW_LON = ( self.ARR_LON[NUM_J][NUM_I] - self.ARR_LON[NUM_J][NUM_I - 1] ) * 0.5
if NUM_J == 0:
NUM_SN_LAT = -1 * ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J + 1][NUM_I ] ) * 0.5
NUM_NS_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J + 1][NUM_I ] ) * 0.5
elif NUM_J == NUM_NY - 1:
NUM_SN_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J - 1][NUM_I ] ) * 0.5
NUM_NS_LAT = -1 * ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J - 1][NUM_I ] ) * 0.5
else:
NUM_SN_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J - 1][NUM_I ] ) * 0.5
NUM_NS_LAT = ( self.ARR_LAT[NUM_J][NUM_I] - self.ARR_LAT[NUM_J + 1][NUM_I ] ) * 0.5
ARR_NE = [ NUM_CENTER_LON + NUM_EW_LON , NUM_CENTER_LAT + NUM_NS_LAT ]
ARR_NW = [ NUM_CENTER_LON + NUM_WE_LON , NUM_CENTER_LAT + NUM_NS_LAT ]
ARR_SE = [ NUM_CENTER_LON + NUM_EW_LON , NUM_CENTER_LAT + NUM_SN_LAT ]
ARR_SW = [ NUM_CENTER_LON + NUM_WE_LON , NUM_CENTER_LAT + NUM_SN_LAT ]
if NUM_INDEX == -999:
NUM_INDEX = self.NUM_LAST_INDEX +1
self.NUM_LAST_INDEX += 1
OBJ_ELEMENT = {"INDEX" : NUM_INDEX,\
"INDEX_I" : NUM_I,\
"INDEX_J" : NUM_J,\
"CENTER" : {"LAT" : NUM_CENTER_LAT, "LON" : NUM_CENTER_LON},\
"VERTEX" : {"NE": ARR_NE, "SE": ARR_SE, "SW": ARR_SW, "NW": ARR_NW},\
"EDGE" : {"N": NUM_CENTER_LAT + NUM_NS_LAT,"S": NUM_CENTER_LAT + NUM_SN_LAT,\
"E": NUM_CENTER_LON + NUM_EW_LON,"W": NUM_CENTER_LON + NUM_WE_LON}}
if len(ARR_VALUE_STR) > 0:
for I, VAR in enumerate(ARR_VALUE_STR):
OBJ_ELEMENT[VAR] = [{ "VALUE" : 0.0} for t in range(NUM_NT) ]
if len(ARR_VALUE_NUM) == NUM_NVAR:
for T in range(NUM_NT):
OBJ_ELEMENT[VAR][T]["VALUE"] = ARR_VALUE_NUM[I][T]
ARR_GRID.append(OBJ_ELEMENT)
def add_an_geo_variable(self, ARR_GRID, NUM_INDEX=-999, NUM_J=0, NUM_I=0, NUM_NT=0,\
STR_VALUE=STR_VALUE_INIT, NUM_VALUE=NUM_VALUE_INIT ):
if NUM_INDEX == -999:
NUM_INDEX = self.INDEX_MAP[NUM_J][NUM_I]
if NUM_NT == 0:
NUM_NT = self.NUM_NT
ARR_GRID[NUM_INDEX][STR_VALUE] = {{"VALUE": NUM_VALUE } for t in range(NUM_NT)}
def create_resample_lat_lon(self, ARR_RANGE_LAT=[0,0],NUM_EDGE_LAT=0,\
ARR_RANGE_LON=[0,0],NUM_EDGE_LON=0 ):
self.NUM_GRIDS_LON = round((ARR_RANGE_LON[1] - ARR_RANGE_LON[0])/NUM_EDGE_LON)
self.NUM_GRIDS_LAT = round((ARR_RANGE_LAT[1] - ARR_RANGE_LAT[0])/NUM_EDGE_LAT)
self.ARR_LAT = [[ 0 for i in range(self.NUM_GRIDS_LON)] for j in range(self.NUM_GRIDS_LAT) ]
self.ARR_LON = [[ 0 for i in range(self.NUM_GRIDS_LON)] for j in range(self.NUM_GRIDS_LAT) ]
for j in range(self.NUM_GRIDS_LAT):
for i in range(self.NUM_GRIDS_LON):
NUM_LAT = ARR_RANGE_LAT[0] + NUM_EDGE_LAT * j
NUM_LON = ARR_RANGE_LON[0] + NUM_EDGE_LON * i
self.ARR_LON[j][i] = ARR_RANGE_LON[0] + NUM_EDGE_LON * i
self.ARR_LAT[j][i] = ARR_RANGE_LAT[0] + NUM_EDGE_LAT * j
def create_reference_map(self, MAP_TARGET, MAP_RESAMPLE, STR_TYPE="FIX", NUM_SHIFT=0.001, IF_PB=False):
"""Must input with OBJ_REFERENCE
WARNING: The edge of gridcells may not be included due to the unfinished algorithm
"""
self.ARR_REFERENCE_MAP = []
if STR_TYPE=="GRIDBYGEO":
NUM_OBJ_G_LEN = len(MAP_TARGET)
for OBJ_G in MAP_TARGET:
NUM_G_COOR = [OBJ_G["CENTER"]["LAT"], OBJ_G["CENTER"]["LON"]]
for OBJ_R in MAP_RESAMPLE:
NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] - OBJ_G["CENTER"]["LON"])
NUM_CHK_IN_SN = (OBJ_R["EDGE"]["N"] - OBJ_G["CENTER"]["LAT"]) *\
(OBJ_R["EDGE"]["S"] - OBJ_G["CENTER"]["LAT"])
if NUM_CHK_IN_EW == 0: NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"])
if NUM_CHK_IN_SN == 0: NUM_CHK_IN_SN = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"])
if NUM_CHK_IN_EW < 0 and NUM_CHK_IN_SN < 0:
OBJ_ELEMENT = {"INDEX" : OBJ_G["INDEX"],\
"CENTER" : OBJ_G["CENTER"],\
"INDEX_REF" : OBJ_R["INDEX"],\
"INDEX_REF_I" : OBJ_R["INDEX_I"],\
"INDEX_REF_J" : OBJ_R["INDEX_J"],\
"CENTER_REF" : OBJ_R["CENTER"],\
}
self.ARR_REFERENCE_MAP.append(OBJ_ELEMENT)
break
if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([OBJ_G["INDEX"]], [NUM_OBJ_G_LEN]), STR_DES="CREATING REFERENCE MAP")
elif STR_TYPE=="FIX":
NUM_OBJ_G_LEN = len(MAP_TARGET)
for OBJ_G in MAP_TARGET:
NUM_G_COOR = [OBJ_G["CENTER"]["LAT"], OBJ_G["CENTER"]["LON"]]
if self.ARR_RESAMPLE_MAP_PARA["EDGE"]["W"] == -999 or self.ARR_RESAMPLE_MAP_PARA["EDGE"]["E"] == -999:
NUM_CHK_EW_IN = -1
else:
NUM_CHK_EW_IN = (NUM_G_COOR[1] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["W"] ) * ( NUM_G_COOR[1] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["E"] )
if self.ARR_RESAMPLE_MAP_PARA["EDGE"]["N"] == -999 or self.ARR_RESAMPLE_MAP_PARA["EDGE"]["S"] == -999:
NUM_CHK_SN_IN = -1
else:
NUM_CHK_SN_IN = (NUM_G_COOR[0] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["S"] ) * ( NUM_G_COOR[0] - self.ARR_RESAMPLE_MAP_PARA["EDGE"]["N"] )
if NUM_CHK_EW_IN < 0 and NUM_CHK_SN_IN < 0:
for OBJ_R in MAP_RESAMPLE:
NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] - OBJ_G["CENTER"]["LON"])
NUM_CHK_IN_SN = (OBJ_R["EDGE"]["N"] - OBJ_G["CENTER"]["LAT"]) *\
(OBJ_R["EDGE"]["S"] - OBJ_G["CENTER"]["LAT"])
if NUM_CHK_IN_EW == 0: NUM_CHK_IN_EW = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"])
if NUM_CHK_IN_SN == 0: NUM_CHK_IN_SN = (OBJ_R["EDGE"]["E"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"]) *\
(OBJ_R["EDGE"]["W"] + NUM_SHIFT - OBJ_G["CENTER"]["LON"])
if NUM_CHK_IN_EW < 0 and NUM_CHK_IN_SN < 0:
OBJ_ELEMENT = {"INDEX" : OBJ_G["INDEX"],\
"INDEX_I" : OBJ_G["INDEX_I"],\
"INDEX_J" : OBJ_G["INDEX_J"],\
"CENTER" : OBJ_G["CENTER"],\
"INDEX_REF" : OBJ_R["INDEX"],\
"INDEX_REF_I" : OBJ_R["INDEX_I"],\
"INDEX_REF_J" : OBJ_R["INDEX_J"],\
"CENTER_REF" : OBJ_R["CENTER"],\
}
self.ARR_REFERENCE_MAP.append(OBJ_ELEMENT)
break
if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([OBJ_G["INDEX"]], [NUM_OBJ_G_LEN]), STR_DES="CREATING REFERENCE MAP")
def export_grid_map(self, ARR_GRID_IN, STR_DIR, STR_FILENAME, ARR_VAR_STR=[],\
ARR_VAR_ITEM=["MEAN", "MEDIAN", "MIN", "MAX", "P95", "P75", "P25", "P05"],\
NUM_NX=0, NUM_NY=0, NUM_NT=0, STR_TYPE="netCDF4", IF_PB=False ):
TIME_NOW = time.gmtime()
STR_DATE_NOW = "{0:04d}-{1:02d}-{2:02d}".format(TIME_NOW.tm_year, TIME_NOW.tm_mon, TIME_NOW.tm_mday)
STR_TIME_NOW = "{0:04d}:{1:02d}:{2:02d}".format(TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec)
if NUM_NX==0: NUM_NX = self.NUM_NX
if NUM_NY==0: NUM_NY = self.NUM_NY
if NUM_NT==0: NUM_NT = self.NUM_NT
if STR_TYPE == "netCDF4":
NCDF4_DATA = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILENAME), 'w', format="NETCDF4")
# CREATE ATTRIBUTEs:
NCDF4_DATA.description = \
"The grid information in netCDF4"
NCDF4_DATA.history = "Create on {0:s} at {1:s}".format(STR_DATE_NOW, STR_TIME_NOW)
# CREATE DIMENSIONs:
NCDF4_DATA.createDimension("Y" , NUM_NY )
NCDF4_DATA.createDimension("X" , NUM_NX )
NCDF4_DATA.createDimension("Time" , NUM_NT )
NCDF4_DATA.createDimension("Values", None )
# CREATE BASIC VARIABLES:
NCDF4_DATA.createVariable("INDEX", "i4", ("Y", "X"))
NCDF4_DATA.createVariable("INDEX_J", "i4", ("Y", "X"))
NCDF4_DATA.createVariable("INDEX_I", "i4", ("Y", "X"))
NCDF4_DATA.createVariable("CENTER_LON", "f8", ("Y", "X"))
NCDF4_DATA.createVariable("CENTER_LAT", "f8", ("Y", "X"))
# CREATE GROUP for Variables:
for VAR in ARR_VAR_STR:
NCDF4_DATA.createGroup(VAR)
for ITEM in ARR_VAR_ITEM:
if ITEM == "VALUE" :
NCDF4_DATA.groups[VAR].createVariable(ITEM, "f8", ("Time", "Y", "X", "Values"))
else:
NCDF4_DATA.groups[VAR].createVariable(ITEM, "f8", ("Time", "Y", "X"))
# WRITE IN VARIABLE
for V in ["INDEX", "INDEX_J", "INDEX_I"]:
map_in = self.convert_grid2map(ARR_GRID_IN, V, NX=NUM_NX, NY=NUM_NY, NC_TYPE="INT")
for n in range(len(map_in)):
NCDF4_DATA.variables[V][n] = map_in[n]
for V1 in ["CENTER"]:
for V2 in ["LON", "LAT"]:
map_in = self.convert_grid2map(ARR_GRID_IN, V1, V2, NX=NUM_NX, NY=NUM_NY, NC_TYPE="FLOAT")
for n in range(len(map_in)):
NCDF4_DATA.variables["{0:s}_{1:s}".format(V1, V2)][n] = map_in[n]
for V1 in ARR_VAR_STR:
for V2 in ARR_VAR_ITEM:
map_in = self.convert_grid2map(ARR_GRID_IN, V1, V2, NX=NUM_NX, NY=NUM_NY, NT=NUM_NT)
for n in range(len(map_in)):
NCDF4_DATA.groups[V1].variables[V2][n] = map_in[n]
NCDF4_DATA.close()
def export_grid(self, ARR_GRID_IN, STR_DIR, STR_FILENAME, ARR_VAR_STR=[],\
ARR_VAR_ITEM=["VALUE", "MEAN", "MEDIAN", "MIN", "MAX", "P95", "P75", "P25", "P05"],\
NUM_NX=0, NUM_NY=0, NUM_NT=0, STR_TYPE="netCDF4", IF_PB=False ):
TIME_NOW = time.gmtime()
STR_DATE_NOW = "{0:04d}-{1:02d}-{2:02d}".format(TIME_NOW.tm_year, TIME_NOW.tm_mon, TIME_NOW.tm_mday)
STR_TIME_NOW = "{0:04d}:{1:02d}:{2:02d}".format(TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec)
if NUM_NX==0: NUM_NX = self.NUM_NX
if NUM_NY==0: NUM_NY = self.NUM_NY
if NUM_NT==0: NUM_NT = self.NUM_NT
if STR_TYPE == "netCDF4":
NCDF4_DATA = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILENAME), 'w', format="NETCDF4")
# CREATE ATTRIBUTEs:
NCDF4_DATA.description = \
"The grid information in netCDF4"
NCDF4_DATA.history = "Create on {0:s} at {1:s}".format(STR_DATE_NOW, STR_TIME_NOW)
# CREATE DIMENSIONs:
NCDF4_DATA.createDimension("Y" , NUM_NY )
NCDF4_DATA.createDimension("X" , NUM_NX )
NCDF4_DATA.createDimension("Time" , NUM_NT )
NCDF4_DATA.createDimension("Values", None )
# CREATE BASIC VARIABLES:
INDEX = NCDF4_DATA.createVariable("INDEX", "i4", ("Y", "X"))
INDEX_J = NCDF4_DATA.createVariable("INDEX_J", "i4", ("Y", "X"))
INDEX_I = NCDF4_DATA.createVariable("INDEX_I", "i4", ("Y", "X"))
CENTER_LON = NCDF4_DATA.createVariable("CENTER_LON", "f8", ("Y", "X"))
CENTER_LAT = NCDF4_DATA.createVariable("CENTER_LAT", "f8", ("Y", "X"))
# CREATE GROUP for Variables:
for VAR in ARR_VAR_STR:
NCDF4_DATA.createGroup(VAR)
for ITEM in ARR_VAR_ITEM:
if ITEM == "VALUE" :
NCDF4_DATA.groups[VAR].createVariable(ITEM, "f8", ("Time", "Y", "X", "Values"))
else:
NCDF4_DATA.groups[VAR].createVariable(ITEM, "f8", ("Time", "Y", "X"))
# WRITE IN VARIABLE
for IND, OBJ in enumerate(ARR_GRID_IN):
j = OBJ["INDEX_J"]
i = OBJ["INDEX_I"]
INDEX [j,i] = OBJ["INDEX"]
INDEX_J [j,i] = OBJ["INDEX_J"]
INDEX_I [j,i] = OBJ["INDEX_I"]
CENTER_LON [j,i] = OBJ["CENTER"]["LON"]
CENTER_LAT [j,i] = OBJ["CENTER"]["LAT"]
for VAR in ARR_VAR_STR:
for ITEM in ARR_VAR_ITEM:
for T in range(NUM_NT):
NCDF4_DATA.groups[VAR].variables[ITEM][T,j,i] = OBJ[VAR][T][ITEM]
if IF_PB: TOOLS.progress_bar((IND+1)/(NUM_NX*NUM_NY), STR_DES="WRITING PROGRESS")
NCDF4_DATA.close()
def export_reference_map(self, STR_DIR, STR_FILENAME, STR_TYPE="netCDF4", IF_PB=False, IF_PARALLEL=False ):
TIME_NOW = time.gmtime()
self.STR_DATE_NOW = "{0:04d}-{1:02d}-{2:02d}".format(TIME_NOW.tm_year, TIME_NOW.tm_mon, TIME_NOW.tm_mday)
self.STR_TIME_NOW = "{0:02d}:{1:02d}:{2:02d}".format(TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec)
STR_INPUT_FILENAME = "{0:s}/{1:s}".format(STR_DIR, STR_FILENAME)
if STR_TYPE == "netCDF4":
IF_FILECHK = os.path.exists(STR_INPUT_FILENAME)
if IF_FILECHK:
NCDF4_DATA = NC.Dataset(STR_INPUT_FILENAME, 'a', format="NETCDF4", parallel=IF_PARALLEL)
INDEX = NCDF4_DATA.variables["INDEX" ]
INDEX_J = NCDF4_DATA.variables["INDEX_J" ]
INDEX_I = NCDF4_DATA.variables["INDEX_I" ]
CENTER_LON = NCDF4_DATA.variables["CENTER_LON" ]
CENTER_LAT = NCDF4_DATA.variables["CENTER_LAT" ]
INDEX_REF = NCDF4_DATA.variables["INDEX_REF" ]
INDEX_REF_J = NCDF4_DATA.variables["INDEX_REF_J" ]
INDEX_REF_I = NCDF4_DATA.variables["INDEX_REF_I" ]
CENTER_REF_LON = NCDF4_DATA.variables["CENTER_REF_LON" ]
CENTER_REF_LAT = NCDF4_DATA.variables["CENTER_REF_LAT" ]
else:
NCDF4_DATA = NC.Dataset(STR_INPUT_FILENAME, 'w', format="NETCDF4", parallel=IF_PARALLEL)
# CREATE ATTRIBUTEs:
NCDF4_DATA.description = \
"The netCDF4 version of reference map which contains grid information for resampling"
NCDF4_DATA.history = "Create on {0:s} at {1:s}".format(self.STR_DATE_NOW, self.STR_TIME_NOW)
# CREATE DIMENSIONs:
NCDF4_DATA.createDimension("Y",self.NUM_NY)
NCDF4_DATA.createDimension("X",self.NUM_NX)
# CREATE_VARIABLES:
INDEX = NCDF4_DATA.createVariable("INDEX", "i4", ("Y", "X"))
INDEX_J = NCDF4_DATA.createVariable("INDEX_J", "i4", ("Y", "X"))
INDEX_I = NCDF4_DATA.createVariable("INDEX_I", "i4", ("Y", "X"))
CENTER_LON = NCDF4_DATA.createVariable("CENTER_LON", "f8", ("Y", "X"))
CENTER_LAT = NCDF4_DATA.createVariable("CENTER_LAT", "f8", ("Y", "X"))
INDEX_REF = NCDF4_DATA.createVariable("INDEX_REF", "i4", ("Y", "X"))
INDEX_REF_J = NCDF4_DATA.createVariable("INDEX_REF_J", "i4", ("Y", "X"))
INDEX_REF_I = NCDF4_DATA.createVariable("INDEX_REF_I", "i4", ("Y", "X"))
CENTER_REF_LON = NCDF4_DATA.createVariable("CENTER_REF_LON", "f8", ("Y", "X"))
CENTER_REF_LAT = NCDF4_DATA.createVariable("CENTER_REF_LAT", "f8", ("Y", "X"))
NUM_TOTAL_OBJ = len(self.ARR_REFERENCE_MAP)
NUM_MAX_I = self.NUM_NX
for OBJ in self.ARR_REFERENCE_MAP:
j = OBJ["INDEX_J"]
i = OBJ["INDEX_I"]
INDEX[j,i] = OBJ["INDEX"]
INDEX_J[j,i] = OBJ["INDEX_J"]
INDEX_I[j,i] = OBJ["INDEX_I"]
INDEX_REF[j,i] = OBJ["INDEX_REF"]
INDEX_REF_J[j,i] = OBJ["INDEX_REF_J"]
INDEX_REF_I[j,i] = OBJ["INDEX_REF_I"]
CENTER_LON [j,i] = OBJ["CENTER"]["LON"]
CENTER_LAT [j,i] = OBJ["CENTER"]["LAT"]
CENTER_REF_LON [j,i] = OBJ["CENTER_REF"]["LON"]
CENTER_REF_LAT [j,i] = OBJ["CENTER_REF"]["LAT"]
if IF_PB: TOOLS.progress_bar((i+j*NUM_MAX_I)/float(NUM_TOTAL_OBJ), STR_DES="Exporting")
NCDF4_DATA.close()
def import_reference_map(self, STR_DIR, STR_FILENAME, ARR_X_RANGE=[], ARR_Y_RANGE=[], STR_TYPE="netCDF4", IF_PB=False):
self.ARR_REFERENCE_MAP = []
self.NUM_MAX_INDEX_RS = 0
self.NUM_MIN_INDEX_RS = 999
if len(ARR_X_RANGE) != 0:
self.I_MIN = ARR_X_RANGE[0]
self.I_MAX = ARR_X_RANGE[1]
else:
self.I_MIN = 0
self.I_MAX = self.REFERENCE_MAP_NX
if len(ARR_Y_RANGE) != 0:
self.J_MIN = ARR_Y_RANGE[0]
self.J_MAX = ARR_Y_RANGE[1]
else:
self.J_MIN = 0
self.J_MAX = self.REFERENCE_MAP_NY
if STR_TYPE == "netCDF4":
NCDF4_DATA = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILENAME), 'r', format="NETCDF4")
# READ DIMENSIONs:
self.REFERENCE_MAP_NY = NCDF4_DATA.dimensions["Y"].size
self.REFERENCE_MAP_NX = NCDF4_DATA.dimensions["X"].size
# CREATE_VARIABLES:
INDEX = NCDF4_DATA.variables["INDEX" ]
INDEX_J = NCDF4_DATA.variables["INDEX_J" ]
INDEX_I = NCDF4_DATA.variables["INDEX_I" ]
CENTER_LON = NCDF4_DATA.variables["CENTER_LON" ]
CENTER_LAT = NCDF4_DATA.variables["CENTER_LAT" ]
INDEX_REF = NCDF4_DATA.variables["INDEX_REF" ]
INDEX_REF_J = NCDF4_DATA.variables["INDEX_REF_J" ]
INDEX_REF_I = NCDF4_DATA.variables["INDEX_REF_I" ]
CENTER_REF_LON = NCDF4_DATA.variables["CENTER_REF_LON" ]
CENTER_REF_LAT = NCDF4_DATA.variables["CENTER_REF_LAT" ]
for j in range(self.J_MIN, self.J_MAX):
for i in range(self.I_MIN, self.I_MAX):
OBJ_ELEMENT = {"INDEX" : 0 ,\
"INDEX_I" : 0 ,\
"INDEX_J" : 0 ,\
"CENTER" : {"LAT": 0.0, "LON": 0.0} ,\
"INDEX_REF" : 0 ,\
"INDEX_REF_I" : 0 ,\
"INDEX_REF_J" : 0 ,\
"CENTER_REF" : {"LAT": 0.0, "LON": 0.0} }
if INDEX [j][i] != None:
OBJ_ELEMENT["INDEX"] = INDEX [j][i]
OBJ_ELEMENT["INDEX_J"] = INDEX_J [j][i]
OBJ_ELEMENT["INDEX_I"] = INDEX_I [j][i]
OBJ_ELEMENT["INDEX_REF"] = INDEX_REF [j][i]
OBJ_ELEMENT["INDEX_REF_J"] = INDEX_REF_J [j][i]
OBJ_ELEMENT["INDEX_REF_I"] = INDEX_REF_I [j][i]
OBJ_ELEMENT["CENTER"]["LAT"] = CENTER_LAT [j][i]
OBJ_ELEMENT["CENTER"]["LON"] = CENTER_LON [j][i]
OBJ_ELEMENT["CENTER_REF"]["LAT"] = CENTER_REF_LAT[j][i]
OBJ_ELEMENT["CENTER_REF"]["LON"] = CENTER_REF_LON[j][i]
else:
OBJ_ELEMENT["INDEX"] = INDEX [j][i]
OBJ_ELEMENT["INDEX_I"] = INDEX_J [j][i]
OBJ_ELEMENT["INDEX_J"] = INDEX_I [j][i]
OBJ_ELEMENT["INDEX_REF"] = -999
OBJ_ELEMENT["INDEX_REF_J"] = -999
OBJ_ELEMENT["INDEX_REF_I"] = -999
OBJ_ELEMENT["CENTER"]["LAT"] = CENTER_LAT [j][i]
OBJ_ELEMENT["CENTER"]["LON"] = CENTER_LON [j][i]
OBJ_ELEMENT["CENTER_REF"]["LAT"] = -999
OBJ_ELEMENT["CENTER_REF"]["LON"] = -999
self.ARR_REFERENCE_MAP.append(OBJ_ELEMENT)
self.NUM_MIN_INDEX_RS = min(self.NUM_MIN_INDEX_RS, INDEX_REF[j][i])
self.NUM_MAX_INDEX_RS = max(self.NUM_MAX_INDEX_RS, INDEX_REF[j][i])
if IF_PB: TOOLS.progress_bar((j - self.J_MIN + 1)/float(self.J_MAX - self.J_MIN), STR_DES="IMPORTING")
if self.NUM_MIN_INDEX_RS == 0:
self.NUM_MAX_RS = self.NUM_MAX_INDEX_RS + 1
NCDF4_DATA.close()
def create_resample_map(self, ARR_REFERENCE_MAP=[], ARR_VARIABLES=["Value"], ARR_GRID_IN=[],\
IF_PB=False, NUM_NT=0, NUM_NX=0, NUM_NY=0, NUM_NULL=-9999.999):
if NUM_NT == 0:
NUM_NT = self.NUM_NT
if NUM_NX == 0:
NUM_NX = self.NUM_NX
if NUM_NY == 0:
NUM_NY = self.NUM_NY
if len(ARR_REFERENCE_MAP) == 0:
self.ARR_RESAMPLE_OUT = []
self.ARR_RESAMPLE_OUT_PARA = {"EDGE": {"N": 0.0,"S": 0.0,"E": 0.0,"W": 0.0}}
NUM_END_J = self.NUM_GRIDS_LAT - 1
NUM_END_I = self.NUM_GRIDS_LON - 1
ARR_EMPTY = [float("NaN") for n in range(self.NUM_NT)]
for J in range(self.NUM_GRIDS_LAT):
for I in range(self.NUM_GRIDS_LON):
NUM_IND = I + J * self.NUM_GRIDS_LON
self.add_an_geo_element(self.ARR_RESAMPLE_OUT, NUM_INDEX=NUM_IND, NUM_J=J, NUM_I=I, \
NUM_NX= self.NUM_GRIDS_LON, NUM_NY= self.NUM_GRIDS_LAT,\
ARR_VALUE_STR=ARR_VARIABLES, NUM_NT=NUM_NT)
self.ARR_RESAMPLE_MAP_PARA["EDGE"]["N"] = max( self.ARR_LAT[NUM_END_J][0], self.ARR_LAT[NUM_END_J][NUM_END_I] )
self.ARR_RESAMPLE_MAP_PARA["EDGE"]["S"] = min( self.ARR_LAT[0][0], self.ARR_LAT[0][NUM_END_I] )
self.ARR_RESAMPLE_MAP_PARA["EDGE"]["W"] = min( self.ARR_LAT[0][0], self.ARR_LAT[NUM_END_J][0] )
self.ARR_RESAMPLE_MAP_PARA["EDGE"]["E"] = max( self.ARR_LAT[0][NUM_END_I], self.ARR_LAT[NUM_END_J][NUM_END_I] )
self.NUM_MAX_INDEX_RS = NUM_IND
else:
if ARR_GRID_IN == []: ARR_GRID_IN = self.ARR_GRID
self.ARR_RESAMPLE_OUT = [ {} for n in range(NUM_NX * NUM_NY)]
for IND in range(len(self.ARR_RESAMPLE_OUT)):
for VAR in ARR_VARIABLES:
self.ARR_RESAMPLE_OUT[IND][VAR] = [{"VALUE" : []} for T in range(NUM_NT) ]
#for IND in range(len(ARR_REFERENCE_MAP)):
for IND in range(len(ARR_GRID_IN)):
R_IND = ARR_REFERENCE_MAP[IND]["INDEX_REF"]
R_J = ARR_REFERENCE_MAP[IND]["INDEX_REF_J"]
R_I = ARR_REFERENCE_MAP[IND]["INDEX_REF_I"]
R_IND_FIX = TOOLS.fix_ind(R_IND, R_J, R_I, ARR_XRANGE=self.ARR_RESAMPLE_LIM_X, ARR_YRANGE=self.ARR_RESAMPLE_LIM_Y, NX=NUM_NX, NY=NUM_NY)
if R_IND != None:
for VAR in ARR_VARIABLES:
for T in range(NUM_NT):
#print("R_IND:{0:d}, T:{1:d}, IND:{2:d} ".format(R_IND, T, IND))
NUM_VAL_IN = ARR_GRID_IN[IND][VAR][T]["VALUE"]
self.ARR_RESAMPLE_OUT[R_IND][VAR][T]["VALUE"].append(NUM_VAL_IN)
self.ARR_RESAMPLE_OUT[R_IND]["INDEX"] = ARR_REFERENCE_MAP[IND]["INDEX_REF"]
self.ARR_RESAMPLE_OUT[R_IND]["INDEX_J"] = ARR_REFERENCE_MAP[IND]["INDEX_REF_J"]
self.ARR_RESAMPLE_OUT[R_IND]["INDEX_I"] = ARR_REFERENCE_MAP[IND]["INDEX_REF_I"]
self.ARR_RESAMPLE_OUT[R_IND]["CENTER"] = {"LAT": 0.0, "LON": 0.0 }
self.ARR_RESAMPLE_OUT[R_IND]["CENTER"]["LAT"] = ARR_REFERENCE_MAP[IND]["CENTER"]["LAT"]
self.ARR_RESAMPLE_OUT[R_IND]["CENTER"]["LON"] = ARR_REFERENCE_MAP[IND]["CENTER"]["LON"]
if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([IND], [len(ARR_GRID_IN)]), STR_DES="RESAMPLING PROGRESS")
def cal_resample_map(self, ARR_VARIABLES, ARR_GRID_IN=[], NUM_NT=0, IF_PB=False, \
DIC_PERCENTILE={ "P05": 0.05, "P10": 0.1, "P25": 0.25, "P75": 0.75, "P90": 0.90, "P95": 0.95}, NUM_NULL=-9999.999):
if NUM_NT == 0:
NUM_NT = self.NUM_NT
NUM_RS_OUT_LEN = len(self.ARR_RESAMPLE_OUT)
for IND in range(NUM_RS_OUT_LEN):
for VAR in ARR_VARIABLES:
for T in range(NUM_NT):
ARR_IN = self.ARR_RESAMPLE_OUT[IND][VAR][T]["VALUE"]
if len(ARR_IN) > 0:
ARR_IN.sort()
NUM_ARR_LEN = len(ARR_IN)
NUM_ARR_MEAN = sum(ARR_IN) / float(NUM_ARR_LEN)
NUM_ARR_S2SUM = 0
if math.fmod(NUM_ARR_LEN,2) == 1:
NUM_MPOS = [int((NUM_ARR_LEN-1)/2.0), int((NUM_ARR_LEN-1)/2.0)]
else:
NUM_MPOS = [int(NUM_ARR_LEN/2.0) , int(NUM_ARR_LEN/2.0 -1) ]
self.ARR_RESAMPLE_OUT[IND][VAR][T]["MIN"] = min(ARR_IN)
self.ARR_RESAMPLE_OUT[IND][VAR][T]["MAX"] = max(ARR_IN)
self.ARR_RESAMPLE_OUT[IND][VAR][T]["MEAN"] = NUM_ARR_MEAN
self.ARR_RESAMPLE_OUT[IND][VAR][T]["MEDIAN"] = ARR_IN[NUM_MPOS[0]] *0.5 + ARR_IN[NUM_MPOS[1]] *0.5
for STVA in DIC_PERCENTILE:
self.ARR_RESAMPLE_OUT[IND][VAR][T][STVA] = ARR_IN[ round(NUM_ARR_LEN * DIC_PERCENTILE[STVA])-1]
for VAL in ARR_IN:
NUM_ARR_S2SUM += (VAL - NUM_ARR_MEAN)**2
self.ARR_RESAMPLE_OUT[IND][VAR][T]["STD"] = (NUM_ARR_S2SUM / max(1, NUM_ARR_LEN-1))**0.5
if IF_PB: TOOLS.progress_bar(TOOLS.cal_loop_progress([IND], [NUM_RS_OUT_LEN]), STR_DES="RESAMPLING CALCULATION")
def convert_grid2map(self, ARR_GRID_IN, STR_VAR, STR_VAR_TYPE="", NX=0, NY=0, NT=0, IF_PB=False, NC_TYPE=""):
if NC_TYPE == "INT":
if NT == 0:
ARR_OUT = NP.empty([NY, NX], dtype=NP.int8)
else:
ARR_OUT = NP.empty([NT, NY, NX], dtype=NP.int8)
elif NC_TYPE == "FLOAT":
if NT == 0:
ARR_OUT = NP.empty([NY, NX], dtype=NP.float64)
else:
ARR_OUT = NP.empty([NT, NY, NX], dtype=NP.float64)
else:
if NT == 0:
ARR_OUT = [[ self.NUM_NULL for i in range(NX)] for j in range(NY) ]
else:
ARR_OUT = [[[ self.NUM_NULL for i in range(NX)] for j in range(NY) ] for t in range(NT)]
if STR_VAR_TYPE == "":
for I, GRID in enumerate(ARR_GRID_IN):
if GRID["INDEX"] != -999:
if NT == 0:
#print(GRID["INDEX_J"], GRID["INDEX_I"], GRID[STR_VAR])
ARR_OUT[ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR]
else:
for T in range(NT):
ARR_OUT[T][ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR][T]
if IF_PB==True: TOOLS.progress_bar(((I+1)/(len(ARR_GRID_IN))))
else:
for I, GRID in enumerate(ARR_GRID_IN):
if GRID["INDEX"] != -999:
if NT == 0:
ARR_OUT[ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR][STR_VAR_TYPE]
else:
for T in range(NT):
ARR_OUT[T][ GRID["INDEX_J"] ][ GRID["INDEX_I"] ] = GRID[STR_VAR][T][STR_VAR_TYPE]
if IF_PB==True: TOOLS.progress_bar(((I+1)/(len(ARR_GRID_IN))))
return ARR_OUT
def mask_grid(self, ARR_GRID_IN, STR_VAR, STR_VAR_TYPE, NUM_NT=0, STR_MASK="MASK",\
ARR_NUM_DTM=[0,1,2], ARR_NUM_DTM_RANGE=[0,1]):
if NUM_NT == 0:
NUM_NT= self.NUM_NT
for IND, GRID in enumerate(ARR_GRID_IN):
for T in range(NUM_NT):
NUM_DTM = GEO_TOOLS.mask_dtm(GRID[STR_VAR][T][STR_VAR_TYPE], ARR_NUM_DTM=ARR_NUM_DTM, ARR_NUM_DTM_RANGE=ARR_NUM_DTM_RANGE)
ARR_GRID_IN[IND][STR_VAR][T][STR_MASK] = NUM_DTM
class MATH_TOOLS:
""" Some math tools that help us to calculate.
gau_kde: kernel density estimator by Gaussian Function
standard_dev: The Standard deviation
"""
def GaussJordanEli(arr_in):
num_ydim = len(arr_in)
num_xdim = len(arr_in[0])
arr_out = arr_in
if num_ydim -num_xdim == 0 or num_xdim - num_ydim == 1:
arr_i = NP.array([[0.0 for j in range(num_ydim)] for i in range(num_ydim)])
for ny in range(num_ydim):
arr_i[ny][ny] = 1.0
#print(arr_i)
for nx in range(num_xdim):
for ny in range(nx+1, num_ydim):
arr_i [ny] = arr_i [ny] - arr_i [nx] * arr_out[ny][nx] / float(arr_out[nx][nx])
arr_out[ny] = arr_out[ny] - arr_out[nx] * arr_out[ny][nx] / float(arr_out[nx][nx])
if num_xdim - num_ydim == 1:
for nx in range(num_xdim-1,-1,-1):
for ny in range(num_ydim-1,nx, -1):
print(nx,ny)
arr_i [nx] = arr_i [nx] - arr_i [ny] * arr_out[nx][ny] / float(arr_out[ny][ny])
arr_out[nx] = arr_out[nx] - arr_out[ny] * arr_out[nx][ny] / float(arr_out[ny][ny])
else:
for nx in range(num_xdim,-1,-1):
for ny in range(num_ydim-1, nx, -1):
print(nx,ny)
arr_i [nx] = arr_i [nx] - arr_i [ny] * arr_out[nx][ny] / float(arr_out[ny][ny])
arr_out[nx] = arr_out[nx] - arr_out[ny] * arr_out[nx][ny] / float(arr_out[ny][ny])
if num_xdim - num_ydim == 1:
arr_sol = [0.0 for n in range(num_ydim)]
for ny in range(num_ydim):
arr_sol[ny] = arr_out[ny][num_xdim-1]/arr_out[ny][ny]
return arr_out, arr_i, arr_sol
else:
return arr_out, arr_i
else:
print("Y dim: {0:d}, X dim: {1:d}: can not apply Gaussian-Jordan".format(num_ydim, num_xdim))
return [0]
def finding_XM_LSM(arr_in1, arr_in2, m=2):
# Finding the by least square method
arr_out=[[0.0 for i in range(m+2)] for j in range(m+1)]
arr_x_power_m = [0.0 for i in range(m+m+1)]
arr_xy_power_m = [0.0 for i in range(m+1)]
for n in range(len(arr_x_power_m)):
for x in range(len(arr_in1)):
arr_x_power_m[n] += arr_in1[x] ** n
for n in range(len(arr_xy_power_m)):
for x in range(len(arr_in1)):
arr_xy_power_m[n] += arr_in1[x] ** n * arr_in2[x]
for j in range(m+1):
for i in range(j,j+m+1):
arr_out[j][i-j] = arr_x_power_m[i]
arr_out[j][m+1] = arr_xy_power_m[j]
return arr_out
def cal_modelperform (arr_obs , arr_sim , num_empty=-999.999):
# Based on Vazquez et al. 2002 (Hydrol. Process.)
num_arr = len(arr_obs)
num_n_total = num_arr
num_sum = 0
num_obs_sum = 0
for n in range( num_arr ):
if math.isnan(arr_obs[n]) or arr_obs[n] == num_empty:
num_n_total += -1
else:
num_sum = num_sum + ( arr_sim[n] - arr_obs[n] ) ** 2
num_obs_sum = num_obs_sum + arr_obs[n]
if num_n_total == 0 or num_obs_sum == 0:
RRMSE = -999.999
RMSE = -999.999
obs_avg = -999.999
else:
RRMSE = ( num_sum / num_n_total ) ** 0.5 * ( num_n_total / num_obs_sum )
RMSE = ( num_sum / num_n_total ) ** 0.5
obs_avg = num_obs_sum / num_n_total
num_n_total = num_arr
oo_sum = 0
po_sum = 0
for nn in range( num_arr ):
if math.isnan(arr_obs[nn]) or arr_obs[nn] == num_empty:
num_n_total = num_n_total - 1
else:
oo_sum = oo_sum + ( arr_obs[nn] - obs_avg ) ** 2
po_sum = po_sum + ( arr_sim[nn] - arr_obs[nn] ) ** 2
if num_n_total == 0 or oo_sum * po_sum == 0:
EF = -999.999
CD = -999.999
else:
EF = ( oo_sum - po_sum ) / oo_sum
CD = oo_sum / po_sum
return RRMSE,EF,CD,RMSE, num_arr
def cal_kappa(ARR_IN, NUM_n=0, NUM_N=0, NUM_k=0):
""" Fleiss' kappa
Mustt input with ARR_IN in the following format:
ARR_IN = [ [ NUM for k in range(catalogue)] for N in range(Subjects)]
Additional parameters: NUM_n is the number of raters (e.g. sim and obs results)
Additional parameters: NUM_N is the number of subjects (e.g the outputs
Additional parameters: NUM_k is the number of catalogue (e.g. results )
"""
if NUM_N == 0:
NUM_N = len(ARR_IN)
if NUM_n == 0:
NUM_n = sum(ARR_IN[0])
if NUM_k == 0:
NUM_k = len(ARR_IN[0])
ARR_p_out = [ 0 for n in range(NUM_k)]
ARR_P_OUT = [ 0 for n in range(NUM_N)]
for N in range(NUM_N):
for k in range(NUM_k):
ARR_p_out[k] += ARR_IN[N][k]
ARR_P_OUT[N] += ARR_IN[N][k] ** 2
ARR_P_OUT[N] -= NUM_n
ARR_P_OUT[N] = ARR_P_OUT[N] * (1./(NUM_n *(NUM_n - 1)))
for k in range(NUM_k):
ARR_p_out[k] = ARR_p_out[k] / (NUM_N * NUM_n)
NUM_P_BAR = 0
for N in range(NUM_N):
NUM_P_BAR += ARR_P_OUT[N]
NUM_P_BAR = NUM_P_BAR / float(NUM_N)
NUM_p_bar = 0
for k in ARR_p_out:
NUM_p_bar += k **2
return (NUM_P_BAR - NUM_p_bar) / (1 - NUM_p_bar)
def gau_kde(ARR_IN_X, ARR_IN_I, NUM_BW=0.1 ):
NUM_SUM = 0.
NUM_LENG = len(ARR_IN_X)
ARR_OUT = [ 0. for n in range(NUM_LENG)]
for IND_J, J in enumerate(ARR_IN_X):
NUM_SUM = 0.0
for I in ARR_IN_I:
NUM_SUM += 1 / (2 * math.pi)**0.5 * math.e ** (-0.5 * ((J-I)/NUM_BW) ** 2 )
ARR_OUT[IND_J] = NUM_SUM / len(ARR_IN_I) / NUM_BW
return ARR_OUT
def standard_dev(ARR_IN):
NUM_SUM = sum(ARR_IN)
NUM_N = len(ARR_IN)
NUM_MEAN = 1.0*NUM_SUM/NUM_N
NUM_SUM2 = 0.0
for N in ARR_IN:
if not math.isnan(N):
NUM_SUM2 = (N-NUM_MEAN)**2
else:
NUM_N += -1
return (NUM_SUM2 / (NUM_N-1)) ** 0.5
def h_esti(ARR_IN):
#A rule-of-thumb bandwidth estimator
NUM_SIGMA = standard_dev(ARR_IN)
NUM_N = len(ARR_IN)
return ((4 * NUM_SIGMA ** 5) / (3*NUM_N) ) ** 0.2
def data2array(ARR_IN, STR_IN="MEAN"):
NUM_J = len(ARR_IN)
NUM_I = len(ARR_IN[0])
ARR_OUT = [[ 0.0 for i in range(NUM_I)] for j in range(NUM_J) ]
for j in range(NUM_J):
for i in range(NUM_I):
ARR_OUT[j][i] = ARR_IN[j][i][STR_IN]
return ARR_OUT
def reshape2d(ARR_IN):
ARR_OUT=[]
for A in ARR_IN:
for B in A:
ARR_OUT.append(B)
return ARR_OUT
def NormalVector( V1, V2):
return [(V1[1]*V2[2] - V1[2]*V2[1]), (V1[2]*V2[0] - V1[0]*V2[2]),(V1[0]*V2[1] - V1[1]*V2[0])]
def NVtoPlane( P0, P1, P2):
"""Input of P should be 3-dimensionals"""
V1 = [(P1[0]-P0[0]),(P1[1]-P0[1]),(P1[2]-P0[2])]
V2 = [(P2[0]-P0[0]),(P2[1]-P0[1]),(P2[2]-P0[2])]
ARR_NV = MATH_TOOLS.NormalVector(V1, V2)
D = ARR_NV[0] * P0[0] + ARR_NV[1] * P0[1] + ARR_NV[2] * P0[2]
return ARR_NV[0],ARR_NV[1],ARR_NV[2],D
def FindZatP3( P0, P1, P2, P3):
""" input of P: (X,Y,Z); but P3 is (X,Y) only """
A,B,C,D = MATH_TOOLS.NVtoPlane(P0, P1, P2)
return (D-A*P3[0] - B*P3[1])/float(C)
class TOOLS:
""" TOOLS is contains:
timestamp
fix_ind
progress_bar
cal_progrss
"""
ARR_HOY = [0, 744, 1416, 2160, 2880, 3624, 4344, 5088, 5832, 6552, 7296, 8016, 8760]
ARR_HOY_LEAP = [0, 744, 1440, 2184, 2904, 3648, 4368, 5112, 5856, 6576, 7320, 8040, 8784]
def NNARR(ARR_IN, IF_PAIRING=False):
"Clean the NaN value in the array"
if IF_PAIRING:
ARR_SIZE = len(ARR_IN)
ARR_OUT = [ [] for N in range(ARR_SIZE)]
for ind_n, N in enumerate(ARR_IN[0]):
IF_NAN = False
for ind_a in range(ARR_SIZE):
if math.isnan(ARR_IN[ind_a][ind_n]):
IF_NAN = True
break
if not IF_NAN:
for ind_a in range(ARR_SIZE):
ARR_OUT[ind_a].append(ARR_IN[ind_a][ind_n])
else:
ARR_OUT = [ ]
for N in ARR_IN:
if not math.isnan(N):
ARR_OUT.append(N)
return ARR_OUT
def DATETIME2HOY(ARR_TIME, ARR_HOY_IN=[]):
if math.fmod(ARR_TIME[0], 4) == 0 and len(ARR_HOY_IN) == 0:
ARR_HOY_IN = [0, 744, 1440, 2184, 2904, 3648, 4368, 5112, 5856, 6576, 7320, 8040, 8784]
elif math.fmod(ARR_TIME[0], 4) != 0 and len(ARR_HOY_IN) == 0:
ARR_HOY_IN = [0, 744, 1416, 2160, 2880, 3624, 4344, 5088, 5832, 6552, 7296, 8016, 8760]
else:
ARR_HOY_IN = ARR_HOY_IN
return ARR_HOY_IN[ARR_TIME[1]-1] + (ARR_TIME[2]-1)*24 + ARR_TIME[3]
def timestamp(STR_IN=""):
print("{0:04d}-{1:02d}-{2:02d}_{3:02d}:{4:02d}:{5:02d} {6:s}".format(time.gmtime().tm_year, time.gmtime().tm_mon, time.gmtime().tm_mday,\
time.gmtime().tm_hour, time.gmtime().tm_min, time.gmtime().tm_sec, STR_IN) )
def fix_ind(IND_IN, IND_J, IND_I, ARR_XRANGE=[], ARR_YRANGE=[], NX=0, NY=0):
NUM_DY = ARR_YRANGE[0]
NUM_NX_F = ARR_XRANGE[0]
NUM_NX_R = NX - (ARR_XRANGE[1]+1)
if IND_J == ARR_YRANGE[0]:
IND_OUT = IND_IN - NUM_DY * NX - NUM_NX_F
else:
IND_OUT = IND_IN - NUM_DY * NX - NUM_NX_F * (IND_J - NUM_DY +1) - NUM_NX_R * (IND_J - NUM_DY)
return IND_OUT
def progress_bar(NUM_PROGRESS, NUM_PROGRESS_BIN=0.05, STR_SYS_SYMBOL="=", STR_DES="Progress"):
NUM_SYM = int(NUM_PROGRESS / NUM_PROGRESS_BIN)
sys.stdout.write('\r')
sys.stdout.write('[{0:20s}] {1:4.2f}% {2:s}'.format(STR_SYS_SYMBOL*NUM_SYM, NUM_PROGRESS*100, STR_DES))
sys.stdout.flush()
def clean_arr(ARR_IN, CRITERIA=1):
ARR_OUT=[]
for i,n in enumerate(ARR_IN):
if len(n)> CRITERIA:
ARR_OUT.append(n)
return ARR_OUT
def cal_loop_progress(ARR_INDEX, ARR_INDEX_MAX, NUM_CUM_MAX=1, NUM_CUM_IND=1, NUM_TOTAL_MAX=1):
""" Please list from smallest to largest, i.e.: x->y->z """
if len(ARR_INDEX) == len(ARR_INDEX_MAX):
for i, i_index in enumerate(ARR_INDEX):
NUM_IND_PER = (i_index+1)/float(ARR_INDEX_MAX[i])
NUM_TOTAL_MAX = NUM_TOTAL_MAX * ARR_INDEX_MAX[i]
if i >0: NUM_CUM_MAX = NUM_CUM_MAX * ARR_INDEX_MAX[i-1]
NUM_CUM_IND = NUM_CUM_IND + NUM_CUM_MAX * i_index
return NUM_CUM_IND / float(NUM_TOTAL_MAX)
else:
print("Wrong dimenstion for in put ARR_INDEX ({0:d}) and ARR_INDEX_MAX ({1:d})".format(len(ARR_INDEX), len(ARR_INDEX_MAX)))
def calendar_cal(ARR_START_TIME, ARR_INTERVAL, ARR_END_TIME_IN=[0, 0, 0, 0, 0, 0.0], IF_LEAP=False):
ARR_END_TIME = [ 0,0,0,0,0,0.0]
ARR_DATETIME = ["SECOND", "MINUTE", "HOUR","DAY", "MON", "YEAR"]
NUM_ARR_DATETIME = len(ARR_DATETIME)
IF_FERTIG = False
ARR_FERTIG = [0,0,0,0,0,0]
DIC_TIME_LIM = \
{"YEAR" : {"START": 0 , "LIMIT": 9999 },\
"MON" : {"START": 1 , "LIMIT": 12 },\
"DAY" : {"START": 1 , "LIMIT": 31 },\
"HOUR" : {"START": 0 , "LIMIT": 23 },\
"MINUTE": {"START": 0 , "LIMIT": 59 },\
"SECOND": {"START": 0 , "LIMIT": 59 },\
}
for I, T in enumerate(ARR_START_TIME):
ARR_END_TIME[I] = T + ARR_INTERVAL[I]
while IF_FERTIG == False:
if math.fmod(ARR_END_TIME[0],4) == 0: IF_LEAP=True
if IF_LEAP:
ARR_DAY_LIM = [0,31,29,31,30,31,30,31,31,30,31,30,31]
else:
ARR_DAY_LIM = [0,31,28,31,30,31,30,31,31,30,31,30,31]
for I, ITEM in enumerate(ARR_DATETIME):
NUM_ARR_POS = NUM_ARR_DATETIME-I-1
if ITEM == "DAY":
if ARR_END_TIME[NUM_ARR_POS] > ARR_DAY_LIM[ARR_END_TIME[1]]:
ARR_END_TIME[NUM_ARR_POS] = ARR_END_TIME[NUM_ARR_POS] - ARR_DAY_LIM[ARR_END_TIME[1]]
ARR_END_TIME[NUM_ARR_POS - 1] += 1
else:
if ARR_END_TIME[NUM_ARR_POS] > DIC_TIME_LIM[ITEM]["LIMIT"]:
ARR_END_TIME[NUM_ARR_POS - 1] += 1
ARR_END_TIME[NUM_ARR_POS] = ARR_END_TIME[NUM_ARR_POS] - DIC_TIME_LIM[ITEM]["LIMIT"] - 1
for I, ITEM in enumerate(ARR_DATETIME):
NUM_ARR_POS = NUM_ARR_DATETIME-I-1
if ITEM == "DAY":
if ARR_END_TIME[NUM_ARR_POS] <= ARR_DAY_LIM[ARR_END_TIME[1]]: ARR_FERTIG[NUM_ARR_POS] = 1
else:
if ARR_END_TIME[NUM_ARR_POS] <= DIC_TIME_LIM[ITEM]["LIMIT"]: ARR_FERTIG[NUM_ARR_POS] = 1
if sum(ARR_FERTIG) == 6: IF_FERTIG = True
return ARR_END_TIME
class MPI_TOOLS:
def __init__(self, MPI_SIZE=1, MPI_RANK=0,\
NUM_NX_END=1, NUM_NY_END=1, NUM_NX_START=0, NUM_NY_START=0, NUM_NX_CORES=1 ,\
NUM_NX_TOTAL=1, NUM_NY_TOTAL=1 ):
""" END number follow the python philisophy: End number is not included in the list """
self.NUM_SIZE = MPI_SIZE
self.NUM_RANK = MPI_RANK
self.NUM_NX_START = NUM_NX_START
self.NUM_NY_START = NUM_NY_START
self.NUM_NX_SIZE = NUM_NX_END - NUM_NX_START
self.NUM_NY_SIZE = NUM_NY_END - NUM_NY_START
self.NUM_NX_CORES = NUM_NX_CORES
self.NUM_NY_CORES = max(1, int(self.NUM_SIZE / NUM_NX_CORES))
self.ARR_RANK_DESIGN = [ {} for n in range(self.NUM_SIZE)]
def CPU_GEOMETRY_2D(self):
NUM_NX_REMAIN = self.NUM_NX_SIZE % self.NUM_NX_CORES
NUM_NY_REMAIN = self.NUM_NY_SIZE % self.NUM_NY_CORES
NUM_NX_DIFF = int((self.NUM_NX_SIZE - NUM_NX_REMAIN) / self.NUM_NX_CORES )
NUM_NY_DIFF = int((self.NUM_NY_SIZE - NUM_NY_REMAIN) / self.NUM_NY_CORES )
NUM_NY_DIFF_P1 = NUM_NY_DIFF + 1
NUM_NX_DIFF_P1 = NUM_NX_DIFF + 1
IND_RANK = 0
ARR_RANK_DESIGN = [ 0 for n in range(self.NUM_SIZE)]
for ny in range(self.NUM_NY_CORES):
for nx in range(self.NUM_NX_CORES):
NUM_RANK = ny * self.NUM_NX_CORES + nx
DIC_IN = {"INDEX_IN": NUM_RANK, "NX_START": 0, "NY_START": 0, "NX_END": 0, "NY_END": 0 }
if ny < NUM_NY_REMAIN:
DIC_IN["NY_START"] = (ny + 0) * NUM_NY_DIFF_P1 + self.NUM_NY_START
DIC_IN["NY_END" ] = (ny + 1) * NUM_NY_DIFF_P1 + self.NUM_NY_START
else:
DIC_IN["NY_START"] = (ny - NUM_NY_REMAIN + 0) * NUM_NY_DIFF + NUM_NY_REMAIN * NUM_NY_DIFF_P1 + self.NUM_NY_START
DIC_IN["NY_END" ] = (ny - NUM_NY_REMAIN + 1) * NUM_NY_DIFF + NUM_NY_REMAIN * NUM_NY_DIFF_P1 + self.NUM_NY_START
if nx < NUM_NX_REMAIN:
DIC_IN["NX_START"] = (nx + 0) * NUM_NX_DIFF_P1 + self.NUM_NX_START
DIC_IN["NX_END" ] = (nx + 1) * NUM_NX_DIFF_P1 + self.NUM_NX_START
else:
DIC_IN["NX_START"] = (nx - NUM_NX_REMAIN + 0) * NUM_NX_DIFF + NUM_NX_REMAIN * NUM_NX_DIFF_P1 + self.NUM_NX_START
DIC_IN["NX_END" ] = (nx - NUM_NX_REMAIN + 1) * NUM_NX_DIFF + NUM_NX_REMAIN * NUM_NX_DIFF_P1 + self.NUM_NX_START
ARR_RANK_DESIGN[NUM_RANK] = DIC_IN
self.ARR_RANK_DESIGN = ARR_RANK_DESIGN
return ARR_RANK_DESIGN
def CPU_MAP(self ):
ARR_CPU_MAP = [ [ NP.nan for i in range(self.NUM_NX_TOTAL)] for j in range(self.NUM_NY_TOTAL) ]
for RANK in range(len(ARR_RANK_DESIGN)):
print("DEAL WITH {0:d} {1:d}".format(RANK, ARR_RANK_DESIGN[RANK]["INDEX_IN"] ))
for jj in range(ARR_RANK_DESIGN[RANK]["NY_START"], ARR_RANK_DESIGN[RANK]["NY_END"]):
for ii in range(ARR_RANK_DESIGN[RANK]["NX_START"], ARR_RANK_DESIGN[RANK]["NX_END"]):
ARR_CPU_MAP[jj][ii] = ARR_RANK_DESIGN[RANK]["INDEX_IN"]
return MAP_CPU
def GATHER_ARR_2D(self, ARR_IN, ARR_IN_GATHER, ARR_RANK_DESIGN=[]):
if ARR_RANK_DESIGN == []:
ARR_RANK_DESIGN = self.ARR_RANK_DESIGN
for N in range(1, self.NUM_SIZE):
I_STA = ARR_RANK_DESIGN[N]["NX_START"]
I_END = ARR_RANK_DESIGN[N]["NX_END" ]
J_STA = ARR_RANK_DESIGN[N]["NY_START"]
J_END = ARR_RANK_DESIGN[N]["NY_END" ]
for J in range(J_STA, J_END ):
for I in range(I_STA, I_END ):
ARR_IN[J][I] = ARR_IN_GATHER[N][J][I]
return ARR_IN
def MPI_MESSAGE(self, STR_TEXT=""):
TIME_NOW = time.gmtime()
print("MPI RANK: {0:5d} @ {1:02d}:{2:02d}:{3:02d} # {4:s}"\
.format(self.NUM_RANK, TIME_NOW.tm_hour, TIME_NOW.tm_min, TIME_NOW.tm_sec, STR_TEXT ))
class GEO_TOOLS:
def __init__(self):
STR_NCDF4PY = NC.__version__
print("Using netCDF4 for Python, Version: {0:s}".format(STR_NCDF4PY))
def mask_dtm(self, NUM, ARR_DTM=[0,1,2], ARR_DTM_RANGE=[0,1], ARR_DTM_STR=["OUT","IN","OUT"]):
""" The determination algorithm is : x-1 < NUM <= x """
for i, n in enumerate(ARR_DTM):
if i == 0:
if NUM <= ARR_DTM_RANGE[i]: NUM_OUT = n
elif i == len(ARR_DTM_RANGE):
if NUM > ARR_DTM_RANGE[i-1]: NUM_OUT = n
else:
if NUM > ARR_DTM_RANGE[i-1] and NUM <= ARR_DTM_RANGE[i]: NUM_OUT = n
return NUM_OUT
def mask_array(self, ARR_IN, ARR_MASK_OUT=[], ARR_DTM=[0,1,2], ARR_DTM_RANGE=[0,1], ARR_DTM_STR=["OUT","IN","OUT"], IF_2D=False):
if IF_2D:
NUM_NX = len(ARR_IN[0])
NUM_NY = len(ARR_IN)
ARR_OUT = [ [ self.NUM_NULL for i in range(NUM_NX)] for j in range(NUM_NY) ]
for J in range(NUM_NY):
for I in range(NUM_NY):
ARR_OUT[J][I] = self.mask_dtm(ARR_IN[J][I], ARR_NUM_DTM=ARR_NUM_DTM, ARR_NUM_DTM_RANGE=ARR_NUM_DTM_RANGE, ARR_STR_DTM=ARR_STR_DTM)
else:
NUM_NX = len(ARR_IN)
ARR_OUT = [0 for n in range(NUM_NX)]
for N in range(NUM_NX):
ARR_OUT[N] = self.mask_dtm(ARR_IN[N], ARR_NUM_DTM=ARR_NUM_DTM, ARR_NUM_DTM_RANGE=ARR_NUM_DTM_RANGE, ARR_STR_DTM=ARR_STR_DTM)
return ARR_OUT
def MAKE_LAT_LON_ARR(self, FILE_NC_IN, STR_LAT="lat", STR_LON="lon", source="CFC"):
""" Reading LAT and LON from a NC file """
NC_DATA_IN = NC.Dataset(FILE_NC_IN, "r", format="NETCDF4")
if source == "CFC":
arr_lat_in = NC_DATA_IN.variables[STR_LAT]
arr_lon_in = NC_DATA_IN.variables[STR_LON]
num_nlat = len(arr_lat_in)
num_nlon = len(arr_lon_in)
arr_lon_out = [[0.0 for i in range(num_nlon)] for j in range(num_nlat)]
arr_lat_out = [[0.0 for i in range(num_nlon)] for j in range(num_nlat)]
for j in range(num_nlat):
for i in range(num_nlon):
arr_lon_out[j][i] = arr_lat_in[j]
arr_lat_out[j][i] = arr_lon_in[i]
return arr_lat_out, arr_lon_out
class NETCDF4_HELPER:
def __init__(self):
STR_NCDF4PY = NC.__version__
print("Using netCDF4 for Python, Version: {0:s}".format(STR_NCDF4PY))
def create_wrf_ensemble(self, STR_FILE_IN, STR_FILE_OUT, ARR_VAR=[], STR_DIR="./", NUM_ENSEMBLE_SIZE=1 ):
FILE_OUT = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILE_OUT), "w",format="NETCDF4")
FILE_IN = NC.Dataset("{1:s}/{1:s}".format(STR_DIR, STR_FILE_IN ), "r",format="NETCDF4")
# CREATE DIMENSIONS:
for DIM in FILE_IN.dimensions:
FILE_OUT.createDimension(DIM, FILE_IN.dimensions[DIM].size )
FILE_OUT.createDimension("Ensembles", NUM_ENSEMBLE_SIZE )
# CREATE ATTRIBUTES:
FILE_OUT.TITLE = FILE_IN.TITLE
FILE_OUT.START_DATE = FILE_IN.START_DATE
FILE_OUT.SIMULATION_START_DATE = FILE_IN.SIMULATION_START_DATE
FILE_OUT.DX = FILE_IN.DX
FILE_OUT.DY = FILE_IN.DY
FILE_OUT.SKEBS_ON = FILE_IN.SKEBS_ON
FILE_OUT.SPEC_BDY_FINAL_MU = FILE_IN.SPEC_BDY_FINAL_MU
FILE_OUT.USE_Q_DIABATIC = FILE_IN.USE_Q_DIABATIC
FILE_OUT.GRIDTYPE = FILE_IN.GRIDTYPE
FILE_OUT.DIFF_OPT = FILE_IN.DIFF_OPT
FILE_OUT.KM_OPT = FILE_IN.KM_OPT
if len(ARR_VAR) >0:
for V in ARR_VAR:
if V[1] == "2D":
FILE_OUT.createVariable(V[0], "f8", ("Ensembles", "Time", "south_north", "west_east" ))
elif V[1] == "3D":
FILE_OUT.createVariable(V[0], "f8", ("Ensembles", "Time", "bottom_top", "south_north", "west_east" ))
FILE_OUT.close()
FILE_IN.close()
def add_ensemble(self, FILE_IN, FILE_OUT, STR_VAR, STR_DIM="2D", STR_DIR="./", IND_ENSEMBLE=0):
FILE_OUT = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, FILE_OUT), "a",format="NETCDF4")
FILE_IN = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, FILE_IN ), "r",format="NETCDF4")
ARR_VAR_IN = FILE_IN.variables[STR_VAR]
NUM_NT = len(ARR_VAR_IN)
NUM_NK = FILE_IN.dimensions["bottom_top"].size
NUM_NJ = FILE_IN.dimensions["south_north"].size
NUM_NI = FILE_IN.dimensions["west_east"].size
for time in range(NUM_NT):
if STR_DIM == "2D":
FILE_OUT.variables[STR_VAR][IND_ENSEMBLE, time] = FILE_IN.variables[STR_VAR][time]
elif STR_DIM == "3D":
for k in range(NUM_NK):
FILE_OUT.variables[STR_VAR][IND_ENSEMBLE, time] = FILE_IN.variables[STR_VAR][time]
FILE_OUT.close()
FILE_IN.close()
class WRF_HELPER:
STR_DIR_ROOT = "./"
NUM_TIME_INIT = 0
NUM_SHIFT = 0.001
def __init__(self):
"""
Remember: most array should be follow the rule of [j,i] instead of [x,y].
"""
STR_NCDF4PY = NC.__version__
print("Using netCDF4 for Python, Version: {0:s}".format(STR_NCDF4PY))
def GEO_INFORMATER(self, STR_FILE="geo_em.d01.nc", STR_DIR=""):
print("INPUT GEO FILE: {0:s}".format(STR_FILE))
if STR_DIR == "":
STR_DIR == self.STR_DIR_ROOT
self.FILE_IN = NC.Dataset("{0:s}/{1:s}".format(STR_DIR, STR_FILE ), "r",format="NETCDF4")
self.MAP_LAT = self.FILE_IN.variables["CLAT"] [self.NUM_TIME_INIT]
self.MAP_LON = self.FILE_IN.variables["CLONG"][self.NUM_TIME_INIT]
ARR_TMP_IN = self.FILE_IN.variables["CLONG"][0]
# Since NetCDF4 for python does not support the hyphen in attributes, I
# am forced to calculate the NX and NY based on a map in the NC file.
self.NUM_NX = len(ARR_TMP_IN[0])
self.NUM_NY = len(ARR_TMP_IN)
self.NUM_DX = self.FILE_IN.DX
self.NUM_DY = self.FILE_IN.DX
def GEO_HELPER(self, ARR_LL_SW, ARR_LL_NE):
self.MAP_CROP_MASK = [[ 0 for i in range(self.NUM_NX)] for j in range(self.NUM_NY)]
self.DIC_CROP_INFO = {"NE": {"LAT":0, "LON":0, "I":0, "J":0},\
"SW": {"LAT":0, "LON":0, "I":0, "J":0}}
ARR_TMP_I = []
ARR_TMP_J = []
for j in range(self.NUM_NY):
for i in range(self.NUM_NX):
NUM_CHK_SW_J = self.MAP_LAT[j][i] - ARR_LL_SW[0]
if NUM_CHK_SW_J == 0:
NUM_CHK_SW_J = self.MAP_LAT[j][i] - ARR_LL_SW[0] + self.NUM_SHIFT
NUM_CHK_SW_I = self.MAP_LON[j][i] - ARR_LL_SW[1]
if NUM_CHK_SW_I == 0:
NUM_CHK_SW_I = self.MAP_LAT[j][i] - ARR_LL_SW[1] - self.NUM_SHIFT
NUM_CHK_NE_J = self.MAP_LAT[j][i] - ARR_LL_NE[0]
if NUM_CHK_NE_J == 0:
NUM_CHK_NE_J = self.MAP_LAT[j][i] - ARR_LL_NE[0] + self.NUM_SHIFT
NUM_CHK_NE_I = self.MAP_LON[j][i] - ARR_LL_NE[1]
if NUM_CHK_NE_I == 0:
NUM_CHK_NE_I = self.MAP_LON[j][i] - ARR_LL_NE[1] - self.NUM_SHIFT
NUM_CHK_NS_IN = NUM_CHK_SW_J * NUM_CHK_NE_J
NUM_CHK_WE_IN = NUM_CHK_SW_I * NUM_CHK_NE_I
if NUM_CHK_NS_IN < 0 and NUM_CHK_WE_IN < 0:
self.MAP_CROP_MASK[j][i] = 1
ARR_TMP_J.append(j)
ARR_TMP_I.append(i)
NUM_SW_J = min( ARR_TMP_J )
NUM_SW_I = min( ARR_TMP_I )
NUM_NE_J = max( ARR_TMP_J )
NUM_NE_I = max( ARR_TMP_I )
self.DIC_CROP_INFO["NE"]["J"] = NUM_NE_J
self.DIC_CROP_INFO["NE"]["I"] = NUM_NE_I
self.DIC_CROP_INFO["NE"]["LAT"] = self.MAP_LAT[NUM_NE_J][NUM_NE_I]
self.DIC_CROP_INFO["NE"]["LON"] = self.MAP_LON[NUM_NE_J][NUM_NE_I]
self.DIC_CROP_INFO["SW"]["J"] = NUM_SW_J
self.DIC_CROP_INFO["SW"]["I"] = NUM_SW_I
self.DIC_CROP_INFO["SW"]["LAT"] = self.MAP_LAT[NUM_SW_J][NUM_SW_I]
self.DIC_CROP_INFO["SW"]["LON"] = self.MAP_LON[NUM_SW_J][NUM_SW_I]
def PROFILE_HELPER(STR_FILE_IN, ARR_DATE_START, NUM_DOMS=3, NUM_TIMESTEPS=24, IF_PB=False):
"""
This functions reads the filename, array of starting date,
and simulation hours and numbers of domains
to profiling the time it takes for WRF.
"""
FILE_READ_IN = open("{0:s}".format(STR_FILE_IN))
ARR_READ_IN = FILE_READ_IN.readlines()
NUM_TIME = NUM_TIMESTEPS
NUM_DOMAIN = NUM_DOMS
NUM_DATE_START = ARR_DATE_START
NUM_LEN_IN = len(ARR_READ_IN)
ARR_TIME_PROFILE = [[0 for T in range(NUM_TIME)] for D in range(NUM_DOMS)]
for I, TEXT_IN in enumerate(ARR_READ_IN):
ARR_TEXT = re.split("\s",TEXT_IN.strip())
if ARR_TEXT[0] == "Timing":
if ARR_TEXT[2] == "main:" or ARR_TEXT[2] == "main":
for ind, T in enumerate(ARR_TEXT):
if T == "time" : ind_time_text = ind + 1
if T == "elapsed": ind_elapsed_text = ind - 1
if T == "domain" : ind_domain_text = ind + 3
arr_time_in = re.split("_", ARR_TEXT[ind_time_text])
arr_date = re.split("-", arr_time_in[0])
arr_time = re.split(":", arr_time_in[1])
num_domain = int(re.split(":", ARR_TEXT[ind_domain_text])[0])
num_elapsed = float(ARR_TEXT[ind_elapsed_text])
NUM_HOUR_FIX = (int(arr_date[2]) - NUM_DATE_START[2]) * 24
NUM_HOUR = NUM_HOUR_FIX + int(arr_time[0])
ARR_TIME_PROFILE[num_domain-1][NUM_HOUR] += num_elapsed
if IF_PB: TOOLS.progress_bar(I/float(NUM_LEN_IN))
#self.ARR_TIME_PROFILE = ARR_TIME_PROFILE
return ARR_TIME_PROFILE
class DATA_READER:
"""
The DATA_READER is based on my old work: gridtrans.py.
"""
def __init__(self, STR_NULL="noData", NUM_NULL=-999.999):
self.STR_NULL=STR_NULL
self.NUM_NULL=NUM_NULL
def stripblnk(arr,*num_typ):
new_arr=[]
for i in arr:
if i == "":
pass
else:
if num_typ[0] == 'int':
new_arr.append(int(i))
elif num_typ[0] == 'float':
new_arr.append(float(i))
elif num_typ[0] == '':
new_arr.append(i)
else:
print("WRONG num_typ!")
return new_arr
def tryopen(self, sourcefile, ag):
try:
opf=open(sourcefile,ag)
return opf
except :
print("No such file.")
return "error"
def READCSV(self, sourcefile):
opf = self.tryopen(sourcefile,'r')
opfchk = self.tryopen(sourcefile,'r')
print("reading source file {0:s}".format(sourcefile))
chk_lines = opfchk.readlines()
num_totallines = len(chk_lines)
ncols = 0
num_notnum = 0
for n in range(num_totallines):
line_in = chk_lines[n]
c_first = re.findall(".",line_in.strip())
if c_first[0] == "#":
num_notnum += 1
else:
ncols = len( re.split(",",line_in.strip()) )
break
if ncols == 0:
print("something wrong with the input file! (all comments?)")
else:
del opfchk
nrows=num_totallines - num_notnum
result_arr=[[self.NUM_NULL for j in range(ncols)] for i in range(nrows)]
result_arr_text=[]
num_pass = 0
for j in range(0,num_totallines):
# chk if comment
#print (j,i,chk_val)
line_in = opf.readline()
c_first = re.findall(".",line_in.strip())[0]
if c_first == "#":
result_arr_text.append(line_in)
num_pass += 1
else:
arr_in = re.split(",",line_in.strip())
for i in range(ncols):
chk_val = arr_in[i]
if chk_val == self.STR_NULL:
result_arr[j-num_pass][i] = self.NUM_NULL
else:
result_arr[j-num_pass][i] = float(chk_val)
return result_arr,result_arr_text
|
metalpen1984/SciTool_Py
|
GRIDINFORMER.py
|
Python
|
lgpl-3.0
| 66,239 |
<?php
declare(strict_types=1);
namespace slapper\entities;
class SlapperVex extends SlapperEntity {
const TYPE_ID = 105;
const HEIGHT = 0.8;
}
|
jojoe77777/Slapper
|
src/slapper/entities/SlapperVex.php
|
PHP
|
lgpl-3.0
| 156 |
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2011 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* Sonar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.core.widgets.reviews;
import org.sonar.api.web.AbstractRubyTemplate;
import org.sonar.api.web.RubyRailsWidget;
import org.sonar.api.web.WidgetCategory;
import org.sonar.api.web.WidgetProperties;
import org.sonar.api.web.WidgetProperty;
import org.sonar.api.web.WidgetPropertyType;
@WidgetCategory({ "Reviews" })
@WidgetProperties(
{
@WidgetProperty(key = "numberOfLines", type = WidgetPropertyType.INTEGER, defaultValue = "5",
description="Maximum number of reviews displayed at the same time.")
}
)
public class MyReviewsWidget extends AbstractRubyTemplate implements RubyRailsWidget {
public String getId() {
return "my_reviews";
}
public String getTitle() {
return "My open reviews";
}
@Override
protected String getTemplatePath() {
return "/org/sonar/plugins/core/widgets/reviews/my_reviews.html.erb";
}
}
|
leodmurillo/sonar
|
plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/reviews/MyReviewsWidget.java
|
Java
|
lgpl-3.0
| 1,757 |
<?php
/**
* Smarty Internal Plugin Compile Section
*
* Compiles the {section} {sectionelse} {/section} tags
*
* @package Brainy
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Section Class
*
* @package Brainy
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Section extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $required_attributes = array('name', 'loop');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $shorttag_order = array('name', 'loop');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('start', 'step', 'max', 'show');
/**
* Compiles code for the {section} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @return string compiled code
*/
public function compile($args, $compiler) {
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
$this->openTag($compiler, 'section', array('section'));
$output = '';
$section_name = $_attr['name'];
$output .= "if (isset(\$_smarty_tpl->tpl_vars['smarty']->value['section'][$section_name])) unset(\$_smarty_tpl->tpl_vars['smarty']->value['section'][$section_name]);\n";
$section_props = "\$_smarty_tpl->tpl_vars['smarty']->value['section'][$section_name]";
foreach ($_attr as $attr_name => $attr_value) {
switch ($attr_name) {
case 'loop':
$output .= "{$section_props}['loop'] = is_array(\$_loop=$attr_value) ? count(\$_loop) : max(0, (int) \$_loop); unset(\$_loop);\n";
break;
case 'show':
if (is_bool($attr_value))
$show_attr_value = $attr_value ? 'true' : 'false';
else
$show_attr_value = "(bool) $attr_value";
$output .= "{$section_props}['show'] = $show_attr_value;\n";
break;
case 'name':
$output .= "{$section_props}['$attr_name'] = $attr_value;\n";
break;
case 'max':
case 'start':
$output .= "{$section_props}['$attr_name'] = (int) $attr_value;\n";
break;
case 'step':
$output .= "{$section_props}['$attr_name'] = ((int) $attr_value) == 0 ? 1 : (int) $attr_value;\n";
break;
}
}
if (!isset($_attr['show']))
$output .= "{$section_props}['show'] = true;\n";
if (!isset($_attr['loop']))
$output .= "{$section_props}['loop'] = 1;\n";
if (!isset($_attr['max']))
$output .= "{$section_props}['max'] = {$section_props}['loop'];\n";
else
$output .= "if ({$section_props}['max'] < 0)\n" . " {$section_props}['max'] = {$section_props}['loop'];\n";
if (!isset($_attr['step']))
$output .= "{$section_props}['step'] = 1;\n";
if (!isset($_attr['start']))
$output .= "{$section_props}['start'] = {$section_props}['step'] > 0 ? 0 : {$section_props}['loop']-1;\n";
else {
$output .= "if ({$section_props}['start'] < 0)\n" . " {$section_props}['start'] = max({$section_props}['step'] > 0 ? 0 : -1, {$section_props}['loop'] + {$section_props}['start']);\n" . "else\n" . " {$section_props}['start'] = min({$section_props}['start'], {$section_props}['step'] > 0 ? {$section_props}['loop'] : {$section_props}['loop']-1);\n";
}
$output .= "if ({$section_props}['show']) {\n";
if (!isset($_attr['start']) && !isset($_attr['step']) && !isset($_attr['max'])) {
$output .= " {$section_props}['total'] = {$section_props}['loop'];\n";
} else {
$output .= " {$section_props}['total'] = min(ceil(({$section_props}['step'] > 0 ? {$section_props}['loop'] - {$section_props}['start'] : {$section_props}['start']+1)/abs({$section_props}['step'])), {$section_props}['max']);\n";
}
$output .= " if ({$section_props}['total'] == 0)\n" . " {$section_props}['show'] = false;\n" . "} else\n" . " {$section_props}['total'] = 0;\n";
$output .= "if ({$section_props}['show']):\n";
$output .= "
for ({$section_props}['index'] = {$section_props}['start'], {$section_props}['iteration'] = 1;
{$section_props}['iteration'] <= {$section_props}['total'];
{$section_props}['index'] += {$section_props}['step'], {$section_props}['iteration']++):\n";
$output .= "{$section_props}['rownum'] = {$section_props}['iteration'];\n";
$output .= "{$section_props}['index_prev'] = {$section_props}['index'] - {$section_props}['step'];\n";
$output .= "{$section_props}['index_next'] = {$section_props}['index'] + {$section_props}['step'];\n";
$output .= "{$section_props}['first'] = ({$section_props}['iteration'] == 1);\n";
$output .= "{$section_props}['last'] = ({$section_props}['iteration'] == {$section_props}['total']);\n";
return $output;
}
}
/**
* Smarty Internal Plugin Compile Sectionelse Class
*
* @package Brainy
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Sectionelse extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {sectionelse} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @return string compiled code
*/
public function compile($args, $compiler) {
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
list($openTag) = $this->closeTag($compiler, array('section'));
$this->openTag($compiler, 'sectionelse', array('sectionelse'));
return "endfor;\nelse:\n";
}
}
/**
* Smarty Internal Plugin Compile Sectionclose Class
*
* @package Brainy
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Sectionclose extends Smarty_Internal_CompileBase
{
/**
* Compiles code for the {/section} tag
*
* @param array $args array with attributes from parser
* @param object $compiler compiler object
* @return string compiled code
*/
public function compile($args, $compiler) {
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
list($openTag) = $this->closeTag($compiler, array('section', 'sectionelse'));
if ($openTag == 'sectionelse') {
return "endif;\n";
} else {
return "endfor;\nendif;\n";
}
}
}
|
chriseling/brainy
|
src/Brainy/sysplugins/smarty_internal_compile_section.php
|
PHP
|
lgpl-3.0
| 7,064 |
/*
* SonarQube JavaScript Plugin
* Copyright (C) 2011-2021 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.javascript.checks;
import org.sonar.check.Rule;
import org.sonar.plugins.javascript.api.EslintBasedCheck;
import org.sonar.plugins.javascript.api.JavaScriptRule;
import org.sonar.plugins.javascript.api.TypeScriptRule;
@JavaScriptRule
@TypeScriptRule
@Rule(key = "S5542")
public class EncryptionSecureModeCheck implements EslintBasedCheck {
@Override
public String eslintKey() {
return "encryption-secure-mode";
}
}
|
SonarSource/sonar-javascript
|
javascript-checks/src/main/java/org/sonar/javascript/checks/EncryptionSecureModeCheck.java
|
Java
|
lgpl-3.0
| 1,307 |
/*
* This file is part of Gaia Sky, which is released under the Mozilla Public License 2.0.
* See the file LICENSE.md in the project root for full license details.
*/
package gaiasky.desktop.util;
import gaiasky.util.Logger;
import gaiasky.util.Logger.Log;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Wee utility class to check the operating system and the desktop environment.
* It also offers retrieval of common system folders.
*
* @author Toni Sagrista
*/
public class SysUtils {
private static Log logger = Logger.getLogger(SysUtils.class);
/**
* Initialise directories
*/
public static void mkdirs() {
// Top level
try {
Files.createDirectories(getDataDir());
Files.createDirectories(getConfigDir());
// Bottom level
Files.createDirectories(getDefaultCameraDir());
Files.createDirectories(getDefaultMusicDir());
Files.createDirectories(getDefaultFramesDir());
Files.createDirectories(getDefaultScreenshotsDir());
Files.createDirectories(getDefaultTmpDir());
Files.createDirectories(getDefaultMappingsDir());
Files.createDirectories(getDefaultBookmarksDir());
} catch (IOException e) {
logger.error(e);
}
}
private static String OS;
private static boolean linux, mac, windows, unix, solaris;
static {
OS = System.getProperty("os.name").toLowerCase();
linux = OS.indexOf("linux") >= 0;
mac = OS.indexOf("macos") >= 0 || OS.indexOf("mac os") >= 0;
windows = OS.indexOf("win") >= 0;
unix = OS.indexOf("unix") >= 0;
solaris = OS.indexOf("sunos") >= 0;
}
public static String getXdgDesktop() {
return System.getenv("XDG_CURRENT_DESKTOP");
}
public static boolean checkLinuxDesktop(String desktop) {
try {
String value = getXdgDesktop();
return value != null && !value.isEmpty() && value.equalsIgnoreCase(desktop);
} catch (Exception e) {
e.printStackTrace(System.err);
}
return false;
}
public static boolean checkUnity() {
return isLinux() && checkLinuxDesktop("ubuntu");
}
public static boolean checkGnome() {
return isLinux() && checkLinuxDesktop("gnome");
}
public static boolean checkKDE() {
return isLinux() && checkLinuxDesktop("kde");
}
public static boolean checkXfce() {
return isLinux() && checkLinuxDesktop("xfce");
}
public static boolean checkBudgie() {
return isLinux() && checkLinuxDesktop("budgie:GNOME");
}
public static boolean checkI3() {
return isLinux() && checkLinuxDesktop("i3");
}
public static String getOSName() {
return OS;
}
public static String getOSFamily() {
if (isLinux())
return "linux";
if (isWindows())
return "win";
if (isMac())
return "macos";
if (isUnix())
return "unix";
if (isSolaris())
return "solaris";
return "unknown";
}
public static boolean isLinux() {
return linux;
}
public static boolean isWindows() {
return windows;
}
public static boolean isMac() {
return mac;
}
public static boolean isUnix() {
return unix;
}
public static boolean isSolaris() {
return solaris;
}
public static String getOSArchitecture() {
return System.getProperty("os.arch");
}
public static String getOSVersion() {
return System.getProperty("os.version");
}
private static final String GAIASKY_DIR_NAME = "gaiasky";
private static final String DOTGAIASKY_DIR_NAME = ".gaiasky";
private static final String CAMERA_DIR_NAME = "camera";
private static final String SCREENSHOTS_DIR_NAME = "screenshots";
private static final String FRAMES_DIR_NAME = "frames";
private static final String MUSIC_DIR_NAME = "music";
private static final String MAPPINGS_DIR_NAME = "mappings";
private static final String BOOKMARKS_DIR_NAME = "bookmarks";
private static final String MPCDI_DIR_NAME = "mpcdi";
private static final String DATA_DIR_NAME = "data";
private static final String TMP_DIR_NAME = "tmp";
private static final String CRASHREPORTS_DIR_NAME = "crashreports";
/**
* Gets a file pointer to the camera directory.
*
* @return A pointer to the Gaia Sky camera directory
*/
public static Path getDefaultCameraDir() {
return getDataDir().resolve(CAMERA_DIR_NAME);
}
/**
* Gets a file pointer to the default screenshots directory.
*
* @return A pointer to the Gaia Sky screenshots directory
*/
public static Path getDefaultScreenshotsDir() {
return getDataDir().resolve(SCREENSHOTS_DIR_NAME);
}
/**
* Gets a file pointer to the frames directory.
*
* @return A pointer to the Gaia Sky frames directory
*/
public static Path getDefaultFramesDir() {
return getDataDir().resolve(FRAMES_DIR_NAME);
}
/**
* Gets a file pointer to the music directory.
*
* @return A pointer to the Gaia Sky music directory
*/
public static Path getDefaultMusicDir() {
return getDataDir().resolve(MUSIC_DIR_NAME);
}
/**
* Gets a file pointer to the mappings directory.
*
* @return A pointer to the Gaia Sky mappings directory
*/
public static Path getDefaultMappingsDir() {
return getConfigDir().resolve(MAPPINGS_DIR_NAME);
}
public static String getMappingsDirName() {
return MAPPINGS_DIR_NAME;
}
/**
* Gets a file pointer to the bookmarks directory.
*
* @return A pointer to the Gaia Sky bookmarks directory
*/
public static Path getDefaultBookmarksDir() {
return getConfigDir().resolve(BOOKMARKS_DIR_NAME);
}
public static String getBookmarksDirName() {
return BOOKMARKS_DIR_NAME;
}
/**
* Gets a file pointer to the mpcdi directory.
*
* @return A pointer to the Gaia Sky mpcdi directory
*/
public static Path getDefaultMpcdiDir() {
return getDataDir().resolve(MPCDI_DIR_NAME);
}
/**
* Gets a file pointer to the local data directory where the data files are downloaded and stored.
*
* @return A pointer to the local data directory where the data files are
*/
public static Path getLocalDataDir() {
return getDataDir().resolve(DATA_DIR_NAME);
}
/**
* Gets a file pointer to the crash reports directory, where crash reports are stored.
*
* @return A pointer to the crash reports directory
*/
public static Path getCrashReportsDir() {
return getDataDir().resolve(CRASHREPORTS_DIR_NAME);
}
/**
* Gets a file pointer to the temporary directory within the cache directory. See {@link #getCacheDir()}.
*
* @return A pointer to the Gaia Sky temporary directory in the user's home.
*/
public static Path getDefaultTmpDir() {
return getCacheDir().resolve(TMP_DIR_NAME);
}
/**
* Returns the default data directory. That is ~/.gaiasky/ in Windows and macOS, and ~/.local/share/gaiasky
* in Linux.
*
* @return Default data directory
*/
public static Path getDataDir() {
if (isLinux()) {
return getXdgDataHome().resolve(GAIASKY_DIR_NAME);
} else {
return getUserHome().resolve(DOTGAIASKY_DIR_NAME);
}
}
/**
* Returns the default cache directory, for non-essential data. This is ~/.gaiasky/ in Windows and macOS, and ~/.cache/gaiasky
* in Linux.
*
* @return The default cache directory
*/
public static Path getCacheDir() {
if (isLinux()) {
return getXdgCacheHome().resolve(GAIASKY_DIR_NAME);
} else {
return getDataDir();
}
}
public static Path getConfigDir() {
if (isLinux()) {
return getXdgConfigHome().resolve(GAIASKY_DIR_NAME);
} else {
return getUserHome().resolve(DOTGAIASKY_DIR_NAME);
}
}
public static Path getHomeDir() {
return getUserHome();
}
public static Path getUserHome() {
return Paths.get(System.getProperty("user.home"));
}
private static Path getXdgDataHome() {
String dataHome = System.getenv("XDG_DATA_HOME");
if (dataHome == null || dataHome.isEmpty()) {
return Paths.get(System.getProperty("user.home"), ".local", "share");
} else {
return Paths.get(dataHome);
}
}
private static Path getXdgConfigHome() {
String configHome = System.getenv("XDG_CONFIG_HOME");
if (configHome == null || configHome.isEmpty()) {
return Paths.get(System.getProperty("user.home"), ".config");
} else {
return Paths.get(configHome);
}
}
private static Path getXdgCacheHome() {
String cacheHome = System.getenv("XDG_CACHE_HOME");
if (cacheHome == null || cacheHome.isEmpty()) {
return Paths.get(System.getProperty("user.home"), ".cache");
} else {
return Paths.get(cacheHome);
}
}
public static double getJavaVersion() {
String version = System.getProperty("java.version");
if (version.contains(("."))) {
int pos = version.indexOf('.');
pos = version.indexOf('.', pos + 1);
return Double.parseDouble(version.substring(0, pos));
} else {
return Double.parseDouble(version);
}
}
}
|
ari-zah/gaiasandbox
|
core/src/gaiasky/desktop/util/SysUtils.java
|
Java
|
lgpl-3.0
| 9,893 |
package com.taiter.ce.Enchantments.Global;
import org.bukkit.Material;
import org.bukkit.entity.Creeper;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.Skeleton.SkeletonType;
import org.bukkit.entity.Zombie;
import org.bukkit.event.Event;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.scheduler.BukkitRunnable;
import com.taiter.ce.EffectManager;
import com.taiter.ce.Enchantments.CEnchantment;
public class Headless extends CEnchantment {
public Headless(Application app) {
super(app);
triggers.add(Trigger.DAMAGE_GIVEN);
resetMaxLevel();
}
@Override
public void effect(Event e, ItemStack item, int level) {
EntityDamageByEntityEvent event = (EntityDamageByEntityEvent) e;
final Player player = (Player) event.getDamager();
final LivingEntity ent = (LivingEntity) event.getEntity();
new BukkitRunnable() {
@Override
public void run() {
if (ent.getHealth() <= 0) {
byte type = 3;
if (ent instanceof Skeleton) {
type = 0;
if (((Skeleton) ent).getSkeletonType().equals(SkeletonType.WITHER))
type = 1;
} else if (ent instanceof Zombie)
type = 2;
else if (ent instanceof Creeper)
type = 4;
ItemStack skull = new ItemStack(Material.SKULL_ITEM, 1, type);
if (type == 3) {
SkullMeta sm = (SkullMeta) skull.getItemMeta();
sm.setOwner(ent.getName());
skull.setItemMeta(sm);
}
ent.getWorld().dropItem(ent.getLocation(), skull);
EffectManager.playSound(player.getLocation(), "BLOCK_ANVIL_LAND", 0.1f, 1.5f);
}
}
}.runTaskLater(getPlugin(), 5l);
}
@Override
public void initConfigEntries() {
}
}
|
Taiterio/ce
|
src/com/taiter/ce/Enchantments/Global/Headless.java
|
Java
|
lgpl-3.0
| 2,233 |
package net.minecraft.src;
// MCPatcher Start
import com.prupe.mcpatcher.cc.ColorizeEntity;
// MCPatcher End
public class ItemArmor extends Item {
/** Holds the 'base' maxDamage that each armorType have. */
private static final int[] maxDamageArray = new int[] {11, 16, 15, 13};
private static final String[] field_94606_cu = new String[] {"leather_helmet_overlay", "leather_chestplate_overlay", "leather_leggings_overlay", "leather_boots_overlay"};
public static final String[] field_94603_a = new String[] {"empty_armor_slot_helmet", "empty_armor_slot_chestplate", "empty_armor_slot_leggings", "empty_armor_slot_boots"};
private static final IBehaviorDispenseItem field_96605_cw = new BehaviorDispenseArmor();
/**
* Stores the armor type: 0 is helmet, 1 is plate, 2 is legs and 3 is boots
*/
public final int armorType;
/** Holds the amount of damage that the armor reduces at full durability. */
public final int damageReduceAmount;
/**
* Used on RenderPlayer to select the correspondent armor to be rendered on the player: 0 is cloth, 1 is chain, 2 is
* iron, 3 is diamond and 4 is gold.
*/
public final int renderIndex;
/** The EnumArmorMaterial used for this ItemArmor */
private final EnumArmorMaterial material;
private Icon field_94605_cw;
private Icon field_94604_cx;
public ItemArmor(int par1, EnumArmorMaterial par2EnumArmorMaterial, int par3, int par4) {
super(par1);
this.material = par2EnumArmorMaterial;
this.armorType = par4;
this.renderIndex = par3;
this.damageReduceAmount = par2EnumArmorMaterial.getDamageReductionAmount(par4);
this.setMaxDamage(par2EnumArmorMaterial.getDurability(par4));
this.maxStackSize = 1;
this.setCreativeTab(CreativeTabs.tabCombat);
BlockDispenser.dispenseBehaviorRegistry.putObject(this, field_96605_cw);
}
public int getColorFromItemStack(ItemStack par1ItemStack, int par2) {
if (par2 > 0) {
return 16777215;
} else {
int var3 = this.getColor(par1ItemStack);
if (var3 < 0) {
var3 = 16777215;
}
return var3;
}
}
public boolean requiresMultipleRenderPasses() {
return this.material == EnumArmorMaterial.CLOTH;
}
/**
* Return the enchantability factor of the item, most of the time is based on material.
*/
public int getItemEnchantability() {
return this.material.getEnchantability();
}
/**
* Return the armor material for this armor item.
*/
public EnumArmorMaterial getArmorMaterial() {
return this.material;
}
/**
* Return whether the specified armor ItemStack has a color.
*/
public boolean hasColor(ItemStack par1ItemStack) {
return this.material != EnumArmorMaterial.CLOTH ? false : (!par1ItemStack.hasTagCompound() ? false : (!par1ItemStack.getTagCompound().hasKey("display") ? false : par1ItemStack.getTagCompound().getCompoundTag("display").hasKey("color")));
}
/**
* Return the color for the specified armor ItemStack.
*/
public int getColor(ItemStack par1ItemStack) {
if (this.material != EnumArmorMaterial.CLOTH) {
return -1;
} else {
NBTTagCompound var2 = par1ItemStack.getTagCompound();
if (var2 == null) {
// MCPatcher Start
return ColorizeEntity.undyedLeatherColor;
// MCPatcher End
} else {
NBTTagCompound var3 = var2.getCompoundTag("display");
// MCPatcher Start
return var3 == null ? ColorizeEntity.undyedLeatherColor : (var3.hasKey("color") ? var3.getInteger("color") : ColorizeEntity.undyedLeatherColor);
// MCPatcher End
}
}
}
/**
* Gets an icon index based on an item's damage value and the given render pass
*/
public Icon getIconFromDamageForRenderPass(int par1, int par2) {
return par2 == 1 ? this.field_94605_cw : super.getIconFromDamageForRenderPass(par1, par2);
}
/**
* Remove the color from the specified armor ItemStack.
*/
public void removeColor(ItemStack par1ItemStack) {
if (this.material == EnumArmorMaterial.CLOTH) {
NBTTagCompound var2 = par1ItemStack.getTagCompound();
if (var2 != null) {
NBTTagCompound var3 = var2.getCompoundTag("display");
if (var3.hasKey("color")) {
var3.removeTag("color");
}
}
}
}
public void func_82813_b(ItemStack par1ItemStack, int par2) {
if (this.material != EnumArmorMaterial.CLOTH) {
throw new UnsupportedOperationException("Can\'t dye non-leather!");
} else {
NBTTagCompound var3 = par1ItemStack.getTagCompound();
if (var3 == null) {
var3 = new NBTTagCompound();
par1ItemStack.setTagCompound(var3);
}
NBTTagCompound var4 = var3.getCompoundTag("display");
if (!var3.hasKey("display")) {
var3.setCompoundTag("display", var4);
}
var4.setInteger("color", par2);
}
}
/**
* Return whether this item is repairable in an anvil.
*/
public boolean getIsRepairable(ItemStack par1ItemStack, ItemStack par2ItemStack) {
return this.material.getArmorCraftingMaterial() == par2ItemStack.itemID ? true : super.getIsRepairable(par1ItemStack, par2ItemStack);
}
public void registerIcons(IconRegister par1IconRegister) {
super.registerIcons(par1IconRegister);
if (this.material == EnumArmorMaterial.CLOTH) {
this.field_94605_cw = par1IconRegister.registerIcon(field_94606_cu[this.armorType]);
}
this.field_94604_cx = par1IconRegister.registerIcon(field_94603_a[this.armorType]);
}
/**
* Called whenever this item is equipped and the right mouse button is pressed. Args: itemStack, world, entityPlayer
*/
public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer par3EntityPlayer) {
int var4 = EntityLiving.getArmorPosition(par1ItemStack) - 1;
ItemStack var5 = par3EntityPlayer.getCurrentArmor(var4);
if (var5 == null) {
par3EntityPlayer.setCurrentItemOrArmor(var4, par1ItemStack.copy());
par1ItemStack.stackSize = 0;
}
return par1ItemStack;
}
public static Icon func_94602_b(int par0) {
switch (par0) {
case 0:
return Item.helmetDiamond.field_94604_cx;
case 1:
return Item.plateDiamond.field_94604_cx;
case 2:
return Item.legsDiamond.field_94604_cx;
case 3:
return Item.bootsDiamond.field_94604_cx;
default:
return null;
}
}
/**
* Returns the 'max damage' factor array for the armor, each piece of armor have a durability factor (that gets
* multiplied by armor material factor)
*/
static int[] getMaxDamageArray() {
return maxDamageArray;
}
}
|
Spoutcraft/Spoutcraft
|
src/main/java/net/minecraft/src/ItemArmor.java
|
Java
|
lgpl-3.0
| 6,355 |
<?php
namespace Cron;
class CronClass
{
/** @var array Обработанный список задач крона */
protected $cron = array();
/** @var string Путь к файлу с задачами крона */
protected $cronFile;
/** @var string Адрес, на который будут высылаться уведомления с крона */
protected $cronEmail;
/** @var \DateTime Время последнего успешного запуска крона */
protected $modifyTime;
/** @var string Путь к файлу с настройками Ideal CMS */
protected $dataFile;
/** @var string Корень сайта */
protected $siteRoot;
/** @var string Сообщение после тестового запуска скрипта */
protected $message = '';
/**
* CronClass constructor.
*
* @param string $siteRoot Корень сайта, относительно которого указываются скрипты в кроне
* @param string $cronFile Путь к файлу crontab сайта
* @param string $dataFile Путь к файлу настроек Ideal CMS (для получения координат отправки сообщений с крона)
*/
public function __construct($siteRoot = '', $cronFile = '', $dataFile = '')
{
$this->cronFile = empty($cronFile) ? __DIR__ . '/../../../crontab' : $cronFile;
$this->dataFile = empty($dataFile) ? __DIR__ . '/../../../site_data.php' : $dataFile;
$this->siteRoot = empty($siteRoot) ? dirname(dirname(dirname(dirname(__DIR__)))) : $siteRoot;
}
/**
* Делает проверку на доступность файла настроек, правильность заданий в системе и возможность
* модификации скрипта обработчика крона
*/
public function testAction()
{
$success = true;
// Проверяем доступность файла настроек для чтения
if (is_readable($this->dataFile)) {
$this->message .= "Файл с настройками сайта существует и доступен для чтения\n";
} else {
$this->message .= "Файл с настройками сайта {$this->dataFile} не существует или он недоступен для чтения\n";
$success = false;
}
// Проверяем доступность запускаемого файла для изменения его даты
if (is_writable($this->cronFile)) {
$this->message .= "Файл \"" . $this->cronFile . "\" позволяет вносить изменения в дату модификации\n";
} else {
$this->message .= "Не получается изменить дату модификации файла \"" . $this->cronFile . "\"\n";
$success = false;
}
// Загружаем данные из cron-файла в переменные класса
try {
$this->loadCrontab($this->cronFile);
} catch (\Exception $e) {
$this->message .= $e->getMessage() . "\n";
$success = false;
}
// Проверяем правильность задач в файле
if (!$this->testTasks($this->cron)) {
$success = false;
}
return $success;
}
/**
* Проверяет правильность введённых задач
*
* @param array $cron Список задач крона
* @return bool Правильно или нет записаны задачи крона
*/
public function testTasks($cron)
{
$success = true;
$taskIsset = false;
$tasks = $currentTasks = '';
foreach ($cron as $cronTask) {
list($taskExpression, $fileTask) = $this->parseCronTask($cronTask);
// Проверяем правильность написания выражения для крона и существование файла для выполнения
if (\Cron\CronExpression::isValidExpression($taskExpression) !== true) {
$this->message .= "Неверное выражение \"{$taskExpression}\"\n";
$success = false;
}
if ($fileTask && !is_readable($fileTask)) {
$this->message .= "Файл \"{$fileTask}\" не существует или он недоступен для чтения\n";
$success = false;
} elseif (!$fileTask) {
$this->message .= "Не задан исполняемый файл для выражения \"{$taskExpression}\"\n";
$success = false;
}
// Получаем дату следующего запуска задачи
$cronModel = \Cron\CronExpression::factory($taskExpression);
$nextRunDate = $cronModel->getNextRunDate($this->modifyTime);
$tasks .= $cronTask . "\nСледующий запуск файла \"{$fileTask}\" назначен на "
. $nextRunDate->format('d.m.Y H:i:s') . "\n";
$taskIsset = true;
// Если дата следующего запуска меньше, либо равна текущей дате, то добавляем задачу на запуск
$now = new \DateTime();
if ($nextRunDate <= $now) {
$currentTasks .= $cronTask . "\n" . $fileTask . "\n"
. 'modify: ' . $this->modifyTime->format('d.m.Y H:i:s') . "\n"
. 'nextRun: ' . $nextRunDate->format('d.m.Y H:i:s') . "\n"
. 'now: ' . $now->format('d.m.Y H:i:s') . "\n";
}
}
// Если в задачах из настройках Ideal CMS не обнаружено ошибок, уведомляем об этом
if ($success && $taskIsset) {
$this->message .= "В задачах из файла crontab ошибок не обнаружено\n";
} elseif (!$taskIsset) {
$this->message .= implode("\n", $cron) . "Пока нет ни одного задания для выполнения\n";
}
// Отображение информации о задачах, требующих запуска в данный момент
if ($currentTasks && $success) {
$this->message .= "\nЗадачи для запуска в данный момент:\n";
$this->message .= $currentTasks;
} elseif ($taskIsset && $success) {
$this->message .= "\nВ данный момент запуск задач не требуется\n";
}
// Отображение информации о запланированных задачах и времени их запуска
$tasks = $tasks && $success ? "\nЗапланированные задачи:\n" . $tasks : '';
$this->message .= $tasks . "\n";
return $success;
}
/**
* Обработка задач крона и запуск нужных задач
* @throws \Exception
*/
public function runAction()
{
// Загружаем данные из cron-файла
$this->loadCrontab($this->cronFile);
// Вычисляем путь до файла "site_data.php" в корне админки
$dataFileName = stream_resolve_include_path($this->dataFile);
// Получаем данные настроек системы
$siteData = require $dataFileName;
$data = array(
'domain' => $siteData['domain'],
'robotEmail' => $siteData['robotEmail'],
'adminEmail' => $this->cronEmail ? $this->cronEmail : $siteData['cms']['adminEmail'],
);
// Переопределяем стандартный обработчик ошибок для отправки уведомлений на почту
set_error_handler(function ($errno, $errstr, $errfile, $errline) use ($data) {
// Формируем текст ошибки
$_err = 'Ошибка [' . $errno . '] ' . $errstr . ', в строке ' . $errline . ' файла ' . $errfile;
// Выводим текст ошибки
echo $_err . "\n";
// Формируем заголовки письма и отправляем уведомление об ошибке на почту ответственного лица
$header = "From: \"{$data['domain']}\" <{$data['robotEmail']}>\r\n";
$header .= "Content-type: text/plain; charset=\"utf-8\"";
mail($data['adminEmail'], 'Ошибка при выполнении крона', $_err, $header);
});
// Обрабатываем задачи для крона из настроек Ideal CMS
$nowCron = new \DateTime();
foreach ($this->cron as $cronTask) {
list($taskExpression, $fileTask) = $this->parseCronTask($cronTask);
if (!$taskExpression || !$fileTask) {
continue;
}
// Получаем дату следующего запуска задачи
$cron = \Cron\CronExpression::factory($taskExpression);
$nextRunDate = $cron->getNextRunDate($this->modifyTime);
$nowCron = new \DateTime();
// Если дата следующего запуска меньше, либо равна текущей дате, то запускаем скрипт
if ($nextRunDate <= $nowCron) {
// Что бы не случилось со скриптом, изменяем дату модификации файла содержащего задачи для крона
touch($this->cronFile, $nowCron->getTimestamp());
// todo завести отдельный временный файл, куда записывать дату последнего прохода по крону, чтобы
// избежать ситуации, когда два задания должны выполниться в одну минуту, а выполняется только одно
// Запускаем скрипт
require_once $fileTask;
break; // Прекращаем цикл выполнения задач, чтобы не произошло наложения задач друг на друга
}
}
// Изменяем дату модификации файла содержащего задачи для крона
touch($this->cronFile, $nowCron->getTimestamp());
}
/**
* Возвращает сообщения после тестирования cron'а
*
* @return string
*/
public function getMessage()
{
return $this->message;
}
/**
* Разбирает задачу для крона из настроек Ideal CMS
* @param string $cronTask Строка в формате "* * * * * /path/to/file.php"
* @return array Массив, где первым элементом является строка соответствующая интервалу запуска задачи по крону,
* а вторым элементом является путь до запускаемого файла
*/
protected function parseCronTask($cronTask)
{
// Получаем cron-формат запуска файла в первых пяти элементах массива и путь до файла в последнем элементе
$taskParts = explode(' ', $cronTask, 6);
$fileTask = '';
if (count($taskParts) >= 6) {
$fileTask = array_pop($taskParts);
}
// Если запускаемый скрипт указан относительно корня сайта, то абсолютизируем его
if ($fileTask && strpos($fileTask, '/') !== 0) {
$fileTask = $this->siteRoot . '/' . $fileTask;
}
$fileTask = trim($fileTask);
$taskExpression = implode(' ', $taskParts);
return array($taskExpression, $fileTask);
}
/**
* Загружаем данные из крона в переменные cron, cronEmail, modifyTime
*
* @throws \Exception
*/
private function loadCrontab($fileName)
{
$fileName = stream_resolve_include_path($fileName);
if ($fileName) {
$this->cron = $this->parseCrontab(file_get_contents($fileName));
} else {
$this->cron = array();
$fileName = stream_resolve_include_path(dirname($fileName)) . 'crontab';
file_put_contents($fileName, '');
}
$this->cronFile = $fileName;
// Получаем дату модификации скрипта (она же считается датой последнего запуска)
$this->modifyTime = new \DateTime();
$this->modifyTime->setTimestamp(filemtime($fileName));
}
/**
* Извлечение почтового адреса для отправки уведомлений с крона. Формат MAILTO="email@email.com"
*
* @param string $cronString Необработанный crontab
* @return array Обработанный crontab
*/
public function parseCrontab($cronString)
{
$cron = explode(PHP_EOL, $cronString);
foreach ($cron as $k => $item) {
$item = trim($item);
if (empty($item)) {
// Пропускаем пустые строки
continue;
}
if ($item[0] === '#') {
// Если это комментарий, то удаляем его из задач
unset($cron[$k]);
continue;
}
if (stripos($item, 'mailto') !== false) {
// Если это адрес, извлекаем его
$arr = explode('=', $item);
if (empty($arr[1])) {
$this->message = 'Некорректно указан почтовый ящик для отправки сообщений';
}
$email = trim($arr[1]);
$this->cronEmail = trim($email, '"\'');
// Убираем строку с адресом из списка задач
unset($cron[$k]);
}
}
return $cron;
}
}
|
ideals/Ideal-CMS
|
Library/Cron/CronClass.php
|
PHP
|
lgpl-3.0
| 14,959 |
/*
* Created on May 19, 2008
*
* Copyright (c) 2008, The JUNG Authors
*
* All rights reserved.
*
* This software is open-source under the BSD license; see either
* "license.txt" or
* https://github.com/jrtom/jung/blob/master/LICENSE for a description.
*/
package edu.uci.ics.jung.algorithms.filters;
import java.util.Collection;
import com.google.common.base.Predicate;
import edu.uci.ics.jung.graph.Graph;
/**
* Transforms the input graph into one which contains only those vertices
* that pass the specified <code>Predicate</code>. The filtered graph
* is a copy of the original graph (same type, uses the same vertex and
* edge objects). Only those edges whose entire incident vertex collection
* passes the predicate are copied into the new graph.
*
* @author Joshua O'Madadhain
*/
public class VertexPredicateFilter<V,E> implements Filter<V,E>
{
protected Predicate<V> vertex_pred;
/**
* Creates an instance based on the specified vertex <code>Predicate</code>.
* @param vertex_pred the predicate that specifies which vertices to add to the filtered graph
*/
public VertexPredicateFilter(Predicate<V> vertex_pred)
{
this.vertex_pred = vertex_pred;
}
@SuppressWarnings("unchecked")
public Graph<V,E> apply(Graph<V,E> g)
{
Graph<V, E> filtered;
try
{
filtered = g.getClass().newInstance();
}
catch (InstantiationException e)
{
throw new RuntimeException("Unable to create copy of existing graph: ", e);
}
catch (IllegalAccessException e)
{
throw new RuntimeException("Unable to create copy of existing graph: ", e);
}
for (V v : g.getVertices())
if (vertex_pred.apply(v))
filtered.addVertex(v);
Collection<V> filtered_vertices = filtered.getVertices();
for (E e : g.getEdges())
{
Collection<V> incident = g.getIncidentVertices(e);
if (filtered_vertices.containsAll(incident))
filtered.addEdge(e, incident);
}
return filtered;
}
}
|
drzhonghao/grapa
|
jung-algorithms/src/main/java/edu/uci/ics/jung/algorithms/filters/VertexPredicateFilter.java
|
Java
|
lgpl-3.0
| 2,185 |
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.ce;
import org.sonar.ce.queue.CeQueueImpl;
import org.sonar.ce.task.log.CeTaskLogging;
import org.sonar.core.platform.Module;
import org.sonar.server.ce.http.CeHttpClientImpl;
public class CeModule extends Module {
@Override
protected void configureModule() {
add(CeTaskLogging.class,
CeHttpClientImpl.class,
// Queue
CeQueueImpl.class);
}
}
|
SonarSource/sonarqube
|
server/sonar-webserver-core/src/main/java/org/sonar/server/ce/CeModule.java
|
Java
|
lgpl-3.0
| 1,241 |
/*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import * as React from 'react';
import { shallow } from 'enzyme';
import SearchFilterContainer from '../SearchFilterContainer';
it('searches', () => {
const onQueryChange = jest.fn();
const wrapper = shallow(<SearchFilterContainer onQueryChange={onQueryChange} query={{}} />);
expect(wrapper).toMatchSnapshot();
wrapper.find('SearchBox').prop<Function>('onChange')('foo');
expect(onQueryChange).toBeCalledWith({ search: 'foo' });
});
|
Godin/sonar
|
server/sonar-web/src/main/js/apps/projects/filters/__tests__/SearchFilterContainer-test.tsx
|
TypeScript
|
lgpl-3.0
| 1,288 |
<?php
/**
* This file is part of MetaModels/core.
*
* (c) 2012-2019 The MetaModels team.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* This project is provided in good faith and hope to be usable by anyone.
*
* @package MetaModels/core
* @author Christian Schiffler <c.schiffler@cyberspectrum.de>
* @author David Maack <david.maack@arcor.de>
* @author Sven Baumann <baumann.sv@gmail.com>
* @copyright 2012-2019 The MetaModels team.
* @license https://github.com/MetaModels/core/blob/master/LICENSE LGPL-3.0-or-later
* @filesource
*/
namespace MetaModels\Helper;
/**
* Gateway to the Contao "Controller" class for usage of the core without
* importing any class.
*
* This is achieved using the magic functions which will relay the call
* to the parent class Controller. See there for a list of function that can
* be called (everything in Controller.php that is declared as protected).
*
* @deprecated Deprecated in favor of contao-events-bindings
*/
class ContaoController extends \Controller
{
/**
* The instance.
*
* @var ContaoController
*/
protected static $objInstance = null;
/**
* Get the static instance.
*
* @static
* @return ContaoController
*/
public static function getInstance()
{
if (self::$objInstance == null) {
self::$objInstance = new self();
}
return self::$objInstance;
}
/**
* Protected constructor for singleton instance.
*/
protected function __construct()
{
parent::__construct();
$this->import('Database');
}
/**
* Makes all protected methods from class Controller callable publically.
*
* @param string $strMethod The method to call.
*
* @param array $arrArgs The arguments.
*
* @return mixed
*
* @throws \RuntimeException When the method is unknown.
*/
public function __call($strMethod, $arrArgs)
{
if (method_exists($this, $strMethod)) {
return call_user_func_array(array($this, $strMethod), $arrArgs);
}
throw new \RuntimeException('undefined method: Controller::' . $strMethod);
}
/**
* Makes all protected methods from class Controller callable publically from static context (requires PHP 5.3).
*
* @param string $strMethod The method to call.
*
* @param array $arrArgs The arguments.
*
* @return mixed
*
* @throws \RuntimeException When the method is unknown.
*/
public static function __callStatic($strMethod, $arrArgs)
{
if (method_exists(__CLASS__, $strMethod)) {
return call_user_func_array(array(self::getInstance(), $strMethod), $arrArgs);
}
throw new \RuntimeException('undefined method: Controller::' . $strMethod);
}
}
|
MetaModels/core
|
src/Helper/ContaoController.php
|
PHP
|
lgpl-3.0
| 2,956 |
/*
* This file is part of AlmightyNotch.
*
* Copyright (c) 2014 <http://dev.bukkit.org/server-mods/almightynotch//>
*
* AlmightyNotch is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* AlmightyNotch is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with AlmightyNotch. If not, see <http://www.gnu.org/licenses/>.
*/
package ninja.amp.almightynotch.event.player;
public class QuicksandEvent {
// Moods: Bored, Displeased
// Mood Modifier: 5
}
|
ampayne2/AlmightyNotch
|
src/main/java/ninja/amp/almightynotch/event/player/QuicksandEvent.java
|
Java
|
lgpl-3.0
| 931 |
/*
* Intake, a command processing library
* Copyright (C) sk89q <http://www.sk89q.com>
* Copyright (C) Intake team and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.intake.example.i18n;
import com.sk89q.intake.example.i18n.util.Messages;
import com.sk89q.intake.util.i18n.ResourceProvider;
public class ExampleResourceProvider implements ResourceProvider {
private final Messages msg = new Messages(I18nExample.RESOURCE_NAME);
@Override
public String getString(String key) {
return msg.getString(key);
}
}
|
TheE/Intake
|
intake-example/src/main/java/com/sk89q/intake/example/i18n/ExampleResourceProvider.java
|
Java
|
lgpl-3.0
| 1,183 |
/*
Copyright 2012-2014 Infinitycoding all rights reserved
This file is part of the HugeUniversalGameEngine.
HUGE 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
any later version.
HUGE 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 the Universe Kernel. If not, see <http://www.gnu.org/licenses/>.
*/
/*
@author Michael Sippel <micha@infinitycoding.de>
*/
#include <huge/math/vector.h>
#include <huge/sdl.h>
namespace huge
{
namespace sdl
{
int init(void)
{
return SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
}
Window::Window()
: title(NULL), size(Vector2i(800, 600))
{
}
Window::Window(char *title_)
: title(title_), size(Vector2i(800, 600))
{
}
Window::Window(Vector2i size_)
: title(NULL), size(size_)
{
}
Window::Window(char *title_, Vector2i size_)
: title(title_), size(size_)
{
}
Window::~Window()
{
}
GLContext::GLContext()
{
GLContext(new GLWindow());
}
GLContext::GLContext(Window *window_)
: window(window_)
{
this->sdl_context = (SDL_GLContext*) SDL_GL_CreateContext(this->window->sdl_window);
if(this->sdl_context == NULL)
{
printf("OpenGL context creation failed!\n");
}
}
GLContext::~GLContext()
{
SDL_GL_DeleteContext(this->sdl_context);
}
void GLContext::activate_(void)
{
SDL_GL_MakeCurrent(this->window->sdl_window, this->sdl_context);
}
GLWindow::GLWindow()
{
this->create();
}
GLWindow::GLWindow(char *title_)
{
this->title = title_;
this->create();
}
GLWindow::GLWindow(Vector2i size_)
{
this->size = size_;
this->create();
}
GLWindow::GLWindow(char *title_, Vector2i size_)
{
this->title = title_;
this->size = size_;
this->create();
}
GLWindow::~GLWindow()
{
SDL_DestroyWindow(this->sdl_window);
}
void GLWindow::swap(void)
{
SDL_GL_SwapWindow(this->sdl_window);
}
void GLWindow::create(void)
{
this->sdl_window = SDL_CreateWindow(this->title, 0, 0, this->size.x(), this->size.y(), SDL_WINDOW_OPENGL);
if(this->sdl_window == NULL)
{
printf("SDL window creation failed!\n");
}
}
}; // namespace sdl
}; // namespace huge
|
infinitycoding/huge
|
src/sdl/sdl.cpp
|
C++
|
lgpl-3.0
| 2,586 |
<?php
require_once(__DIR__."/../model/JuradoProfesional.php");
require_once(__DIR__."/../model/JuradoProfesionalMapper.php");
require_once(__DIR__."/../model/User.php");
require_once(__DIR__."/../model/UserMapper.php");
require_once(__DIR__."/../model/Concurso.php");
require_once(__DIR__."/../model/ConcursoMapper.php");
require_once(__DIR__."/../core/ViewManager.php");
require_once(__DIR__."/../controller/BaseController.php");
require_once(__DIR__."/../controller/UsersController.php");
class JuradoProfesionalController extends BaseController {
private $juradoProfesionalMapper;
private $userMapper;
private $concursoMapper;
public function __construct() {
parent::__construct();
$this->juradoProfesionalMapper = new JuradoProfesionalMapper();
$this->concursoMapper = new ConcursoMapper();
$this->userMapper = new UserMapper();
}
/*redirecciona a la página principal del sitio web*/
public function index() {
$juradoProfesional = $this->juradoProfesionalMapper->findAll();
$concursos = $this->concursoMapper->findConcurso("pinchosOurense");
$this->view->setVariable("juradoProfesional", $juradoProfesional);
$this->view->setVariable("concursos", $concursos);
$this->view->render("concursos", "index");
}
/*redirecciona a la vista del perfil del jurado profesional*/
public function perfil(){
$currentuser = $this->view->getVariable("currentusername");
$juradoProfesional = $this->juradoProfesionalMapper->findById($currentuser);
$this->view->setVariable("juradoPro", $juradoProfesional);
$this->view->render("juradoProfesional", "perfil");
}
/*redirecciona al formulario de modificacion de los datos de un jurado profesional*/
public function modificar(){
$currentuser = $this->view->getVariable("currentusername");
$juradoProfesional = $this->juradoProfesionalMapper->findById($currentuser);
$this->view->setVariable("juradoPro", $juradoProfesional);
$this->view->render("juradoProfesional", "modificar");
}
/*Recupera los datos del formulario de modificacion de un jurado profesional,
comprueba que son correctos y llama a update() de JuradoProfesionalMapper.php
donde se realiza la actualizacion de los datos.*/
public function update(){
$jproid = $_REQUEST["usuario"];
$jpro = $this->juradoProfesionalMapper->findById($jproid);
$errors = array();
if($this->userMapper->isValidUser($_POST["usuario"],$_POST["passActual"])){
if (isset($_POST["submit"])) {
$jpro->setNombre($_POST["nombre"]);
$jpro->setEmail($_POST["correo"]);
$jpro->setProfesion($_POST["profesion"]);
if(!(strlen(trim($_POST["passNew"])) == 0)){
if ($_POST["passNew"]==$_POST["passNueva"]) {
$jpro->setPassword($_POST["passNueva"]);
}
else{
$errors["pass"] = "Las contraseñas tienen que ser iguales";
$this->view->setVariable("errors", $errors);
$this->view->setVariable("juradoPro", $jpro);
$this->view->render("juradoProfesional", "modificar");
return false;
}
}
try{
$this->juradoProfesionalMapper->update($jpro);
$this->view->setFlash(sprintf("Usuario \"%s\" modificado correctamente.",$jpro ->getNombre()));
$this->view->redirect("juradoProfesional", "index");
}catch(ValidationException $ex) {
$errors = $ex->getErrors();
$this->view->setVariable("errors", $errors);
}
}
}
else{
$errors["passActual"] = "<span>La contraseña es obligatoria</span>";
$this->view->setVariable("errors", $errors);
$this->view->setVariable("juradoPro", $jpro);
$this->view->render("juradoProfesional", "modificar");
}
}
/*Llama a delete() de JuradoProfesionalMapper.php que elimina un jurado profesional y las votaciones
que este realizó.*/
public function eliminar(){
$jproid = $_REQUEST["usuario"];
$juradoProfesional = $this->juradoProfesionalMapper->findById($jproid);
// Does the post exist?
if ($juradoProfesional == NULL) {
throw new Exception("No existe el usuario ".$jproid);
}
// Delete the Jurado Popular object from the database
$this->juradoProfesionalMapper->delete($juradoProfesional);
$this->view->setFlash(sprintf("Usuario \"%s\" eliminado.",$juradoProfesional ->getId()));
$this->view->redirect("organizador", "index");
}
/*lista los jurado profesionales para eliminarlos*/
public function listarEliminar(){
$juradoProfesional = $this->juradoProfesionalMapper->findAll();
$this->view->setVariable("juradoProfesional", $juradoProfesional);
$this->view->render("juradoProfesional", "listaEliminar");
}
/*lista los jurados profesionales*/
public function listar(){
$juradoProfesional = $this->juradoProfesionalMapper->findAll();
$this->view->setVariable("juradoProfesional", $juradoProfesional);
$this->view->render("juradoProfesional", "listar");
}
/*redirecciona a la vista de votar de un jurado profesional*/
public function votar(){
$currentuser = $this->view->getVariable("currentusername");
$juradoProfesional = $this->juradoProfesionalMapper->findById($currentuser);
//devuelve los pinchos con sus votos de un jurado profesional
$votos = $this->juradoProfesionalMapper->votos($currentuser);
//devuelve la ronda en la que esta el jurado profesional
$ronda = $this->juradoProfesionalMapper->getRonda($currentuser);
$this->view->setVariable("juradoPro", $juradoProfesional);
$this->view->setVariable("votos", $votos);
$this->view->setVariable("ronda", $ronda);
$this->view->render("juradoProfesional", "votar");
}
/*modifica el pincho y su voto correspondiente de un jurado profesional*/
public function votarPincho(){
$currentuser = $this->view->getVariable("currentusername");
$juradoProfesional = $this->juradoProfesionalMapper->findById($currentuser);
$votos = $this->juradoProfesionalMapper->votar($_POST['currentusername'], $_POST['idPincho'], $_POST['voto']);
$this->view->redirect("juradoProfesional", "votar");
}
}
|
xrlopez/ABP
|
controller/JuradoProfesionalController.php
|
PHP
|
lgpl-3.0
| 6,331 |
let idCounter = 0;
function nextId() {
return ++idCounter;
}
// if the platform throws an exception, the worker will kill & restart it, however if a callback comes in there could
// be a race condition which tries to still access session functions which have already been terminated by the worker.
// this function wrapper only calls the session functions if they still exist.
function referenceProtection(session) {
if (typeof session === 'undefined') { throw new Error('session object not provided'); }
function checkScope(funcName) {
return (msg) => {
if (typeof session[funcName] === 'function') {
session[funcName](msg);
}
}
}
return {
actor: session.actor,
debug: checkScope('debug'),
sendToClient: checkScope('sendToClient')
}
}
class IncomingHandlers {
constructor(session) {
this.session = referenceProtection(session);
}
buddy(from, state, statusText) {
if (from !== this.session.actor['@id']) {
this.session.debug('received buddy presence update: ' + from + ' - ' + state);
this.session.sendToClient({
'@type': 'update',
actor: { '@id': from },
target: this.session.actor,
object: {
'@type': 'presence',
status: statusText,
presence: state
}
});
}
}
buddyCapabilities(id, capabilities) {
this.session.debug('received buddyCapabilities: ' + id);
}
chat(from, message) {
this.session.debug("received chat message from " + from);
this.session.sendToClient({
'@type': 'send',
actor: {
'@type': 'person',
'@id': from
},
target: this.session.actor,
object: {
'@type': 'message',
content: message,
'@id': nextId()
}
});
}
chatstate(from, name) {
this.session.debug('received chatstate event: ' + from, name);
}
close() {
this.session.debug('received close event with no handler specified');
this.session.sendToClient({
'@type': 'close',
actor: this.session.actor,
target: this.session.actor
});
this.session.debug('**** xmpp this.session.for ' + this.session.actor['@id'] + ' closed');
this.session.connection.disconnect();
}
error(error) {
try {
this.session.debug("*** XMPP ERROR (rl): " + error);
this.session.sendToClient({
'@type': 'error',
object: {
'@type': 'error',
content: error
}
});
} catch (e) {
this.session.debug('*** XMPP ERROR (rl catch): ', e);
}
}
groupBuddy(id, groupBuddy, state, statusText) {
this.session.debug('received groupbuddy event: ' + id);
this.session.sendToClient({
'@type': 'update',
actor: {
'@id': `${id}/${groupBuddy}`,
'@type': 'person',
displayName: groupBuddy
},
target: {
'@id': id,
'@type': 'room'
},
object: {
'@type': 'presence',
status: statusText,
presence: state
}
});
}
groupChat(room, from, message, stamp) {
this.session.debug('received groupchat event: ' + room, from, message, stamp);
this.session.sendToClient({
'@type': 'send',
actor: {
'@type': 'person',
'@id': from
},
target: {
'@type': 'room',
'@id': room
},
object: {
'@type': 'message',
content: message,
'@id': nextId()
}
});
}
online() {
this.session.debug('online');
this.session.debug('reconnectioned ' + this.session.actor['@id']);
}
subscribe(from) {
this.session.debug('received subscribe request from ' + from);
this.session.sendToClient({
'@type': "request-friend",
actor: { '@id': from },
target: this.session.actor
});
}
unsubscribe(from) {
this.session.debug('received unsubscribe request from ' + from);
this.session.sendToClient({
'@type': "remove-friend",
actor: { '@id': from },
target: this.session.actor
});
}
/**
* Handles all unknown conditions that we don't have an explicit handler for
**/
__stanza(stanza) {
// simple-xmpp currently doesn't seem to handle error state presence so we'll do it here for now.
// TODO: consider moving this.session.to simple-xmpp once it's ironed out and proven to work well.
if ((stanza.attrs.type === 'error')) {
const error = stanza.getChild('error');
let message = stanza.toString();
let type = 'message';
if (stanza.is('presence')) {
type = 'update';
}
if (error) {
message = error.toString();
if (error.getChild('remote-server-not-found')) {
// when we get this.session.type of return message, we know it was a response from a join
type = 'join';
message = 'remote server not found ' + stanza.attrs.from;
}
}
this.session.sendToClient({
'@type': type,
actor: {
'@id': stanza.attrs.from,
'@type': 'room'
},
object: {
'@type': 'error', // type error
content: message
},
target: {
'@id': stanza.attrs.to,
'@type': 'person'
}
});
} else if (stanza.is('iq')) {
if (stanza.attrs.id === 'muc_id' && stanza.attrs.type === 'result') {
this.session.debug('got room attendance list');
this.roomAttendance(stanza);
return;
}
const query = stanza.getChild('query');
if (query) {
const entries = query.getChildren('item');
for (let e in entries) {
if (! entries.hasOwnProperty(e)) {
continue;
}
this.session.debug('STANZA ATTRS: ', entries[e].attrs);
if (entries[e].attrs.subscription === 'both') {
this.session.sendToClient({
'@type': 'update',
actor: { '@id': entries[e].attrs.jid, displayName: entries[e].attrs.name },
target: this.session.actor,
object: {
'@type': 'presence',
status: '',
presence: state
}
});
} else if ((entries[e].attrs.subscription === 'from') &&
(entries[e].attrs.ask) && (entries[e].attrs.ask === 'subscribe')) {
this.session.sendToClient({
'@type': 'update',
actor: { '@id': entries[e].attrs.jid, displayName: entries[e].attrs.name },
target: this.session.actor,
object: {
'@type': 'presence',
statusText: '',
presence: 'notauthorized'
}
});
} else {
/**
* cant figure out how to know if one of these query stanzas are from
* added contacts or pending requests
*/
this.session.sendToClient({
'@type': 'request-friend',
actor: { '@id': entries[e].attrs.jid, displayName: entries[e].attrs.name },
target: this.session.actor
});
}
}
}
// } else {
// this.session.debug("got XMPP unknown stanza... " + stanza);
}
}
roomAttendance(stanza) {
const query = stanza.getChild('query');
if (query) {
let members = [];
const entries = query.getChildren('item');
for (let e in entries) {
if (!entries.hasOwnProperty(e)) {
continue;
}
members.push(entries[e].attrs.name);
}
this.session.sendToClient({
'@type': 'observe',
actor: {
'@id': stanza.attrs.from,
'@type': 'room'
},
target: {
'@id': stanza.attrs.to,
'@type': 'person'
},
object: {
'@type': 'attendance',
members: members
}
});
}
}
}
module.exports = IncomingHandlers;
|
sockethub/sockethub-platform-xmpp
|
lib/incoming-handlers.js
|
JavaScript
|
lgpl-3.0
| 7,988 |
# -*- coding: utf-8 -*-
module Vnet
module Event
#
# Shared events:
#
ACTIVATE_INTERFACE = "activate_interface"
DEACTIVATE_INTERFACE = "deactivate_interface"
# *_INITIALIZED
#
# First event queued after the non-yielding and non-blocking
# initialization of an item query from the database.
#
# *_UNLOAD_ITEM
#
# When the node wants to unload it's own loaded items the
# 'unload_item' event should be used instead of 'deleted_item'.
#
# *_CREATED_ITEM
#
# The item was added to the database and basic information of
# the item sent to relevant nodes. The manager should decide if it
# should initialize the item or not.
#
# *_DELETED_ITEM
#
# The item was deleted from the database and should be unloaded
# from all nodes.
#
# Active Interface events:
#
ACTIVE_INTERFACE_INITIALIZED = "active_interface_initialized"
ACTIVE_INTERFACE_UNLOAD_ITEM = "active_interface_unload_item"
ACTIVE_INTERFACE_CREATED_ITEM = "active_interface_created_item"
ACTIVE_INTERFACE_DELETED_ITEM = "active_interface_deleted_item"
ACTIVE_INTERFACE_UPDATED = "active_interface_updated"
#
# Active Network events:
#
ACTIVE_NETWORK_INITIALIZED = "active_network_initialized"
ACTIVE_NETWORK_UNLOAD_ITEM = "active_network_unload_item"
ACTIVE_NETWORK_CREATED_ITEM = "active_network_created_item"
ACTIVE_NETWORK_DELETED_ITEM = "active_network_deleted_item"
ACTIVE_NETWORK_ACTIVATE = "active_network_activate"
ACTIVE_NETWORK_DEACTIVATE = "active_network_deactivate"
#
# Active Route Link events:
#
ACTIVE_ROUTE_LINK_INITIALIZED = "active_route_link_initialized"
ACTIVE_ROUTE_LINK_UNLOAD_ITEM = "active_route_link_unload_item"
ACTIVE_ROUTE_LINK_CREATED_ITEM = "active_route_link_created_item"
ACTIVE_ROUTE_LINK_DELETED_ITEM = "active_route_link_deleted_item"
ACTIVE_ROUTE_LINK_ACTIVATE = "active_route_link_activate"
ACTIVE_ROUTE_LINK_DEACTIVATE = "active_route_link_deactivate"
#
# Active Segment events:
#
ACTIVE_SEGMENT_INITIALIZED = "active_segment_initialized"
ACTIVE_SEGMENT_UNLOAD_ITEM = "active_segment_unload_item"
ACTIVE_SEGMENT_CREATED_ITEM = "active_segment_created_item"
ACTIVE_SEGMENT_DELETED_ITEM = "active_segment_deleted_item"
ACTIVE_SEGMENT_ACTIVATE = "active_segment_activate"
ACTIVE_SEGMENT_DEACTIVATE = "active_segment_deactivate"
#
# Active Port events:
#
ACTIVE_PORT_INITIALIZED = "active_port_initialized"
ACTIVE_PORT_UNLOAD_ITEM = "active_port_unload_item"
ACTIVE_PORT_CREATED_ITEM = "active_port_created_item"
ACTIVE_PORT_DELETED_ITEM = "active_port_deleted_item"
ACTIVE_PORT_ACTIVATE = "active_port_activate"
ACTIVE_PORT_DEACTIVATE = "active_port_deactivate"
#
# Datapath events:
#
DATAPATH_INITIALIZED = 'datapath_initialized'
DATAPATH_UNLOAD_ITEM = 'datapath_unload_item'
DATAPATH_CREATED_ITEM = 'datapath_created_item'
DATAPATH_DELETED_ITEM = 'datapath_deleted_item'
DATAPATH_UPDATED_ITEM = 'datapath_updated_item'
HOST_DATAPATH_INITIALIZED = 'host_datapath_initialized'
HOST_DATAPATH_UNLOAD_ITEM = 'host_datapath_unload_item'
ACTIVATE_NETWORK_ON_HOST = 'activate_network_on_host'
DEACTIVATE_NETWORK_ON_HOST = 'deactivate_network_on_host'
ADDED_DATAPATH_NETWORK = 'added_datapath_network'
REMOVED_DATAPATH_NETWORK = 'removed_datapath_network'
ACTIVATE_DATAPATH_NETWORK = 'activate_datapath_network'
DEACTIVATE_DATAPATH_NETWORK = 'deactivate_datapath_network'
ACTIVATE_SEGMENT_ON_HOST = 'activate_segment_on_host'
DEACTIVATE_SEGMENT_ON_HOST = 'deactivate_segment_on_host'
ADDED_DATAPATH_SEGMENT = 'added_datapath_segment'
REMOVED_DATAPATH_SEGMENT = 'removed_datapath_segment'
ACTIVATE_DATAPATH_SEGMENT = 'activate_datapath_segment'
DEACTIVATE_DATAPATH_SEGMENT = 'deactivate_datapath_segment'
ACTIVATE_ROUTE_LINK_ON_HOST = 'activate_route_link_on_host'
DEACTIVATE_ROUTE_LINK_ON_HOST = 'deactivate_route_link_on_host'
ADDED_DATAPATH_ROUTE_LINK = 'added_datapath_route_link'
REMOVED_DATAPATH_ROUTE_LINK = 'removed_datapath_route_link'
ACTIVATE_DATAPATH_ROUTE_LINK = 'activate_datapath_route_link'
DEACTIVATE_DATAPATH_ROUTE_LINK = 'deactivate_datapath_route_link'
#
# Interface events:
#
INTERFACE_INITIALIZED = "interface_initialized"
INTERFACE_UNLOAD_ITEM = "interface_unload_item"
INTERFACE_CREATED_ITEM = "interface_created_item"
INTERFACE_DELETED_ITEM = "interface_deleted_item"
INTERFACE_UPDATED = "interface_updated"
INTERFACE_ENABLED_FILTERING = "interface_enabled_filtering"
INTERFACE_DISABLED_FILTERING = "interface_disabled_filtering"
INTERFACE_ENABLED_FILTERING2 = "interface_enabled_filtering2"
INTERFACE_DISABLED_FILTERING2 = "interface_disabled_filtering2"
# MAC and IPv4 addresses:
INTERFACE_LEASED_MAC_ADDRESS = "interface_leased_mac_address"
INTERFACE_RELEASED_MAC_ADDRESS = "interface_released_mac_address"
INTERFACE_LEASED_IPV4_ADDRESS = "interface_leased_ipv4_address"
INTERFACE_RELEASED_IPV4_ADDRESS = "interface_released_ipv4_address"
#
# Interface Network events:
#
INTERFACE_NETWORK_INITIALIZED = "interface_network_initialized"
INTERFACE_NETWORK_UNLOAD_ITEM = "interface_network_unload_item"
INTERFACE_NETWORK_CREATED_ITEM = "interface_network_created_item"
INTERFACE_NETWORK_DELETED_ITEM = "interface_network_deleted_item"
INTERFACE_NETWORK_UPDATED_ITEM = "interface_network_updated_item"
#
# Interface Route Link events:
#
INTERFACE_ROUTE_LINK_INITIALIZED = "interface_route_link_initialized"
INTERFACE_ROUTE_LINK_UNLOAD_ITEM = "interface_route_link_unload_item"
INTERFACE_ROUTE_LINK_CREATED_ITEM = "interface_route_link_created_item"
INTERFACE_ROUTE_LINK_DELETED_ITEM = "interface_route_link_deleted_item"
INTERFACE_ROUTE_LINK_UPDATED_ITEM = "interface_route_link_updated_item"
#
# Interface Segment events:
#
INTERFACE_SEGMENT_INITIALIZED = "interface_segment_initialized"
INTERFACE_SEGMENT_UNLOAD_ITEM = "interface_segment_unload_item"
INTERFACE_SEGMENT_CREATED_ITEM = "interface_segment_created_item"
INTERFACE_SEGMENT_DELETED_ITEM = "interface_segment_deleted_item"
INTERFACE_SEGMENT_UPDATED_ITEM = "interface_segment_updated_item"
#
# Interface Port events:
#
INTERFACE_PORT_INITIALIZED = "interface_port_initialized"
INTERFACE_PORT_UNLOAD_ITEM = "interface_port_unload_item"
INTERFACE_PORT_CREATED_ITEM = "interface_port_created_item"
INTERFACE_PORT_DELETED_ITEM = "interface_port_deleted_item"
INTERFACE_PORT_UPDATED = "interface_port_updated"
INTERFACE_PORT_ACTIVATE = "interface_port_activate"
INTERFACE_PORT_DEACTIVATE = "interface_port_deactivate"
#
# Filter events:
#
FILTER_INITIALIZED = "filter_initialized"
FILTER_UNLOAD_ITEM = "filter_unload_item"
FILTER_CREATED_ITEM = "filter_created_item"
FILTER_DELETED_ITEM = "filter_deleted_item"
FILTER_UPDATED = "filter_updated"
FILTER_ADDED_STATIC = "filter_added_static"
FILTER_REMOVED_STATIC = "filter_removed_static"
#
# Filter events:
#
MAC_RANGE_GROUP_CREATED_ITEM = "mac_range_group_created_item"
MAC_RANGE_GROUP_DELETED_ITEM = "mac_range_group_deleted_item"
#
# Network event:
#
NETWORK_INITIALIZED = "network_initialized"
NETWORK_UNLOAD_ITEM = "network_unload_item"
NETWORK_DELETED_ITEM = "network_deleted_item"
NETWORK_UPDATE_ITEM_STATES = "network_update_item_states"
#
# lease policy event
#
LEASE_POLICY_INITIALIZED = "lease_policy_initialized"
LEASE_POLICY_CREATED_ITEM = "lease_policy_created_item"
LEASE_POLICY_DELETED_ITEM = "lease_policy_deleted_item"
#
# Port events:
#
PORT_INITIALIZED = "port_initialized"
PORT_FINALIZED = "port_finalized"
PORT_ATTACH_INTERFACE = "port_attach_interface"
PORT_DETACH_INTERFACE = "port_detach_interface"
#
# Route events:
#
ROUTE_INITIALIZED = "route_initialized"
ROUTE_UNLOAD_ITEM = "route_unload_item"
ROUTE_CREATED_ITEM = "route_created_item"
ROUTE_DELETED_ITEM = "route_deleted_item"
ROUTE_ACTIVATE_NETWORK = "route_activate_network"
ROUTE_DEACTIVATE_NETWORK = "route_deactivate_network"
ROUTE_ACTIVATE_ROUTE_LINK = "route_activate_route_link"
ROUTE_DEACTIVATE_ROUTE_LINK = "route_deactivate_route_link"
#
# Router event:
#
ROUTER_INITIALIZED = "router_initialized"
ROUTER_UNLOAD_ITEM = "router_unload_item"
ROUTER_CREATED_ITEM = "router_created_item"
ROUTER_DELETED_ITEM = "router_deleted_item"
#
# Segment events:
#
SEGMENT_INITIALIZED = "segment_initialized"
SEGMENT_UNLOAD_ITEM = "segment_unload_item"
SEGMENT_CREATED_ITEM = "segment_created_item"
SEGMENT_DELETED_ITEM = "segment_deleted_item"
SEGMENT_UPDATE_ITEM_STATES = "segment_update_item_states"
#
# Service events:
#
SERVICE_INITIALIZED = "service_initialized"
SERVICE_UNLOAD_ITEM = "service_unload_item"
SERVICE_CREATED_ITEM = "service_created_item"
SERVICE_DELETED_ITEM = "service_deleted_item"
SERVICE_ACTIVATE_INTERFACE = "service_activate_interface"
SERVICE_DEACTIVATE_INTERFACE = "service_deactivate_interface"
#
# Translation events:
#
TRANSLATION_INITIALIZED = "translation_initialized"
TRANSLATION_UNLOAD_ITEM = "translation_unload_item"
TRANSLATION_CREATED_ITEM = "translation_created_item"
TRANSLATION_DELETED_ITEM = "translation_deleted_item"
TRANSLATION_ADDED_STATIC_ADDRESS = "translation_added_static_address"
TRANSLATION_REMOVED_STATIC_ADDRESS = "translation_removed_static_address"
#
# Topology events:
#
TOPOLOGY_INITIALIZED = 'topology_initialized'
TOPOLOGY_UNLOAD_ITEM = 'topology_unload_item'
TOPOLOGY_CREATED_ITEM = 'topology_created_item'
TOPOLOGY_DELETED_ITEM = 'topology_deleted_item'
TOPOLOGY_ADDED_DATAPATH = 'topology_added_datapath'
TOPOLOGY_REMOVED_DATAPATH = 'topology_removed_datapath'
TOPOLOGY_ADDED_LAYER = 'topology_added_layer'
TOPOLOGY_REMOVED_LAYER = 'topology_removed_layer'
TOPOLOGY_ADDED_MAC_RANGE_GROUP = 'topology_added_mac_range_group'
TOPOLOGY_REMOVED_MAC_RANGE_GROUP = 'topology_removed_mac_range_group'
TOPOLOGY_ADDED_NETWORK = 'topology_added_network'
TOPOLOGY_REMOVED_NETWORK = 'topology_removed_network'
TOPOLOGY_ADDED_SEGMENT = 'topology_added_segment'
TOPOLOGY_REMOVED_SEGMENT = 'topology_removed_segment'
TOPOLOGY_ADDED_ROUTE_LINK = 'topology_added_route_link'
TOPOLOGY_REMOVED_ROUTE_LINK = 'topology_removed_route_link'
TOPOLOGY_NETWORK_ACTIVATED = 'topology_network_activated'
TOPOLOGY_NETWORK_DEACTIVATED = 'topology_network_deactivated'
TOPOLOGY_SEGMENT_ACTIVATED = 'topology_segment_activated'
TOPOLOGY_SEGMENT_DEACTIVATED = 'topology_segment_deactivated'
TOPOLOGY_ROUTE_LINK_ACTIVATED = 'topology_route_link_activated'
TOPOLOGY_ROUTE_LINK_DEACTIVATED = 'topology_route_link_deactivated'
#
# tunnel event
#
ADDED_TUNNEL = "added_tunnel"
REMOVED_TUNNEL = "removed_tunnel"
INITIALIZED_TUNNEL = "initialized_tunnel"
TUNNEL_UPDATE_PROPERTY_STATES = "tunnel_update_property_states"
ADDED_HOST_DATAPATH_NETWORK = "added_host_datapath_network"
ADDED_REMOTE_DATAPATH_NETWORK = "added_remote_datapath_network"
ADDED_HOST_DATAPATH_SEGMENT = "added_host_datapath_segment"
ADDED_REMOTE_DATAPATH_SEGMENT = "added_remote_datapath_segment"
ADDED_HOST_DATAPATH_ROUTE_LINK = "added_host_datapath_route_link"
ADDED_REMOTE_DATAPATH_ROUTE_LINK = "added_remote_datapath_route_link"
REMOVED_HOST_DATAPATH_NETWORK = "removed_host_datapath_network"
REMOVED_REMOTE_DATAPATH_NETWORK = "removed_remote_datapath_network"
REMOVED_HOST_DATAPATH_SEGMENT = "removed_host_datapath_segment"
REMOVED_REMOTE_DATAPATH_SEGMENT = "removed_remote_datapath_segment"
REMOVED_HOST_DATAPATH_ROUTE_LINK = "removed_host_datapath_route_link"
REMOVED_REMOTE_DATAPATH_ROUTE_LINK = "removed_remote_datapath_route_link"
#
# dns service
#
SERVICE_ADDED_DNS = "added_dns_service"
SERVICE_REMOVED_DNS = "removed_dns_service"
SERVICE_UPDATED_DNS = "updated_dns_service"
#
# dns record
#
ADDED_DNS_RECORD = "added_dns_record"
REMOVED_DNS_RECORD = "removed_dns_record"
#
# Ip Retention Container Events:
#
IP_RETENTION_CONTAINER_INITIALIZED = 'ip_retention_container_initialized'
IP_RETENTION_CONTAINER_UNLOAD_ITEM = 'ip_retention_container_unload_item'
IP_RETENTION_CONTAINER_CREATED_ITEM = 'ip_retention_container_created_item'
IP_RETENTION_CONTAINER_DELETED_ITEM = 'ip_retention_container_deleted_item'
IP_RETENTION_CONTAINER_ADDED_IP_RETENTION = 'ip_retention_container_added_ip_retention'
IP_RETENTION_CONTAINER_REMOVED_IP_RETENTION = 'ip_retention_container_removed_ip_retention'
IP_RETENTION_CONTAINER_LEASE_TIME_EXPIRED = 'ip_retention_container_lease_time_expired'
IP_RETENTION_CONTAINER_GRACE_TIME_EXPIRED = 'ip_retention_container_grace_time_expired'
end
end
|
axsh/openvnet
|
vnet/lib/vnet/event.rb
|
Ruby
|
lgpl-3.0
| 13,317 |
/*
* ARMarkerSquare.cpp
* ARToolKitUWP
*
* This work is a modified version of the original "ARMarkerSquare.cpp" of
* ARToolKit. The copyright and license information of ARToolKit is included
* in this document as required by its GNU Lesser General Public License
* version 3.
*
* This file is a part of ARToolKitUWP.
*
* ARToolKitUWP is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARToolKitUWP is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ARToolKitUWP. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2017 Long Qian
*
* Author: Long Qian
* Contact: lqian8@jhu.edu
*
*/
/* The original copyright information: *//*
* ARMarkerSquare.cpp
* ARToolKit5
*
* This file is part of ARToolKit.
*
* ARToolKit is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ARToolKit is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with ARToolKit. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules, and to
* copy and distribute the resulting executable under terms of your choice,
* provided that you also meet, for each linked independent module, the terms and
* conditions of the license of that module. An independent module is a module
* which is neither derived from nor based on this library. If you modify this
* library, you may extend this exception to your version of the library, but you
* are not obligated to do so. If you do not wish to do so, delete this exception
* statement from your version.
*
* Copyright 2015 Daqri, LLC.
* Copyright 2010-2015 ARToolworks, Inc.
*
* Author(s): Philip Lamb.
*
*/
#include "pch.h"
#include <ARMarkerSquare.h>
#include <ARController.h>
#ifndef MAX
# define MAX(x,y) (x > y ? x : y)
#endif
ARMarkerSquare::ARMarkerSquare() : ARMarker(SINGLE),
m_loaded(false),
m_arPattHandle(NULL),
m_cf(0.0f),
m_cfMin(AR_CONFIDENCE_CUTOFF_DEFAULT),
patt_id(-1),
patt_type(-1),
useContPoseEstimation(true)
{
}
ARMarkerSquare::~ARMarkerSquare()
{
if (m_loaded) unload();
}
bool ARMarkerSquare::unload()
{
if (m_loaded) {
freePatterns();
if (patt_type == AR_PATTERN_TYPE_TEMPLATE && patt_id != -1) {
if (m_arPattHandle) {
arPattFree(m_arPattHandle, patt_id);
m_arPattHandle = NULL;
}
}
patt_id = patt_type = -1;
m_cf = 0.0f;
m_width = 0.0f;
m_loaded = false;
}
return (true);
}
bool ARMarkerSquare::initWithPatternFile(const char* path, ARdouble width, ARPattHandle *arPattHandle)
{
// Ensure the pattern string is valid
if (!path || !arPattHandle) return false;
if (m_loaded) unload();
ARController::logv(AR_LOG_LEVEL_INFO, "Loading single AR marker from file '%s', width %f.", path, width);
m_arPattHandle = arPattHandle;
patt_id = arPattLoad(m_arPattHandle, path);
if (patt_id < 0) {
ARController::logv(AR_LOG_LEVEL_ERROR, "Error: unable to load single AR marker from file '%s'.", path);
arPattHandle = NULL;
return false;
}
patt_type = AR_PATTERN_TYPE_TEMPLATE;
m_width = width;
visible = visiblePrev = false;
// An ARPattern to hold an image of the pattern for display to the user.
allocatePatterns(1);
patterns[0]->loadTemplate(patt_id, m_arPattHandle, (float)m_width);
m_loaded = true;
return true;
}
bool ARMarkerSquare::initWithPatternFromBuffer(const char* buffer, ARdouble width, ARPattHandle *arPattHandle)
{
// Ensure the pattern string is valid
if (!buffer || !arPattHandle) return false;
if (m_loaded) unload();
ARController::logv(AR_LOG_LEVEL_INFO, "Loading single AR marker from buffer, width %f.", width);
m_arPattHandle = arPattHandle;
patt_id = arPattLoadFromBuffer(m_arPattHandle, buffer);
if (patt_id < 0) {
ARController::logv(AR_LOG_LEVEL_ERROR, "Error: unable to load single AR marker from buffer.");
return false;
}
patt_type = AR_PATTERN_TYPE_TEMPLATE;
m_width = width;
visible = visiblePrev = false;
// An ARPattern to hold an image of the pattern for display to the user.
allocatePatterns(1);
patterns[0]->loadTemplate(patt_id, arPattHandle, (float)m_width);
m_loaded = true;
return true;
}
bool ARMarkerSquare::initWithBarcode(int barcodeID, ARdouble width)
{
if (barcodeID < 0) return false;
if (m_loaded) unload();
ARController::logv(AR_LOG_LEVEL_INFO, "Adding single AR marker with barcode %d, width %f.", barcodeID, width);
patt_id = barcodeID;
patt_type = AR_PATTERN_TYPE_MATRIX;
m_width = width;
visible = visiblePrev = false;
// An ARPattern to hold an image of the pattern for display to the user.
allocatePatterns(1);
patterns[0]->loadMatrix(patt_id, AR_MATRIX_CODE_3x3, (float)m_width); // FIXME: need to determine actual matrix code type.
m_loaded = true;
return true;
}
ARdouble ARMarkerSquare::getConfidence()
{
return (m_cf);
}
ARdouble ARMarkerSquare::getConfidenceCutoff()
{
return (m_cfMin);
}
void ARMarkerSquare::setConfidenceCutoff(ARdouble value)
{
if (value >= AR_CONFIDENCE_CUTOFF_DEFAULT && value <= 1.0f) {
m_cfMin = value;
}
}
bool ARMarkerSquare::updateWithDetectedMarkers(ARMarkerInfo* markerInfo, int markerNum, AR3DHandle *ar3DHandle) {
ARController::logv(AR_LOG_LEVEL_DEBUG, "ARMarkerSquare::update(), id: %d\n", patt_id);
if (patt_id < 0) return false; // Can't update if no pattern loaded
visiblePrev = visible;
if (markerInfo) {
int k = -1;
if (patt_type == AR_PATTERN_TYPE_TEMPLATE) {
// Iterate over all detected markers.
for (int j = 0; j < markerNum; j++) {
if (patt_id == markerInfo[j].idPatt) {
// The pattern of detected trapezoid matches marker[k].
if (k == -1) {
if (markerInfo[j].cfPatt > m_cfMin) k = j; // Count as a match if match confidence exceeds cfMin.
}
else if (markerInfo[j].cfPatt > markerInfo[k].cfPatt) k = j; // Or if it exceeds match confidence of a different already matched trapezoid (i.e. assume only one instance of each marker).
}
}
if (k != -1) {
markerInfo[k].id = markerInfo[k].idPatt;
markerInfo[k].cf = markerInfo[k].cfPatt;
markerInfo[k].dir = markerInfo[k].dirPatt;
}
}
else {
for (int j = 0; j < markerNum; j++) {
if (patt_id == markerInfo[j].idMatrix) {
if (k == -1) {
if (markerInfo[j].cfMatrix >= m_cfMin) k = j; // Count as a match if match confidence exceeds cfMin.
}
else if (markerInfo[j].cfMatrix > markerInfo[k].cfMatrix) k = j; // Or if it exceeds match confidence of a different already matched trapezoid (i.e. assume only one instance of each marker).
}
}
if (k != -1) {
markerInfo[k].id = markerInfo[k].idMatrix;
markerInfo[k].cf = markerInfo[k].cfMatrix;
markerInfo[k].dir = markerInfo[k].dirMatrix;
}
}
// Consider marker visible if a match was found.
if (k != -1) {
visible = true;
m_cf = markerInfo[k].cf;
// If the model is visible, update its transformation matrix
if (visiblePrev && useContPoseEstimation) {
// If the marker was visible last time, use "cont" version of arGetTransMatSquare
arGetTransMatSquareCont(ar3DHandle, &(markerInfo[k]), trans, m_width, trans);
}
else {
// If the marker wasn't visible last time, use normal version of arGetTransMatSquare
arGetTransMatSquare(ar3DHandle, &(markerInfo[k]), m_width, trans);
}
}
else {
visible = false;
m_cf = 0.0f;
}
}
else {
visible = false;
m_cf = 0.0f;
}
return (ARMarker::update()); // Parent class will finish update.
}
|
qian256/HoloLensARToolKit
|
ARToolKitUWP/ARToolKitUWP/src/ARMarkerSquare.cpp
|
C++
|
lgpl-3.0
| 8,515 |
/*
This source file is part of KBEngine
For the latest info, see http://www.kbengine.org/
Copyright (c) 2008-2012 KBEngine.
KBEngine is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
KBEngine is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with KBEngine. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(DEFINE_IN_INTERFACE)
#undef __CELLAPPMGR_INTERFACE_H__
#endif
#ifndef __CELLAPPMGR_INTERFACE_H__
#define __CELLAPPMGR_INTERFACE_H__
// common include
#if defined(CELLAPPMGR)
#include "cellappmgr.hpp"
#endif
#include "cellappmgr_interface_macros.hpp"
#include "network/interface_defs.hpp"
//#define NDEBUG
// windows include
#if KBE_PLATFORM == PLATFORM_WIN32
#else
// linux include
#endif
namespace KBEngine{
/**
BASEAPPMGRËùÓÐÏûÏ¢½Ó¿ÚÔڴ˶¨Òå
*/
NETWORK_INTERFACE_DECLARE_BEGIN(CellappmgrInterface)
// ijapp×¢²á×Ô¼ºµÄ½Ó¿ÚµØÖ·µ½±¾app
CELLAPPMGR_MESSAGE_DECLARE_ARGS10(onRegisterNewApp, MERCURY_VARIABLE_MESSAGE,
int32, uid,
std::string, username,
int8, componentType,
uint64, componentID,
int8, globalorderID,
int8, grouporderID,
uint32, intaddr,
uint16, intport,
uint32, extaddr,
uint16, extport)
// ijappÖ÷¶¯ÇëÇólook¡£
CELLAPPMGR_MESSAGE_DECLARE_ARGS0(lookApp, MERCURY_FIXED_MESSAGE)
// ij¸öappÇëÇó²é¿´¸Ãapp¸ºÔØ×´Ì¬¡£
CELLAPPMGR_MESSAGE_DECLARE_ARGS0(queryLoad, MERCURY_FIXED_MESSAGE)
// ij¸öappÏò±¾app¸æÖª´¦Óڻ״̬¡£
CELLAPPMGR_MESSAGE_DECLARE_ARGS2(onAppActiveTick, MERCURY_FIXED_MESSAGE,
COMPONENT_TYPE, componentType,
COMPONENT_ID, componentID)
// baseEntityÇëÇó´´½¨ÔÚÒ»¸öеÄspaceÖС£
CELLAPPMGR_MESSAGE_DECLARE_STREAM(reqCreateInNewSpace, MERCURY_VARIABLE_MESSAGE)
// baseEntityÇëÇó»Ö¸´ÔÚÒ»¸öеÄspaceÖС£
CELLAPPMGR_MESSAGE_DECLARE_STREAM(reqRestoreSpaceInCell, MERCURY_VARIABLE_MESSAGE)
// ÏûϢת·¢£¬ ÓÉij¸öappÏëͨ¹ý±¾app½«ÏûϢת·¢¸øÄ³¸öapp¡£
CELLAPPMGR_MESSAGE_DECLARE_STREAM(forwardMessage, MERCURY_VARIABLE_MESSAGE)
// ÇëÇ󹨱շþÎñÆ÷
CELLAPPMGR_MESSAGE_DECLARE_STREAM(reqCloseServer, MERCURY_VARIABLE_MESSAGE)
// ÇëÇó²éѯwatcherÊý¾Ý
CELLAPPMGR_MESSAGE_DECLARE_STREAM(queryWatcher, MERCURY_VARIABLE_MESSAGE)
// ¸üÐÂcellappÐÅÏ¢¡£
CELLAPPMGR_MESSAGE_DECLARE_ARGS2(updateCellapp, MERCURY_FIXED_MESSAGE,
COMPONENT_ID, componentID,
float, load)
NETWORK_INTERFACE_DECLARE_END()
#ifdef DEFINE_IN_INTERFACE
#undef DEFINE_IN_INTERFACE
#endif
}
#endif
|
cnsoft/kbengine-cocos2dx
|
kbe/src/server/cellappmgr/cellappmgr_interface.hpp
|
C++
|
lgpl-3.0
| 3,080 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from lxml import html
import requests
import csv, codecs, cStringIO
import sys
class Person:
def __init__(self, party, name, email):
self.party = party
self.name = name
self.email = email
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
# For some very weird reason, party can contain utf-8 characters. But last_name can. Weird
party_pages = {
'Socialdemokraterna': 'http://www.riksdagen.se/sv/ledamoter-partier/Socialdemokraterna/Ledamoter/',
'Moderaterna': 'http://www.riksdagen.se/sv/ledamoter-partier/Moderata-samlingspartiet/Ledamoter/',
'Sverigedemokraterna': 'http://www.riksdagen.se/sv/ledamoter-partier/Sverigedemokraterna/Ledamoter/',
'Miljopartiet': 'http://www.riksdagen.se/sv/ledamoter-partier/Miljopartiet-de-grona/Ledamoter/',
'Centerpartiet': 'http://www.riksdagen.se/sv/ledamoter-partier/Centerpartiet/Ledamoter/',
'Vansterpartiet': 'http://www.riksdagen.se/sv/ledamoter-partier/Vansterpartiet/Ledamoter/',
'Liberalerna': 'http://www.riksdagen.se/sv/ledamoter-partier/Folkpartiet/Ledamoter/',
'Kristdemokraterna': 'http://www.riksdagen.se/sv/ledamoter-partier/Kristdemokraterna/Ledamoter/',
}
if __name__ == "__main__":
all_people = []
for party, party_page in party_pages.iteritems():
page = requests.get(party_page)
tree = html.fromstring(page.text)
# Only include "ledamöter", not "partisekreterare" and such since they don't have emails
names = tree.xpath("//*[contains(@class, 'large-12 columns alphabetical component-fellows-list')]//a[contains(@class, 'fellow-item-container')]/@href")
root = "http://www.riksdagen.se"
unique_name_list = []
for name in names:
full_url = root + name
if full_url not in unique_name_list:
unique_name_list.append(full_url)
print unique_name_list
print "unique:"
for name_url in unique_name_list:
print name_url
personal_page = requests.get(name_url)
personal_tree = html.fromstring(personal_page.text)
email_list = personal_tree.xpath("//*[contains(@class, 'scrambled-email')]/text()")
email_scrambled = email_list[0]
email = email_scrambled.replace(u'[på]', '@')
print email
name_list = personal_tree.xpath("//header/h1[contains(@class, 'biggest fellow-name')]/text()")
name = name_list[0]
name = name.replace("\n", "")
name = name.replace("\r", "")
name = name[:name.find("(")-1]
name = name.strip()
print name
print "-----"
person = Person(party, name, email)
all_people.append(person)
for person in all_people:
print person.party + ", " + person.name + ", " + person.email
with open('names.csv', 'wb') as csvfile:
fieldnames = ['name', 'email', 'party']
writer = UnicodeWriter(csvfile)
writer.writerow(fieldnames)
for person in all_people:
print person.party + ", " + person.name + ", " + person.email
writer.writerow([person.name, person.email, person.party])
|
samuelskanberg/riksdagen-crawler
|
scraper.py
|
Python
|
unlicense
| 4,168 |
<?php
class regis_kec extends kecamatan_controller{
var $controller;
function regis_kec(){
parent::__construct();
$this->controller = get_class($this);
$this->load->model('regis_kec_model','dm');
$this->load->model("coremodel","cm");
//$this->load->helper("serviceurl");
}
function index(){
$data_array=array();
$content = $this->load->view($this->controller."_view",$data_array,true);
$this->set_subtitle("Registrasi Pertanahan");
$this->set_title("Kecamatan");
$this->set_content($content);
$this->cetak();
}
function get_data() {
// show_array($userdata);
$draw = $_REQUEST['draw']; // get the requested page
$start = $_REQUEST['start'];
$limit = $_REQUEST['length']; // get how many rows we want to have into the grid
$sidx = isset($_REQUEST['order'][0]['column'])?$_REQUEST['order'][0]['column']:0; // get index row - i.e. user click to sort
$sord = isset($_REQUEST['order'][0]['dir'])?$_REQUEST['order'][0]['dir']:"asc"; // get the direction if(!$sidx) $sidx =1;
$nama_pemilik = $_REQUEST['columns'][1]['search']['value'];
$userdata = $this->session->userdata('kec_login');
$desa = $userdata['kecamatan'];
// $this->db->where('desa_tanah', $desa);
// order[0][column]
$req_param = array (
"sort_by" => $sidx,
"sort_direction" => $sord,
"limit" => null,
"nama_pemilik" => $nama_pemilik,
"desa" => $desa
);
$row = $this->dm->data($req_param)->result_array();
$count = count($row);
$req_param['limit'] = array(
'start' => $start,
'end' => $limit
);
$result = $this->dm->data($req_param)->result_array();
$arr_data = array();
foreach($result as $row) :
$id = $row['id'];
if ($row['status'] == 1) {
$action = "<div class='btn-group'>
<button type='button' class='btn btn-danger'>Pending</button>
<button type='button' class='btn btn-danger dropdown-toggle' data-toggle='dropdown'>
<span class='caret'></span>
<span class='sr-only'>Toggle Dropdown</span>
</button>
<ul class='dropdown-menu' role='menu'>
<li><a href='#' onclick=\"approved('$id')\" ><i class='fa fa-trash'></i> Menyetujui</a></li>
<li><a href='regis_kec/detail?id=$id'><i class='fa fa-edit'></i> Detail</a></li>
</ul>
</div>";
}else {
$action = '<div class="btn-group">
<button type="button" class="btn btn-success">Selsai</button>
<button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
</ul>
</div>';
}
$row['tgl_register_desa'] = flipdate($row['tgl_register_desa']);
$arr_data[] = array(
$row['tgl_register_desa'],
$row['no_register_desa'],
$row['nama_pemilik'],
$action,
);
endforeach;
$responce = array('draw' => $draw, // ($start==0)?1:$start,
'recordsTotal' => $count,
'recordsFiltered' => $count,
'data'=>$arr_data
);
echo json_encode($responce);
}
function detail(){
$get = $this->input->get();
$id = $get['id'];
$this->db->where('id',$id);
$biro_jasa = $this->db->get('tanah');
$data = $biro_jasa->row_array();
$this->db->where('id', $id);
$rs = $this->db->get('tanah');
$data = $rs->row_array();
extract($data);
$this->db->where('id', $desa_tanah);
$qr = $this->db->get('tiger_desa');
$rs = $qr->row_array();
$data['desa_tanah'] = $rs['desa'];
$this->db->where('id', $kec_tanah);
$qr = $this->db->get('tiger_kecamatan');
$rs = $qr->row_array();
$data['kec_tanah'] = $rs['kecamatan'];
$this->db->where('id', $kab_tanah);
$qr = $this->db->get('tiger_kota');
$rs = $qr->row_array();
$data['kab_tanah'] = $rs['kota'];
$data['tgl_lhr_pemilik'] = flipdate($data['tgl_lhr_pemilik']);
$data['tgl_pernyataan'] = flipdate($data['tgl_pernyataan']);
$data['tgl_register_desa'] = flipdate($data['tgl_register_desa']);
$userdata = $this->session->userdata('kec_login');
$this->db->where('kec_tanah', $userdata['kecamatan']);
$this->db->where('status', 2);
$rs = $this->db->get('tanah');
$data['no_data_kec'] = $rs->num_rows()+1;
$data['arr_kecamatan'] = $this->cm->arr_dropdown3("tiger_kecamatan", "id", "kecamatan", "kecamatan", "id_kota", "19_5");
$data['action'] = 'update';
$content = $this->load->view("regis_kec_view_form_detail",$data,true);
$this->set_subtitle("");
$this->set_title("Detail Registrasi Pertanahan");
$this->set_content($content);
$this->cetak();
}
function cek_no_reg($no_register_kec){
$this->db->where("no_register_kec",$no_register_kec);
if(empty($no_register_kec)){
$this->form_validation->set_message('cek_no_reg', ' No Registrasi Harus Di Isi');
return false;
}
if($this->db->get("tanah")->num_rows() > 0)
{
$this->form_validation->set_message('cek_no_reg', ' Sudah Ada Data Dengan No Registrasi Ini');
return false;
}
}
function update(){
$post = $this->input->post();
$this->load->library('form_validation');
$this->form_validation->set_rules('tgl_register_kec','Tanggal Registrasi','required');
$userdata = $this->session->userdata('kec_login');
$post['no_register_kec'] = $post['no_data_kec'].''.$userdata['format_reg'];
$post['no_ket_kec'] = $post['no_data_kec'].''.$userdata['format_ket'];
$this->form_validation->set_message('required', ' %s Harus diisi ');
$this->form_validation->set_error_delimiters('', '<br>');
//show_array($data);
if($this->form_validation->run() == TRUE ) {
$userdata = $this->session->userdata('kec_login');
$post['camat'] = $userdata['nama_camat'];
$post['jabatan_camat'] = $userdata['jabatan_camat'];
$post['nip_camat'] = $userdata['nip_camat'];
$post['tgl_register_kec'] = flipdate($post['tgl_register_kec']);
$post['status'] = 2;
$this->db->where("id",$post['id']);
$res = $this->db->update('tanah', $post);
if($res){
$arr = array("error"=>false,'message'=>"Register Kecamatan Berhasil");
}
else {
$arr = array("error"=>true,'message'=>"Register Kecamatan Gagal");
}
}
else {
$arr = array("error"=>true,'message'=>validation_errors());
}
echo json_encode($arr);
}
function approved(){
$get = $this->input->post();
$id = $get['id'];
$userdata = $this->session->userdata();
$this->db->where("id",$post['id']);
$res = $this->db->update('tanah', $post);
if($res){
$arr = array("error"=>false,"message"=>$this->db->last_query()." DATA BERASIL DI SETUJUI");
}
else {
$arr = array("error"=>true,"message"=>"DATA GAGAL DISETUJUI ".mysql_error());
}
//redirect('sa_birojasa_user');
echo json_encode($arr);
}
}
?>
|
NizarHafizulllah/pertanahan
|
application/modules/regis_kec/controllers/regis_kec.php
|
PHP
|
unlicense
| 8,314 |
module Collectable
extend ActiveSupport::Concern
included do
attr_readonly :collectors_count
has_many :collections, as: :target
has_many :collectors, through: :collections, class_name: 'User', source: :user
end
def collected_by?(current_user)
return false if current_user.nil?
!!collections.where(user_id: current_user.id).first
end
end
|
Edisonangela/manager
|
app/models/concerns/collectable.rb
|
Ruby
|
unlicense
| 379 |
package org.hyperic.hq.api.model;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.hyperic.hq.api.model.common.MapPropertiesAdapter;
import org.hyperic.hq.api.model.common.PropertyListMapAdapter;
@XmlRootElement(namespace=RestApiConstants.SCHEMA_NAMESPACE)
@XmlType(name="ResourceConfigType", namespace=RestApiConstants.SCHEMA_NAMESPACE)
public class ResourceConfig implements Serializable{
private static final long serialVersionUID = 8233944180632888593L;
private String resourceID;
private Map<String,String> mapProps ;
private Map<String,PropertyList> mapListProps;
public ResourceConfig() {}//EOM
public ResourceConfig(final String resourceID, final Map<String,String> mapProps, final Map<String,PropertyList> mapListProps) {
this.resourceID = resourceID ;
this.mapProps = mapProps ;
this.mapListProps = mapListProps ;
}//EOM
public final void setResourceID(final String resourceID) {
this.resourceID = resourceID ;
}//EOM
public final String getResourceID() {
return this.resourceID ;
}//EOM
public final void setMapProps(final Map<String,String> configValues) {
this.mapProps= configValues ;
}//EOM
@XmlJavaTypeAdapter(MapPropertiesAdapter.class)
public final Map<String,String> getMapProps() {
return this.mapProps ;
}//EOM
@XmlJavaTypeAdapter(PropertyListMapAdapter.class)
public Map<String,PropertyList> getMapListProps() {
return mapListProps;
}
public void setMapListProps(Map<String,PropertyList> mapListProps) {
this.mapListProps = mapListProps;
}
/**
* Adds properties to the given key if it already exists,
* otherwise adds the key with the given properties list
* @param key
* @param properties Values to add to the Property list
*/
public void putMapListProps(String key, Collection<ConfigurationValue> properties) {
if (null == this.mapListProps) {
this.mapListProps = new HashMap<String, PropertyList>();
}
if (mapListProps.containsKey(key)) {
mapListProps.get(key).addAll(properties);
} else {
mapListProps.put(key, new PropertyList(properties));
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((resourceID == null) ? 0 : resourceID.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ResourceConfig other = (ResourceConfig) obj;
if (resourceID == null) {
if (other.resourceID != null)
return false;
} else if (!resourceID.equals(other.resourceID))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder() ;
return this.toString(builder, "").toString() ;
}//EOM
public final StringBuilder toString(final StringBuilder builder, final String indentation) {
return builder.append(indentation).append("ResourceConfig [resourceID=").append(resourceID).append("\n").append(indentation).append(", mapProps=").
append(mapProps.toString().replaceAll(",", "\n"+indentation + " ")).append("]") ;
}//EOM
}//EOC
|
cc14514/hq6
|
hq-api/src/main/java/org/hyperic/hq/api/model/ResourceConfig.java
|
Java
|
unlicense
| 3,524 |
import matplotlib.pyplot as plt
import numpy as np
n = 50
x = np.random.randn(n)
y = x * np.random.randn(n)
fig, ax = plt.subplots(2, figsize=(6, 6))
ax[0].scatter(x, y, s=50)
sizes = (np.random.randn(n) * 8) ** 2
ax[1].scatter(x, y, s=sizes)
fig.show()
"""(

)"""
|
pythonpatterns/patterns
|
p0171.py
|
Python
|
unlicense
| 323 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PLCv4.Models
{
public class ApplicationRoleListViewModel
{
public string Id { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public int NumberOfUsers { get; set; }
}
}
|
AdrianPT/Eureka-PLC
|
src/PLCv4/Models/ApplicationRoleListViewModel.cs
|
C#
|
unlicense
| 369 |
/**
* Gulp Task HTML
* @author kuakman <3dimentionar@gmail.com>
**/
let fs = require('fs-extra');
let _ = require('underscore');
let spawnSync = require('child_process').spawnSync;
module.exports = function(package, args) {
return () => {
return spawnSync('./node_modules/.bin/pug', [
'--path', './src/html',
'--out', './dist',
'--obj', `\'${JSON.stringify(_.pick(package, 'name', 'version', 'profile'))}\'`, '--pretty', './src/html'
], {
cwd: process.cwd(),
stdio: 'inherit',
shell: true
});
};
};
|
kuakman/app-start-pipeline
|
scripts/html.js
|
JavaScript
|
unlicense
| 526 |
function nSplit(msg, n) {
let expr = new RegExp(".{1," + n + "}", "g");
let presplit = msg.match(expr);
let twoSplit = presplit.map((x) => {
if (x.length != n) {
let i = 0;
let ret = "";
while (i < n - x.length) {
ret += " ";
i++
};
return x + ret;
} else
return x;
});
return twoSplit;
}
function backSwap(msg) {
let newBw = "";
let newFw = "";
let newArr = [];
for (let fw = 0; fw < msg.length; fw++) {
let bw = msg.length - (fw + 1);
let myFw = msg[fw];
let myBw = msg[bw];
newFw = myBw[0] + myFw.slice(1);
newBw = myFw[0] + myBw.slice(1);
newArr[fw] = newFw;
newArr[bw] = newBw;
// console.log(fw, newFw, bw, newBw);
if (bw <= fw)
break;
}
return newArr;
}
function encode(msg, n) {
let comp_msg = msg.split(' ').join('');
let split_msg = nSplit(comp_msg, n);
return backSwap(split_msg);
}
// var myLoveMsg = "Dear Jade, I love you so much! Lets go on adventures & make memories.";
var myLoveMsg = "Ja de Il ov ey ou so mu ch .Y ou ar ew on de rf ul an da ma zi ng in so ma ny wa ys .Y ou ar et ru ly sp ec ia lt om eb ee b an dl ho pe we ca ns up po rt ea ch ot he ra nd be tw ee nu sd oa ma zi ng th in gs ❤";
// var rvLoveMsg = "se ir oa ee eI ao &e eo us nm vc a! oe gs to Ln hd ue ot ur ys vm lk ,m dm Jr ae D.";
var rvLoveMsg = ".a ge il tv ny zu mo ou sh nY eu tr bw nn re hf ol cn ea ra pi ug nn co wa py ha ds aY bu er et ou ly ip ec sa lt rm eb ae o, .n yl wo ne me sa is np zo mt da ah ut re da od ee aw oe .u cd ma sa oi eg oh In ds J❤";
var nwsMsg = myLoveMsg.split(' ').join('');
var nwsrvMsg = rvLoveMsg.split(' ').join('');
var myCode = nSplit(myLoveMsg, 2);
var nwsCode = nSplit(nwsMsg, 2);
var nwsrvCode = nSplit(nwsrvMsg, 2);
var bsmyCode = backSwap(myCode);
var bsmynwsCode = backSwap(nwsCode);
var bsmynwsrvCode = backSwap(nwsrvCode);
console.log(myLoveMsg);
// console.log(myCode.join(' '));
// console.log(bsmyCode.join(' '));
console.log(nwsCode.join(' '));
console.log(bsmynwsCode.join(' '));
console.log(nwsrvCode.join(' '));
console.log(bsmynwsrvCode.join(' '));
// let myText = encode("Hello Dawg, HEllo DAWGDJLKSAD", 2);
// console.log(myText.join(' '));
|
ConflictingTheories/scripts
|
javascript/lib/nSplit.js
|
JavaScript
|
unlicense
| 2,366 |
import enum
class H264Trellis(enum.Enum):
DISABLED = 'DISABLED'
ENABLED_FINAL_MB = 'ENABLED_FINAL_MB'
ENABLED_ALL = 'ENABLED_ALL'
|
bitmovin/bitmovin-python
|
bitmovin/resources/enums/h264_trellis.py
|
Python
|
unlicense
| 144 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Visio = Microsoft.Office.Interop.Visio;
using VisCellIndicies = Microsoft.Office.Interop.Visio.VisCellIndices;
using VisSectionIndices = Microsoft.Office.Interop.Visio.VisSectionIndices;
using VisRowIndicies = Microsoft.Office.Interop.Visio.VisRowIndices;
using VisSLO = Microsoft.Office.Interop.Visio.VisSpatialRelationCodes;
using PomExplorer.PomAccess;
using System.IO;
namespace PomExplorer.VisioDrawing
{
class PomPainter
{
private Dictionary<String, Visio.Shape> _artifactsAlreadyDrawn = new Dictionary<string, Visio.Shape>();
private Visio.Page _page;
private double _rectWidth = 2.5;
private double _rectHeight = 0.5;
private double _spacing = 0.5;
private double _centerHor;
private double _centerVert;
private double _pageTop;
private String _fontSize = "9pt";
private MavenProject _project;
private PomPainterStyle _style;
public PomPainter(Visio.Page page, MavenProject project)
{
_page = page;
_centerHor = _page.PageSheet.CellsU["PageWidth"].ResultIU / 2;
_pageTop = _page.PageSheet.CellsU["PageHeight"].ResultIU;
_centerVert = _pageTop / 2;
_project = project;
}
public void Paint(PomPainterStyle style)
{
_style = style;
if (_project.Shape == null)
{
_project.Shape = CreateRect(_project, 0, _rectHeight * 2);
}
DrawProject(_project);
}
public void DrawProject(MavenProject project)
{
if (_style == PomPainterStyle.PomDependencies || _style == PomPainterStyle.PomHierarchy) DrawDependencies(project);
if (_style == PomPainterStyle.PomHierarchy) DrawModules(project);
}
private void DrawModules(MavenProject project)
{
foreach (var module in project.Modules)
{
if (module.Project.Shape == null)
{
module.Project.Shape = CreateRect(module.Project, _centerHor, _centerVert);
}
Connect(project.Shape, module.Project.Shape);
DrawProject(module.Project);
}
}
private void DrawDependencies(MavenProject project)
{
foreach (var dependency in project.Dependencies)
{
var rectDependency = CreateRect(dependency, _centerHor, _centerVert);
Connect(project.Shape, rectDependency);
}
}
private double getBottom(Visio.Shape shape)
{
return shape.CellsU["PinY"].ResultIU+shape.CellsU["Height"].ResultIU;
}
private Visio.Shape CreateRect(Artifact artifact, double offsetX, double offsetY)
{
if (!_artifactsAlreadyDrawn.ContainsKey(artifact.ArtifactKey))
{
_artifactsAlreadyDrawn.Add(artifact.ArtifactKey, CreateRect(artifact.ArtifactSummary, offsetX, offsetY, _rectWidth, _rectHeight));
}
return _artifactsAlreadyDrawn[artifact.ArtifactKey];
}
private Visio.Shape CreateRect(String name, double offsetX, double offsetY, double width, double height)
{
Visio.Page page = Globals.ThisAddIn.Application.ActivePage;
var rect = page.DrawRectangle(_centerHor + offsetX - width / 2, _pageTop - offsetY, _centerHor + offsetX + width / 2, _pageTop - offsetY - height);
var textFont = rect.CellsSRC[(short)VisSectionIndices.visSectionCharacter, 0, (short)VisCellIndicies.visCharacterSize];
var textAlign = rect.CellsSRC[(short)VisSectionIndices.visSectionCharacter, 0, (short)VisCellIndicies.visHorzAlign];
textFont.FormulaU = _fontSize;
rect.Text = name;
textAlign.FormulaU = "0";
return rect;
}
private void Connect(Visio.Shape shape1, Visio.Shape shape2)
{
var cn = _page.Application.ConnectorToolDataObject;
var connector = _page.Drop(cn, 3, 3) as Visio.Shape;
// https://msdn.microsoft.com/en-us/library/office/ff767991.aspx
var anchorShape1 = shape1.CellsSRC[1, 1, 0];
var beginConnector = connector.CellsU["BeginX"];
var anchorShape2 = shape2.CellsSRC[1, 1, 0];
var endConnector = connector.CellsU["EndX"];
beginConnector.GlueTo(anchorShape1);
endConnector.GlueTo(anchorShape2);
connector.CellsSRC[(short)VisSectionIndices.visSectionObject, (short)VisRowIndicies.visRowLine, (short)VisCellIndicies.visLineEndArrow].FormulaU = "13";
connector.CellsSRC[(short)VisSectionIndices.visSectionObject, (short)VisRowIndicies.visRowShapeLayout, (short)VisCellIndicies.visLineEndArrow].FormulaU = "1";
connector.CellsSRC[(short)VisSectionIndices.visSectionObject, (short)VisRowIndicies.visRowShapeLayout, (short)VisCellIndicies.visSLOLineRouteExt].FormulaU = "16";
}
}
}
|
mamu7211/VisioPomAnalyzer
|
PomExplorer/PomExplorer/VisioDrawing/PomPainter.cs
|
C#
|
unlicense
| 5,331 |
#!/usr/local/bin/elev8
var EXPAND_BOTH = { x : 1.0, y : 1.0 };
var FILL_BOTH = { x : -1.0, y : -1.0 };
var logo_icon = elm.Icon ({
image : elm.datadir + "data/images/logo_small.png",
});
var logo_icon_unscaled = elm.Icon ({
image : elm.datadir + "data/images/logo_small.png",
resizable_up : false,
resizable_down : false,
});
var desc = elm.Window({
title : "Radios demo",
elements : {
the_background : elm.Background ({
weight : EXPAND_BOTH,
resize : true,
}),
radio_box : elm.Box ({
weight : EXPAND_BOTH,
resize : true,
elements : {
sized_radio_icon : elm.Radio ({
icon : logo_icon,
label : "Icon sized to radio",
weight : EXPAND_BOTH,
align : { x : 1.0, y : 0.5 },
value : 0,
group : "rdg",
}),
unscaled_radio_icon : elm.Radio ({
icon : logo_icon_unscaled,
label : "Icon no scale",
weight : EXPAND_BOTH,
align : { x : 1.0, y : 0.5 },
value : 1,
group : "rdg",
}),
label_only_radio : elm.Radio ({
label : "Label Only",
value : 2,
group : "rdg",
}),
disabled_radio : elm.Radio ({
label : "Disabled",
enabled : false,
value : 3,
group : "rdg",
}),
icon_radio : elm.Radio ({
icon : logo_icon_unscaled,
value : 4,
group : "rdg",
}),
disabled_icon_radio : elm.Radio ({
enabled : false,
icon : logo_icon_unscaled,
value : 5,
group : "rdg",
}),
},
}),
},
});
var win = elm.realise(desc);
|
maikodaraine/EnlightenmentUbuntu
|
bindings/elev8/data/javascript/radio.js
|
JavaScript
|
unlicense
| 2,132 |
#include <iostream>
int main(int argc, char const *argv[])
{
int x = 1;
int y = 9;
printf("0. x:%i y:%i\n",x,y);
//newbie
int s;
s = x;
x = y;
y = s;
printf("1. x:%i y:%i\n",x,y);
//hacker
x=x+y;
y=x-y;
x=x-y;
printf("2. x:%i y:%i\n",x,y);
//pro hacker
x^=y;
y^=x;
x^=y;
printf("3. x:%i y:%i\n",x,y);
return 0;
}
|
varpeti/Suli
|
Angol/Előad/p009.cpp
|
C++
|
unlicense
| 399 |
package crazypants.enderio.conduits.conduit.redstone;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.enderio.core.api.client.gui.ITabPanel;
import com.enderio.core.common.util.DyeColor;
import com.enderio.core.common.util.NNList;
import com.enderio.core.common.util.NullHelper;
import com.enderio.core.common.vecmath.Vector4f;
import com.google.common.collect.Lists;
import crazypants.enderio.base.EnderIO;
import crazypants.enderio.base.conduit.ConduitUtil;
import crazypants.enderio.base.conduit.ConnectionMode;
import crazypants.enderio.base.conduit.IClientConduit;
import crazypants.enderio.base.conduit.IConduit;
import crazypants.enderio.base.conduit.IConduitNetwork;
import crazypants.enderio.base.conduit.IConduitTexture;
import crazypants.enderio.base.conduit.IGuiExternalConnection;
import crazypants.enderio.base.conduit.RaytraceResult;
import crazypants.enderio.base.conduit.geom.CollidableComponent;
import crazypants.enderio.base.conduit.redstone.ConnectivityTool;
import crazypants.enderio.base.conduit.redstone.signals.BundledSignal;
import crazypants.enderio.base.conduit.redstone.signals.CombinedSignal;
import crazypants.enderio.base.conduit.redstone.signals.Signal;
import crazypants.enderio.base.conduit.registry.ConduitRegistry;
import crazypants.enderio.base.diagnostics.Prof;
import crazypants.enderio.base.filter.FilterRegistry;
import crazypants.enderio.base.filter.capability.CapabilityFilterHolder;
import crazypants.enderio.base.filter.capability.IFilterHolder;
import crazypants.enderio.base.filter.gui.FilterGuiUtil;
import crazypants.enderio.base.filter.redstone.DefaultInputSignalFilter;
import crazypants.enderio.base.filter.redstone.DefaultOutputSignalFilter;
import crazypants.enderio.base.filter.redstone.IInputSignalFilter;
import crazypants.enderio.base.filter.redstone.IOutputSignalFilter;
import crazypants.enderio.base.filter.redstone.IRedstoneSignalFilter;
import crazypants.enderio.base.filter.redstone.items.IItemInputSignalFilterUpgrade;
import crazypants.enderio.base.filter.redstone.items.IItemOutputSignalFilterUpgrade;
import crazypants.enderio.base.render.registry.TextureRegistry;
import crazypants.enderio.base.tool.ToolUtil;
import crazypants.enderio.conduits.conduit.AbstractConduit;
import crazypants.enderio.conduits.config.ConduitConfig;
import crazypants.enderio.conduits.gui.RedstoneSettings;
import crazypants.enderio.conduits.render.BlockStateWrapperConduitBundle;
import crazypants.enderio.conduits.render.ConduitTexture;
import crazypants.enderio.powertools.lang.Lang;
import crazypants.enderio.util.EnumReader;
import crazypants.enderio.util.Prep;
import net.minecraft.block.Block;
import net.minecraft.block.BlockRedstoneWire;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.world.World;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import static crazypants.enderio.conduits.init.ConduitObject.item_redstone_conduit;
public class InsulatedRedstoneConduit extends AbstractConduit implements IRedstoneConduit, IFilterHolder<IRedstoneSignalFilter> {
static final Map<String, IConduitTexture> ICONS = new HashMap<>();
static {
ICONS.put(KEY_INS_CORE_OFF_ICON, new ConduitTexture(TextureRegistry.registerTexture("blocks/conduit_core_1"), ConduitTexture.core(3)));
ICONS.put(KEY_INS_CORE_ON_ICON, new ConduitTexture(TextureRegistry.registerTexture("blocks/conduit_core_0"), ConduitTexture.core(3)));
ICONS.put(KEY_INS_CONDUIT_ICON, new ConduitTexture(TextureRegistry.registerTexture("blocks/conduit"), ConduitTexture.arm(1)));
ICONS.put(KEY_CONDUIT_ICON, new ConduitTexture(TextureRegistry.registerTexture("blocks/conduit"), ConduitTexture.arm(3)));
ICONS.put(KEY_TRANSMISSION_ICON, new ConduitTexture(TextureRegistry.registerTexture("blocks/conduit"), ConduitTexture.arm(2)));
}
// --------------------------------- Class Start
// -------------------------------------------
private final EnumMap<EnumFacing, IRedstoneSignalFilter> outputFilters = new EnumMap<EnumFacing, IRedstoneSignalFilter>(EnumFacing.class);
private final EnumMap<EnumFacing, IRedstoneSignalFilter> inputFilters = new EnumMap<EnumFacing, IRedstoneSignalFilter>(EnumFacing.class);
private final EnumMap<EnumFacing, ItemStack> outputFilterUpgrades = new EnumMap<EnumFacing, ItemStack>(EnumFacing.class);
private final EnumMap<EnumFacing, ItemStack> inputFilterUpgrades = new EnumMap<EnumFacing, ItemStack>(EnumFacing.class);
private Map<EnumFacing, ConnectionMode> forcedConnections = new EnumMap<EnumFacing, ConnectionMode>(EnumFacing.class);
private Map<EnumFacing, DyeColor> inputSignalColors = new EnumMap<EnumFacing, DyeColor>(EnumFacing.class);
private Map<EnumFacing, DyeColor> outputSignalColors = new EnumMap<EnumFacing, DyeColor>(EnumFacing.class);
private Map<EnumFacing, Boolean> signalStrengths = new EnumMap<EnumFacing, Boolean>(EnumFacing.class);
private RedstoneConduitNetwork network;
private int activeUpdateCooldown = 0;
private boolean activeDirty = false;
private boolean connectionsDirty = false; // TODO: can this be merged with super.connectionsDirty?
private int signalIdBase = 0;
@SuppressWarnings("unused")
public InsulatedRedstoneConduit() {
}
@Override
public @Nullable RedstoneConduitNetwork getNetwork() {
return network;
}
@Override
public boolean setNetwork(@Nonnull IConduitNetwork<?, ?> network) {
this.network = (RedstoneConduitNetwork) network;
return super.setNetwork(network);
}
@Override
public void clearNetwork() {
this.network = null;
}
@Override
@Nonnull
public Class<? extends IConduit> getBaseConduitType() {
return IRedstoneConduit.class;
}
@Override
public void updateNetwork() {
World world = getBundle().getEntity().getWorld();
if (NullHelper.untrust(world) != null) {
updateNetwork(world);
}
}
@Override
public void updateEntity(@Nonnull World world) {
super.updateEntity(world);
if (!world.isRemote) {
if (activeUpdateCooldown > 0) {
--activeUpdateCooldown;
Prof.start(world, "updateActiveState");
updateActiveState();
Prof.stop(world);
}
if (connectionsDirty) {
if (hasExternalConnections()) {
network.updateInputsFromConduit(this, false);
}
connectionsDirty = false;
}
}
}
@Override
public void setActive(boolean active) {
if (active != this.active) {
activeDirty = true;
}
this.active = active;
updateActiveState();
}
private void updateActiveState() {
if (ConduitConfig.showState.get() && activeDirty && activeUpdateCooldown == 0) {
setClientStateDirty();
activeDirty = false;
activeUpdateCooldown = 4;
}
}
@Override
public void onChunkUnload() {
RedstoneConduitNetwork networkR = getNetwork();
if (networkR != null) {
BundledSignal oldSignals = networkR.getBundledSignal();
List<IRedstoneConduit> conduits = Lists.newArrayList(networkR.getConduits());
super.onChunkUnload();
networkR.afterChunkUnload(conduits, oldSignals);
}
}
@Override
public boolean onBlockActivated(@Nonnull EntityPlayer player, @Nonnull EnumHand hand, @Nonnull RaytraceResult res, @Nonnull List<RaytraceResult> all) {
World world = getBundle().getEntity().getWorld();
DyeColor col = DyeColor.getColorFromDye(player.getHeldItem(hand));
final CollidableComponent component = res.component;
if (col != null && component != null && component.isDirectional()) {
if (!world.isRemote) {
if (getConnectionMode(component.getDirection()).acceptsInput()) {
// Note: There's no way to set the input color in IN_OUT mode...
setOutputSignalColor(component.getDirection(), col);
} else {
setInputSignalColor(component.getDirection(), col);
}
}
return true;
} else if (ToolUtil.isToolEquipped(player, hand)) {
if (world.isRemote) {
return true;
}
if (component != null) {
EnumFacing faceHit = res.movingObjectPosition.sideHit;
if (component.isCore()) {
BlockPos pos = getBundle().getLocation().offset(faceHit);
Block id = world.getBlockState(pos).getBlock();
if (id == ConduitRegistry.getConduitModObjectNN().getBlock()) {
IRedstoneConduit neighbour = ConduitUtil.getConduit(world, pos.getX(), pos.getY(), pos.getZ(), IRedstoneConduit.class);
if (neighbour != null && neighbour.getConnectionMode(faceHit.getOpposite()) == ConnectionMode.DISABLED) {
neighbour.setConnectionMode(faceHit.getOpposite(), ConnectionMode.NOT_SET);
}
setConnectionMode(faceHit, ConnectionMode.NOT_SET);
return ConduitUtil.connectConduits(this, faceHit);
}
forceConnectionMode(faceHit, ConnectionMode.IN_OUT);
return true;
} else {
EnumFacing connDir = component.getDirection();
if (externalConnections.contains(connDir)) {
if (network != null) {
network.destroyNetwork();
}
externalConnectionRemoved(connDir);
forceConnectionMode(connDir, ConnectionMode.getNext(getConnectionMode(connDir)));
return true;
} else if (containsConduitConnection(connDir)) {
BlockPos pos = getBundle().getLocation().offset(connDir);
IRedstoneConduit neighbour = ConduitUtil.getConduit(getBundle().getEntity().getWorld(), pos.getX(), pos.getY(), pos.getZ(), IRedstoneConduit.class);
if (neighbour != null) {
if (network != null) {
network.destroyNetwork();
}
final RedstoneConduitNetwork neighbourNetwork = neighbour.getNetwork();
if (neighbourNetwork != null) {
neighbourNetwork.destroyNetwork();
}
neighbour.conduitConnectionRemoved(connDir.getOpposite());
conduitConnectionRemoved(connDir);
neighbour.connectionsChanged();
connectionsChanged();
updateNetwork();
neighbour.updateNetwork();
return true;
}
}
}
}
}
return false;
}
@Override
public void forceConnectionMode(@Nonnull EnumFacing dir, @Nonnull ConnectionMode mode) {
setConnectionMode(dir, mode);
forcedConnections.put(dir, mode);
onAddedToBundle();
if (network != null) {
network.updateInputsFromConduit(this, false);
}
}
@Override
@Nonnull
public ItemStack createItem() {
return new ItemStack(item_redstone_conduit.getItemNN(), 1, 0);
}
@Override
public void onInputsChanged(@Nonnull EnumFacing side, int[] inputValues) {
}
@Override
public void onInputChanged(@Nonnull EnumFacing side, int inputValue) {
}
@Override
@Nonnull
public DyeColor getInputSignalColor(@Nonnull EnumFacing dir) {
DyeColor res = inputSignalColors.get(dir);
if (res == null) {
return DyeColor.RED;
}
return res;
}
@Override
public void setInputSignalColor(@Nonnull EnumFacing dir, @Nonnull DyeColor col) {
inputSignalColors.put(dir, col);
if (network != null) {
network.updateInputsFromConduit(this, false);
}
setClientStateDirty();
collidablesDirty = true;
}
@Override
@Nonnull
public DyeColor getOutputSignalColor(@Nonnull EnumFacing dir) {
DyeColor res = outputSignalColors.get(dir);
if (res == null) {
return DyeColor.GREEN;
}
return res;
}
@Override
public void setOutputSignalColor(@Nonnull EnumFacing dir, @Nonnull DyeColor col) {
outputSignalColors.put(dir, col);
if (network != null) {
network.updateInputsFromConduit(this, false);
}
setClientStateDirty();
collidablesDirty = true;
}
@Override
public boolean isOutputStrong(@Nonnull EnumFacing dir) {
if (signalStrengths.containsKey(dir)) {
return signalStrengths.get(dir);
}
return false;
}
@Override
public void setOutputStrength(@Nonnull EnumFacing dir, boolean isStrong) {
if (isOutputStrong(dir) != isStrong) {
if (isStrong) {
signalStrengths.put(dir, isStrong);
} else {
signalStrengths.remove(dir);
}
if (network != null) {
network.notifyNeigborsOfSignalUpdate();
}
}
}
@Override
public boolean canConnectToExternal(@Nonnull EnumFacing direction, boolean ignoreConnectionState) {
if (ignoreConnectionState) { // you can always force an external connection
return true;
}
ConnectionMode forcedConnection = forcedConnections.get(direction);
if (forcedConnection == ConnectionMode.DISABLED) {
return false;
} else if (forcedConnection == ConnectionMode.IN_OUT || forcedConnection == ConnectionMode.OUTPUT || forcedConnection == ConnectionMode.INPUT) {
return true;
}
// Not set so figure it out
World world = getBundle().getBundleworld();
BlockPos pos = getBundle().getLocation().offset(direction);
IBlockState bs = world.getBlockState(pos);
if (bs.getBlock() == ConduitRegistry.getConduitModObjectNN().getBlock()) {
return false;
}
return ConnectivityTool.shouldAutoConnectRedstone(world, bs, pos, direction.getOpposite());
}
@Override
public int isProvidingWeakPower(@Nonnull EnumFacing toDirection) {
toDirection = toDirection.getOpposite();
if (!getConnectionMode(toDirection).acceptsInput()) {
return 0;
}
if (network == null || !network.isNetworkEnabled()) {
return 0;
}
int result = 0;
CombinedSignal signal = getNetworkOutput(toDirection);
result = Math.max(result, signal.getStrength());
return result;
}
@Override
public int isProvidingStrongPower(@Nonnull EnumFacing toDirection) {
if (isOutputStrong(toDirection.getOpposite())) {
return isProvidingWeakPower(toDirection);
} else {
return 0;
}
}
@Override
@Nonnull
public CombinedSignal getNetworkOutput(@Nonnull EnumFacing side) {
ConnectionMode mode = getConnectionMode(side);
if (network == null || !mode.acceptsInput()) {
return CombinedSignal.NONE;
}
DyeColor col = getOutputSignalColor(side);
BundledSignal bundledSignal = network.getBundledSignal();
return bundledSignal.getFilteredSignal(col, (IOutputSignalFilter) getSignalFilter(side, true));
}
@Override
@Nonnull
public Signal getNetworkInput(@Nonnull EnumFacing side) {
if (network != null) {
network.setNetworkEnabled(false);
}
CombinedSignal result = CombinedSignal.NONE;
if (acceptSignalsForDir(side)) {
int input = getExternalPowerLevel(side);
result = new CombinedSignal(input);
IInputSignalFilter filter = (IInputSignalFilter) getSignalFilter(side, false);
result = filter.apply(result, getBundle().getBundleworld(), getBundle().getLocation().offset(side));
}
if (network != null) {
network.setNetworkEnabled(true);
}
return new Signal(result, signalIdBase + side.ordinal());
}
protected int getExternalPowerLevelProtected(@Nonnull EnumFacing side) {
if (network != null) {
network.setNetworkEnabled(false);
}
int input = getExternalPowerLevel(side);
if (network != null) {
network.setNetworkEnabled(true);
}
return input;
}
protected int getExternalPowerLevel(@Nonnull EnumFacing dir) {
World world = getBundle().getBundleworld();
BlockPos loc = getBundle().getLocation().offset(dir);
int res = 0;
if (world.isBlockLoaded(loc)) {
int strong = world.getStrongPower(loc, dir);
if (strong > 0) {
return strong;
}
res = world.getRedstonePower(loc, dir);
IBlockState bs = world.getBlockState(loc);
Block block = bs.getBlock();
if (res <= 15 && block == Blocks.REDSTONE_WIRE) {
int wireIn = bs.getValue(BlockRedstoneWire.POWER);
res = Math.max(res, wireIn);
}
}
return res;
}
// @Optional.Method(modid = "computercraft")
// @Override
// @Nonnull
// public Map<DyeColor, Signal> getComputerCraftSignals(@Nonnull EnumFacing side) {
// Map<DyeColor, Signal> ccSignals = new EnumMap<DyeColor, Signal>(DyeColor.class);
//
// int bundledInput = getComputerCraftBundledPowerLevel(side);
// if (bundledInput >= 0) {
// for (int i = 0; i < 16; i++) {
// int color = bundledInput >>> i & 1;
// Signal signal = new Signal(color == 1 ? 16 : 0, signalIdBase + side.ordinal());
// ccSignals.put(DyeColor.fromIndex(Math.max(0, 15 - i)), signal);
// }
// }
//
// return ccSignals;
// }
// @Optional.Method(modid = "computercraft")
// private int getComputerCraftBundledPowerLevel(EnumFacing dir) {
// World world = getBundle().getBundleworld();
// BlockPos pos = getBundle().getLocation().offset(dir);
//
// if (world.isBlockLoaded(pos)) {
// return ComputerCraftAPI.getBundledRedstoneOutput(world, pos, dir.getOpposite());
// } else {
// return -1;
// }
// }
@Override
@Nonnull
public ConnectionMode getConnectionMode(@Nonnull EnumFacing dir) {
ConnectionMode res = forcedConnections.get(dir);
if (res == null) {
return getDefaultConnectionMode();
}
return res;
}
@Override
@Nonnull
public ConnectionMode getDefaultConnectionMode() {
return ConnectionMode.OUTPUT;
}
@Override
@Nonnull
public NNList<ItemStack> getDrops() {
NNList<ItemStack> res = super.getDrops();
for (ItemStack stack : inputFilterUpgrades.values()) {
if (stack != null && Prep.isValid(stack)) {
res.add(stack);
}
}
for (ItemStack stack : outputFilterUpgrades.values()) {
if (stack != null && Prep.isValid(stack)) {
res.add(stack);
}
}
return res;
}
@Override
public boolean onNeighborBlockChange(@Nonnull Block blockId) {
World world = getBundle().getBundleworld();
if (world.isRemote) {
return false;
}
boolean res = super.onNeighborBlockChange(blockId);
if (network == null || network.updatingNetwork) {
return false;
}
if (blockId != ConduitRegistry.getConduitModObjectNN().getBlock()) {
connectionsDirty = true;
}
return res;
}
private boolean acceptSignalsForDir(@Nonnull EnumFacing dir) {
if (!getConnectionMode(dir).acceptsOutput()) {
return false;
}
BlockPos loc = getBundle().getLocation().offset(dir);
return ConduitUtil.getConduit(getBundle().getEntity().getWorld(), loc.getX(), loc.getY(), loc.getZ(), IRedstoneConduit.class) == null;
}
// ---------------------
// TEXTURES
// ---------------------
@Override
public int getRedstoneSignalForColor(@Nonnull DyeColor col) {
if (network != null) {
return network.getSignalStrengthForColor(col);
}
return 0;
}
@SuppressWarnings("null")
@Override
@Nonnull
public IConduitTexture getTextureForState(@Nonnull CollidableComponent component) {
if (component.isCore()) {
return ConduitConfig.showState.get() && isActive() ? ICONS.get(KEY_INS_CORE_ON_ICON) : ICONS.get(KEY_INS_CORE_OFF_ICON);
}
return ICONS.get(KEY_INS_CONDUIT_ICON);
}
@SuppressWarnings("null")
@Override
@Nonnull
public IConduitTexture getTransmitionTextureForState(@Nonnull CollidableComponent component) {
return ConduitConfig.showState.get() && isActive() ? ICONS.get(KEY_TRANSMISSION_ICON) : ICONS.get(KEY_CONDUIT_ICON);
}
@Override
@SideOnly(Side.CLIENT)
public @Nullable Vector4f getTransmitionTextureColorForState(@Nonnull CollidableComponent component) {
return null;
}
@Override
protected void readTypeSettings(@Nonnull EnumFacing dir, @Nonnull NBTTagCompound dataRoot) {
forceConnectionMode(dir, EnumReader.get(ConnectionMode.class, dataRoot.getShort("connectionMode")));
setInputSignalColor(dir, EnumReader.get(DyeColor.class, dataRoot.getShort("inputSignalColor")));
setOutputSignalColor(dir, EnumReader.get(DyeColor.class, dataRoot.getShort("outputSignalColor")));
setOutputStrength(dir, dataRoot.getBoolean("signalStrong"));
}
@Override
protected void writeTypeSettingsToNbt(@Nonnull EnumFacing dir, @Nonnull NBTTagCompound dataRoot) {
dataRoot.setShort("connectionMode", (short) forcedConnections.get(dir).ordinal());
dataRoot.setShort("inputSignalColor", (short) getInputSignalColor(dir).ordinal());
dataRoot.setShort("outputSignalColor", (short) getOutputSignalColor(dir).ordinal());
dataRoot.setBoolean("signalStrong", isOutputStrong(dir));
}
@Override
public void writeToNBT(@Nonnull NBTTagCompound nbtRoot) {
super.writeToNBT(nbtRoot);
if (!forcedConnections.isEmpty()) {
byte[] modes = new byte[6];
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
ConnectionMode mode = forcedConnections.get(dir);
if (mode != null) {
modes[i] = (byte) mode.ordinal();
} else {
modes[i] = -1;
}
i++;
}
nbtRoot.setByteArray("forcedConnections", modes);
}
if (!inputSignalColors.isEmpty()) {
byte[] modes = new byte[6];
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
DyeColor col = inputSignalColors.get(dir);
if (col != null) {
modes[i] = (byte) col.ordinal();
} else {
modes[i] = -1;
}
i++;
}
nbtRoot.setByteArray("signalColors", modes);
}
if (!outputSignalColors.isEmpty()) {
byte[] modes = new byte[6];
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
DyeColor col = outputSignalColors.get(dir);
if (col != null) {
modes[i] = (byte) col.ordinal();
} else {
modes[i] = -1;
}
i++;
}
nbtRoot.setByteArray("outputSignalColors", modes);
}
if (!signalStrengths.isEmpty()) {
byte[] modes = new byte[6];
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
boolean isStrong = dir != null && isOutputStrong(dir);
if (isStrong) {
modes[i] = 1;
} else {
modes[i] = 0;
}
i++;
}
nbtRoot.setByteArray("signalStrengths", modes);
}
for (Entry<EnumFacing, IRedstoneSignalFilter> entry : inputFilters.entrySet()) {
if (entry.getValue() != null) {
IRedstoneSignalFilter f = entry.getValue();
NBTTagCompound itemRoot = new NBTTagCompound();
FilterRegistry.writeFilterToNbt(f, itemRoot);
nbtRoot.setTag("inSignalFilts." + entry.getKey().name(), itemRoot);
}
}
for (Entry<EnumFacing, IRedstoneSignalFilter> entry : outputFilters.entrySet()) {
if (entry.getValue() != null) {
IRedstoneSignalFilter f = entry.getValue();
NBTTagCompound itemRoot = new NBTTagCompound();
FilterRegistry.writeFilterToNbt(f, itemRoot);
nbtRoot.setTag("outSignalFilts." + entry.getKey().name(), itemRoot);
}
}
for (Entry<EnumFacing, ItemStack> entry : inputFilterUpgrades.entrySet()) {
ItemStack up = entry.getValue();
if (up != null && Prep.isValid(up)) {
IRedstoneSignalFilter filter = getSignalFilter(entry.getKey(), true);
FilterRegistry.writeFilterToStack(filter, up);
NBTTagCompound itemRoot = new NBTTagCompound();
up.writeToNBT(itemRoot);
nbtRoot.setTag("inputSignalFilterUpgrades." + entry.getKey().name(), itemRoot);
}
}
for (Entry<EnumFacing, ItemStack> entry : outputFilterUpgrades.entrySet()) {
ItemStack up = entry.getValue();
if (up != null && Prep.isValid(up)) {
IRedstoneSignalFilter filter = getSignalFilter(entry.getKey(), false);
FilterRegistry.writeFilterToStack(filter, up);
NBTTagCompound itemRoot = new NBTTagCompound();
up.writeToNBT(itemRoot);
nbtRoot.setTag("outputSignalFilterUpgrades." + entry.getKey().name(), itemRoot);
}
}
}
@Override
public void readFromNBT(@Nonnull NBTTagCompound nbtRoot) {
super.readFromNBT(nbtRoot);
forcedConnections.clear();
byte[] modes = nbtRoot.getByteArray("forcedConnections");
if (modes.length == 6) {
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
if (modes[i] >= 0) {
forcedConnections.put(dir, ConnectionMode.values()[modes[i]]);
}
i++;
}
}
inputSignalColors.clear();
byte[] cols = nbtRoot.getByteArray("signalColors");
if (cols.length == 6) {
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
if (cols[i] >= 0) {
inputSignalColors.put(dir, DyeColor.values()[cols[i]]);
}
i++;
}
}
outputSignalColors.clear();
byte[] outCols = nbtRoot.getByteArray("outputSignalColors");
if (outCols.length == 6) {
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
if (outCols[i] >= 0) {
outputSignalColors.put(dir, DyeColor.values()[outCols[i]]);
}
i++;
}
}
signalStrengths.clear();
byte[] strengths = nbtRoot.getByteArray("signalStrengths");
if (strengths.length == 6) {
int i = 0;
for (EnumFacing dir : EnumFacing.VALUES) {
if (strengths[i] > 0) {
signalStrengths.put(dir, true);
}
i++;
}
}
inputFilters.clear();
outputFilters.clear();
inputFilterUpgrades.clear();
outputFilterUpgrades.clear();
for (EnumFacing dir : EnumFacing.VALUES) {
String key = "inSignalFilts." + dir.name();
if (nbtRoot.hasKey(key)) {
NBTTagCompound filterTag = (NBTTagCompound) nbtRoot.getTag(key);
IRedstoneSignalFilter filter = (IRedstoneSignalFilter) FilterRegistry.loadFilterFromNbt(filterTag);
inputFilters.put(dir, filter);
}
key = "inputSignalFilterUpgrades." + dir.name();
if (nbtRoot.hasKey(key)) {
NBTTagCompound upTag = (NBTTagCompound) nbtRoot.getTag(key);
ItemStack ups = new ItemStack(upTag);
inputFilterUpgrades.put(dir, ups);
}
key = "outputSignalFilterUpgrades." + dir.name();
if (nbtRoot.hasKey(key)) {
NBTTagCompound upTag = (NBTTagCompound) nbtRoot.getTag(key);
ItemStack ups = new ItemStack(upTag);
outputFilterUpgrades.put(dir, ups);
}
key = "outSignalFilts." + dir.name();
if (nbtRoot.hasKey(key)) {
NBTTagCompound filterTag = (NBTTagCompound) nbtRoot.getTag(key);
IRedstoneSignalFilter filter = (IRedstoneSignalFilter) FilterRegistry.loadFilterFromNbt(filterTag);
outputFilters.put(dir, filter);
}
}
}
@Override
public String toString() {
return "RedstoneConduit [network=" + network + " connections=" + conduitConnections + " active=" + active + "]";
}
@SideOnly(Side.CLIENT)
@Override
public void hashCodeForModelCaching(BlockStateWrapperConduitBundle.ConduitCacheKey hashCodes) {
super.hashCodeForModelCaching(hashCodes);
hashCodes.addEnum(inputSignalColors);
hashCodes.addEnum(outputSignalColors);
if (ConduitConfig.showState.get() && isActive()) {
hashCodes.add(1);
}
}
@Override
public @Nonnull RedstoneConduitNetwork createNetworkForType() {
return new RedstoneConduitNetwork();
}
@SideOnly(Side.CLIENT)
@Nonnull
@Override
public ITabPanel createGuiPanel(@Nonnull IGuiExternalConnection gui, @Nonnull IClientConduit con) {
return new RedstoneSettings(gui, con);
}
@Override
@SideOnly(Side.CLIENT)
public boolean updateGuiPanel(@Nonnull ITabPanel panel) {
if (panel instanceof RedstoneSettings) {
return ((RedstoneSettings) panel).updateConduit(this);
}
return false;
}
@SideOnly(Side.CLIENT)
@Override
public int getGuiPanelTabOrder() {
return 2;
}
// ----------------- CAPABILITIES ------------
@Override
public boolean hasInternalCapability(@Nonnull Capability<?> capability, @Nullable EnumFacing facing) {
if (capability == CapabilityFilterHolder.FILTER_HOLDER_CAPABILITY) {
return true;
}
return super.hasInternalCapability(capability, facing);
}
@Override
@Nullable
public <T> T getInternalCapability(@Nonnull Capability<T> capability, @Nullable EnumFacing facing) {
if (capability == CapabilityFilterHolder.FILTER_HOLDER_CAPABILITY) {
return CapabilityFilterHolder.FILTER_HOLDER_CAPABILITY.cast(this);
}
return super.getInternalCapability(capability, facing);
}
// -------------------------------------------
// FILTERS
// -------------------------------------------
@Override
public void setSignalIdBase(int id) {
signalIdBase = id;
}
@Override
@Nonnull
public IRedstoneSignalFilter getSignalFilter(@Nonnull EnumFacing dir, boolean isOutput) {
if (!isOutput) {
return NullHelper.first(inputFilters.get(dir), DefaultInputSignalFilter.instance);
} else {
return NullHelper.first(outputFilters.get(dir), DefaultOutputSignalFilter.instance);
}
}
public void setSignalFilter(@Nonnull EnumFacing dir, boolean isInput, @Nonnull IRedstoneSignalFilter filter) {
if (!isInput) {
inputFilters.put(dir, filter);
} else {
outputFilters.put(dir, filter);
}
setClientStateDirty();
connectionsDirty = true;
}
@Override
public @Nonnull IRedstoneSignalFilter getFilter(int filterIndex, int param1) {
return getSignalFilter(EnumFacing.getFront(param1), filterIndex == getInputFilterIndex() ? true : !(filterIndex == getOutputFilterIndex()));
}
@Override
public void setFilter(int filterIndex, int param1, @Nonnull IRedstoneSignalFilter filter) {
setSignalFilter(EnumFacing.getFront(param1), filterIndex == getInputFilterIndex() ? true : !(filterIndex == getOutputFilterIndex()), filter);
}
@Override
@Nonnull
public ItemStack getFilterStack(int filterIndex, int param1) {
if (filterIndex == getInputFilterIndex()) {
return NullHelper.first(inputFilterUpgrades.get(EnumFacing.getFront(param1)), Prep.getEmpty());
} else if (filterIndex == getOutputFilterIndex()) {
return NullHelper.first(outputFilterUpgrades.get(EnumFacing.getFront(param1)), Prep.getEmpty());
}
return Prep.getEmpty();
}
@Override
public void setFilterStack(int filterIndex, int param1, @Nonnull ItemStack stack) {
if (filterIndex == getInputFilterIndex()) {
if (Prep.isValid(stack)) {
inputFilterUpgrades.put(EnumFacing.getFront(param1), stack);
} else {
inputFilterUpgrades.remove(EnumFacing.getFront(param1));
}
} else if (filterIndex == getOutputFilterIndex()) {
if (Prep.isValid(stack)) {
outputFilterUpgrades.put(EnumFacing.getFront(param1), stack);
} else {
outputFilterUpgrades.remove(EnumFacing.getFront(param1));
}
}
final IRedstoneSignalFilter filterForUpgrade = FilterRegistry.<IRedstoneSignalFilter> getFilterForUpgrade(stack);
if (filterForUpgrade != null) {
setFilter(filterIndex, param1, filterForUpgrade);
}
}
@Override
public int getInputFilterIndex() {
return FilterGuiUtil.INDEX_INPUT_REDSTONE;
}
@Override
public int getOutputFilterIndex() {
return FilterGuiUtil.INDEX_OUTPUT_REDSTONE;
}
@Override
public boolean isFilterUpgradeAccepted(@Nonnull ItemStack stack, boolean isInput) {
if (!isInput) {
return stack.getItem() instanceof IItemInputSignalFilterUpgrade;
} else {
return stack.getItem() instanceof IItemOutputSignalFilterUpgrade;
}
}
@Override
@Nonnull
public NNList<ITextComponent> getConduitProbeInformation(@Nonnull EntityPlayer player) {
final NNList<ITextComponent> result = super.getConduitProbeInformation(player);
if (getExternalConnections().isEmpty()) {
ITextComponent elem = Lang.GUI_CONDUIT_PROBE_REDSTONE_HEADING_NO_CONNECTIONS.toChatServer();
elem.getStyle().setColor(TextFormatting.GOLD);
result.add(elem);
} else {
for (EnumFacing dir : getExternalConnections()) {
if (dir == null) {
continue;
}
ITextComponent elem = Lang.GUI_CONDUIT_PROBE_REDSTONE_HEADING.toChatServer(new TextComponentTranslation(EnderIO.lang.addPrefix("facing." + dir)));
elem.getStyle().setColor(TextFormatting.GREEN);
result.add(elem);
ConnectionMode mode = getConnectionMode(dir);
if (mode.acceptsInput()) {
elem = Lang.GUI_CONDUIT_PROBE_REDSTONE_STRONG.toChatServer(isProvidingStrongPower(dir));
elem.getStyle().setColor(TextFormatting.BLUE);
result.add(elem);
elem = Lang.GUI_CONDUIT_PROBE_REDSTONE_WEAK.toChatServer(isProvidingWeakPower(dir));
elem.getStyle().setColor(TextFormatting.BLUE);
result.add(elem);
}
if (mode.acceptsOutput()) {
elem = Lang.GUI_CONDUIT_PROBE_REDSTONE_EXTERNAL.toChatServer(getExternalPowerLevelProtected(dir));
elem.getStyle().setColor(TextFormatting.BLUE);
result.add(elem);
}
}
}
return result;
}
}
|
HenryLoenwind/EnderIO
|
enderio-conduits/src/main/java/crazypants/enderio/conduits/conduit/redstone/InsulatedRedstoneConduit.java
|
Java
|
unlicense
| 33,880 |
$.extend(window.lang_fa, {
"helpStop": "متوقف کردن آموزش",
});
|
trollderius/wouldyourather_phonegap
|
www/~commons/modules/tutorial/lang/fa.js
|
JavaScript
|
unlicense
| 76 |
package crazypants.enderio.machine.capbank.network;
import javax.annotation.Nonnull;
import com.enderio.core.common.util.BlockCoord;
import crazypants.enderio.conduit.IConduitBundle;
import crazypants.enderio.conduit.power.IPowerConduit;
import crazypants.enderio.machine.IoMode;
import crazypants.enderio.machine.capbank.TileCapBank;
import crazypants.enderio.power.IPowerInterface;
import net.minecraft.util.EnumFacing;
public class EnergyReceptor {
private final @Nonnull IPowerInterface receptor;
private final @Nonnull EnumFacing fromDir;
private final @Nonnull IoMode mode;
private final BlockCoord location;
private final IPowerConduit conduit;
public EnergyReceptor(@Nonnull TileCapBank cb, @Nonnull IPowerInterface receptor, @Nonnull EnumFacing dir) {
this.receptor = receptor;
fromDir = dir;
mode = cb.getIoMode(dir);
if(receptor.getProvider() instanceof IConduitBundle) {
conduit = ((IConduitBundle) receptor.getProvider()).getConduit(IPowerConduit.class);
} else {
conduit = null;
}
location = cb.getLocation();
}
public IPowerConduit getConduit() {
return conduit;
}
public @Nonnull IPowerInterface getReceptor() {
return receptor;
}
public @Nonnull EnumFacing getDir() {
return fromDir;
}
public @Nonnull IoMode getMode() {
return mode;
}
//NB: Special impl of equals and hash code based solely on the location and dir
//This is done to ensure the receptors in the Networks Set are added / removed correctly
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + fromDir.hashCode();
result = prime * result + ((location == null) ? 0 : location.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(obj == null) {
return false;
}
if(getClass() != obj.getClass()) {
return false;
}
EnergyReceptor other = (EnergyReceptor) obj;
if(fromDir != other.fromDir) {
return false;
}
if(location == null) {
if(other.location != null) {
return false;
}
} else if(!location.equals(other.location)) {
return false;
}
return true;
}
@Override
public String toString() {
return "EnergyReceptor [receptor=" + receptor + ", fromDir=" + fromDir + ", mode=" + mode + ", conduit=" + conduit + "]";
}
}
|
D-Inc/EnderIO
|
src/main/java/crazypants/enderio/machine/capbank/network/EnergyReceptor.java
|
Java
|
unlicense
| 2,445 |
/*****************************************************************************
*
* HOPERUN PROPRIETARY INFORMATION
*
* The information contained herein is proprietary to HopeRun
* and shall not be reproduced or disclosed in whole or in part
* or used for any design or manufacture
* without direct written authorization from HopeRun.
*
* Copyright (c) 2012 by HopeRun. All rights reserved.
*
*****************************************************************************/
package com.hoperun.telematics.mobile.activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.hoperun.telematics.mobile.R;
import com.hoperun.telematics.mobile.framework.net.ENetworkServiceType;
import com.hoperun.telematics.mobile.framework.net.callback.INetCallback;
import com.hoperun.telematics.mobile.framework.net.callback.INetCallbackArgs;
import com.hoperun.telematics.mobile.framework.service.NetworkService;
import com.hoperun.telematics.mobile.helper.AnimationHelper;
import com.hoperun.telematics.mobile.helper.CacheManager;
import com.hoperun.telematics.mobile.helper.DialogHelper;
import com.hoperun.telematics.mobile.helper.NetworkCallbackHelper;
import com.hoperun.telematics.mobile.helper.TestDataManager;
import com.hoperun.telematics.mobile.model.fuel.FuelRequest;
import com.hoperun.telematics.mobile.model.fuel.FuelResponse;
/**
*
* @author fan_leilei
*
*/
public class FuelStateActivity extends DefaultActivity {
private ImageView pointerImage;
private TextView consumeText;
private TextView remainText;
private static final String TAG = "FuelStateActivity";
private FuelResponse fuelResponse;
/*
* (non-Javadoc)
*
* @see
* com.hoperun.telematics.mobile.framework.BaseActivity#onCreate(android
* .os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ui_fuel_layout);
initViews();
setTitleBar(this, getString(R.string.fuel_title));
}
/**
*
*/
private void initViews() {
pointerImage = (ImageView) findViewById(R.id.pointerImage);
consumeText = (TextView) findViewById(R.id.consumeText);
remainText = (TextView) findViewById(R.id.remainText);
}
@Override
protected void onBindServiceFinish(ComponentName className) {
super.onBindServiceFinish(className);
if (className.getClassName().equals(NetworkService.class.getName())) {
startProgressDialog(ENetworkServiceType.Fuel);
getFuelInfo();
}
}
/**
*
*/
private void getFuelInfo() {
// leilei,test code if
// if (TestDataManager.IS_TEST_MODE) {
// mCallBack2.callback(null);
// } else {
String vin = CacheManager.getInstance().getVin();
if (vin == null) {
vin = getString(R.string.testVin);
}
String license = CacheManager.getInstance().getLicense();
if (license == null) {
license = getString(R.string.testLicense1);
}
FuelRequest request = new FuelRequest(vin, license);
String postJson = request.toJsonStr();
sendAsyncMessage(ENetworkServiceType.Fuel, postJson, mCallBack);
// }
}
// NetworkCallbackHelper.IErrorEventListener displayer = new
// NetworkCallbackHelper.IErrorEventListener() {
// @Override
// public void onResponseReturned(BaseResponse response) {
// fuelResponse = (FuelResponse) response;
// updateViews(fuelResponse);
// }
//
// @Override
// public void onRetryButtonClicked() {
// // refresh(null);
// }
// };
// NetworkCallbackHelper.showInfoFromResponse(FuelStateActivity.this, args,
// FuelResponse.class, displayer);
private INetCallback mCallBack = new INetCallback() {
@Override
public void callback(final INetCallbackArgs args) {
stopProgressDialog();
Context context = FuelStateActivity.this;
OnClickListener retryBtnListener = new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startProgressDialog(ENetworkServiceType.Fuel);
}
};
// 检查是否有非业务级的错误
if (!NetworkCallbackHelper.haveSystemError(context, args.getStatus())) {
stopProgressDialog();
String payload = args.getPayload();
if (NetworkCallbackHelper.isPayloadNullOrEmpty(payload)) {
DialogHelper.alertDialog(context, R.string.error_empty_payload, R.string.ok);
} else {
Gson gson = new Gson();
fuelResponse = gson.fromJson(payload, FuelResponse.class);
if (NetworkCallbackHelper.isErrorResponse(context, fuelResponse)) {
// 当返回的信息为异常提示信息的时候,判断异常类型并弹出提示对话框
NetworkCallbackHelper.alertBusinessError(context, fuelResponse.getErrorCode());
} else {
updateViews(fuelResponse);
}
}
} else {
// 根据各接口情况选择重试或直接提示
String errMsg = args.getErrorMessage();
Log.e(TAG, errMsg);
errMsg = getString(R.string.error_async_return_fault);
startReload(errMsg, retryBtnListener);
}
}
};
// leilei,test code
// private INetCallback mCallBack2 = new INetCallback() {
//
// @Override
// public void callback(INetCallbackArgs args) {
// new Thread() {
// @Override
// public void run() {
// try {
// Thread.sleep(1500);
// stopProgressDialog();
// mHandler.post(new Runnable() {
//
// @Override
// public void run() {
// updateViews(TestDataManager.getInstance().getFuelInfo());
// }
// });
// } catch (InterruptedException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
// }.start();
//
// }
// };
private static final long ANIMATION_DURATION = 1000;
private static final float ANIMATION_START_DEGREE = 0;
private static final float ANIMATION_END_DEGREE = 108;
private static final float ANIMATION_DEGREE_RANGE = ANIMATION_END_DEGREE - ANIMATION_START_DEGREE;
private void updateViews(FuelResponse response) {
consumeText.setText(getString(R.string.fuel_consume, response.getConsumption()));
remainText.setText(getString(R.string.fuel_remaining, response.getRemainingMileage()));
float maxFuel = response.getMaxFuel();
float remainFuel = response.getRemainingFuel();
float endDegree = ANIMATION_DEGREE_RANGE * remainFuel / maxFuel;
AnimationHelper.startOnceRotateAnimation(pointerImage, ANIMATION_START_DEGREE, endDegree, ANIMATION_DURATION);
}
}
|
yangjun2/android
|
telematics_android/src/com/hoperun/telematics/mobile/activity/FuelStateActivity.java
|
Java
|
unlicense
| 6,629 |
'use strict';
function ProfileSearch(injector) {
var service = this;
service.list = function(params) {
var connection = injector.connection;
var ProfileModel = injector.ProfileModel;
var profileSearch = new ProfileModel();
var page = params.page || 1;
var where = params.where || [];
var order = params.order || [];
var limit = params.limit || 10;
var fields = params.fields || profileSearch.fields;
profileSearch.page = page;
profileSearch.order = order;
profileSearch.where = where;
profileSearch.limit = limit;
profileSearch.fields = fields;
connection.search(profileSearch);
};
}
module.exports = ProfileSearch;
|
luiz-simples/kauris
|
server/src/profile/profile.search.js
|
JavaScript
|
unlicense
| 703 |
import {GameConfig} from '../../../config/game.config';
import {GuiUtils} from '../../../utils/gui.utils';
import {isString} from 'util';
export class CrossButton {
private state: Phaser.State = null;
private game: Phaser.Game = null;
private url: string = '';
private container: Phaser.Group = null;
private btns: Phaser.Button[] = [];
private sprites: Phaser.Sprite[] = [];
constructor(state: Phaser.State, crossUrl: string = '') {
this.state = state;
this.game = GameConfig.GAME;
this.url = crossUrl;
this.container = this.game.add.group();
}
link(url: string): CrossButton {
this.url = url;
return this;
}
sprite(): CrossButton {
return this;
}
animatedSprite(): CrossButton {
return this;
}
button(x: number, y: number, scale: number, asset: string, frames?: any|any[],
overHandler: Function = GuiUtils.addOverHandler,
outHandler: Function = GuiUtils.addOutHandler): CrossButton {
if (frames == null) {
frames = [0, 0, 0];
}
else if (isString(frames)) {
frames = [frames, frames, frames];
}
this.btns.push(GuiUtils.makeButton(
this.state, this.container,
x, y, scale,
'', asset, frames,
true, true, true, GuiUtils.goCross(this.url), overHandler, outHandler));
return this;
}
buttonAndReturn(x: number, y: number, scale: number, asset: string, frames?: any|any[],
overHandler: Function = GuiUtils.addOverHandler,
outHandler: Function = GuiUtils.addOutHandler): Phaser.Button {
if (frames == null) {
frames = [0, 0, 0];
}
else if (isString(frames)) {
frames = [frames, frames, frames];
}
const btn = GuiUtils.makeButton(
this.state, this.container,
x, y, scale,
'', asset, frames,
true, true, true, GuiUtils.goCross(this.url), overHandler, outHandler);
this.btns.push(btn);
return btn;
}
getBody(): Phaser.Group {
return this.container;
}
dispose() {
for (let btn of this.btns) {
btn.destroy(true);
}
for (let spr of this.sprites) {
spr.destroy(true);
}
this.container.destroy(true);
}
}
|
B1zDelNick/phaser-npm-webpack-typescript-starter-project-master
|
src/states/template/final/cross.button.ts
|
TypeScript
|
unlicense
| 2,417 |
package BreadthAndDepthFirstSearch;
// https://leetcode.com/problems/increasing-order-search-tree/
import java.util.ArrayList;
import java.util.Arrays;
public class IncreasingOrderBinarySearchTree {
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int value) {
val = value;
}
static TreeNode buildBinaryTree(ArrayList<Integer> array) {
return buildBinaryTree(array, 0, array.size() - 1);
}
private static TreeNode buildBinaryTree(ArrayList<Integer> array, int start, int end) {
if (start > end || array.get(start) == null) {
return null;
}
TreeNode node = new TreeNode(array.get(start));
int leftChildIndex = 2 * start + 1;
int rightChildIndex = 2 * start + 2;
if (leftChildIndex <= end) {
node.left = buildBinaryTree(array, leftChildIndex, end);
}
if (rightChildIndex <= end) {
node.right = buildBinaryTree(array, rightChildIndex, end);
}
return node;
}
}
private static TreeNode current = null;
private static TreeNode increasingBST(TreeNode root) {
TreeNode result = new TreeNode(0);
current = result;
inOrder(root);
return result.right;
}
private static void inOrder(TreeNode node) {
if (node == null) {
return;
}
inOrder(node.left);
node.left = null;
current.right = node;
current = node;
inOrder(node.right);
}
public static void main(String[] args) {
ArrayList<Integer> array = new ArrayList<>(Arrays.asList(5, 3, 6, 2, 4, null, 8, 1, null, null, null, 7, 9));
TreeNode root = TreeNode.buildBinaryTree(array);
TreeNode result = increasingBST(root);
System.out.println(result);
}
}
|
gagarwal/codingproblemsandsolutions
|
src/BreadthAndDepthFirstSearch/IncreasingOrderBinarySearchTree.java
|
Java
|
unlicense
| 1,654 |
var net = require('net')
var chatServer = net.createServer(),
clientList = []
chatServer.on('connection', function(client) {
client.name = client.remoteAddress + ':' + client.remotePort
client.write('Hi ' + client.name + '!\n');
console.log(client.name + ' joined')
clientList.push(client)
client.on('data', function(data) {
broadcast(data, client)
})
client.on('end', function(data) {
console.log(client.name + ' quit')
clientList.splice(clientList.indexOf(client), 1)
})
client.on('error', function(e) {
console.log(e)
})
})
function broadcast(message, client) {
for(var i=0;i<clientList.length;i+=1) {
if(client !== clientList[i]) {
if(clientList[i].writable) {
clientList[i].write(client.name + " says " + message)
} else {
cleanup.push(clientList[i])
clientList[i].destroy()
}
}
}
}
chatServer.listen(9000)
|
mattcoffey/node.js
|
chatServer.js
|
JavaScript
|
unlicense
| 1,002 |
/*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['sap/ui/model/FormatException', 'sap/ui/model/odata/type/ODataType',
'sap/ui/model/ParseException', 'sap/ui/model/ValidateException'],
function(FormatException, ODataType, ParseException, ValidateException) {
"use strict";
var rGuid = /^[A-F0-9]{8}-([A-F0-9]{4}-){3}[A-F0-9]{12}$/i;
/**
* Returns the locale-dependent error message.
*
* @returns {string}
* the locale-dependent error message.
* @private
*/
function getErrorMessage() {
return sap.ui.getCore().getLibraryResourceBundle().getText("EnterGuid");
}
/**
* Sets the constraints.
*
* @param {sap.ui.model.odata.type.Guid} oType
* the type instance
* @param {object} [oConstraints]
* constraints, see {@link #constructor}
*/
function setConstraints(oType, oConstraints) {
var vNullable = oConstraints && oConstraints.nullable;
oType.oConstraints = undefined;
if (vNullable === false || vNullable === "false") {
oType.oConstraints = {nullable: false};
} else if (vNullable !== undefined && vNullable !== true && vNullable !== "true") {
jQuery.sap.log.warning("Illegal nullable: " + vNullable, null, oType.getName());
}
}
/**
* Constructor for an OData primitive type <code>Edm.Guid</code>.
*
* @class This class represents the OData primitive type <a
* href="http://www.odata.org/documentation/odata-version-2-0/overview#AbstractTypeSystem">
* <code>Edm.Guid</code></a>.
*
* In {@link sap.ui.model.odata.v2.ODataModel ODataModel} this type is represented as a
* <code>string</code>.
*
* @extends sap.ui.model.odata.type.ODataType
*
* @author SAP SE
* @version 1.28.10
*
* @alias sap.ui.model.odata.type.Guid
* @param {object} [oFormatOptions]
* format options as defined in the interface of {@link sap.ui.model.SimpleType}; this
* type ignores them since it does not support any format options
* @param {object} [oConstraints]
* constraints; {@link #validateValue validateValue} throws an error if any constraint is
* violated
* @param {boolean|string} [oConstraints.nullable=true]
* if <code>true</code>, the value <code>null</code> is accepted
* @public
* @since 1.27.0
*/
var EdmGuid = ODataType.extend("sap.ui.model.odata.type.Guid",
/** @lends sap.ui.model.odata.type.Guid.prototype */
{
constructor : function (oFormatOptions, oConstraints) {
ODataType.apply(this, arguments);
setConstraints(this, oConstraints);
}
}
);
/**
* Formats the given value to the given target type.
*
* @param {string} sValue
* the value to be formatted
* @param {string} sTargetType
* the target type; may be "any" or "string".
* See {@link sap.ui.model.odata.type} for more information.
* @returns {string}
* the formatted output value in the target type; <code>undefined</code> or <code>null</code>
* are formatted to <code>null</code>
* @throws {sap.ui.model.FormatException}
* if <code>sTargetType</code> is unsupported
* @public
*/
EdmGuid.prototype.formatValue = function(sValue, sTargetType) {
if (sValue === undefined || sValue === null) {
return null;
}
if (sTargetType === "string" || sTargetType === "any") {
return sValue;
}
throw new FormatException("Don't know how to format " + this.getName() + " to "
+ sTargetType);
};
/**
* Returns the type's name.
*
* @returns {string}
* the type's name
* @public
*/
EdmGuid.prototype.getName = function () {
return "sap.ui.model.odata.type.Guid";
};
/**
* Parses the given value to a GUID.
*
* @param {string} sValue
* the value to be parsed, maps <code>""</code> to <code>null</code>
* @param {string} sSourceType
* the source type (the expected type of <code>sValue</code>); must be "string".
* See {@link sap.ui.model.odata.type} for more information.
* @returns {string}
* the parsed value
* @throws {sap.ui.model.ParseException}
* if <code>sSourceType</code> is unsupported
* @public
*/
EdmGuid.prototype.parseValue = function (sValue, sSourceType) {
var sResult;
if (sValue === "" || sValue === null) {
return null;
}
if (sSourceType !== "string") {
throw new ParseException("Don't know how to parse " + this.getName() + " from "
+ sSourceType);
}
// remove all whitespaces and separators
sResult = sValue.replace(/[-\s]/g, '');
if (sResult.length != 32) {
// don't try to add separators to invalid value
return sValue;
}
sResult = sResult.slice(0, 8) + '-' + sResult.slice(8, 12) + '-' + sResult.slice(12, 16)
+ '-' + sResult.slice(16, 20) + '-' + sResult.slice(20);
return sResult.toUpperCase();
};
/**
* Validates whether the given value in model representation is valid and meets the
* given constraints.
*
* @param {string} sValue
* the value to be validated
* @returns {void}
* @throws {sap.ui.model.ValidateException}
* if the value is not valid
* @public
*/
EdmGuid.prototype.validateValue = function (sValue) {
if (sValue === null) {
if (this.oConstraints && this.oConstraints.nullable === false) {
throw new ValidateException(getErrorMessage());
}
return;
}
if (typeof sValue !== "string") {
// This is a "technical" error by calling validate w/o parse
throw new ValidateException("Illegal " + this.getName() + " value: " + sValue);
}
if (!rGuid.test(sValue)) {
throw new ValidateException(getErrorMessage());
}
};
return EdmGuid;
});
|
ghostxwheel/utorrent-webui
|
resources/sap/ui/model/odata/type/Guid-dbg.js
|
JavaScript
|
unlicense
| 5,646 |
#include "escapeTimeFractal.h"
escapeTimeFractal::escapeTimeFractal() : fractal()
{
zoomed_fr_x_max = FR_X_MAX;
zoomed_fr_x_min = FR_X_MIN;
zoomed_fr_y_max = FR_Y_MAX;
zoomed_fr_y_min = FR_Y_MIN;
}
void escapeTimeFractal::render(QImage *image, int begin, int end)
{
for (int i = begin; i < end; ++i)
{
for (int j = 0; j < screenWidth; ++j)
{
int iteration = escape((double)j, (double)i);
image->setPixel(j, i, getColor(iteration, maxIterations).rgb());
}
}
}
QColor escapeTimeFractal::getColor(int value, int maxValue) const
{
QColor color;
if (value >= maxValue)
{
// zwróć czarny kolor
color.setRgb(0, 0, 0);
return color;
}
double t = value / (double) maxValue;
int r = (int)(9 * (1 - t) * t * t * t * 255);
int g = (int)(15 * (1 - t) * (1 - t) * t * t * 255);
int b = (int)(8.5 * (1 - t) * (1 - t) * (1 - t) * t * 255);
color.setRgb(r, g, b);
return color;
}
|
kamilwu/fracx
|
src/escapeTimeFractal.cpp
|
C++
|
unlicense
| 904 |