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 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.ui;
import com.google.analytics.tracking.android.EasyTracker;
import gdg.devfest.app.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.ImageFetcher;
import com.google.android.apps.iosched.util.UIUtils;
import com.actionbarsherlock.app.SherlockFragment;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* A fragment that shows detail information for a developer sandbox company, including
* company name, description, logo, etc.
*/
public class VendorDetailFragment extends SherlockFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
private static final String TAG = makeLogTag(VendorDetailFragment.class);
private Uri mVendorUri;
private TextView mName;
private ImageView mLogo;
private TextView mUrl;
private TextView mDesc;
private ImageFetcher mImageFetcher;
public interface Callbacks {
public void onTrackIdAvailable(String trackId);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onTrackIdAvailable(String trackId) {}
};
private Callbacks mCallbacks = sDummyCallbacks;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments());
mVendorUri = intent.getData();
if (mVendorUri == null) {
return;
}
mImageFetcher = UIUtils.getImageFetcher(getActivity());
mImageFetcher.setImageFadeIn(false);
setHasOptionsMenu(true);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (mVendorUri == null) {
return;
}
// Start background query to load vendor details
getLoaderManager().initLoader(VendorsQuery._TOKEN, null, this);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new ClassCastException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
}
@Override
public void onStop() {
super.onStop();
if (mImageFetcher != null) {
mImageFetcher.closeCache();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_vendor_detail, null);
mName = (TextView) rootView.findViewById(R.id.vendor_name);
mLogo = (ImageView) rootView.findViewById(R.id.vendor_logo);
mUrl = (TextView) rootView.findViewById(R.id.vendor_url);
mDesc = (TextView) rootView.findViewById(R.id.vendor_desc);
return rootView;
}
public void buildUiFromCursor(Cursor cursor) {
if (getActivity() == null) {
return;
}
if (!cursor.moveToFirst()) {
return;
}
String nameString = cursor.getString(VendorsQuery.NAME);
mName.setText(nameString);
// Start background fetch to load vendor logo
final String logoUrl = cursor.getString(VendorsQuery.LOGO_URL);
if (!TextUtils.isEmpty(logoUrl)) {
mImageFetcher.loadThumbnailImage(logoUrl, mLogo, R.drawable.sandbox_logo_empty);
}
mUrl.setText(cursor.getString(VendorsQuery.URL));
mDesc.setText(cursor.getString(VendorsQuery.DESC));
EasyTracker.getTracker().trackView("Sandbox Vendor: " + nameString);
LOGD("Tracker", "Sandbox Vendor: " + nameString);
mCallbacks.onTrackIdAvailable(cursor.getString(VendorsQuery.TRACK_ID));
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
return new CursorLoader(getActivity(), mVendorUri, VendorsQuery.PROJECTION, null, null,
null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
buildUiFromCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
/**
* {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors}
* query parameters.
*/
private interface VendorsQuery {
int _TOKEN = 0x4;
String[] PROJECTION = {
ScheduleContract.Vendors.VENDOR_NAME,
ScheduleContract.Vendors.VENDOR_DESC,
ScheduleContract.Vendors.VENDOR_URL,
ScheduleContract.Vendors.VENDOR_LOGO_URL,
ScheduleContract.Vendors.TRACK_ID,
};
int NAME = 0;
int DESC = 1;
int URL = 2;
int LOGO_URL = 3;
int TRACK_ID = 4;
}
}
| printminion/gdgsched | android/src/com/google/android/apps/iosched/ui/VendorDetailFragment.java | Java | apache-2.0 | 6,196 |
/**
* Generated with Acceleo
*/
package org.wso2.developerstudio.eclipse.gmf.esb.parts.forms;
// Start of user code for imports
import org.eclipse.emf.common.util.Enumerator;
import org.eclipse.emf.ecore.util.EcoreAdapterFactory;
import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;
import org.eclipse.emf.eef.runtime.EEFRuntimePlugin;
import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;
import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart;
import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;
import org.eclipse.emf.eef.runtime.part.impl.SectionPropertiesEditingPart;
import org.eclipse.emf.eef.runtime.ui.parts.PartComposer;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionStep;
import org.eclipse.emf.eef.runtime.ui.utils.EditingUtils;
import org.eclipse.emf.eef.runtime.ui.widgets.EMFComboViewer;
import org.eclipse.emf.eef.runtime.ui.widgets.FormUtils;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbViewsRepository;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.TaskPropertyPropertiesEditionPart;
import org.wso2.developerstudio.eclipse.gmf.esb.providers.EsbMessages;
// End of user code
/**
*
*
*/
public class TaskPropertyPropertiesEditionPartForm extends SectionPropertiesEditingPart implements IFormPropertiesEditionPart, TaskPropertyPropertiesEditionPart {
protected Text propertyName;
protected Text propertyValue;
protected EMFComboViewer propertyType;
/**
* For {@link ISection} use only.
*/
public TaskPropertyPropertiesEditionPartForm() { super(); }
/**
* Default constructor
* @param editionComponent the {@link IPropertiesEditionComponent} that manage this part
*
*/
public TaskPropertyPropertiesEditionPartForm(IPropertiesEditionComponent editionComponent) {
super(editionComponent);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
* createFigure(org.eclipse.swt.widgets.Composite, org.eclipse.ui.forms.widgets.FormToolkit)
*
*/
public Composite createFigure(final Composite parent, final FormToolkit widgetFactory) {
ScrolledForm scrolledForm = widgetFactory.createScrolledForm(parent);
Form form = scrolledForm.getForm();
view = form.getBody();
GridLayout layout = new GridLayout();
layout.numColumns = 3;
view.setLayout(layout);
createControls(widgetFactory, view);
return scrolledForm;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
* createControls(org.eclipse.ui.forms.widgets.FormToolkit, org.eclipse.swt.widgets.Composite)
*
*/
public void createControls(final FormToolkit widgetFactory, Composite view) {
CompositionSequence taskPropertyStep = new BindingCompositionSequence(propertiesEditionComponent);
CompositionStep propertiesStep = taskPropertyStep.addStep(EsbViewsRepository.TaskProperty.Properties.class);
propertiesStep.addStep(EsbViewsRepository.TaskProperty.Properties.propertyName);
propertiesStep.addStep(EsbViewsRepository.TaskProperty.Properties.propertyValue);
propertiesStep.addStep(EsbViewsRepository.TaskProperty.Properties.propertyType);
composer = new PartComposer(taskPropertyStep) {
@Override
public Composite addToPart(Composite parent, Object key) {
if (key == EsbViewsRepository.TaskProperty.Properties.class) {
return createPropertiesGroup(widgetFactory, parent);
}
if (key == EsbViewsRepository.TaskProperty.Properties.propertyName) {
return createPropertyNameText(widgetFactory, parent);
}
if (key == EsbViewsRepository.TaskProperty.Properties.propertyValue) {
return createPropertyValueText(widgetFactory, parent);
}
if (key == EsbViewsRepository.TaskProperty.Properties.propertyType) {
return createPropertyTypeEMFComboViewer(widgetFactory, parent);
}
return parent;
}
};
composer.compose(view);
}
/**
*
*/
protected Composite createPropertiesGroup(FormToolkit widgetFactory, final Composite parent) {
Section propertiesSection = widgetFactory.createSection(parent, Section.TITLE_BAR | Section.TWISTIE | Section.EXPANDED);
propertiesSection.setText(EsbMessages.TaskPropertyPropertiesEditionPart_PropertiesGroupLabel);
GridData propertiesSectionData = new GridData(GridData.FILL_HORIZONTAL);
propertiesSectionData.horizontalSpan = 3;
propertiesSection.setLayoutData(propertiesSectionData);
Composite propertiesGroup = widgetFactory.createComposite(propertiesSection);
GridLayout propertiesGroupLayout = new GridLayout();
propertiesGroupLayout.numColumns = 3;
propertiesGroup.setLayout(propertiesGroupLayout);
propertiesSection.setClient(propertiesGroup);
return propertiesGroup;
}
protected Composite createPropertyNameText(FormToolkit widgetFactory, Composite parent) {
createDescription(parent, EsbViewsRepository.TaskProperty.Properties.propertyName, EsbMessages.TaskPropertyPropertiesEditionPart_PropertyNameLabel);
propertyName = widgetFactory.createText(parent, ""); //$NON-NLS-1$
propertyName.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData propertyNameData = new GridData(GridData.FILL_HORIZONTAL);
propertyName.setLayoutData(propertyNameData);
propertyName.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(
TaskPropertyPropertiesEditionPartForm.this,
EsbViewsRepository.TaskProperty.Properties.propertyName,
PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, propertyName.getText()));
propertiesEditionComponent
.firePropertiesChanged(new PropertiesEditionEvent(
TaskPropertyPropertiesEditionPartForm.this,
EsbViewsRepository.TaskProperty.Properties.propertyName,
PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_LOST,
null, propertyName.getText()));
}
}
/**
* @see org.eclipse.swt.events.FocusAdapter#focusGained(org.eclipse.swt.events.FocusEvent)
*/
@Override
public void focusGained(FocusEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent
.firePropertiesChanged(new PropertiesEditionEvent(
TaskPropertyPropertiesEditionPartForm.this,
null,
PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_GAINED,
null, null));
}
}
});
propertyName.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(TaskPropertyPropertiesEditionPartForm.this, EsbViewsRepository.TaskProperty.Properties.propertyName, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, propertyName.getText()));
}
}
});
EditingUtils.setID(propertyName, EsbViewsRepository.TaskProperty.Properties.propertyName);
EditingUtils.setEEFtype(propertyName, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.TaskProperty.Properties.propertyName, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$
// Start of user code for createPropertyNameText
// End of user code
return parent;
}
protected Composite createPropertyValueText(FormToolkit widgetFactory, Composite parent) {
createDescription(parent, EsbViewsRepository.TaskProperty.Properties.propertyValue, EsbMessages.TaskPropertyPropertiesEditionPart_PropertyValueLabel);
propertyValue = widgetFactory.createText(parent, ""); //$NON-NLS-1$
propertyValue.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
widgetFactory.paintBordersFor(parent);
GridData propertyValueData = new GridData(GridData.FILL_HORIZONTAL);
propertyValue.setLayoutData(propertyValueData);
propertyValue.addFocusListener(new FocusAdapter() {
/**
* @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void focusLost(FocusEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(
TaskPropertyPropertiesEditionPartForm.this,
EsbViewsRepository.TaskProperty.Properties.propertyValue,
PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, propertyValue.getText()));
propertiesEditionComponent
.firePropertiesChanged(new PropertiesEditionEvent(
TaskPropertyPropertiesEditionPartForm.this,
EsbViewsRepository.TaskProperty.Properties.propertyValue,
PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_LOST,
null, propertyValue.getText()));
}
}
/**
* @see org.eclipse.swt.events.FocusAdapter#focusGained(org.eclipse.swt.events.FocusEvent)
*/
@Override
public void focusGained(FocusEvent e) {
if (propertiesEditionComponent != null) {
propertiesEditionComponent
.firePropertiesChanged(new PropertiesEditionEvent(
TaskPropertyPropertiesEditionPartForm.this,
null,
PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_GAINED,
null, null));
}
}
});
propertyValue.addKeyListener(new KeyAdapter() {
/**
* @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
*
*/
@Override
@SuppressWarnings("synthetic-access")
public void keyPressed(KeyEvent e) {
if (e.character == SWT.CR) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(TaskPropertyPropertiesEditionPartForm.this, EsbViewsRepository.TaskProperty.Properties.propertyValue, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, propertyValue.getText()));
}
}
});
EditingUtils.setID(propertyValue, EsbViewsRepository.TaskProperty.Properties.propertyValue);
EditingUtils.setEEFtype(propertyValue, "eef::Text"); //$NON-NLS-1$
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.TaskProperty.Properties.propertyValue, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$
// Start of user code for createPropertyValueText
// End of user code
return parent;
}
/**
* @generated NOT
*/
protected Composite createPropertyTypeEMFComboViewer(FormToolkit widgetFactory, Composite parent) {
createDescription(parent, EsbViewsRepository.TaskProperty.Properties.propertyType, EsbMessages.TaskPropertyPropertiesEditionPart_PropertyTypeLabel);
propertyType = new EMFComboViewer(parent);
propertyType.setContentProvider(new ArrayContentProvider());
propertyType.setLabelProvider(new AdapterFactoryLabelProvider(EEFRuntimePlugin.getDefault().getAdapterFactory()));
GridData propertyTypeData = new GridData(GridData.FILL_HORIZONTAL);
propertyType.getCombo().setLayoutData(propertyTypeData);
propertyType.getCombo().addListener(SWT.MouseVerticalWheel, new Listener() {
@Override
public void handleEvent(Event arg0) {
arg0.doit = false;
}
});
propertyType.addSelectionChangedListener(new ISelectionChangedListener() {
/**
* {@inheritDoc}
*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*
*/
public void selectionChanged(SelectionChangedEvent event) {
if (propertiesEditionComponent != null)
propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(TaskPropertyPropertiesEditionPartForm.this, EsbViewsRepository.TaskProperty.Properties.propertyType, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, getPropertyType()));
}
});
propertyType.setID(EsbViewsRepository.TaskProperty.Properties.propertyType);
FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.TaskProperty.Properties.propertyType, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$
// Start of user code for createPropertyTypeEMFComboViewer
// End of user code
return parent;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
*
*/
public void firePropertiesChanged(IPropertiesEditionEvent event) {
// Start of user code for tab synchronization
// End of user code
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TaskPropertyPropertiesEditionPart#getPropertyName()
*
*/
public String getPropertyName() {
return propertyName.getText();
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TaskPropertyPropertiesEditionPart#setPropertyName(String newValue)
*
*/
public void setPropertyName(String newValue) {
if (newValue != null) {
propertyName.setText(newValue);
} else {
propertyName.setText(""); //$NON-NLS-1$
}
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.TaskProperty.Properties.propertyName);
if (eefElementEditorReadOnlyState && propertyName.isEnabled()) {
propertyName.setEnabled(false);
propertyName.setToolTipText(EsbMessages.TaskProperty_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !propertyName.isEnabled()) {
propertyName.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TaskPropertyPropertiesEditionPart#getPropertyValue()
*
*/
public String getPropertyValue() {
return propertyValue.getText();
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TaskPropertyPropertiesEditionPart#setPropertyValue(String newValue)
*
*/
public void setPropertyValue(String newValue) {
if (newValue != null) {
propertyValue.setText(newValue);
} else {
propertyValue.setText(""); //$NON-NLS-1$
}
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.TaskProperty.Properties.propertyValue);
if (eefElementEditorReadOnlyState && propertyValue.isEnabled()) {
propertyValue.setEnabled(false);
propertyValue.setToolTipText(EsbMessages.TaskProperty_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !propertyValue.isEnabled()) {
propertyValue.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TaskPropertyPropertiesEditionPart#getPropertyType()
*
*/
public Enumerator getPropertyType() {
Enumerator selection = (Enumerator) ((StructuredSelection) propertyType.getSelection()).getFirstElement();
return selection;
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TaskPropertyPropertiesEditionPart#initPropertyType(Object input, Enumerator current)
*/
public void initPropertyType(Object input, Enumerator current) {
propertyType.setInput(input);
propertyType.modelUpdating(new StructuredSelection(current));
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.TaskProperty.Properties.propertyType);
if (eefElementEditorReadOnlyState && propertyType.isEnabled()) {
propertyType.setEnabled(false);
propertyType.setToolTipText(EsbMessages.TaskProperty_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !propertyType.isEnabled()) {
propertyType.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.wso2.developerstudio.eclipse.gmf.esb.parts.TaskPropertyPropertiesEditionPart#setPropertyType(Enumerator newValue)
*
*/
public void setPropertyType(Enumerator newValue) {
propertyType.modelUpdating(new StructuredSelection(newValue));
boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.TaskProperty.Properties.propertyType);
if (eefElementEditorReadOnlyState && propertyType.isEnabled()) {
propertyType.setEnabled(false);
propertyType.setToolTipText(EsbMessages.TaskProperty_ReadOnly);
} else if (!eefElementEditorReadOnlyState && !propertyType.isEnabled()) {
propertyType.setEnabled(true);
}
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle()
*
*/
public String getTitle() {
return EsbMessages.TaskProperty_Part_Title;
}
// Start of user code additional methods
// End of user code
}
| prabushi/devstudio-tooling-esb | plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src-gen/org/wso2/developerstudio/eclipse/gmf/esb/parts/forms/TaskPropertyPropertiesEditionPartForm.java | Java | apache-2.0 | 18,210 |
package CustomOreGen.Util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public abstract class MapCollection<K,V> implements Collection<V>
{
protected final Map<K,V> backingMap;
public MapCollection(Map<K,V> backingMap)
{
this.backingMap = backingMap;
for (Entry<K,V> entry : backingMap.entrySet()) {
K key = entry.getKey();
V value = entry.getValue();
K nKey = this.getKey(value);
if (key != nKey && (key == null || !key.equals(nKey))) {
throw new IllegalArgumentException("Backing set contains inconsistent key/value pair \'" + key + "\' -> \'" + value + "\', expected \'" + nKey + "\' -> \'" + value + "\'");
}
}
}
protected abstract K getKey(V value);
public int size()
{
return this.backingMap.size();
}
public boolean isEmpty()
{
return this.backingMap.isEmpty();
}
public boolean contains(Object o)
{
try {
@SuppressWarnings("unchecked")
K key = this.getKey((V)o);
return this.backingMap.containsKey(key);
} catch(ClassCastException e) {
return false;
}
}
public Iterator<V> iterator()
{
return this.backingMap.values().iterator();
}
public Object[] toArray()
{
return this.backingMap.values().toArray();
}
public <T> T[] toArray(T[] a)
{
return this.backingMap.values().toArray(a);
}
public boolean add(V v)
{
K key = this.getKey(v);
if (v != null)
{
return this.backingMap.put(key, v) != v;
}
else
{
boolean hasKey = this.backingMap.containsKey(key);
V prev = this.backingMap.put(key, v);
return !hasKey || v != prev;
}
}
public boolean remove(Object o)
{
try {
@SuppressWarnings("unchecked")
K key = this.getKey((V)o);
return this.backingMap.keySet().remove(key);
} catch(ClassCastException e) {
return false;
}
}
public boolean containsAll(Collection<?> c)
{
for (Object o : c) {
if (!this.contains(o))
return false;
}
return true;
}
public boolean addAll(Collection<? extends V> c)
{
boolean changed = false;
for (V v : c) {
changed |= this.add(v);
}
return changed;
}
public boolean removeAll(Collection<?> c)
{
boolean changed = false;
for (Object o : c) {
changed |= this.remove(o);
}
return changed;
}
public boolean retainAll(Collection<?> c)
{
ArrayList<K> keys = new ArrayList<K>(this.backingMap.size());
for (Object o : c) {
try {
@SuppressWarnings("unchecked")
K key = this.getKey((V)o);
keys.add(key);
} catch(ClassCastException e) {
}
}
return this.backingMap.keySet().retainAll(keys);
}
public void clear()
{
this.backingMap.clear();
}
public int hashCode()
{
return this.backingMap.hashCode();
}
public boolean equals(Object obj)
{
return obj instanceof MapCollection ? this.backingMap.equals(((MapCollection<?, ?>)obj).backingMap) : false;
}
public String toString()
{
return this.backingMap.values().toString();
}
}
| reteo/CustomOreGen | src/main/java/CustomOreGen/Util/MapCollection.java | Java | artistic-2.0 | 3,588 |
class Helmfile < Formula
desc "Deploy Kubernetes Helm Charts"
homepage "https://github.com/roboll/helmfile"
url "https://github.com/roboll/helmfile/archive/v0.142.0.tar.gz"
sha256 "5475a041f0a1eb5777cc45e3fb06458ae76b1d4840aec89f2fed509d833d0cde"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "29cf096405cc834e7888ebdee9c811a3e375e8a43b2e045ec0295e8ff654bad3"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "80e9c9d81f57b0331038108026263d6d9b184403659b66a976172e9dde916792"
sha256 cellar: :any_skip_relocation, monterey: "73e5bab63a7d9c0af77ccc72f8bca63cc8f72b96923ebfe41430a356cbf2cdeb"
sha256 cellar: :any_skip_relocation, big_sur: "ca024a40610d455dce99ef913baee47fa1d82dc821d780b94e56a54b3ecbde7b"
sha256 cellar: :any_skip_relocation, catalina: "7fa829db664c78079ba1c8ac19ec75b47e9664dfc55cf79d18970070e81d0fc2"
sha256 cellar: :any_skip_relocation, x86_64_linux: "53ff4d7a0816b82fcd87c791e6a9db70699425931bbba96181b545a837fb7fb7"
end
depends_on "go" => :build
depends_on "helm"
def install
system "go", "build", "-ldflags", "-X github.com/roboll/helmfile/pkg/app/version.Version=v#{version}",
"-o", bin/"helmfile", "-v", "github.com/roboll/helmfile"
end
test do
(testpath/"helmfile.yaml").write <<-EOS
repositories:
- name: stable
url: https://charts.helm.sh/stable
releases:
- name: vault # name of this release
namespace: vault # target namespace
createNamespace: true # helm 3.2+ automatically create release namespace (default true)
labels: # Arbitrary key value pairs for filtering releases
foo: bar
chart: stable/vault # the chart being installed to create this release, referenced by `repository/chart` syntax
version: ~1.24.1 # the semver of the chart. range constraint is supported
EOS
system Formula["helm"].opt_bin/"helm", "create", "foo"
output = "Adding repo stable https://charts.helm.sh/stable"
assert_match output, shell_output("#{bin}/helmfile -f helmfile.yaml repos 2>&1")
assert_match version.to_s, shell_output("#{bin}/helmfile -v")
end
end
| sjackman/homebrew-core | Formula/helmfile.rb | Ruby | bsd-2-clause | 2,316 |
import re
# Python 2/3 compatibility hackery
try:
unicode
except NameError:
unicode = str
def compile_url(url):
clean_url = unicode(url).lstrip(u'/')
return re.compile(clean_url)
def compile_urls(urls):
return [compile_url(expr) for expr in urls]
| ghickman/incuna-auth | incuna_auth/middleware/utils.py | Python | bsd-2-clause | 272 |
class Helmsman < Formula
desc "Helm Charts as Code tool"
homepage "https://github.com/Praqma/helmsman"
url "https://github.com/Praqma/helmsman.git",
tag: "v3.7.2",
revision: "6d7e6ddb2c7747b8789dd72db7714431fe17e779"
license "MIT"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "a307ed84ab8c572b9256fb54aaad6a7300f9384c94163dfeafc7419188aed4d0"
sha256 cellar: :any_skip_relocation, big_sur: "2f8fa84afd13560540da1be94ba442d8d140821436e14b038b8f034e561d7ca7"
sha256 cellar: :any_skip_relocation, catalina: "c0604c09ea08fd0aefb7ad9f24ec6df256156670fa8d30c180365c9b479cf99f"
sha256 cellar: :any_skip_relocation, mojave: "4841f957b4825a3501faa2ccf437d79042ea9019389ad344d4f20f9cecfe3830"
sha256 cellar: :any_skip_relocation, x86_64_linux: "dd61ceab712bafb407449a97d4e5e3df51bf50514f27c4bdd228796032748527"
end
depends_on "go" => :build
depends_on "helm"
depends_on "kubernetes-cli"
def install
system "go", "build", *std_go_args, "-ldflags", "-s -w -X main.version=#{version}", "./cmd/helmsman"
pkgshare.install "examples/example.yaml"
end
test do
assert_match version.to_s, shell_output("#{bin}/helmsman version")
output = shell_output("#{bin}/helmsman --apply -f #{pkgshare}/example.yaml 2>&1", 1)
assert_match "helm diff not found", output
end
end
| zyedidia/homebrew-core | Formula/helmsman.rb | Ruby | bsd-2-clause | 1,369 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from math import log
import argh
import numpy as np
from chemreac import ReactionDiffusion
from chemreac.integrate import run
from chemreac.util.plotting import plot_solver_linear_error
def efield_cb(x, logx=False):
"""
Returns a flat efield (-1)
"""
return -np.ones_like(x)
def y0_flat_cb(x, logx=False, use_log2=False):
xc = x[:-1] + np.diff(x)/2
if logx:
expb = (lambda arg: 2**arg) if use_log2 else np.exp
x, xc = map(expb, (x, xc))
return 17 - 11*(xc-x[0])/(x[-1]-x[0])
def y0_cylindrical_cb(x, logx=False, use_log2=False):
xc = x[:-1] + np.diff(x)/2
if logx:
expb = (lambda arg: 2**arg) if use_log2 else np.exp
x, xc = map(expb, (x, xc))
return 17 - np.log((xc-x[0])/(x[-1]-x[0]))
def y0_spherical_cb(x, logx=False, use_log2=False):
xc = x[:-1] + np.diff(x)/2
if logx:
expb = (lambda arg: 2**arg) if use_log2 else np.exp
x, xc = map(expb, (x, xc))
return 3 + 0.1/((xc-x[0])/(x[-1]-x[0]))
def integrate_rd(D=2e-3, t0=3., tend=7., x0=0.0, xend=1.0, mu=None, N=32,
nt=25, geom='f', logt=False, logy=False, logx=False,
random=False, nstencil=3, lrefl=False, rrefl=False,
num_jacobian=False, method='bdf', plot=False,
atol=1e-6, rtol=1e-6, efield=False, random_seed=42,
verbose=False, use_log2=False):
if random_seed:
np.random.seed(random_seed)
n = 1
mu = float(mu or x0)
tout = np.linspace(t0, tend, nt)
assert geom in 'fcs'
# Setup the grid
logb = (lambda arg: log(arg)/log(2)) if use_log2 else log
_x0 = logb(x0) if logx else x0
_xend = logb(xend) if logx else xend
x = np.linspace(_x0, _xend, N+1)
if random:
x += (np.random.random(N+1)-0.5)*(_xend-_x0)/(N+2)
mob = 0.3
# Initial conditions
y0 = {
'f': y0_flat_cb,
'c': y0_cylindrical_cb,
's': y0_spherical_cb
}[geom](x, logx)
# Setup the system
stoich_active = []
stoich_prod = []
k = []
assert not lrefl
assert not rrefl
rd = ReactionDiffusion(
n, stoich_active, stoich_prod, k, N,
D=[D],
z_chg=[1],
mobility=[mob],
x=x,
geom=geom,
logy=logy,
logt=logt,
logx=logx,
nstencil=nstencil,
lrefl=lrefl,
rrefl=rrefl,
use_log2=use_log2
)
if efield:
if geom != 'f':
raise ValueError("Only analytic sol. for flat drift implemented.")
rd.efield = efield_cb(rd.xcenters, logx)
# Analytic reference values
t = tout.copy().reshape((nt, 1))
Cref = np.repeat(y0[np.newaxis, :, np.newaxis], nt, axis=0)
if efield:
Cref += t.reshape((nt, 1, 1))*mob
# Run the integration
integr = run(rd, y0, tout, atol=atol, rtol=rtol,
with_jacobian=(not num_jacobian), method=method)
Cout, info = integr.Cout, integr.info
if verbose:
print(info)
def lin_err(i=slice(None), j=slice(None)):
return integr.Cout[i, :, j] - Cref[i, :, j]
rmsd = np.sum(lin_err()**2 / N, axis=1)**0.5
ave_rmsd_over_atol = np.average(rmsd, axis=0)/info['atol']
# Plot results
if plot:
import matplotlib.pyplot as plt
def _plot(y, c, ttl=None, apply_exp_on_y=False):
plt.plot(rd.xcenters, rd.expb(y) if apply_exp_on_y else y, c=c)
if N < 100:
plt.vlines(rd.x, 0, np.ones_like(rd.x)*max(y), linewidth=.1,
colors='gray')
plt.xlabel('x / m')
plt.ylabel('C / M')
if ttl:
plt.title(ttl)
for i in range(nt):
c = 1-tout[i]/tend
c = (1.0-c, .5-c/2, .5-c/2) # over time: dark red -> light red
plt.subplot(4, 1, 1)
_plot(Cout[i, :, 0], c, 'Simulation (N={})'.format(rd.N),
apply_exp_on_y=logy)
plt.subplot(4, 1, 2)
_plot(Cref[i, :, 0], c, 'Analytic', apply_exp_on_y=logy)
ax_err = plt.subplot(4, 1, 3)
plot_solver_linear_error(integr, Cref, ax_err, ti=i,
bi=slice(None),
color=c, fill=(i == 0))
plt.title('Linear rel error / Log abs. tol. (={})'.format(
info['atol']))
plt.subplot(4, 1, 4)
tspan = [tout[0], tout[-1]]
plt.plot(tout, rmsd[:, 0] / info['atol'], 'r')
plt.plot(tspan, [ave_rmsd_over_atol[0]]*2, 'r--')
plt.xlabel('Time / s')
plt.ylabel(r'$\sqrt{\langle E^2 \rangle} / atol$')
plt.tight_layout()
plt.show()
return tout, Cout, info, ave_rmsd_over_atol, rd
if __name__ == '__main__':
argh.dispatch_command(integrate_rd, output_file=None)
| bjodah/chemreac | examples/steady_state.py | Python | bsd-2-clause | 4,970 |
package org.jvnet.jaxb2_commons.xml.bind.model.concrete;
import java.util.ArrayList;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.activation.MimeType;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import org.jvnet.jaxb2_commons.lang.Validate;
import org.jvnet.jaxb2_commons.xml.bind.model.MBuiltinLeafInfo;
import org.jvnet.jaxb2_commons.xml.bind.model.MClassInfo;
import org.jvnet.jaxb2_commons.xml.bind.model.MClassTypeInfo;
import org.jvnet.jaxb2_commons.xml.bind.model.MContainer;
import org.jvnet.jaxb2_commons.xml.bind.model.MElement;
import org.jvnet.jaxb2_commons.xml.bind.model.MElementInfo;
import org.jvnet.jaxb2_commons.xml.bind.model.MElementTypeRef;
import org.jvnet.jaxb2_commons.xml.bind.model.MEnumLeafInfo;
import org.jvnet.jaxb2_commons.xml.bind.model.MModelInfo;
import org.jvnet.jaxb2_commons.xml.bind.model.MPackageInfo;
import org.jvnet.jaxb2_commons.xml.bind.model.MPropertyInfo;
import org.jvnet.jaxb2_commons.xml.bind.model.MTypeInfo;
import org.jvnet.jaxb2_commons.xml.bind.model.concrete.origin.CMAnyAttributePropertyInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.concrete.origin.CMBuiltinLeafInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.concrete.origin.CMClassInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.concrete.origin.CMElementInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.concrete.origin.CMElementOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.concrete.origin.CMElementTypeRefOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.concrete.origin.CMEnumConstantInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.concrete.origin.CMEnumLeafInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.concrete.origin.CMModelInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.concrete.origin.CMPropertyInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.concrete.origin.CMWildcardTypeInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.origin.MBuiltinLeafInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.origin.MClassInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.origin.MElementInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.origin.MElementOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.origin.MElementTypeRefOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.origin.MEnumConstantInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.origin.MEnumLeafInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.origin.MModelInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.origin.MPropertyInfoOrigin;
import org.jvnet.jaxb2_commons.xml.bind.model.origin.MWildcardTypeInfoOrigin;
import com.sun.xml.bind.v2.model.core.Adapter;
import com.sun.xml.bind.v2.model.core.AttributePropertyInfo;
import com.sun.xml.bind.v2.model.core.BuiltinLeafInfo;
import com.sun.xml.bind.v2.model.core.ClassInfo;
import com.sun.xml.bind.v2.model.core.Element;
import com.sun.xml.bind.v2.model.core.ElementInfo;
import com.sun.xml.bind.v2.model.core.ElementPropertyInfo;
import com.sun.xml.bind.v2.model.core.EnumConstant;
import com.sun.xml.bind.v2.model.core.EnumLeafInfo;
import com.sun.xml.bind.v2.model.core.ID;
import com.sun.xml.bind.v2.model.core.MapPropertyInfo;
import com.sun.xml.bind.v2.model.core.PropertyInfo;
import com.sun.xml.bind.v2.model.core.ReferencePropertyInfo;
import com.sun.xml.bind.v2.model.core.TypeInfo;
import com.sun.xml.bind.v2.model.core.TypeInfoSet;
import com.sun.xml.bind.v2.model.core.TypeRef;
import com.sun.xml.bind.v2.model.core.ValuePropertyInfo;
import com.sun.xml.bind.v2.model.core.WildcardTypeInfo;
public abstract class CMInfoFactory<T, C extends T, TIS extends TypeInfoSet<T, C, ?, ?>,
//
TI extends TypeInfo<T, C>,
//
BLI extends BuiltinLeafInfo<T, C>,
//
E extends Element<T, C>,
//
EI extends ElementInfo<T, C>,
//
ELI extends EnumLeafInfo<T, C>,
//
EC extends EnumConstant<T, C>,
//
CI extends ClassInfo<T, C>,
//
PI extends PropertyInfo<T, C>,
//
API extends AttributePropertyInfo<T, C>,
//
VPI extends ValuePropertyInfo<T, C>,
//
EPI extends ElementPropertyInfo<T, C>,
//
RPI extends ReferencePropertyInfo<T, C>,
//
WTI extends WildcardTypeInfo<T, C>,
//
TR extends TypeRef<T, C>> {
private final Map<BLI, MBuiltinLeafInfo<T, C>> builtinLeafInfos = new IdentityHashMap<BLI, MBuiltinLeafInfo<T, C>>();
private final Map<CI, MClassInfo<T, C>> classInfos = new IdentityHashMap<CI, MClassInfo<T, C>>();
private final Map<ELI, MEnumLeafInfo<T, C>> enumLeafInfos = new IdentityHashMap<ELI, MEnumLeafInfo<T, C>>();
private final Map<EI, MElementInfo<T, C>> elementInfos = new IdentityHashMap<EI, MElementInfo<T, C>>();
private final TIS typeInfoSet;
public CMInfoFactory(TIS typeInfoSet) {
Validate.notNull(typeInfoSet);
this.typeInfoSet = typeInfoSet;
}
public TIS getTypeInfoSet() {
return typeInfoSet;
}
public MModelInfo<T, C> createModel() {
final CMModel<T, C> model = new CMModel<T, C>(
createModelInfoOrigin(typeInfoSet));
createBuiltinLeafInfos(model);
createEnumLeafInfos(model);
createClassInfos(model);
createElementInfos(model);
return model;
}
private void createElementInfos(final CMModel<T, C> model) {
Iterable<? extends ElementInfo<T, C>> elements = typeInfoSet
.getAllElements();
for (ElementInfo<T, C> element : elements) {
final EI ei = (EI) element;
getElementInfo(ei);
}
for (ElementInfo<T, C> element : elements) {
model.addElementInfo(getElementInfo((EI) element));
}
}
private void createEnumLeafInfos(final CMModel<T, C> model) {
Collection<? extends EnumLeafInfo<T, C>> enums = typeInfoSet.enums()
.values();
for (EnumLeafInfo<T, C> enumLeafInfo : enums) {
@SuppressWarnings("unchecked")
final ELI eli = (ELI) enumLeafInfo;
getTypeInfo(eli);
}
for (Map.Entry<ELI, MEnumLeafInfo<T, C>> entry : enumLeafInfos
.entrySet()) {
populateEnumLeafInfo(entry.getKey(), entry.getValue());
}
for (EnumLeafInfo<T, C> enumLeafInfo : enums) {
model.addEnumLeafInfo(getTypeInfo((ELI) enumLeafInfo));
}
}
private void createBuiltinLeafInfos(final CMModel<T, C> model) {
Collection<? extends BuiltinLeafInfo<T, C>> builtins = typeInfoSet
.builtins().values();
for (BuiltinLeafInfo<T, C> builtinLeafInfo : builtins) {
@SuppressWarnings("unchecked")
final BLI bli = (BLI) builtinLeafInfo;
getTypeInfo(bli);
}
for (BuiltinLeafInfo<T, C> builtinLeafInfo : builtins) {
model.addBuiltinLeafInfo(getTypeInfo((BLI) builtinLeafInfo));
}
}
private void createClassInfos(final CMModel<T, C> model) {
Collection<? extends ClassInfo<T, C>> beans = typeInfoSet.beans()
.values();
for (ClassInfo<T, C> classInfo : beans) {
@SuppressWarnings("unchecked")
final CI ci = (CI) classInfo;
getTypeInfo(ci);
}
for (Map.Entry<CI, MClassInfo<T, C>> entry : classInfos.entrySet()) {
populateClassInfo(entry.getKey(), entry.getValue());
}
for (ClassInfo<T, C> classInfo : beans) {
model.addClassInfo(getTypeInfo((CI) classInfo));
}
}
protected MTypeInfo<T, C> getTypeInfo(PropertyInfo<T, C> propertyInfo,
TI typeInfo, boolean list, Adapter<T, C> adapter, ID id,
MimeType mimeType) {
final MTypeInfo<T, C> ti = getTypeInfo(typeInfo);
if (list) {
switch (id) {
case ID:
final MTypeInfo<T, C> tid = new CMID<T, C>(ti.getTargetType(),
ti);
return new CMList<T, C>(createListType(tid.getTargetType()),
tid, null);
case IDREF:
return new CMIDREFS<T, C>(createListType(ti.getTargetType()),
ti);
default:
return new CMList<T, C>(createListType(ti.getTargetType()), ti,
null);
}
} else {
switch (id) {
case ID:
return new CMID<T, C>(ti.getTargetType(), ti);
case IDREF:
return new CMIDREF<T, C>(ti.getTargetType(), ti);
default:
return ti;
}
}
}
protected MTypeInfo<T, C> getTypeInfo(TI typeInfo) {
if (typeInfo instanceof BuiltinLeafInfo) {
return getTypeInfo((BLI) typeInfo);
} else if (typeInfo instanceof EnumLeafInfo) {
return getTypeInfo((ELI) typeInfo);
} else if (typeInfo instanceof ElementInfo) {
return getTypeInfo((EI) typeInfo);
} else if (typeInfo instanceof WildcardTypeInfo) {
return createWildcardTypeInfo((WTI) typeInfo);
} else if (typeInfo instanceof ClassInfo) {
return getTypeInfo((CI) typeInfo);
} else {
throw new UnsupportedOperationException(typeInfo.getClass()
.getName());
}
}
private MBuiltinLeafInfo<T, C> getTypeInfo(BLI info) {
MBuiltinLeafInfo<T, C> builtinLeafInfo = builtinLeafInfos.get(info);
if (builtinLeafInfo == null) {
builtinLeafInfo = createBuiltinLeafInfo(info);
builtinLeafInfos.put(info, builtinLeafInfo);
}
return builtinLeafInfo;
}
private MTypeInfo<T, C> getTypeInfo(EI info) {
@SuppressWarnings("unchecked")
EPI p = (EPI) info.getProperty();
@SuppressWarnings("unchecked")
TI contentType = (TI) info.getContentType();
return getTypeInfo(p, contentType, p.isValueList(), p.getAdapter(),
p.id(), p.getExpectedMimeType());
}
protected MClassInfo<T, C> getTypeInfo(CI info) {
MClassInfo<T, C> classInfo = classInfos.get(info);
if (classInfo == null) {
classInfo = createClassInfo(info);
classInfos.put(info, classInfo);
}
return classInfo;
}
private MEnumLeafInfo<T, C> getTypeInfo(ELI info) {
MEnumLeafInfo<T, C> enumLeafInfo = enumLeafInfos.get(info);
if (enumLeafInfo == null) {
enumLeafInfo = createEnumLeafInfo(info);
enumLeafInfos.put(info, enumLeafInfo);
}
return enumLeafInfo;
}
private void populateEnumLeafInfo(ELI info, MEnumLeafInfo<T, C> enumLeafInfo) {
@SuppressWarnings("rawtypes")
Iterable<? extends EnumConstant> _constants = info.getConstants();
@SuppressWarnings("unchecked")
final Iterable<? extends EnumConstant<T, C>> enumConstants = (Iterable<? extends EnumConstant<T, C>>) _constants;
for (EnumConstant<?, ?> enumConstant : enumConstants) {
enumLeafInfo.addEnumConstantInfo(createEnumContantInfo(
enumLeafInfo, (EC) enumConstant));
}
}
protected MElementInfo<T, C> getElementInfo(EI info) {
MElementInfo<T, C> elementInfo = elementInfos.get(info);
if (elementInfo == null) {
elementInfo = createElementInfo(info);
elementInfos.put(info, elementInfo);
}
return elementInfo;
}
protected MClassInfo<T, C> createClassInfo(CI info) {
return new CMClassInfo<T, C>(createClassInfoOrigin(info),
info.getClazz(), getPackage(info), getContainer(info),
getLocalName(info), createBaseTypeInfo(info),
info.isElement() ? info.getElementName() : null,
info.getTypeName());
}
private void populateClassInfo(CI info, MClassInfo<T, C> classInfo) {
if (info.hasAttributeWildcard()) {
classInfo.addProperty(createAnyAttributePropertyInfo(classInfo));
}
for (PropertyInfo<T, C> p : (List<? extends PropertyInfo<T, C>>) info
.getProperties()) {
classInfo.addProperty(createPropertyInfo(classInfo, (PI) p));
}
}
protected MClassTypeInfo<T, C, ?> createBaseTypeInfo(CI info) {
return info.getBaseClass() == null ? null : getTypeInfo((CI) info
.getBaseClass());
}
private MPropertyInfo<T, C> createPropertyInfo(
final MClassInfo<T, C> classInfo, PI p) {
if (p instanceof AttributePropertyInfo) {
@SuppressWarnings("unchecked")
final API api = (API) p;
return createAttributePropertyInfo(classInfo, api);
} else if (p instanceof ValuePropertyInfo) {
@SuppressWarnings("unchecked")
final VPI vpi = (VPI) p;
return createValuePropertyInfo(classInfo, vpi);
} else if (p instanceof ElementPropertyInfo) {
@SuppressWarnings("unchecked")
final EPI ep = (EPI) p;
if (ep.getTypes().size() == 1) {
return createElementPropertyInfo(classInfo, ep);
} else {
return createElementsPropertyInfo(classInfo, ep);
}
} else if (p instanceof ReferencePropertyInfo) {
@SuppressWarnings("unchecked")
final RPI rp = (RPI) p;
final Set<? extends Element<T, C>> elements = rp.getElements();
if (elements.size() == 0
&& rp.getWildcard() != null
&& (rp.getWildcard().allowDom || rp.getWildcard().allowTypedObject)) {
return createAnyElementPropertyInfo(classInfo, rp);
} else if (elements.size() == 1) {
return createElementRefPropertyInfo(classInfo, rp);
} else {
return createElementRefsPropertyInfo(classInfo, rp);
}
} else if (p instanceof MapPropertyInfo) {
// System.out.println("Map property: " + p.getName());
// MapPropertyInfo<T, C> mp = (MapPropertyInfo<T, C>) p;
throw new UnsupportedOperationException();
} else {
throw new AssertionError();
}
}
protected MPropertyInfo<T, C> createAttributePropertyInfo(
final MClassInfo<T, C> classInfo, final API propertyInfo) {
return new CMAttributePropertyInfo<T, C>(
createPropertyInfoOrigin((PI) propertyInfo), classInfo,
propertyInfo.getName(), getTypeInfo(propertyInfo),
propertyInfo.getXmlName(), propertyInfo.isRequired(),
getDefaultValue(propertyInfo),
getDefaultValueNamespaceContext(propertyInfo));
}
protected MPropertyInfo<T, C> createValuePropertyInfo(
final MClassInfo<T, C> classInfo, final VPI propertyInfo) {
return new CMValuePropertyInfo<T, C>(
createPropertyInfoOrigin((PI) propertyInfo), classInfo,
propertyInfo.getName(), getTypeInfo(propertyInfo), null, null);
}
protected MPropertyInfo<T, C> createElementPropertyInfo(
final MClassInfo<T, C> classInfo, final EPI ep) {
final TR typeRef = (TR) ep.getTypes().get(0);
return new CMElementPropertyInfo<T, C>(
createPropertyInfoOrigin((PI) ep), classInfo, ep.getName(),
ep.isCollection() && !ep.isValueList(), ep.isRequired(),
getTypeInfo(ep, typeRef), typeRef.getTagName(),
ep.getXmlName(), typeRef.isNillable(),
getDefaultValue(typeRef),
getDefaultValueNamespaceContext(typeRef));
}
protected MPropertyInfo<T, C> createElementsPropertyInfo(
final MClassInfo<T, C> classInfo, final EPI ep) {
List<? extends TR> types = (List<? extends TR>) ep.getTypes();
final Collection<MElementTypeRef<T, C>> typedElements = new ArrayList<MElementTypeRef<T, C>>(
types.size());
for (TR typeRef : types) {
typedElements.add(new CMElementTypeRef<T, C>(
createElementTypeRefOrigin(ep, typeRef), typeRef
.getTagName(), getTypeInfo(ep, typeRef), typeRef
.isNillable(), getDefaultValue(typeRef),
getDefaultValueNamespaceContext(typeRef)));
}
return new CMElementsPropertyInfo<T, C>(
createPropertyInfoOrigin((PI) ep), classInfo, ep.getName(),
ep.isCollection() && !ep.isValueList(), ep.isRequired(),
typedElements, ep.getXmlName());
}
protected MPropertyInfo<T, C> createAnyElementPropertyInfo(
final MClassInfo<T, C> classInfo, final RPI rp) {
return new CMAnyElementPropertyInfo<T, C>(
createPropertyInfoOrigin((PI) rp), classInfo, rp.getName(),
rp.isCollection(), rp.isRequired(), rp.isMixed(),
rp.getWildcard().allowDom, rp.getWildcard().allowTypedObject);
}
protected MPropertyInfo<T, C> createElementRefPropertyInfo(
final MClassInfo<T, C> classInfo, final RPI rp) {
final Element<T, C> element = rp.getElements().iterator().next();
return new CMElementRefPropertyInfo<T, C>(
createPropertyInfoOrigin((PI) rp), classInfo, rp.getName(),
rp.isCollection(), rp.isRequired(), getTypeInfo(rp, element),
element.getElementName(), rp.getXmlName(),
rp.isMixed(), rp.getWildcard() == null ? false
: rp.getWildcard().allowDom,
rp.getWildcard() == null ? true
: rp.getWildcard().allowTypedObject,
getDefaultValue(element),
getDefaultValueNamespaceContext(element));
}
protected MPropertyInfo<T, C> createElementRefsPropertyInfo(
final MClassInfo<T, C> classInfo, final RPI rp) {
final List<MElement<T, C>> typedElements = new ArrayList<MElement<T, C>>();
for (Element<T, C> e : rp.getElements()) {
final E element = (E) e;
typedElements.add(new CMElement<T, C>(createElementOrigin(element),
element.getElementName(), getTypeInfo(rp, element), true,
getDefaultValue(element),
getDefaultValueNamespaceContext(element)));
}
return new CMElementRefsPropertyInfo<T, C>(
createPropertyInfoOrigin((PI) rp), classInfo, rp.getName(),
rp.isCollection(), rp.isRequired(), typedElements,
rp.getXmlName(), rp.isMixed(), rp.getWildcard() == null ? false
: rp.getWildcard().allowDom,
rp.getWildcard() == null ? true
: rp.getWildcard().allowTypedObject);
}
protected CMAnyAttributePropertyInfo<T, C> createAnyAttributePropertyInfo(
final MClassInfo<T, C> classInfo) {
return new CMAnyAttributePropertyInfo<T, C>(
createAnyAttributePropertyInfoOrigin(), classInfo,
"otherAttributes");
}
protected MTypeInfo<T, C> getTypeInfo(final ValuePropertyInfo<T, C> vp) {
return getTypeInfo(vp, (TI) vp.ref().iterator().next(),
vp.isCollection(), vp.getAdapter(), vp.id(),
vp.getExpectedMimeType());
}
protected MTypeInfo<T, C> getTypeInfo(final AttributePropertyInfo<T, C> ap) {
return getTypeInfo(ap, (TI) ap.ref().iterator().next(),
ap.isCollection(), ap.getAdapter(), ap.id(),
ap.getExpectedMimeType());
}
protected MTypeInfo<T, C> getTypeInfo(final ElementPropertyInfo<T, C> ep,
final TR typeRef) {
return getTypeInfo(ep, (TI) typeRef.getTarget(),
ep.isValueList(), ep.getAdapter(), ep.id(), ep.getExpectedMimeType());
}
protected MTypeInfo<T, C> getTypeInfo(final ReferencePropertyInfo<T, C> rp,
Element<T, C> element) {
return getTypeInfo(rp, (TI) element, false, rp.getAdapter(), rp.id(),
rp.getExpectedMimeType());
}
private String getDefaultValue(Element<T, C> element) {
if (element instanceof ElementInfo) {
final ElementInfo<T, C> elementInfo = (ElementInfo<T, C>) element;
final ElementPropertyInfo<T, C> property = elementInfo
.getProperty();
if (property != null) {
final List<? extends TR> types = (List<? extends TR>) property.getTypes();
if (types.size() == 1) {
final TR typeRef = types.get(0);
return getDefaultValue(typeRef);
}
}
}
return null;
}
private NamespaceContext getDefaultValueNamespaceContext(
Element<T, C> element) {
if (element instanceof ElementInfo) {
final ElementInfo<T, C> elementInfo = (ElementInfo<T, C>) element;
final ElementPropertyInfo<T, C> property = elementInfo
.getProperty();
if (property != null) {
final List<? extends TypeRef<T, C>> types = property.getTypes();
if (types.size() == 1) {
final TypeRef<T, C> typeRef = types.get(0);
return getDefaultValueNamespaceContext(typeRef);
}
}
}
return null;
}
protected abstract MPackageInfo getPackage(CI info);
protected abstract String getLocalName(CI info);
protected abstract MClassInfo<T, C> getScope(CI info);
protected abstract MPackageInfo getPackage(ELI info);
protected abstract String getLocalName(ELI info);
protected abstract String getLocalName(EI info);
protected abstract MPackageInfo getPackage(EI info);
protected abstract MContainer getContainer(CI info);
protected abstract MContainer getContainer(EI info);
protected abstract MContainer getContainer(ELI info);
//
protected MBuiltinLeafInfo<T, C> createBuiltinLeafInfo(BLI info) {
return new CMBuiltinLeafInfo<T, C>(createBuiltinLeafInfoOrigin(info),
info.getType(), info.getTypeName());
}
protected MEnumLeafInfo<T, C> createEnumLeafInfo(final ELI info) {
@SuppressWarnings("unchecked")
final TI baseType = (TI) info.getBaseType();
return new CMEnumLeafInfo<T, C>(createEnumLeafInfoOrigin(info),
info.getClazz(), getPackage(info), getContainer(info),
getLocalName(info), getTypeInfo(baseType),
info.getElementName(), info.getTypeName());
}
protected CMEnumConstantInfo<T, C> createEnumContantInfo(
MEnumLeafInfo<T, C> enumLeafInfo, EC enumConstant) {
return new CMEnumConstantInfo<T, C>(
createEnumConstantInfoOrigin(enumConstant), enumLeafInfo,
enumConstant.getLexicalValue());
}
protected MElementInfo<T, C> createElementInfo(EI element) {
@SuppressWarnings("unchecked")
final CI scopeCI = (CI) element.getScope();
final MClassInfo<T, C> scope = element.getScope() == null ? null
: getTypeInfo(scopeCI);
final QName substitutionHead = element.getSubstitutionHead() == null ? null
: element.getSubstitutionHead().getElementName();
final MElementInfo<T, C> elementInfo = new CMElementInfo<T, C>(
createElementInfoOrigin(element), getPackage(element),
getContainer(element), getLocalName(element),
element.getElementName(), scope, getTypeInfo(element),
substitutionHead, getDefaultValue(element),
getDefaultValueNamespaceContext(element));
return elementInfo;
}
protected MTypeInfo<T, C> createWildcardTypeInfo(WTI info) {
return new CMWildcardTypeInfo<T, C>(createWildcardTypeInfoOrigin(info),
info.getType());
}
protected MModelInfoOrigin createModelInfoOrigin(TIS info) {
return new CMModelInfoOrigin<T, C, TIS>(info);
}
protected MBuiltinLeafInfoOrigin createBuiltinLeafInfoOrigin(BLI info) {
return new CMBuiltinLeafInfoOrigin<T, C, BLI>(info);
}
protected MClassInfoOrigin createClassInfoOrigin(CI info) {
return new CMClassInfoOrigin<T, C, CI>(info);
}
protected MPropertyInfoOrigin createAnyAttributePropertyInfoOrigin() {
return new CMAnyAttributePropertyInfoOrigin();
}
protected MPropertyInfoOrigin createPropertyInfoOrigin(PI info) {
return new CMPropertyInfoOrigin<T, C, PI>(info);
}
protected MElementOrigin createElementOrigin(E info) {
return new CMElementOrigin<T, C, E>(info);
}
protected MElementTypeRefOrigin createElementTypeRefOrigin(EPI ep,
TR typeRef) {
return new CMElementTypeRefOrigin<T, C, EPI, TR>(ep, typeRef);
}
protected MElementInfoOrigin createElementInfoOrigin(EI info) {
return new CMElementInfoOrigin<T, C, EI>(info);
}
protected MEnumLeafInfoOrigin createEnumLeafInfoOrigin(ELI info) {
return new CMEnumLeafInfoOrigin<T, C, ELI>(info);
}
protected MEnumConstantInfoOrigin createEnumConstantInfoOrigin(EC info) {
return new CMEnumConstantInfoOrigin<T, C, EC>(info);
}
protected MWildcardTypeInfoOrigin createWildcardTypeInfoOrigin(WTI info) {
return new CMWildcardTypeInfoOrigin<T, C, WTI>(info);
}
protected abstract T createListType(T elementType);
/**
* Returns Java class for the reference type or null if it can't be found.
*
* @param referencedType
* referenced type.
* @return Java class for the reference type or null.
*/
protected abstract Class<?> loadClass(T referencedType);
protected abstract String getDefaultValue(API propertyInfo);
protected abstract NamespaceContext getDefaultValueNamespaceContext(
API propertyInfo);
protected abstract String getDefaultValue(TypeRef<T, C> typeRef);
protected abstract NamespaceContext getDefaultValueNamespaceContext(
TypeRef<T, C> typeRef);
}
| Stephan202/jaxb2-basics | runtime/src/main/java/org/jvnet/jaxb2_commons/xml/bind/model/concrete/CMInfoFactory.java | Java | bsd-2-clause | 22,939 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: |
When "String" is called as part of a new expression, it is a constructor: it initialises the newly created object and
The [[Value]] property of the newly constructed object is set to ToString(value), or to the empty string if value is not supplied
es5id: 15.5.2.1_A1_T16
description: >
Creating string object with "new String()" initialized with .12345
and other numbers
---*/
var __str = new String(.12345);
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (typeof __str !== "object") {
$ERROR('#1: __str =new String(.12345); typeof __str === "object". Actual: typeof __str ===' + typeof __str);
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#1.5
if (__str.constructor !== String) {
$ERROR('#1.5: __str =new String(.12345); __str.constructor === String. Actual: __str.constructor ===' + __str.constructor);
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#2
if (__str != "0.12345") {
$ERROR('#2: __str =new String(.12345); __str =="0.12345". Actual: __str ==' + __str);
}
//
//////////////////////////////////////////////////////////////////////////////
__str = new String(.012345);
//////////////////////////////////////////////////////////////////////////////
//CHECK#3
if (typeof __str !== "object") {
$ERROR('#3: __str =new String(.012345); typeof __str === "object". Actual: typeof __str ===' + typeof __str);
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#2.5
if (__str.constructor !== String) {
$ERROR('#3.5: __str =new String(.012345); __str.constructor === String. Actual: __str.constructor ===' + __str.constructor);
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#4
if (__str != "0.012345") {
$ERROR('#4: __str =new String(.012345); __str =="0.012345". Actual: __str ==' + __str);
}
//
//////////////////////////////////////////////////////////////////////////////
__str = new String(.0012345);
//////////////////////////////////////////////////////////////////////////////
//CHECK#5
if (typeof __str !== "object") {
$ERROR('#5: __str =new String(.0012345); typeof __str === "object". Actual: typeof __str ===' + typeof __str);
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#5.5
if (__str.constructor !== String) {
$ERROR('#5.5: __str =new String(.0012345); __str.constructor === String. Actual: __str.constructor ===' + __str.constructor);
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#6
if (__str != "0.0012345") {
$ERROR('#6: __str =new String(.0012345); __str =="0.0012345". Actual: __str ==' + __str);
}
//
//////////////////////////////////////////////////////////////////////////////
__str = new String(.00000012345);
//////////////////////////////////////////////////////////////////////////////
//CHECK#7
if (typeof __str !== "object") {
$ERROR('#7: __str =new String(.00000012345); typeof __str === "object". Actual: typeof __str ===' + typeof __str);
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#7.5
if (__str.constructor !== String) {
$ERROR('#7.5: __str =new String(.00000012345); __str.constructor === String. Actual: __str.constructor ===' + __str.constructor);
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#8
if (__str != "1.2345e-7") {
$ERROR('#8: __str =new String(.00000012345); __str =="1.2345e-7". Actual: __str ==' + __str);
}
//
//////////////////////////////////////////////////////////////////////////////
| sebastienros/jint | Jint.Tests.Test262/test/built-ins/String/S15.5.2.1_A1_T16.js | JavaScript | bsd-2-clause | 4,487 |
cask 'anka-flow' do
version '1.1.1.79'
sha256 '9f91222458f5b7b52bee53a62e878faed4a4894ca02fe3d37b52b79b54c523fa'
# d1efqjhnhbvc57.cloudfront.net was verified as official when first introduced to the cask
url "https://d1efqjhnhbvc57.cloudfront.net/AnkaFlow-#{version}.pkg",
referer: 'https://veertu.com/download-anka-run/'
appcast 'https://ankadoc.bitbucket.io/release-notes/index.html',
checkpoint: '902e8a6a51287459ac85fb33f03569004dc105637b9c6a86827beacf53f341c9'
name 'Veertu Anka Flow'
homepage 'https://veertu.com/'
depends_on macos: '>= :yosemite'
pkg "AnkaFlow-#{version}.pkg"
uninstall launchctl: [
'com.veertu.nlimit',
'com.veertu.vlaunch',
],
script: {
executable: '/Library/Application Support/Veertu/Anka/tools/uninstall.sh',
args: ['-f'],
sudo: true,
}
zap trash: [
'~/.anka',
'~/Library/Application Support/Veertu/Anka',
'~/Library/Logs/Anka',
'~/Library/Preferences/com.veertu.ankaview.plist',
'/Library/Application Support/Veertu/Anka',
],
rmdir: [
'~/Library/Application Support/Veertu',
'/Library/Application Support/Veertu',
]
caveats <<~EOS
Installing this Cask means you have AGREED to the
Veertu End User License Agreement at
https://veertu.com/terms-and-conditions/
EOS
end
| tedski/homebrew-cask | Casks/anka-flow.rb | Ruby | bsd-2-clause | 1,593 |
/*
* Copyright (C) 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "config.h"
#if ENABLE(MEDIA_STREAM)
#include "MediaTrackConstraints.h"
#include "MediaTrackConstraint.h"
#include "MediaTrackConstraintSet.h"
#include "NotImplemented.h"
using namespace JSC;
namespace WebCore {
RefPtr<MediaTrackConstraints> MediaTrackConstraints::create(PassRefPtr<MediaConstraintsImpl> constraints)
{
return adoptRef(new MediaTrackConstraints(constraints));
}
MediaTrackConstraints::MediaTrackConstraints(PassRefPtr<MediaConstraintsImpl> constraints)
: m_constraints(constraints)
{
}
Vector<PassRefPtr<MediaTrackConstraint>> MediaTrackConstraints::optional(bool) const
{
// https://bugs.webkit.org/show_bug.cgi?id=121954
notImplemented();
return Vector<PassRefPtr<MediaTrackConstraint>>();
}
RefPtr<MediaTrackConstraintSet> MediaTrackConstraints::mandatory(bool) const
{
// https://bugs.webkit.org/show_bug.cgi?id=121954
notImplemented();
return nullptr;
}
} // namespace WebCore
#endif
| aosm/WebCore | Modules/mediastream/MediaTrackConstraints.cpp | C++ | bsd-2-clause | 2,294 |
# Generated by Django 3.1.4 on 2020-12-15 15:58
from django.db import migrations
def copy_labels(apps, schema_editor):
Trek = apps.get_model('trekking', 'Trek')
Label = apps.get_model('common', 'Label')
for trek in Trek.objects.all():
for label in trek.labels.all():
label2, created = Label.objects.get_or_create(name=label.name, defaults={'advice': label.advice, 'filter': label.filter_rando})
trek.labels2.add(label2)
class Migration(migrations.Migration):
dependencies = [
('trekking', '0023_trek_labels2'),
]
operations = [
migrations.RunPython(copy_labels),
]
| makinacorpus/Geotrek | geotrek/trekking/migrations/0024_copy_labels.py | Python | bsd-2-clause | 649 |
class Cuetools < Formula
desc "Utilities for .cue and .toc files"
homepage "https://github.com/svend/cuetools"
url "https://github.com/svend/cuetools/archive/1.4.1.tar.gz"
sha256 "24a2420f100c69a6539a9feeb4130d19532f9f8a0428a8b9b289c6da761eb107"
head "https://github.com/svend/cuetools.git"
bottle do
cellar :any_skip_relocation
sha256 "1e36c3c8d2d53947b73a9f0a0aed74145e2b1890f83764de02f1d12566d0300f" => :mojave
sha256 "4393d6db857a9568a34de3a09ff049fbec9a55a95b029eacd24e35d6ce792074" => :high_sierra
sha256 "9456e5957a78f993f5a8cef76aa583ac6a42a8298fb05bded243dbaf810f9a44" => :sierra
sha256 "7f0effc75d64fca0f2695b5f7ddb4d8713cc83522d40dcd37842e83c120ac117" => :el_capitan
sha256 "81d06ef2e3d98061f332a535b810102c1be0505371c1ac1aed711cf2ae8de5a3" => :yosemite
sha256 "95216c0df3840b2602e61dd3bef7d4c9b65cec0315e5b23ac87329320d9f6be9" => :mavericks
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
# see https://github.com/svend/cuetools/pull/18
patch :DATA
def install
system "autoreconf", "-i"
system "./configure", "--prefix=#{prefix}", "--mandir=#{man}"
system "make", "install"
end
test do
(testpath/"test.cue").write <<~EOS
FILE "sampleimage.bin" BINARY
TRACK 01 MODE1/2352
INDEX 01 00:00:00
EOS
system "cueconvert", testpath/"test.cue", testpath/"test.toc"
assert_predicate testpath/"test.toc", :exist?
end
end
__END__
diff --git a/configure.ac b/configure.ac
index f54bb92..84ab467 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,5 +1,5 @@
AC_INIT([cuetools], [1.4.0], [svend@ciffer.net])
-AM_INIT_AUTOMAKE([-Wall -Werror foreign])
+AM_INIT_AUTOMAKE([-Wall -Werror -Wno-extra-portability foreign])
AC_PROG_CC
AC_PROG_INSTALL
AC_PROG_RANLIB
| jdubois/homebrew-core | Formula/cuetools.rb | Ruby | bsd-2-clause | 1,827 |
#define SOL_CHECK_ARGUMENTS 1
#include <sol.hpp>
#include "assert.hpp"
#include <iostream>
int main(int, char*[]) {
std::cout << "=== coroutine state transfer ===" << std::endl;
sol::state lua;
lua.open_libraries();
sol::function transferred_into;
lua["f"] = [&lua, &transferred_into](sol::object t, sol::this_state this_L) {
std::cout << "state of main : " << (void*)lua.lua_state() << std::endl;
std::cout << "state of function : " << (void*)this_L.lua_state() << std::endl;
// pass original lua_State* (or sol::state/sol::state_view)
// transfers ownership from the state of "t",
// to the "lua" sol::state
transferred_into = sol::function(lua, t);
};
lua.script(R"(
i = 0
function test()
co = coroutine.create(
function()
local g = function() i = i + 1 end
f(g)
g = nil
collectgarbage()
end
)
coroutine.resume(co)
co = nil
collectgarbage()
end
)");
// give it a try
lua.safe_script("test()");
// should call 'g' from main thread, increment i by 1
transferred_into();
// check
int i = lua["i"];
c_assert(i == 1);
std::cout << std::endl;
return 0;
}
| Project-OSRM/osrm-backend | third_party/sol2/examples/coroutine_state.cpp | C++ | bsd-2-clause | 1,131 |
/*
* w-driver-volleyball-lstm-evaluator.cpp
*
* Created on: Jul 13, 2015
* Author: msibrahi
*/
#include <iostream>
#include <vector>
#include <stdio.h>
#include <string>
#include <set>
#include <set>
#include <map>
#include <iomanip>
using std::vector;
using std::set;
using std::multiset;
using std::map;
using std::pair;
using std::string;
using std::endl;
using std::cerr;
#include "boost/algorithm/string.hpp"
#include "google/protobuf/text_format.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/net.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/db.hpp"
#include "caffe/util/io.hpp"
#include "caffe/vision_layers.hpp"
using caffe::Blob;
using caffe::Caffe;
using caffe::Datum;
using caffe::Net;
using caffe::Layer;
using caffe::LayerParameter;
using caffe::DataParameter;
using caffe::NetParameter;
using boost::shared_ptr;
namespace db = caffe::db;
#include "../src/utilities.h"
#include "../src/leveldb-reader.h"
void evaluate(vector<int> truthLabels, vector<int> resultLabels, int w) {
set<int> total_labels;
map<int, map<int, int> > confusion_freq_maps;
map<int, int> label_freq;
int correct = 0;
cerr<<"\n\n";
for (int i = 0; i < (int) truthLabels.size(); ++i) {
correct += truthLabels[i] == resultLabels[i];
cerr << "Test " << i + 1 << ": Result = " << resultLabels[i] << " GroundTruth = " << truthLabels[i] << "\n";
confusion_freq_maps[truthLabels[i]][resultLabels[i]]++;
total_labels.insert(truthLabels[i]);
total_labels.insert(resultLabels[i]);
label_freq[truthLabels[i]]++;
}
cerr.setf(std::ios::fixed);
cerr.precision(2);
cerr<<"\n\n";
cerr << "Total testing frames: " << truthLabels.size() << " with temporal window: " << w << "\n";
cerr << "Temporal accuracy : " << 100.0 * correct / truthLabels.size() << " %\n";
cerr << "\n=======================================================================================\n";
cerr << "\nConfusion Matrix - Truth (col) / Result(row)\n\n";
cerr << std::setw(5) << "T/R" << ": ";
for (auto r_label : total_labels)
cerr << std::setw(5) << r_label;
cerr << "\n=======================================================================================\n";
for (auto t_label : total_labels) {
int sum = 0;
cerr << std::setw(5) << t_label << ": ";
for (auto r_label : total_labels)
{
cerr << std::setw(5) << confusion_freq_maps[t_label][r_label];
sum += confusion_freq_maps[t_label][r_label];
}
double percent = 0;
if (label_freq[t_label] > 0)
percent = 100.0 * confusion_freq_maps[t_label][t_label] / label_freq[t_label];
cerr << " \t=> Total Correct = " << std::setw(5) << confusion_freq_maps[t_label][t_label] << " / " << std::setw(5) << sum << " = " << percent << " %\n";
}
cerr<<"\n\n";
cerr << std::setw(7) << "T/R" << ": ";
for (auto r_label : total_labels)
cerr << std::setw(7) << r_label;
cerr << "\n=======================================================================================\n";
for (auto t_label : total_labels) {
cerr << std::setw(7) << t_label << ": ";
for (auto r_label : total_labels)
{
double percent = 0;
if (label_freq[t_label] > 0)
percent = 100.0 * confusion_freq_maps[t_label][r_label] / label_freq[t_label];
cerr << std::setw(7) << percent;
}
cerr<<"\n";
}
cerr<<"\nTo get labels corresponding to IDs..see dataset loading logs\n";
}
int getArgmax(vector<float> &v) {
int pos = 0;
assert(v.size() > 0);
for (int j = 1; j < (int) v.size(); ++j) {
if (v[j] > v[pos])
pos = j;
}
return pos;
}
template<typename Dtype>
void feature_extraction_pipeline(int &argc, char** &argv) {
int frames_window = MostCV::consumeIntParam(argc, argv);
LOG(ERROR)<< "Temporal Window = " << frames_window;
string computation_mode = MostCV::consumeStringParam(argc, argv);
if (strcmp(computation_mode.c_str(), "GPU") == 0) {
uint device_id = MostCV::consumeIntParam(argc, argv);
LOG(ERROR)<< "Using GPU";
LOG(ERROR)<< "Using Device_id = " << device_id;
Caffe::SetDevice(device_id);
Caffe::set_mode(Caffe::GPU);
} else {
LOG(ERROR)<< "Using CPU";
Caffe::set_mode(Caffe::CPU);
}
string pretrained_binary_proto(MostCV::consumeStringParam(argc, argv));
string feature_extraction_proto(MostCV::consumeStringParam(argc, argv));
LOG(ERROR)<<"Model: "<<pretrained_binary_proto<<"\n";
LOG(ERROR)<<"Proto: "<<feature_extraction_proto<<"\n";
LOG(ERROR)<<"Creating the test network\n";
shared_ptr<Net<Dtype> > feature_extraction_net(new Net<Dtype>(feature_extraction_proto, caffe::Phase::TEST));
LOG(ERROR)<<"Loading the Model\n";
feature_extraction_net->CopyTrainedLayersFrom(pretrained_binary_proto);
string blob_name = MostCV::consumeStringParam(argc, argv);
LOG(ERROR)<<"blob_name: "<<blob_name<<"\n";
CHECK(feature_extraction_net->has_blob(blob_name)) << "Unknown feature blob name " << blob_name << " in the network " << feature_extraction_proto;
int num_mini_batches = MostCV::consumeIntParam(argc, argv);
LOG(ERROR)<<"num_mini_batches: "<<num_mini_batches<<"\n";
vector<Blob<float>*> input_vec;
int batch_size = -1;
int dim_features = -1;
std::set<int> labels; // every (2w+1) * batch size MUST all have same label
vector<int> truthLabels;
vector<int> propAvgMaxResultLabels;
for (int batch_index = 0; batch_index < num_mini_batches; ++batch_index) { // e.g. 100 iterations. Probably roll on data if needed
feature_extraction_net->Forward(input_vec); // Take one batch of data (e.g. 50 images), and pass them to end of network
// Load the Labels
const shared_ptr<Blob<Dtype> > label_blob = feature_extraction_net->blob_by_name("label");
batch_size = label_blob->num(); // e.g. 50 batches
assert(batch_size == frames_window);
int current_label = -1;
for (int n = 0; n < batch_size; ++n) {
const Dtype* label_blob_data = label_blob->cpu_data() + label_blob->offset(n); // move offset to ith blob in batch
current_label = label_blob_data[0]; // all will be same value
labels.insert(current_label);
if (n == 0)
truthLabels.push_back(current_label);
}
if (labels.size() != 1) { // every 1 batch should have same value
LOG(ERROR)<< "Something wrong. every 1 batch should have same value. New value at element " << batch_index + 1 << "\n";
assert(false);
}
labels.clear();
const shared_ptr<Blob<Dtype> > feature_blob = feature_extraction_net->blob_by_name(blob_name); // get e.g. fc7 blob for the batch
dim_features = feature_blob->count() / batch_size;
assert(dim_features > 1);
const Dtype* feature_blob_data = nullptr;
vector<float> test_case_sum(dim_features);
for (int n = 0; n < batch_size; ++n) {
feature_blob_data = feature_blob->cpu_data() + feature_blob->offset(n); // move offset to ith blob in batch
vector<float> test_case;
for (int j = 0; j < dim_features; ++j) {
test_case.push_back(feature_blob_data[j]);
test_case_sum[j] += feature_blob_data[j];
}
}
propAvgMaxResultLabels.push_back( getArgmax(test_case_sum) );
}
evaluate(truthLabels, propAvgMaxResultLabels, 1);
}
int main(int argc, char** argv) {
::google::InitGoogleLogging(argv[0]);
MostCV::consumeStringParam(argc, argv); // read program entry data
if (argc < 6) {
LOG(ERROR)<< "At least 6 parameters expected\n";
assert(false);
}
LOG(ERROR)<< "Make sure to have LD_LIBRARY_PATH pointing to LSTM implementation in case of LSTM\n\n";
feature_extraction_pipeline<float>(argc, argv);
return 0;
}
| mostafa-saad/deep-activity-rec | eclipse-project/ibrahim16-deep-act-rec-part/apps/exePhase4.cpp | C++ | bsd-2-clause | 7,728 |
/*
* Copyright (c) 2008-2011 Juli Mallett. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <common/test.h>
#include <event/action.h>
struct Cancelled {
Test test_;
bool cancelled_;
Cancelled(TestGroup& g)
: test_(g, "Cancellation does occur."),
cancelled_(false)
{
Action *a = cancellation(this, &Cancelled::cancel);
a->cancel();
}
~Cancelled()
{
if (cancelled_)
test_.pass();
}
void cancel(void)
{
ASSERT("/cancelled", !cancelled_);
cancelled_ = true;
}
};
struct NotCancelled {
Test test_;
bool cancelled_;
Action *action_;
NotCancelled(TestGroup& g)
: test_(g, "Cancellation does not occur."),
cancelled_(false),
action_(NULL)
{
action_ = cancellation(this, &NotCancelled::cancel);
}
~NotCancelled()
{
if (!cancelled_) {
if (action_ != NULL) {
action_->cancel();
action_ = NULL;
ASSERT("/not/cancelled", cancelled_);
}
}
}
void cancel(void)
{
ASSERT("/not/cancelled", !cancelled_);
cancelled_ = true;
test_.pass();
}
};
int
main(void)
{
TestGroup g("/test/action/cancel1", "Action::cancel #1");
{
Cancelled _(g);
}
{
NotCancelled _(g);
}
}
| diegows/wanproxy | event/test/action-cancel1/action-cancel1.cc | C++ | bsd-2-clause | 2,406 |
//
// Created by 王晓辰 on 15/10/2.
//
#include "test_dirname.h"
#include <ftxpath.h>
#include "tester.h"
bool test_dirname_path()
{
std::string path = "/a/b/c/d";
std::string dirname = "/a/b/c";
return dirname == ftx::path::dirname(path);
}
bool test_dirname_onename()
{
std::string name = "name";
return ftx::path::dirname(name).empty();
}
bool test_dirname_filepath()
{
std::string filepath = "a/b/c/d.txt";
std::string dirname = "a/b/c";
return dirname == ftx::path::dirname(filepath);
}
bool test_dirname_folderpath()
{
std::string folderpath = "a/b/c/folder/";
std::string dirname = "a/b/c/folder";
return dirname == ftx::path::dirname(folderpath);
}
bool test_dirname_root()
{
std::string root = "/";
return root == ftx::path::dirname(root);
}
bool test_dirname() {
LOG_TEST_STRING("");
TEST_BOOL_TO_BOOL(test_dirname_path(), "dir dirname failed");
TEST_BOOL_TO_BOOL(test_dirname_onename(), "one name dirname failed");
TEST_BOOL_TO_BOOL(test_dirname_filepath(), "file path dirname failed");
TEST_BOOL_TO_BOOL(test_dirname_folderpath(), "folder path dirname failed");
TEST_BOOL_TO_BOOL(test_dirname_root(), "root dirname failed");
return true;
}
| XiaochenFTX/ftxpath | test/test_dirname.cpp | C++ | bsd-2-clause | 1,239 |
/*
* Copyright (C) 2009 Google Inc. All rights reserved.
* Copyright (C) 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "RuntimeEnabledFeatures.h"
#include "DatabaseManager.h"
#include "MediaPlayer.h"
#include "SharedWorkerRepository.h"
#include "WebSocket.h"
#include <wtf/NeverDestroyed.h>
namespace WebCore {
RuntimeEnabledFeatures::RuntimeEnabledFeatures()
: m_isLocalStorageEnabled(true)
, m_isSessionStorageEnabled(true)
, m_isWebkitNotificationsEnabled(false)
, m_isApplicationCacheEnabled(true)
, m_isDataTransferItemsEnabled(true)
, m_isGeolocationEnabled(true)
, m_isIndexedDBEnabled(false)
, m_isTouchEnabled(true)
, m_isDeviceMotionEnabled(true)
, m_isDeviceOrientationEnabled(true)
, m_isSpeechInputEnabled(true)
, m_isCSSExclusionsEnabled(true)
, m_isCSSShapesEnabled(true)
, m_isCSSRegionsEnabled(false)
, m_isCSSCompositingEnabled(false)
, m_isLangAttributeAwareFormControlUIEnabled(false)
#if PLATFORM(IOS)
, m_isPluginReplacementEnabled(true)
#else
, m_isPluginReplacementEnabled(false)
#endif
#if ENABLE(SCRIPTED_SPEECH)
, m_isScriptedSpeechEnabled(false)
#endif
#if ENABLE(MEDIA_STREAM)
, m_isMediaStreamEnabled(true)
, m_isPeerConnectionEnabled(true)
#endif
#if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
, m_isLegacyCSSVendorPrefixesEnabled(false)
#endif
#if ENABLE(JAVASCRIPT_I18N_API)
, m_isJavaScriptI18NAPIEnabled(false)
#endif
#if ENABLE(VIDEO_TRACK)
, m_isVideoTrackEnabled(true)
#endif
#if ENABLE(INPUT_TYPE_DATE)
, m_isInputTypeDateEnabled(true)
#endif
#if ENABLE(INPUT_TYPE_DATETIME_INCOMPLETE)
, m_isInputTypeDateTimeEnabled(false)
#endif
#if ENABLE(INPUT_TYPE_DATETIMELOCAL)
, m_isInputTypeDateTimeLocalEnabled(true)
#endif
#if ENABLE(INPUT_TYPE_MONTH)
, m_isInputTypeMonthEnabled(true)
#endif
#if ENABLE(INPUT_TYPE_TIME)
, m_isInputTypeTimeEnabled(true)
#endif
#if ENABLE(INPUT_TYPE_WEEK)
, m_isInputTypeWeekEnabled(true)
#endif
#if ENABLE(CSP_NEXT)
, m_areExperimentalContentSecurityPolicyFeaturesEnabled(false)
#endif
#if ENABLE(FONT_LOAD_EVENTS)
, m_isFontLoadEventsEnabled(false)
#endif
#if ENABLE(GAMEPAD)
, m_areGamepadsEnabled(false)
#endif
{
}
RuntimeEnabledFeatures& RuntimeEnabledFeatures::sharedFeatures()
{
static NeverDestroyed<RuntimeEnabledFeatures> runtimeEnabledFeatures;
return runtimeEnabledFeatures;
}
#if ENABLE(JAVASCRIPT_I18N_API)
bool RuntimeEnabledFeatures::javaScriptI18NAPIEnabled()
{
return m_isJavaScriptI18NAPIEnabled;
}
#endif
#if ENABLE(VIDEO)
bool RuntimeEnabledFeatures::audioEnabled() const
{
return MediaPlayer::isAvailable();
}
bool RuntimeEnabledFeatures::htmlMediaElementEnabled() const
{
return MediaPlayer::isAvailable();
}
bool RuntimeEnabledFeatures::htmlAudioElementEnabled() const
{
return MediaPlayer::isAvailable();
}
bool RuntimeEnabledFeatures::htmlVideoElementEnabled() const
{
return MediaPlayer::isAvailable();
}
bool RuntimeEnabledFeatures::htmlSourceElementEnabled() const
{
return MediaPlayer::isAvailable();
}
bool RuntimeEnabledFeatures::mediaControllerEnabled() const
{
return MediaPlayer::isAvailable();
}
bool RuntimeEnabledFeatures::mediaErrorEnabled() const
{
return MediaPlayer::isAvailable();
}
bool RuntimeEnabledFeatures::timeRangesEnabled() const
{
return MediaPlayer::isAvailable();
}
#endif
#if ENABLE(SHARED_WORKERS)
bool RuntimeEnabledFeatures::sharedWorkerEnabled() const
{
return SharedWorkerRepository::isAvailable();
}
#endif
#if ENABLE(WEB_SOCKETS)
bool RuntimeEnabledFeatures::webSocketEnabled() const
{
return WebSocket::isAvailable();
}
#endif
} // namespace WebCore
| aosm/WebCore | bindings/generic/RuntimeEnabledFeatures.cpp | C++ | bsd-2-clause | 5,200 |
package org.joshy.gfx.test.itunes;
/**
* Created by IntelliJ IDEA.
* User: josh
* Date: Jan 28, 2010
* Time: 9:20:01 PM
* To change this template use File | Settings | File Templates.
*/
class Song {
int trackNumber;
int totalTracks;
String name;
String album;
String artist;
int duration;
public Song(int trackNumber, int totalTracks, String name, String album, String artist, int duration) {
this.trackNumber = trackNumber;
this.totalTracks = totalTracks;
this.name = name;
this.album = album;
this.artist = artist;
this.duration = duration;
}
}
| tonykwok/leonardosketch.amino | src/org/joshy/gfx/test/itunes/Song.java | Java | bsd-2-clause | 622 |
class Dxpy < Formula
include Language::Python::Virtualenv
desc "DNAnexus toolkit utilities and platform API bindings for Python"
homepage "https://github.com/dnanexus/dx-toolkit"
url "https://files.pythonhosted.org/packages/7e/d8/9529a045270fe2cee67c01fde759864b9177ecdd486d016c3a38863f3895/dxpy-0.320.0.tar.gz"
sha256 "aef4c16d73cf9e7513d1f8e503f7e0d3ed7f2135fe6f8596a97196a8df109977"
license "Apache-2.0"
bottle do
sha256 cellar: :any, arm64_monterey: "f833c2a2b486b3a54ba1b4f5c205aa73dc815b498053bfe1197a7c497a6e4646"
sha256 cellar: :any, arm64_big_sur: "984872c26ab277ba25764029bea2df0bb697452e589c537cc6c2fbec77fb463e"
sha256 cellar: :any, monterey: "90709e2bff817faabb7ab6e3a726bde68dadbc33bc4ef9e830154f8d5b852b4b"
sha256 cellar: :any, big_sur: "3a063ce13281a975cfc03a14b58ddd33b8ceb5dcc851c6f5f8e01e7d4c4d5fdf"
sha256 cellar: :any, catalina: "56f0159e7a3193f3baa3c6710a70ee2d141d74fb46b9b9aa6128149240d6a603"
sha256 cellar: :any_skip_relocation, x86_64_linux: "c6c14d2acbe34e5763b3b6352af63d3252655b479ae5cefe556dbbe51720e6c4"
end
depends_on "rust" => :build # for cryptography
depends_on "python@3.10"
depends_on "six"
on_macos do
depends_on "readline"
end
on_linux do
depends_on "pkg-config" => :build
depends_on "libffi"
end
resource "argcomplete" do
url "https://files.pythonhosted.org/packages/05/f8/67851ae4fe5396ba6868c5d84219b81ea6a5d53991a6853616095c30adc0/argcomplete-2.0.0.tar.gz"
sha256 "6372ad78c89d662035101418ae253668445b391755cfe94ea52f1b9d22425b20"
end
resource "certifi" do
url "https://files.pythonhosted.org/packages/6c/ae/d26450834f0acc9e3d1f74508da6df1551ceab6c2ce0766a593362d6d57f/certifi-2021.10.8.tar.gz"
sha256 "78884e7c1d4b00ce3cea67b44566851c4343c120abd683433ce934a68ea58872"
end
resource "cffi" do
url "https://files.pythonhosted.org/packages/00/9e/92de7e1217ccc3d5f352ba21e52398372525765b2e0c4530e6eb2ba9282a/cffi-1.15.0.tar.gz"
sha256 "920f0d66a896c2d99f0adbb391f990a84091179542c205fa53ce5787aff87954"
end
resource "charset-normalizer" do
url "https://files.pythonhosted.org/packages/e8/e8/b6cfd28fb430b2ec9923ad0147025bf8bbdf304b1eb3039b69f1ce44ed6e/charset-normalizer-2.0.11.tar.gz"
sha256 "98398a9d69ee80548c762ba991a4728bfc3836768ed226b3945908d1a688371c"
end
resource "cryptography" do
url "https://files.pythonhosted.org/packages/f9/4b/1cf8e281f7ae4046a59e5e39dd7471d46db9f61bb564fddbff9084c4334f/cryptography-36.0.1.tar.gz"
sha256 "53e5c1dc3d7a953de055d77bef2ff607ceef7a2aac0353b5d630ab67f7423638"
end
resource "idna" do
url "https://files.pythonhosted.org/packages/62/08/e3fc7c8161090f742f504f40b1bccbfc544d4a4e09eb774bf40aafce5436/idna-3.3.tar.gz"
sha256 "9d643ff0a55b762d5cdb124b8eaa99c66322e2157b69160bc32796e824360e6d"
end
resource "psutil" do
url "https://files.pythonhosted.org/packages/47/b6/ea8a7728f096a597f0032564e8013b705aa992a0990becd773dcc4d7b4a7/psutil-5.9.0.tar.gz"
sha256 "869842dbd66bb80c3217158e629d6fceaecc3a3166d3d1faee515b05dd26ca25"
end
resource "pycparser" do
url "https://files.pythonhosted.org/packages/5e/0b/95d387f5f4433cb0f53ff7ad859bd2c6051051cebbb564f139a999ab46de/pycparser-2.21.tar.gz"
sha256 "e644fdec12f7872f86c58ff790da456218b10f863970249516d60a5eaca77206"
end
resource "python-dateutil" do
url "https://files.pythonhosted.org/packages/4c/c4/13b4776ea2d76c115c1d1b84579f3764ee6d57204f6be27119f13a61d0a9/python-dateutil-2.8.2.tar.gz"
sha256 "0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86"
end
resource "requests" do
url "https://files.pythonhosted.org/packages/e7/01/3569e0b535fb2e4a6c384bdbed00c55b9d78b5084e0fb7f4d0bf523d7670/requests-2.26.0.tar.gz"
sha256 "b8aa58f8cf793ffd8782d3d8cb19e66ef36f7aba4353eec859e74678b01b07a7"
end
resource "urllib3" do
url "https://files.pythonhosted.org/packages/b0/b1/7bbf5181f8e3258efae31702f5eab87d8a74a72a0aa78bc8c08c1466e243/urllib3-1.26.8.tar.gz"
sha256 "0e7c33d9a63e7ddfcb86780aac87befc2fbddf46c58dbb487e0855f7ceec283c"
end
resource "websocket-client" do
url "https://files.pythonhosted.org/packages/8b/0f/52de51b9b450ed52694208ab952d5af6ebbcbce7f166a48784095d930d8c/websocket_client-0.57.0.tar.gz"
sha256 "d735b91d6d1692a6a181f2a8c9e0238e5f6373356f561bb9dc4c7af36f452010"
end
def install
virtualenv_install_with_resources
end
test do
dxenv = <<~EOS
API server protocol https
API server host api.dnanexus.com
API server port 443
Current workspace None
Current folder None
Current user None
EOS
assert_match dxenv, shell_output("#{bin}/dx env")
end
end
| filcab/homebrew-core | Formula/dxpy.rb | Ruby | bsd-2-clause | 4,787 |
/* global define */
define([
'jquery',
'underscore',
'./dist',
'./axis'
], function($, _, dist, axis) {
var EditableFieldChart = dist.FieldChart.extend({
template: 'charts/editable-chart',
toolbarAnimationTime: 200,
formAnimationTime: 300,
events: _.extend({
'click .fullsize': 'toggleExpanded'
}, dist.FieldChart.prototype.events),
ui: _.extend({
toolbar: '.btn-toolbar',
fullsizeToggle: '.fullsize',
form: '.editable',
xAxis: '[name=x-Axis]',
yAxis: '[name=y-Axis]',
series: '[name=series]'
}, dist.FieldChart.prototype.ui),
onRender: function() {
if (this.options.editable === false) {
this.ui.form.detach();
this.ui.toolbar.detach();
}
else {
this.xAxis = new axis.FieldAxis({
el: this.ui.xAxis,
collection: this.collection
});
this.yAxis = new axis.FieldAxis({
el: this.ui.yAxis,
collection: this.collection
});
this.series = new axis.FieldAxis({
el: this.ui.series,
enumerableOnly: true,
collection: this.collection
});
if (this.model) {
if (this.model.get('xAxis')) {
this.ui.form.hide();
}
if (this.model.get('expanded')) {
this.expand();
}
else {
this.contract();
}
}
}
},
customizeOptions: function(options) {
this.ui.status.detach();
this.ui.heading.text(options.title.text);
options.title.text = '';
// Check if any data is present.
if (!options.series[0]) {
this.ui.chart.html('<p class=no-data>Unfortunately, there is no ' +
'data to graph here.</p>');
return;
}
this.ui.form.hide();
var statusText = [];
if (options.clustered) {
statusText.push('Clustered');
}
if (statusText[0]) {
this.ui.status.text(statusText.join(', ')).show();
this.ui.heading.append(this.$status);
}
if (this.interactive(options)) {
this.enableChartEvents();
}
$.extend(true, options, this.chartOptions);
options.chart.renderTo = this.ui.chart[0];
return options;
},
// Ensure rapid successions of this method do not occur.
changeChart: function(event) {
if (event) {
event.preventDefault();
}
var _this = this;
this.collection.when(function() {
var xAxis, yAxis, series, seriesIdx;
// TODO fix this nonsense
if (event === null || typeof event === 'undefined') {
xAxis = _this.model.get('xAxis');
if (xAxis) {
_this.xAxis.$el.val(xAxis.toString());
}
yAxis = _this.model.get('yAxis');
if (yAxis) {
_this.yAxis.$el.val(yAxis.toString());
}
series = _this.model.get('series');
if (series) {
this.series.$el.val(series.toString());
}
}
xAxis = _this.xAxis.getSelected();
yAxis = _this.yAxis.getSelected();
series = _this.series.getSelected();
if (!xAxis) return;
var url = _this.model.links.distribution;
var fields = [xAxis];
var data = 'dimension=' + xAxis.id;
if (yAxis) {
fields.push(yAxis);
data = data + '&dimension=' + yAxis.id;
}
if (series) {
if (yAxis) {
seriesIdx = 2;
}
else {
seriesIdx = 1;
}
data = data + '&dimension=' + series.id;
}
if (event && _this.model) {
_this.model.set({
xAxis: xAxis.id,
yAxis: (yAxis) ? yAxis.id : null,
series: (series) ? series.id : null
});
}
_this.update(url, data, fields, seriesIdx);
});
},
// Disable selected fields since using the same field for multiple
// axes doesn't make sense.
disableSelected: function(event) {
var $target = $(event.target);
// Changed to an empty value, unhide other dropdowns.
if (this.xAxis.el === event.target) {
this.yAxis.$('option').prop('disabled', false);
this.series.$('option').prop('disabled', false);
}
else if (this.yAxis.el === event.target) {
this.xAxis.$('option').prop('disabled', false);
this.series.$('option').prop('disabled', false);
}
else {
this.xAxis.$('option').prop('disabled', false);
this.yAxis.$('option').prop('disabled', false);
}
var value = $target.val();
if (value !== '') {
if (this.xAxis.el === event.target) {
this.yAxis.$('option[value=' + value + ']')
.prop('disabled', true).val('');
this.series.$('option[value=' + value + ']')
.prop('disabled', true).val('');
}
else if (this.yAxis.el === event.target) {
this.xAxis.$('option[value=' + value + ']')
.prop('disable', true).val('');
this.series.$('option[value=' + value + ']')
.prop('disable', true).val('');
}
else {
this.xAxis.$('option[value=' + value + ']')
.prop('disable', true).val('');
this.yAxis.$('option[value=' + value + ']')
.prop('disable', true).val('');
}
}
},
toggleExpanded: function() {
var expanded = this.model.get('expanded');
if (expanded) {
this.contract();
}
else {
this.expand();
}
this.model.save({
expanded: !expanded
});
},
resize: function() {
var chartWidth = this.ui.chart.width();
if (this.chart) {
this.chart.setSize(chartWidth, null, false);
}
},
expand: function() {
this.$fullsizeToggle.children('i')
.removeClass('icon-resize-small')
.addClass('icon-resize-full');
this.$el.addClass('expanded');
this.resize();
},
contract: function() {
this.$fullsizeToggle.children('i')
.removeClass('icon-resize-full')
.addClass('icon-resize-small');
this.$el.removeClass('expanded');
this.resize();
},
hideToolbar: function() {
this.ui.toolbar.fadeOut(this.toolbarAnimationTime);
},
showToolbar: function() {
this.ui.toolbar.fadeIn(this.toolbarAnimationTime);
},
toggleEdit: function() {
if (this.ui.form.is(':visible')) {
this.ui.form.fadeOut(this.formAnimationTime);
}
else {
this.ui.form.fadeIn(this.formAnimationTime);
}
}
});
return {
EditableFieldChart: EditableFieldChart
};
});
| chop-dbhi/cilantro | src/js/cilantro/ui/charts/editable.js | JavaScript | bsd-2-clause | 8,396 |
# frozen_string_literal: true
require_relative "commands/break"
require_relative "commands/catch"
require_relative "commands/condition"
require_relative "commands/continue"
require_relative "commands/debug"
require_relative "commands/delete"
require_relative "commands/disable"
require_relative "commands/display"
require_relative "commands/down"
require_relative "commands/edit"
require_relative "commands/enable"
require_relative "commands/finish"
require_relative "commands/frame"
require_relative "commands/help"
require_relative "commands/history"
require_relative "commands/info"
require_relative "commands/interrupt"
require_relative "commands/irb"
require_relative "commands/kill"
require_relative "commands/list"
require_relative "commands/method"
require_relative "commands/next"
require_relative "commands/pry"
require_relative "commands/quit"
require_relative "commands/restart"
require_relative "commands/save"
require_relative "commands/set"
require_relative "commands/show"
require_relative "commands/skip"
require_relative "commands/source"
require_relative "commands/step"
require_relative "commands/thread"
require_relative "commands/tracevar"
require_relative "commands/undisplay"
require_relative "commands/untracevar"
require_relative "commands/up"
require_relative "commands/var"
require_relative "commands/where"
| deivid-rodriguez/byebug | lib/byebug/commands.rb | Ruby | bsd-2-clause | 1,337 |
module.exports =
{
"WMSC": {
"WMSC_1_1_1" : require('./1.1.1/WMSC_1_1_1')
}
};
| juanrapoport/ogc-schemas | scripts/tests/WMSC/WMSC.js | JavaScript | bsd-2-clause | 84 |
package cz.metacentrum.perun.core.bl;
import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.Member;
import cz.metacentrum.perun.core.api.PerunSession;
import cz.metacentrum.perun.core.api.User;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
/**
* Searcher Class for searching objects by Map of Attributes
*
* @author Michal Stava <stavamichal@gmail.com>
*/
public interface SearcherBl {
/**
* This method get Map of Attributes with searching values and try to find all users, which have specific attributes in format.
* Better information about format below. When there are more than 1 attribute in Map, it means all must be true "looking for all of them" (AND)
*
* @param sess perun session
* @param attributesWithSearchingValues map of attributes names
* when attribute is type String, so value is string and we are looking for total match (Partial is not supported now, will be supported later by symbol *)
* when attribute is type Integer, so value is integer in String and we are looking for total match
* when attribute is type List<String>, so value is String and we are looking for at least one total or partial matching element
* when attribute is type Map<String> so value is String in format "key=value" and we are looking total match of both or if is it "key" so we are looking for total match of key
* IMPORTANT: In map there is not allowed char '=' in key. First char '=' is delimiter in MAP item key=value!!!
* @return list of users who have attributes with specific values (behavior above)
* if no user exist, return empty list of users
*
* @throws AttributeNotExistsException
* @throws InternalErrorException
* @throws WrongAttributeAssignmentException
*/
List<User> getUsers(PerunSession sess, Map<String, String> attributesWithSearchingValues) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException;
/**
* This method take map of coreAttributes with search values and return all
* users who have the specific match for all of these core attributes.
*
* @param sess
* @param coreAttributesWithSearchingValues
* @return
* @throws InternalErrorException
* @throws AttributeNotExistsException
* @throws WrongAttributeAssignmentException
*/
List<User> getUsersForCoreAttributes(PerunSession sess, Map<String, String> coreAttributesWithSearchingValues) throws InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException;
/**
* Return members with expiration date set, which will expire on today +/- X days.
* You can specify operator for comparison (by default "=") returning exact match.
* So you can get all expired members (including today) using "<=" and zero days shift.
* or using "<" and +1 day shift.
*
* Method ignores current member state, just compares expiration date !
*
* @param sess PerunSession
* @param operator One of "=", "<", ">", "<=", ">=". If null, "=" is anticipated.
* @param days X days before/after today
* @return Members with expiration relative to method params.
* @throws InternalErrorException
*/
List<Member> getMembersByExpiration(PerunSession sess, String operator, int days) throws InternalErrorException;
/**
* Return members with expiration date set, which will expire on specified date.
* You can specify operator for comparison (by default "=") returning exact match.
* So you can get all expired members (including today) using "<=" and today date.
* or using "<" and tomorrow date.
*
* Method ignores current member state, just compares expiration date !
*
* @param sess PerunSession
* @param operator One of "=", "<", ">", "<=", ">=". If null, "=" is anticipated.
* @param date Date to compare expiration with (if null, current date is used).
* @return Members with expiration relative to method params.
* @throws InternalErrorException
*/
List<Member> getMembersByExpiration(PerunSession sess, String operator, Calendar date) throws InternalErrorException;
}
| jirmauritz/perun | perun-core/src/main/java/cz/metacentrum/perun/core/bl/SearcherBl.java | Java | bsd-2-clause | 4,338 |
<?php
class Kwc_Menu_EditableItems_Controller extends Kwf_Controller_Action_Auto_Kwc_Grid
{
protected $_buttons = array();
protected $_model = 'Kwc_Menu_EditableItems_Model';
protected $_defaultOrder = array('field' => 'pos', 'direction' => 'ASC');
protected function _initColumns()
{
$this->_columns->add(new Kwf_Grid_Column('pos'));
$this->_columns->add(new Kwf_Grid_Column('name', trlKwf('Page name'), 200));
}
protected function _getSelect()
{
$ret = parent::_getSelect();
$ret->whereEquals('parent_component_id', $this->_getParam('componentId'));
$ret->whereEquals('ignore_visible', true);
return $ret;
}
}
| fraxachun/koala-framework | Kwc/Menu/EditableItems/Controller.php | PHP | bsd-2-clause | 698 |
class Wimlib < Formula
desc "Library to create, extract, and modify Windows Imaging files"
homepage "https://wimlib.net/"
url "https://wimlib.net/downloads/wimlib-1.13.1.tar.gz"
sha256 "47f4bc645c1b6ee15068d406a90bb38aec816354e140291ccb01e536f2cdaf5f"
bottle do
cellar :any
rebuild 1
sha256 "ea449f8e0aeea806e5925974a0a3f8a04ac256a5a44edc858272a57c5f88814d" => :catalina
sha256 "7969f20ce9f26b7435b4242fb241c2527848581469be0cad09a3f5de77b11a05" => :mojave
sha256 "33a3397f536e339ca4177d3639b55e223040883af9d5afbbb47cc3e9b1bb87e9" => :high_sierra
sha256 "66a39e7eaa96a26f988a0c6eba0ad614ca449b0bb5688ebd70830f8863da5244" => :sierra
end
depends_on "pkg-config" => :build
depends_on "openssl@1.1"
def install
# fuse requires librt, unavailable on OSX
args = %W[
--disable-debug
--disable-dependency-tracking
--disable-silent-rules
--prefix=#{prefix}
--without-fuse
--without-ntfs-3g
]
system "./configure", *args
system "make", "install"
end
test do
# make a directory containing a dummy 1M file
mkdir("foo")
system "dd", "if=/dev/random", "of=foo/bar", "bs=1m", "count=1"
# capture an image
ENV.append "WIMLIB_IMAGEX_USE_UTF8", "1"
system "#{bin}/wimcapture", "foo", "bar.wim"
assert_predicate testpath/"bar.wim", :exist?
# get info on the image
system "#{bin}/wiminfo", "bar.wim"
end
end
| wolffaxn/homebrew-core | Formula/wimlib.rb | Ruby | bsd-2-clause | 1,434 |
#include "hamiltonian/Hamiltonian.hpp"
namespace cpb {
namespace {
struct IsValid {
template<class scalar_t>
bool operator()(SparseMatrixRC<scalar_t> const& p) const { return p != nullptr; }
};
struct Reset {
template<class scalar_t>
void operator()(SparseMatrixRC<scalar_t>& p) const { p.reset(); }
};
struct GetSparseRef {
template<class scalar_t>
ComplexCsrConstRef operator()(SparseMatrixRC<scalar_t> const& m) const { return csrref(*m); }
};
struct NonZeros {
template<class scalar_t>
idx_t operator()(SparseMatrixRC<scalar_t> const& m) const { return m->nonZeros(); }
};
struct Rows {
template<class scalar_t>
idx_t operator()(SparseMatrixRC<scalar_t> const& m) const { return m->rows(); }
};
struct Cols {
template<class scalar_t>
idx_t operator()(SparseMatrixRC<scalar_t> const& m) const { return m->cols(); }
};
} // namespace
Hamiltonian::operator bool() const {
return var::apply_visitor(IsValid(), variant_matrix);
}
void Hamiltonian::reset() {
return var::apply_visitor(Reset(), variant_matrix);
}
ComplexCsrConstRef Hamiltonian::csrref() const {
return var::apply_visitor(GetSparseRef(), variant_matrix);
}
idx_t Hamiltonian::non_zeros() const {
return var::apply_visitor(NonZeros(), variant_matrix);
}
idx_t Hamiltonian::rows() const {
return var::apply_visitor(Rows(), variant_matrix);
}
idx_t Hamiltonian::cols() const {
return var::apply_visitor(Cols(), variant_matrix);
}
} // namespace cpb
| dean0x7d/pybinding | cppcore/src/hamiltonian/Hamiltonian.cpp | C++ | bsd-2-clause | 1,497 |
@extends('skins.bootstrap.admin.layout')
@section('module')
<section id="admin-site">
{{
Form::open(array(
'autocomplete' => 'off',
'role' => 'form',
'class' => 'form-horizontal',
))
}}
<div class="row">
<div class="col-sm-12">
<fieldset>
<legend>{{ Lang::get('admin.site_settings') }}</legend>
<ul id="tabs-site" class="nav nav-tabs">
<li class="active">
<a href="#site-general" data-toggle="tab">{{ Lang::get('admin.general') }}</a>
</li>
<li>
<a href="#site-content" data-toggle="tab">{{ Lang::get('admin.content') }}</a>
</li>
<li>
<a href="#site-banners" data-toggle="tab">{{ Lang::get('admin.banners') }}</a>
</li>
</ul>
<div class="tab-content">
<div id="site-general" class="tab-pane fade in active">
<div class="form-group">
{{
Form::label('fqdn', Lang::get('admin.fqdn'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::text('fqdn', $site->general->fqdn, array(
'class' => 'form-control',
))
}}
<div class="help-block">
{{ Lang::get('admin.fqdn_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('title', Lang::get('admin.site_title'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::text('title', $site->general->title, array(
'class' => 'form-control',
'maxlength' => 20
))
}}
</div>
</div>
<div class="form-group">
{{
Form::label('lang', Lang::get('admin.language'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('lang', $langs, $site->general->lang, array(
'class' => 'form-control'
))
}}
</div>
</div>
<div class="form-group">
{{
Form::label('copyright', Lang::get('admin.copyright'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::textarea('copyright', $site->general->copyright, array(
'class' => 'form-control',
'rows' => 4,
))
}}
<div class="help-block">
{{ Lang::get('admin.copyright_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('ajax_nav', Lang::get('admin.ajax_nav'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('ajax_nav', array(
'1' => Lang::get('admin.enabled'),
'0' => Lang::get('admin.disabled'),
), $site->general->ajaxNav, array(
'class' => 'form-control'
))
}}
<div class="help-block">
{{ Lang::get('admin.ajax_nav_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('per_page', Lang::get('admin.list_length'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::text('per_page', $site->general->perPage, array(
'class' => 'form-control',
))
}}
<div class="help-block">
{{ Lang::get('admin.list_length_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('proxy', Lang::get('admin.ip_tracking'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('proxy', array(
'0' => Lang::get('admin.ignore_proxy'),
'1' => Lang::get('admin.trust_proxy'),
), $site->general->proxy, array(
'class' => 'form-control'
))
}}
<div class="help-block">
{{ Lang::get('admin.ip_tracking_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('csrf', Lang::get('admin.csrf_token'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('csrf', array(
'1' => Lang::get('admin.enabled'),
'0' => Lang::get('admin.disabled'),
), $site->general->csrf, array(
'class' => 'form-control'
))
}}
<div class="help-block">
{{ Lang::get('admin.csrf_token_exp') }}
</div>
</div>
</div>
</div>
<div id="site-content" class="tab-pane fade">
<div class="form-group">
{{
Form::label('guest_posts', Lang::get('admin.guest_posts'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('guest_posts', array(
'1' => Lang::get('admin.enabled'),
'0' => Lang::get('admin.disabled'),
), $site->general->guestPosts, array(
'class' => 'form-control'
))
}}
<div class="help-block">
{{ Lang::get('admin.guest_posts_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('paste_visibility', Lang::get('admin.visibility'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('paste_visibility', array(
'default' => Lang::get('admin.allow_all'),
'public' => Lang::get('admin.enforce_public'),
'private' => Lang::get('admin.enforce_private'),
), $site->general->pasteVisibility, array(
'class' => 'form-control'
))
}}
<div class="help-block">
{{ Lang::get('admin.visibility_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('flag_paste', Lang::get('admin.flagging'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('flag_paste', array(
'all' => Lang::get('admin.flag_all'),
'user' => Lang::get('admin.flag_user'),
'off' => Lang::get('admin.flag_off'),
), $site->general->flagPaste, array(
'class' => 'form-control'
))
}}
<div class="help-block">
{{ Lang::get('admin.flagging_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('allow_paste_del', Lang::get('admin.delete_pastes'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('allow_paste_del', array(
'1' => Lang::get('admin.enabled'),
'0' => Lang::get('admin.disabled'),
), $site->general->allowPasteDel, array(
'class' => 'form-control'
))
}}
<div class="help-block">
{{ Lang::get('admin.delete_pastes_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('allow_attachment', Lang::get('admin.attachment'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('allow_attachment', array(
'1' => Lang::get('admin.enabled'),
'0' => Lang::get('admin.disabled'),
), $site->general->allowAttachment, array(
'class' => 'form-control'
))
}}
<div class="help-block">
{{ Lang::get('admin.attachment_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('paste_age', Lang::get('admin.paste_age'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('paste_age', Paste::getExpiration('admin'), $site->general->pasteAge, array(
'class' => 'form-control'
))
}}
<div class="help-block">
{{ Lang::get('admin.paste_age_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('max_paste_size', Lang::get('admin.size_limit'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
<div class="input-group">
{{
Form::text('max_paste_size', $site->general->maxPasteSize, array(
'class' => 'form-control',
))
}}
<div class="input-group-addon">
{{ Lang::get('admin.bytes') }}
</div>
</div>
<div class="help-block">
{{ Lang::get('admin.size_limit_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('no_expire', Lang::get('admin.expiration'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('no_expire', array(
'none' => Lang::get('admin.noexpire_none'),
'user' => Lang::get('admin.noexpire_user'),
'all' => Lang::get('admin.noexpire_all'),
), $site->general->noExpire, array(
'class' => 'form-control'
))
}}
<div class="help-block">
{{ Lang::get('admin.expiration_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('show_exp', Lang::get('admin.show_exp'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('show_exp', array(
'1' => Lang::get('admin.enabled'),
'0' => Lang::get('admin.disabled'),
), $site->general->showExp, array(
'class' => 'form-control'
))
}}
<div class="help-block">
{{ Lang::get('admin.show_exp_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('paste_search', Lang::get('admin.paste_search'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('paste_search', array(
'1' => Lang::get('admin.enabled'),
'0' => Lang::get('admin.disabled'),
), $site->general->pasteSearch, array(
'class' => 'form-control'
))
}}
<div class="help-block">
{{ Lang::get('admin.paste_search_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('comments', Lang::get('global.comments'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('comments', array(
'1' => Lang::get('admin.enabled'),
'0' => Lang::get('admin.disabled'),
), $site->general->comments, array(
'class' => 'form-control'
))
}}
<div class="help-block">
{{ Lang::get('admin.comments_exp') }}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('share', Lang::get('admin.share'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::select('share', array(
'1' => Lang::get('admin.enabled'),
'0' => Lang::get('admin.disabled'),
), $site->general->share, array(
'class' => 'form-control'
))
}}
<div class="help-block">
{{ Lang::get('admin.share_exp') }}
</div>
</div>
</div>
</div>
<div id="site-banners" class="tab-pane fade">
<div class="row">
<div class="col-sm-12">
<div class="alert alert-info">
{{ Lang::get('admin.banners_exp') }}
</div>
<div class="alert alert-success">
{{{ sprintf(Lang::get('admin.allowed_tags'), $site->general->allowedTags) }}}
</div>
</div>
</div>
<div class="form-group">
{{
Form::label('banner_top', Lang::get('admin.banner_top'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::textarea('banner_top', $site->general->bannerTop, array(
'class' => 'form-control',
'rows' => 5,
))
}}
</div>
</div>
<div class="form-group">
{{
Form::label('banner_bottom', Lang::get('admin.banner_bottom'), array(
'class' => 'control-label col-sm-3 col-lg-2'
))
}}
<div class="col-sm-9 col-lg-10">
{{
Form::textarea('banner_bottom', $site->general->bannerBottom, array(
'class' => 'form-control',
'rows' => 5,
))
}}
</div>
</div>
</div>
</div>
<hr />
<div class="form-group">
<div class="col-sm-12">
{{
Form::submit(Lang::get('admin.save_all'), array(
'name' => '_save',
'class' => 'btn btn-primary'
))
}}
</div>
</div>
</fieldset>
</div>
</div>
{{ Form::close() }}
</section>
@stop
| solitaryr/sticky-notes | app/views/skins/bootstrap/admin/site.blade.php | PHP | bsd-2-clause | 14,466 |
package cz.metacentrum.perun.webgui.tabs.cabinettabs;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.client.ui.*;
import cz.metacentrum.perun.webgui.client.PerunWebSession;
import cz.metacentrum.perun.webgui.client.UiElements;
import cz.metacentrum.perun.webgui.client.mainmenu.MainMenu;
import cz.metacentrum.perun.webgui.client.resources.*;
import cz.metacentrum.perun.webgui.json.GetEntityById;
import cz.metacentrum.perun.webgui.json.JsonCallbackEvents;
import cz.metacentrum.perun.webgui.json.JsonUtils;
import cz.metacentrum.perun.webgui.json.cabinetManager.*;
import cz.metacentrum.perun.webgui.model.Author;
import cz.metacentrum.perun.webgui.model.Category;
import cz.metacentrum.perun.webgui.model.Publication;
import cz.metacentrum.perun.webgui.model.Thanks;
import cz.metacentrum.perun.webgui.tabs.CabinetTabs;
import cz.metacentrum.perun.webgui.tabs.TabItem;
import cz.metacentrum.perun.webgui.tabs.TabItemWithUrl;
import cz.metacentrum.perun.webgui.tabs.UrlMapper;
import cz.metacentrum.perun.webgui.widgets.CustomButton;
import cz.metacentrum.perun.webgui.widgets.ListBoxWithObjects;
import cz.metacentrum.perun.webgui.widgets.TabMenu;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
/**
* Tab which shows publication's details.
*
* @author Pavel Zlamal <256627@mail.muni.cz>
*/
public class PublicationDetailTabItem implements TabItem, TabItemWithUrl {
/**
* Perun web session
*/
private PerunWebSession session = PerunWebSession.getInstance();
/**
* Content widget - should be simple panel
*/
private SimplePanel contentWidget = new SimplePanel();
/**
* Title widget
*/
private Label titleWidget = new Label("Loading publication");
//data
private Publication publication;
private int publicationId;
private boolean fromSelf = false; // accessed from perun admin by default
/**
* Creates a tab instance
*
* @param pub publication
*/
public PublicationDetailTabItem(Publication pub){
this.publication = pub;
this.publicationId = pub.getId();
}
/**
* Creates a tab instance
* @param pub publication
* @param fromSelf TRUE if accessed from user section / FALSE otherwise
*/
public PublicationDetailTabItem(Publication pub, boolean fromSelf){
this.publication = pub;
this.publicationId = pub.getId();
this.fromSelf = fromSelf;
}
/**
* Creates a tab instance
* @param publicationId publication
* @param fromSelf TRUE if accessed from user section / FALSE otherwise
*/
public PublicationDetailTabItem(int publicationId, boolean fromSelf){
this.publicationId = publicationId;
this.fromSelf = fromSelf;
GetEntityById call = new GetEntityById(PerunEntity.PUBLICATION, publicationId, new JsonCallbackEvents(){
public void onFinished(JavaScriptObject jso){
publication = jso.cast();
}
});
// do not use cache this time because of update publ. method !!
call.retrieveData();
}
public boolean isPrepared(){
return !(publication == null);
}
@Override
public boolean isRefreshParentOnClose() {
return false;
}
@Override
public void onClose() {
}
public Widget draw() {
// show only part of title
titleWidget.setText(Utils.getStrippedStringWithEllipsis(publication.getTitle()));
// MAIN PANEL
ScrollPanel sp = new ScrollPanel();
sp.addStyleName("perun-tableScrollPanel");
VerticalPanel vp = new VerticalPanel();
vp.addStyleName("perun-table");
sp.add(vp);
// resize perun table to correct size on screen
session.getUiElements().resizePerunTable(sp, 350, this);
// content
final FlexTable ft = new FlexTable();
ft.setStyleName("inputFormFlexTable");
if (publication.getLocked() == false) {
ft.setHTML(1, 0, "Id / Origin:");
ft.setHTML(2, 0, "Title:");
ft.setHTML(3, 0, "Year:");
ft.setHTML(4, 0, "Category:");
ft.setHTML(5, 0, "Rank:");
ft.setHTML(6, 0, "ISBN / ISSN:");
ft.setHTML(7, 0, "DOI:");
ft.setHTML(8, 0, "Full cite:");
ft.setHTML(9, 0, "Created by:");
ft.setHTML(10, 0, "Created date:");
for (int i=0; i<ft.getRowCount(); i++) {
ft.getFlexCellFormatter().setStyleName(i, 0, "itemName");
}
ft.getFlexCellFormatter().setWidth(1, 0, "100px");
final ListBoxWithObjects<Category> listbox = new ListBoxWithObjects<Category>();
// fill listbox
JsonCallbackEvents events = new JsonCallbackEvents(){
public void onFinished(JavaScriptObject jso) {
for (Category cat : JsonUtils.<Category>jsoAsList(jso)){
listbox.addItem(cat);
// if right, selected
if (publication.getCategoryId() == cat.getId()) {
listbox.setSelected(cat, true);
}
}
}
};
GetCategories categories = new GetCategories(events);
categories.retrieveData();
final TextBox rank = new TextBox();
rank.setWidth("30px");
rank.setMaxLength(4);
rank.setText(String.valueOf(publication.getRank()));
final TextBox title = new TextBox();
title.setMaxLength(1024);
title.setText(publication.getTitle());
title.setWidth("500px");
final TextBox year = new TextBox();
year.setText(String.valueOf(publication.getYear()));
year.setMaxLength(4);
year.setWidth("30px");
final TextBox isbn = new TextBox();
isbn.setText(publication.getIsbn());
isbn.setMaxLength(32);
final TextBox doi = new TextBox();
doi.setText(publication.getDoi());
doi.setMaxLength(256);
final TextArea main = new TextArea();
main.setText(publication.getMain());
main.setSize("500px", "70px");
// set max length
main.getElement().setAttribute("maxlength", "4000");
ft.setHTML(1, 1, publication.getId()+" / <Strong>Ext. Id: </strong>"+publication.getExternalId()+" <Strong>System: </strong>"+ SafeHtmlUtils.fromString(publication.getPublicationSystemName()).asString());
ft.setWidget(2, 1, title);
ft.setWidget(3, 1, year);
ft.setWidget(4, 1, listbox);
if (session.isPerunAdmin()) {
// only perunadmin can change rank
ft.setWidget(5, 1, rank);
} else {
ft.setHTML(5, 1, SafeHtmlUtils.fromString(String.valueOf(publication.getRank()) +"").asString());
}
ft.setWidget(6, 1, isbn);
ft.setWidget(7, 1, doi);
ft.setWidget(8, 1, main);
ft.setHTML(9, 1, SafeHtmlUtils.fromString((publication.getCreatedBy() != null) ? publication.getCreatedBy() : "").asString());
ft.setHTML(10, 1, SafeHtmlUtils.fromString((String.valueOf(publication.getCreatedDate()) != null) ? String.valueOf(publication.getCreatedDate()) : "").asString());
// update button
final CustomButton change = TabMenu.getPredefinedButton(ButtonType.SAVE, "Save changes in publication details");
change.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
Publication pub = JsonUtils.clone(publication).cast();
if (!JsonUtils.checkParseInt(year.getText())){
JsonUtils.cantParseIntConfirm("YEAR", year.getText());
} else {
pub.setYear(Integer.parseInt(year.getText()));
}
if (session.isPerunAdmin()) {
pub.setRank(Double.parseDouble(rank.getText()));
}
pub.setCategoryId(listbox.getSelectedObject().getId());
pub.setTitle(title.getText());
pub.setMain(main.getText());
pub.setIsbn(isbn.getText());
pub.setDoi(doi.getText());
UpdatePublication upCall = new UpdatePublication(JsonCallbackEvents.disableButtonEvents(change, new JsonCallbackEvents(){
public void onFinished(JavaScriptObject jso) {
// refresh page content
Publication p = jso.cast();
publication = p;
draw();
}
}));
upCall.updatePublication(pub);
}
});
ft.setWidget(0, 0, change);
} else {
ft.getFlexCellFormatter().setColSpan(0, 0, 2);
ft.setWidget(0, 0, new HTML(new Image(SmallIcons.INSTANCE.lockIcon())+" <strong>Publication is locked. Ask administrator to perform any changes for you at meta@cesnet.cz.</strong>"));
ft.setHTML(1, 0, "Id / Origin:");
ft.setHTML(2, 0, "Title:");
ft.setHTML(3, 0, "Year:");
ft.setHTML(4, 0, "Category:");
ft.setHTML(5, 0, "Rank:");
ft.setHTML(6, 0, "ISBN / ISSN:");
ft.setHTML(7, 0, "DOI:");
ft.setHTML(8, 0, "Full cite:");
ft.setHTML(9, 0, "Created by:");
ft.setHTML(10, 0, "Created date:");
for (int i=0; i<ft.getRowCount(); i++) {
ft.getFlexCellFormatter().setStyleName(i, 0, "itemName");
}
ft.getFlexCellFormatter().setWidth(1, 0, "100px");
ft.setHTML(1, 1, publication.getId()+" / <Strong>Ext. Id: </strong>"+publication.getExternalId()+" <Strong>System: </strong>"+SafeHtmlUtils.fromString(publication.getPublicationSystemName()).asString());
ft.setHTML(2, 1, SafeHtmlUtils.fromString((publication.getTitle() != null) ? publication.getTitle() : "").asString());
ft.setHTML(3, 1, SafeHtmlUtils.fromString((String.valueOf(publication.getYear()) != null) ? String.valueOf(publication.getYear()) : "").asString());
ft.setHTML(4, 1, SafeHtmlUtils.fromString((publication.getCategoryName() != null) ? publication.getCategoryName() : "").asString());
ft.setHTML(5, 1, SafeHtmlUtils.fromString(String.valueOf(publication.getRank()) + " (default is 0)").asString());
ft.setHTML(6, 1, SafeHtmlUtils.fromString((publication.getIsbn() != null) ? publication.getIsbn() : "").asString());
ft.setHTML(7, 1, SafeHtmlUtils.fromString((publication.getDoi() != null) ? publication.getDoi() : "").asString());
ft.setHTML(8, 1, SafeHtmlUtils.fromString((publication.getMain() != null) ? publication.getMain() : "").asString());
ft.setHTML(9, 1, SafeHtmlUtils.fromString((publication.getCreatedBy() != null) ? publication.getCreatedBy() : "").asString());
ft.setHTML(10, 1, SafeHtmlUtils.fromString((String.valueOf(publication.getCreatedDate()) != null) ? String.valueOf(publication.getCreatedDate()) : "").asString());
}
// LOCK / UNLOCK button for PerunAdmin
if (session.isPerunAdmin()) {
final CustomButton lock;
if (publication.getLocked()) {
lock = new CustomButton("Unlock", "Allow editing of publication details (for users).", SmallIcons.INSTANCE.lockOpenIcon());
ft.setWidget(0, 0, lock);
ft.getFlexCellFormatter().setColSpan(0, 0, 1);
ft.setWidget(0, 1, new HTML(new Image(SmallIcons.INSTANCE.lockIcon())+" Publication is locked."));
} else {
lock = new CustomButton("Lock", "Deny editing of publication details (for users).", SmallIcons.INSTANCE.lockIcon());
ft.setWidget(0, 1, lock);
}
lock.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent event) {
LockUnlockPublications upCall = new LockUnlockPublications(JsonCallbackEvents.disableButtonEvents(lock, new JsonCallbackEvents(){
public void onFinished(JavaScriptObject jso) {
// refresh page content
publication.setLocked(!publication.getLocked());
draw();
}
}));
Publication p = JsonUtils.clone(publication).cast();
upCall.lockUnlockPublication(!publication.getLocked(), p);
}
});
}
DisclosurePanel dp = new DisclosurePanel();
dp.setWidth("100%");
dp.setContent(ft);
dp.setOpen(true);
FlexTable detailsHeader = new FlexTable();
detailsHeader.setWidget(0, 0, new Image(LargeIcons.INSTANCE.bookIcon()));
detailsHeader.setHTML(0, 1, "<h3>Details</h3>");
dp.setHeader(detailsHeader);
vp.add(dp);
vp.add(loadAuthorsSubTab());
vp.add(loadThanksSubTab());
this.contentWidget.setWidget(sp);
return getWidget();
}
/**
* Returns widget with authors management for publication
*
* @return widget
*/
private Widget loadAuthorsSubTab(){
DisclosurePanel dp = new DisclosurePanel();
dp.setWidth("100%");
dp.setOpen(true);
VerticalPanel vp = new VerticalPanel();
vp.setSize("100%", "100%");
dp.setContent(vp);
FlexTable header = new FlexTable();
header.setWidget(0, 0, new Image(LargeIcons.INSTANCE.userGreenIcon()));
header.setHTML(0, 1, "<h3>Authors / Reported by</h3>");
dp.setHeader(header);
// menu
TabMenu menu = new TabMenu();
// callback
final FindAuthorsByPublicationId call = new FindAuthorsByPublicationId(publication.getId());
call.setCheckable(false);
if (!publication.getLocked()) {
// editable if not locked
vp.add(menu);
vp.setCellHeight(menu, "30px");
call.setCheckable(true);
}
final CustomButton addButton = new CustomButton("Add myself", "Add you as author of publication", SmallIcons.INSTANCE.addIcon());
addButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
JsonCallbackEvents events = JsonCallbackEvents.refreshTableEvents(call);
CreateAuthorship request = new CreateAuthorship(JsonCallbackEvents.disableButtonEvents(addButton, events));
request.createAuthorship(publicationId, session.getActiveUser().getId());
}
});
menu.addWidget(addButton);
CustomButton addOthersButton = new CustomButton("Add others", "Add more authors", SmallIcons.INSTANCE.addIcon());
addOthersButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
session.getTabManager().addTabToCurrentTab(new AddAuthorTabItem(publication, JsonCallbackEvents.refreshTableEvents(call)), true);
}
});
menu.addWidget(addOthersButton);
// fill table
CellTable<Author> table = call.getEmptyTable();
call.retrieveData();
final CustomButton removeButton = TabMenu.getPredefinedButton(ButtonType.REMOVE, "Remove select author(s) from publication");
removeButton.setEnabled(false);
JsonUtils.addTableManagedButton(call, table, removeButton);
menu.addWidget(removeButton);
removeButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
final ArrayList<Author> list = call.getTableSelectedList();
String text = "Following users will be removed from publication's authors. They will lose any benefit granted by publication's rank.";
UiElements.showDeleteConfirm(list, text, new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
// TODO - SHOULD HAVE ONLY ONE CALLBACK TO CORE
for(int i=0; i<list.size(); i++){
// calls the request
if (i == list.size()-1) {
DeleteAuthorship request = new DeleteAuthorship(JsonCallbackEvents.disableButtonEvents(removeButton, JsonCallbackEvents.refreshTableEvents(call)));
request.deleteAuthorship(publicationId, list.get(i).getId());
} else {
DeleteAuthorship request = new DeleteAuthorship();
request.deleteAuthorship(publicationId, list.get(i).getId());
}
}
}
});
}
});
ScrollPanel sp = new ScrollPanel();
sp.add(table);
table.addStyleName("perun-table");
sp.addStyleName("perun-tableScrollPanel");
vp.add(sp);
return dp;
}
/**
* Returns thanks management widget for publication
*
* @return widget
*/
private Widget loadThanksSubTab(){
DisclosurePanel dp = new DisclosurePanel();
dp.setWidth("100%");
dp.setOpen(true);
VerticalPanel vp = new VerticalPanel();
vp.setSize("100%", "100%");
dp.setContent(vp);
FlexTable header = new FlexTable();
header.setWidget(0, 0, new Image(LargeIcons.INSTANCE.smallBusinessIcon()));
header.setHTML(0, 1, "<h3>Acknowledgement</h3>");
dp.setHeader(header);
// menu
TabMenu menu = new TabMenu();
// callback
final GetRichThanksByPublicationId thanksCall = new GetRichThanksByPublicationId(publicationId);
thanksCall.setCheckable(false);
if (!publication.getLocked()) {
// editable if not locked
vp.add(menu);
vp.setCellHeight(menu, "30px");
thanksCall.setCheckable(true);
}
CellTable<Thanks> table = thanksCall.getTable();
menu.addWidget(TabMenu.getPredefinedButton(ButtonType.ADD, "Add acknowledgement to publication", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
session.getTabManager().addTabToCurrentTab(new CreateThanksTabItem(publication, JsonCallbackEvents.refreshTableEvents(thanksCall)), true);
}
}));
final CustomButton removeButton = TabMenu.getPredefinedButton(ButtonType.REMOVE, "Remove acknowledgement from publication");
removeButton.setEnabled(false);
JsonUtils.addTableManagedButton(thanksCall, table, removeButton);
menu.addWidget(removeButton);
removeButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
final ArrayList<Thanks> list = thanksCall.getTableSelectedList();
String text = "Following acknowledgements will be removed from publication.";
UiElements.showDeleteConfirm(list, text, new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
// TODO - SHOULD HAVE ONLY ONE CALLBACK TO CORE
for(int i=0; i<list.size(); i++){
// calls the request
if (i == list.size()-1) {
DeleteThanks request = new DeleteThanks(JsonCallbackEvents.disableButtonEvents(removeButton, JsonCallbackEvents.refreshTableEvents(thanksCall)));
request.deleteThanks(list.get(i).getId());
} else {
DeleteThanks request = new DeleteThanks(JsonCallbackEvents.disableButtonEvents(removeButton));
request.deleteThanks(list.get(i).getId());
}
}
}
});
}
});
table.addStyleName("perun-table");
ScrollPanel sp = new ScrollPanel();
sp.add(table);
sp.addStyleName("perun-tableScrollPanel");
vp.add(sp);
return dp;
}
public Widget getWidget() {
return this.contentWidget;
}
public Widget getTitle() {
return this.titleWidget;
}
public ImageResource getIcon() {
return SmallIcons.INSTANCE.bookIcon();
}
@Override
public int hashCode() {
final int prime = 613;
int result = 1;
result = prime * result * 22 * publicationId;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PublicationDetailTabItem other = (PublicationDetailTabItem)obj;
if (publicationId != other.publicationId)
return false;
return true;
}
public boolean multipleInstancesEnabled() {
return false;
}
public void open() {
if (fromSelf) {
session.getUiElements().getBreadcrumbs().setLocation(MainMenu.USER, "My publications", CabinetTabs.URL+UrlMapper.TAB_NAME_SEPARATOR+"userpubs?user=" + session.getUser().getId(), publication.getTitle(), getUrlWithParameters());
} else {
session.getUiElements().getBreadcrumbs().setLocation(MainMenu.PERUN_ADMIN, "Publications", CabinetTabs.URL+UrlMapper.TAB_NAME_SEPARATOR+"all", publication.getTitle(), getUrlWithParameters());
}
}
public boolean isAuthorized() {
if (session.isSelf()) {
return true;
} else {
return false;
}
}
public final static String URL = "pbl";
public String getUrl()
{
return URL;
}
public String getUrlWithParameters() {
return CabinetTabs.URL + UrlMapper.TAB_NAME_SEPARATOR + getUrl() + "?id=" + publicationId + "&self="+fromSelf;
}
static public PublicationDetailTabItem load(Map<String, String> parameters) {
int pubId = Integer.parseInt(parameters.get("id"));
boolean fromSelf = Boolean.parseBoolean(parameters.get("self"));
return new PublicationDetailTabItem(pubId, fromSelf);
}
}
| stavamichal/perun | perun-web-gui/src/main/java/cz/metacentrum/perun/webgui/tabs/cabinettabs/PublicationDetailTabItem.java | Java | bsd-2-clause | 19,457 |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'', include('project.core.urls', namespace='core')),
)
| pombredanne/django-boilerplate-1 | project/urls.py | Python | bsd-2-clause | 248 |
"""Auxiliary functions."""
import cPickle as pickle
import os
import sys
import gzip
import urllib
import numpy
import theano
import theano.tensor as T
import theano.sandbox.cuda
from athenet.utils import BIN_DIR, DATA_DIR
def load_data_from_pickle(filename):
"""Load data from pickle file.
:param filename: File with pickled data, may be gzipped.
:return: Data loaded from file.
"""
try:
f = gzip.open(filename, 'rb')
data = pickle.load(f)
except:
f = open(filename, 'rb')
data = pickle.load(f)
f.close()
return data
def save_data_to_pickle(data, filename):
"""Saves data to gzipped pickle file.
:param data: Data to be saved.
:param filename: Name of file to save data.
"""
with gzip.open(filename, 'wb') as f:
pickle.dump(data, f)
def load_data(filename, url=None):
"""Load data from file, download file if it doesn't exist.
:param filename: File with pickled data, may be gzipped.
:param url: Url for downloading file.
:return: Unpickled data.
"""
if not os.path.isfile(filename):
if not url:
return None
download_file(filename, url)
data = load_data_from_pickle(filename)
return data
def download_file(filename, url):
"""Download file from given url.
:param filename: Name of a file to be downloaded.
:param url: Url for downloading file.
"""
directory = os.path.dirname(filename)
if not os.path.exists(directory):
os.makedirs(directory)
print 'Downloading ' + os.path.basename(filename) + '...',
sys.stdout.flush()
urllib.urlretrieve(url, filename)
print 'Done'
def get_data_path(name):
"""Return absolute path to the data file.
:param name: Name of the file.
:return: Full path to the file.
"""
return os.path.join(DATA_DIR, name)
def get_bin_path(name):
"""Return absolute path to the binary data file.
:param name: Name of the file.
:return: Full path to the file.
"""
return os.path.join(BIN_DIR, name)
def zero_fraction(network):
"""Returns fraction of zeros in weights of Network.
Biases are not considered.
:param network: Network for which we count fraction of zeros.
:return: Fraction of zeros.
"""
params = [layer.W for layer in network.weighted_layers]
n_non_zero = 0
n_fields = 0
for param in params:
n_fields += numpy.size(param)
n_non_zero += numpy.count_nonzero(param)
n_zero = n_fields - n_non_zero
return (1.0 * n_zero) / (1.0 * n_fields)
def count_zeros_in_layer(layer):
return layer.W.size - numpy.count_nonzero(layer.W)
def count_zeros(network):
"""
Returns zeros in weights of Network.
Biases are not considered.
:param network: Network for which we count zeros.
:return: List of number of weights being zero for each layer.
"""
return numpy.array([count_zeros_in_layer(layer)
for layer in network.weighted_layers])
len_prev = 0
def overwrite(text='', length=None):
"""Write text in a current line, overwriting previously written text.
Previously written text also needs to be written using this function for
it to work properly. Otherwise optional argument length can be given to
specify length of a previous text.
:param string text: Text to be written.
:param integer length: Length of a previous text.
"""
global len_prev
if length is None:
length = len_prev
print '\r' + ' '*length,
print '\r' + text,
len_prev = len(text)
def cudnn_available():
"""Check if cuDNN is available.
:return: True, if cuDNN is available, False otherwise.
"""
try:
return theano.sandbox.cuda.dnn_available()
except:
return False
def reshape_for_padding(layer_input, image_shape, batch_size, padding,
value=0.0):
"""Returns padded tensor.
:param theano.tensor4 layer_input: input in shape
(batch_size, number of channels,
height, width)
:param tuple of integers image_shape: shape of input images in format
(height, width, number of channels)
:param integer batch_size: size of input batch size
:param pair of integers padding: padding to be applied to layer_input
:param float value: value of new fields
:returns: padded layer_input
:rtype: theano.tensor4
"""
if padding == (0, 0):
return layer_input
h, w, n_channels = image_shape
pad_h, pad_w = padding
h_in = h + 2*pad_h
w_in = w + 2*pad_w
extra_pixels = T.alloc(numpy.array(value, dtype=theano.config.floatX),
batch_size, n_channels, h_in, w_in)
extra_pixels = T.set_subtensor(
extra_pixels[:, :, pad_h:pad_h+h, pad_w:pad_w+w], layer_input)
return extra_pixels
def convolution(layer_input, w_shared, stride, n_groups, image_shape,
padding, batch_size, filter_shape):
"""Returns result of applying convolution to layer_input.
:param theano.tensor4 layer_input: input of convolution in format
(batch_size, number of channels,
height, width)
:param theano.tensor4 w_shared: weights in format
(number of output channels,
number of input channels,
height, width)
:param pair of integers stride: stride of convolution
:param integer n_groups: number of groups in convolution
:param image_shape: shape of single image in layer_input in format
(height, width, number of channels)
:type image_shape: tuple of 3 integers
:param pair of integers padding: padding of convolution
:param integer batch_size: size of batch of layer_input
:param filter_shape: shape of single filter in format
(height, width, number of output channels)
:type filter_shape: tuple of 3 integers
"""
n_channels = image_shape[2]
n_filters = filter_shape[2]
n_group_channels = n_channels / n_groups
n_group_filters = n_filters / n_groups
h, w = image_shape[0:2]
pad_h, pad_w = padding
group_image_shape = (batch_size, n_group_channels,
h + 2*pad_h, w + 2*pad_w)
h, w = filter_shape[0:2]
group_filter_shape = (n_group_filters, n_group_channels, h, w)
conv_outputs = [T.nnet.conv.conv2d(
input=layer_input[:, i*n_group_channels:(i+1)*n_group_channels,
:, :],
filters=w_shared[i*n_group_filters:(i+1)*n_group_filters,
:, :, :],
filter_shape=group_filter_shape,
image_shape=group_image_shape,
subsample=stride
) for i in xrange(n_groups)]
return T.concatenate(conv_outputs, axis=1)
| heurezjusz/Athena | athenet/utils/misc.py | Python | bsd-2-clause | 7,019 |
<?php
$player = new stdClass();
$player->name = "Chuck";
$player->score = 0;
$player->score++;
print_r($player);
class Player {
public $name = "Sally";
public $score = 0;
}
$p2 = new Player();
$p2->score++;
print_r($p2);
| csev/wa4e | code/objects/scratch.php | PHP | bsd-2-clause | 236 |
using Example.Domain.Domain;
using LightBDD.Framework;
using LightBDD.Framework.Parameters;
using LightBDD.XUnit2;
namespace Example.LightBDD.XUnit2.Features
{
public partial class Calculator_feature : FeatureFixture
{
private Calculator _calculator;
private void Given_a_calculator()
{
_calculator = new Calculator();
}
private void Then_adding_X_to_Y_should_give_RESULT(int x, int y, Verifiable<int> result)
{
result.SetActual(() => _calculator.Add(x, y));
}
private void Then_dividing_X_by_Y_should_give_RESULT(int x, int y, Verifiable<int> result)
{
result.SetActual(() => _calculator.Divide(x, y));
}
private void Then_multiplying_X_by_Y_should_give_RESULT(int x, int y, Verifiable<int> result)
{
if (x < 0 || y < 0)
StepExecution.Current.IgnoreScenario("Negative numbers are not supported yet");
result.SetActual(() => _calculator.Multiply(x, y));
}
}
} | Suremaker/LightBDD | examples/Example.LightBDD.XUnit2/Features/Calculator_feature.Steps.cs | C# | bsd-2-clause | 1,059 |
class Nsd < Formula
desc "Name server daemon"
homepage "https://www.nlnetlabs.nl/projects/nsd/"
url "https://www.nlnetlabs.nl/downloads/nsd/nsd-4.2.2.tar.gz"
sha256 "83b333940a25fe6d453bcac6ea39edfa244612a879117c4a624c97eb250246fb"
revision 1
bottle do
sha256 "ca69db82461ccb04f94857b03715b967f80896539d7abce2b2cebb4dc3124082" => :catalina
sha256 "70d66d7396db21ace3541a6be4b556b9f339570e71fa817941df594c1205686a" => :mojave
sha256 "9fbd67d1d673c34b06f0f597e45b02121e98d286733e9df1d553daf8292b9b25" => :high_sierra
sha256 "9391533efaae88803ac27fc7f450523d7a40ab02b4da422e15f8c6bb925cc6cb" => :sierra
end
depends_on "libevent"
depends_on "openssl@1.1"
def install
system "./configure", "--prefix=#{prefix}",
"--sysconfdir=#{etc}",
"--localstatedir=#{var}",
"--with-libevent=#{Formula["libevent"].opt_prefix}",
"--with-ssl=#{Formula["openssl@1.1"].opt_prefix}"
system "make", "install"
end
test do
system "#{sbin}/nsd", "-v"
end
end
| zmwangx/homebrew-core | Formula/nsd.rb | Ruby | bsd-2-clause | 1,093 |
class Ejabberd < Formula
desc "XMPP application server"
homepage "https://www.ejabberd.im"
url "https://static.process-one.net/ejabberd/downloads/20.03/ejabberd-20.03.tgz"
sha256 "1a54ef1cdc391a25b81c3ed3e9e8aa43434a8d4549b4e86c54af3ecf121d0144"
bottle do
cellar :any
sha256 "9518b32a672d6a756a29594892982c175a54c32aee9b5253c20e57dcf7760c44" => :catalina
sha256 "74e8c73f8032241b193fb8e4b54a5164efb0aca5fb357857392feeee05d758f6" => :mojave
sha256 "9b6bf1b79ee1d24bf099b93173d4b4c461be63834cd79185be1e3bd3884bd9e7" => :high_sierra
end
head do
url "https://github.com/processone/ejabberd.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
end
depends_on "erlang"
depends_on "gd"
depends_on "libyaml"
depends_on "openssl@1.1"
def install
ENV["TARGET_DIR"] = ENV["DESTDIR"] = "#{lib}/ejabberd/erlang/lib/ejabberd-#{version}"
ENV["MAN_DIR"] = man
ENV["SBIN_DIR"] = sbin
args = ["--prefix=#{prefix}",
"--sysconfdir=#{etc}",
"--localstatedir=#{var}",
"--enable-pgsql",
"--enable-mysql",
"--enable-odbc",
"--enable-pam"]
system "./autogen.sh" if build.head?
system "./configure", *args
# Set CPP to work around cpp shim issue:
# https://github.com/Homebrew/brew/issues/5153
system "make", "CPP=clang -E"
ENV.deparallelize
system "make", "install"
(etc/"ejabberd").mkpath
end
def post_install
(var/"lib/ejabberd").mkpath
(var/"spool/ejabberd").mkpath
end
def caveats
<<~EOS
If you face nodedown problems, concat your machine name to:
/private/etc/hosts
after 'localhost'.
EOS
end
plist_options :manual => "#{HOMEBREW_PREFIX}/sbin/ejabberdctl start"
def plist
<<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>EnvironmentVariables</key>
<dict>
<key>HOME</key>
<string>#{var}/lib/ejabberd</string>
</dict>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_sbin}/ejabberdctl</string>
<string>start</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>WorkingDirectory</key>
<string>#{var}/lib/ejabberd</string>
</dict>
</plist>
EOS
end
test do
system sbin/"ejabberdctl", "ping"
end
end
| BrewTestBot/homebrew-core | Formula/ejabberd.rb | Ruby | bsd-2-clause | 2,601 |
# encoding: utf-8
from django.db.utils import IntegrityError, DatabaseError
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding unique constraint on 'PollAnswerUser', fields ['poll_answer', 'user']
db.create_unique('pybb_pollansweruser', ['poll_answer_id', 'user_id'])
def backwards(self, orm):
# Removing unique constraint on 'PollAnswerUser', fields ['poll_answer', 'user']
db.delete_unique('pybb_pollansweruser', ['poll_answer_id', 'user_id'])
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'pybb.attachment': {
'Meta': {'object_name': 'Attachment'},
'file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'post': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'attachments'", 'to': "orm['pybb.Post']"}),
'size': ('django.db.models.fields.IntegerField', [], {})
},
'pybb.category': {
'Meta': {'ordering': "['position']", 'object_name': 'Category'},
'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '80'}),
'position': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'})
},
'pybb.forum': {
'Meta': {'ordering': "['position']", 'object_name': 'Forum'},
'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'forums'", 'to': "orm['pybb.Category']"}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'headline': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'moderators': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['%s.%s']"% (User._meta.app_label, User._meta.object_name), 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '80'}),
'position': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}),
'post_count': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}),
'readed_by': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'readed_forums'", 'symmetrical': 'False', 'through': "orm['pybb.ForumReadTracker']", 'to': "orm['%s.%s']"% (User._meta.app_label, User._meta.object_name)}),
'topic_count': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})
},
'pybb.forumreadtracker': {
'Meta': {'object_name': 'ForumReadTracker'},
'forum': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['pybb.Forum']", 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'time_stamp': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s.%s']"% (User._meta.app_label, User._meta.object_name)})
},
'pybb.pollanswer': {
'Meta': {'object_name': 'PollAnswer'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'text': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'topic': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'poll_answers'", 'to': "orm['pybb.Topic']"})
},
'pybb.pollansweruser': {
'Meta': {'unique_together': "(('poll_answer', 'user'),)", 'object_name': 'PollAnswerUser'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'poll_answer': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'users'", 'to': "orm['pybb.PollAnswer']"}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'poll_answers'", 'to': "orm['%s.%s']"% (User._meta.app_label, User._meta.object_name)})
},
'pybb.post': {
'Meta': {'ordering': "['created']", 'object_name': 'Post'},
'body': ('django.db.models.fields.TextField', [], {}),
'body_html': ('django.db.models.fields.TextField', [], {}),
'body_text': ('django.db.models.fields.TextField', [], {}),
'created': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'on_moderation': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'topic': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'posts'", 'to': "orm['pybb.Topic']"}),
'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'posts'", 'to': "orm['%s.%s']"% (User._meta.app_label, User._meta.object_name)}),
'user_ip': ('django.db.models.fields.IPAddressField', [], {'default': "'0.0.0.0'", 'max_length': '15', 'blank': 'True'})
},
'pybb.profile': {
'Meta': {'object_name': 'Profile'},
'autosubscribe': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'avatar': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.CharField', [], {'default': "'ru-RU'", 'max_length': '10', 'blank': 'True'}),
'post_count': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}),
'show_signatures': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'signature': ('django.db.models.fields.TextField', [], {'max_length': '1024', 'blank': 'True'}),
'signature_html': ('django.db.models.fields.TextField', [], {'max_length': '1054', 'blank': 'True'}),
'time_zone': ('django.db.models.fields.FloatField', [], {'default': '3.0'}),
'user': ('annoying.fields.AutoOneToOneField', [], {'related_name': "'pybb_profile'", 'unique': 'True', 'to': "orm['%s.%s']"% (User._meta.app_label, User._meta.object_name)})
},
'pybb.topic': {
'Meta': {'ordering': "['-created']", 'object_name': 'Topic'},
'closed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'created': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'forum': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'topics'", 'to': "orm['pybb.Forum']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'on_moderation': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'poll_question': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'poll_type': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'post_count': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}),
'readed_by': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'readed_topics'", 'symmetrical': 'False', 'through': "orm['pybb.TopicReadTracker']", 'to': "orm['%s.%s']"% (User._meta.app_label, User._meta.object_name)}),
'sticky': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'subscribers': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'subscriptions'", 'blank': 'True', 'to': "orm['%s.%s']"% (User._meta.app_label, User._meta.object_name)}),
'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s.%s']"% (User._meta.app_label, User._meta.object_name)}),
'views': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'})
},
'pybb.topicreadtracker': {
'Meta': {'object_name': 'TopicReadTracker'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'time_stamp': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'topic': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['pybb.Topic']", 'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s.%s']"% (User._meta.app_label, User._meta.object_name)})
}
}
complete_apps = ['pybb'] | zekone/dj_pybb | pybb/migrations/0023_auto__add_unique_pollansweruser_poll_answer_user.py | Python | bsd-2-clause | 12,958 |
goog.require('ol.Map');
goog.require('ol.View');
goog.require('ol.events.condition');
goog.require('ol.interaction.Select');
goog.require('ol.layer.Tile');
goog.require('ol.layer.Vector');
goog.require('ol.source.GeoJSON');
goog.require('ol.source.MapQuest');
var raster = new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
});
var vector = new ol.layer.Vector({
source: new ol.source.GeoJSON({
projection: 'EPSG:3857',
url: 'data/geojson/countries.geojson'
})
});
var map = new ol.Map({
layers: [raster, vector],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
var select = null; // ref to currently selected interaction
// select interaction working on "singleclick"
var selectSingleClick = new ol.interaction.Select();
// select interaction working on "click"
var selectClick = new ol.interaction.Select({
condition: ol.events.condition.click
});
// select interaction working on "pointermove"
var selectPointerMove = new ol.interaction.Select({
condition: ol.events.condition.pointerMove
});
var selectElement = document.getElementById('type');
var changeInteraction = function() {
if (select !== null) {
map.removeInteraction(select);
}
var value = selectElement.value;
if (value == 'singleclick') {
select = selectSingleClick;
} else if (value == 'click') {
select = selectClick;
} else if (value == 'pointermove') {
select = selectPointerMove;
} else {
select = null;
}
if (select !== null) {
map.addInteraction(select);
select.on('select', function(e) {
$('#status').html(' ' + e.target.getFeatures().getLength() +
' selected features (last operation selected ' + e.selected.length +
' and deselected ' + e.deselected.length + ' features)');
});
}
};
/**
* onchange callback on the select element.
*/
selectElement.onchange = changeInteraction;
changeInteraction();
| mechdrew/ol3 | examples/select-features.js | JavaScript | bsd-2-clause | 1,939 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "webkit/plugins/ppapi/url_response_info_util.h"
#include "base/logging.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebHTTPHeaderVisitor.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURL.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebURLResponse.h"
#include "webkit/base/file_path_string_conversions.h"
#include "webkit/plugins/ppapi/ppb_file_ref_impl.h"
#include "webkit/glue/webkit_glue.h"
using WebKit::WebHTTPHeaderVisitor;
using WebKit::WebString;
using WebKit::WebURLResponse;
namespace webkit {
namespace ppapi {
namespace {
class HeaderFlattener : public WebHTTPHeaderVisitor {
public:
const std::string& buffer() const { return buffer_; }
virtual void visitHeader(const WebString& name, const WebString& value) {
if (!buffer_.empty())
buffer_.append("\n");
buffer_.append(name.utf8());
buffer_.append(": ");
buffer_.append(value.utf8());
}
private:
std::string buffer_;
};
bool IsRedirect(int32_t status) {
return status >= 300 && status <= 399;
}
} // namespace
::ppapi::URLResponseInfoData DataFromWebURLResponse(
PP_Instance pp_instance,
const WebURLResponse& response) {
::ppapi::URLResponseInfoData data;
data.url = response.url().spec();
data.status_code = response.httpStatusCode();
data.status_text = response.httpStatusText().utf8();
if (IsRedirect(data.status_code)) {
data.redirect_url = response.httpHeaderField(
WebString::fromUTF8("Location")).utf8();
}
HeaderFlattener flattener;
response.visitHTTPHeaderFields(&flattener);
data.headers = flattener.buffer();
WebString file_path = response.downloadFilePath();
if (!file_path.isEmpty()) {
scoped_refptr<PPB_FileRef_Impl> file_ref(
PPB_FileRef_Impl::CreateExternal(
pp_instance,
webkit_base::WebStringToFilePath(file_path),
std::string()));
data.body_as_file_ref = file_ref->GetCreateInfo();
file_ref->GetReference(); // The returned data has one ref for the plugin.
}
return data;
}
} // namespace ppapi
} // namespace webkit
| leighpauls/k2cro4 | webkit/plugins/ppapi/url_response_info_util.cc | C++ | bsd-3-clause | 2,394 |
<?php
/**
* Created by PhpStorm.
* User: User
* Date: 2/24/2015
* Time: 12:18 PM
*/
namespace common\modules\reporting\widgets\emergency_situation;
use common\modules\reporting\models\EmergencySituation;
use yii\base\Exception;
use yii\base\Widget;
use yii\helpers\Json;
use yii\web\View;
class Create extends Widget
{
public $actionRoute;
public $model;
public $mapDivId;
public $widgetId;
public $clientOptions;
public $juiDialogOptions;
public $jqToggleBtnSelector;
public $formId;
public $jQueryFormSelector;
public function init()
{
if(!$this->actionRoute){
throw new Exception(
'route to the action to which the form to be submitted must be specified! Example :: /girc/dmis/frontend/web/site/event-create'
);
}
$this->formId=($this->formId)?$this->formId:'formEventCreate';
$this->jQueryFormSelector = '#'.$this->formId;
$this->widgetId=($this->widgetId)?$this->widgetId:$this->id;
$this->clientOptions['formId']=$this->formId;
$this->clientOptions['actionRoute']=$this->actionRoute;
$this->clientOptions['widgetId']=$this->widgetId;
$this->clientOptions['jqToggleBtnSelector']=$this->jqToggleBtnSelector;
$this->clientOptions = Json::encode($this->clientOptions);
$this->registerClientScripts();
}
public function run()
{
$this->model = new EmergencySituation();
return $this->render('_form',
[
'model'=>$this->model,
'formId'=>$this->formId,
'jQueryFormSelector'=>$this->jQueryFormSelector,
'actionRoute'=>$this->actionRoute,
'widgetId'=>$this->widgetId,
'jqToggleBtnSelector'=>$this->jqToggleBtnSelector,
'clientOptions'=>$this->clientOptions,
]);
}
public function registerClientScripts(){
\common\assets\YiiAjaxFormSubmitAsset::register($this->getView());
$this->getView()->registerJs("$('#$this->widgetId').yiiAjaxFormWidget($this->clientOptions);", View::POS_READY);
}
} | girc/dmis | common/modules/reporting/widgets/emergency_situation/Create.php | PHP | bsd-3-clause | 2,168 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "opentrain.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| hasadna/OpenTrain | webserver/opentrain/manage.py | Python | bsd-3-clause | 252 |
class AddQuestionAndDisplayAsAndSequenceToEvaluationQuestion < ActiveRecord::Migration
def self.up
add_column :evaluation_questions, :question, :text
add_column :evaluation_questions, :display_as, :string
add_column :evaluation_questions, :sequence, :integer
add_column :evaluation_questions, :required, :boolean
end
def self.down
remove_column :evaluation_questions, :required
remove_column :evaluation_questions, :sequence
remove_column :evaluation_questions, :display_as
remove_column :evaluation_questions, :question
end
end
| joshlin/expo2 | db/migrate/207_add_question_and_display_as_and_sequence_to_evaluation_question.rb | Ruby | bsd-3-clause | 570 |
#!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import glob
import json
import os
import pipes
import shutil
import subprocess
import sys
script_dir = os.path.dirname(os.path.realpath(__file__))
chrome_src = os.path.abspath(os.path.join(script_dir, os.pardir))
SRC_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(chrome_src, 'tools', 'gyp', 'pylib'))
json_data_file = os.path.join(script_dir, 'win_toolchain.json')
import gyp
# Use MSVS2013 as the default toolchain.
CURRENT_DEFAULT_TOOLCHAIN_VERSION = '2013'
def SetEnvironmentAndGetRuntimeDllDirs():
"""Sets up os.environ to use the depot_tools VS toolchain with gyp, and
returns the location of the VS runtime DLLs so they can be copied into
the output directory after gyp generation.
"""
vs_runtime_dll_dirs = None
depot_tools_win_toolchain = \
bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', '1')))
# When running on a non-Windows host, only do this if the SDK has explicitly
# been downloaded before (in which case json_data_file will exist).
if ((sys.platform in ('win32', 'cygwin') or os.path.exists(json_data_file))
and depot_tools_win_toolchain):
if ShouldUpdateToolchain():
Update()
with open(json_data_file, 'r') as tempf:
toolchain_data = json.load(tempf)
toolchain = toolchain_data['path']
version = toolchain_data['version']
win_sdk = toolchain_data.get('win_sdk')
if not win_sdk:
win_sdk = toolchain_data['win8sdk']
wdk = toolchain_data['wdk']
# TODO(scottmg): The order unfortunately matters in these. They should be
# split into separate keys for x86 and x64. (See CopyVsRuntimeDlls call
# below). http://crbug.com/345992
vs_runtime_dll_dirs = toolchain_data['runtime_dirs']
os.environ['GYP_MSVS_OVERRIDE_PATH'] = toolchain
os.environ['GYP_MSVS_VERSION'] = version
# We need to make sure windows_sdk_path is set to the automated
# toolchain values in GYP_DEFINES, but don't want to override any
# otheroptions.express
# values there.
gyp_defines_dict = gyp.NameValueListToDict(gyp.ShlexEnv('GYP_DEFINES'))
gyp_defines_dict['windows_sdk_path'] = win_sdk
os.environ['GYP_DEFINES'] = ' '.join('%s=%s' % (k, pipes.quote(str(v)))
for k, v in gyp_defines_dict.iteritems())
os.environ['WINDOWSSDKDIR'] = win_sdk
os.environ['WDK_DIR'] = wdk
# Include the VS runtime in the PATH in case it's not machine-installed.
runtime_path = os.path.pathsep.join(vs_runtime_dll_dirs)
os.environ['PATH'] = runtime_path + os.path.pathsep + os.environ['PATH']
elif sys.platform == 'win32' and not depot_tools_win_toolchain:
if not 'GYP_MSVS_OVERRIDE_PATH' in os.environ:
os.environ['GYP_MSVS_OVERRIDE_PATH'] = DetectVisualStudioPath()
if not 'GYP_MSVS_VERSION' in os.environ:
os.environ['GYP_MSVS_VERSION'] = GetVisualStudioVersion()
return vs_runtime_dll_dirs
def _RegistryGetValueUsingWinReg(key, value):
"""Use the _winreg module to obtain the value of a registry key.
Args:
key: The registry key.
value: The particular registry value to read.
Return:
contents of the registry key's value, or None on failure. Throws
ImportError if _winreg is unavailable.
"""
import _winreg
try:
root, subkey = key.split('\\', 1)
assert root == 'HKLM' # Only need HKLM for now.
with _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, subkey) as hkey:
return _winreg.QueryValueEx(hkey, value)[0]
except WindowsError:
return None
def _RegistryGetValue(key, value):
try:
return _RegistryGetValueUsingWinReg(key, value)
except ImportError:
raise Exception('The python library _winreg not found.')
def GetVisualStudioVersion():
"""Return GYP_MSVS_VERSION of Visual Studio.
"""
return os.environ.get('GYP_MSVS_VERSION', CURRENT_DEFAULT_TOOLCHAIN_VERSION)
def DetectVisualStudioPath():
"""Return path to the GYP_MSVS_VERSION of Visual Studio.
"""
# Note that this code is used from
# build/toolchain/win/setup_toolchain.py as well.
version_as_year = GetVisualStudioVersion()
year_to_version = {
'2013': '12.0',
'2015': '14.0',
}
if version_as_year not in year_to_version:
raise Exception(('Visual Studio version %s (from GYP_MSVS_VERSION)'
' not supported. Supported versions are: %s') % (
version_as_year, ', '.join(year_to_version.keys())))
version = year_to_version[version_as_year]
keys = [r'HKLM\Software\Microsoft\VisualStudio\%s' % version,
r'HKLM\Software\Wow6432Node\Microsoft\VisualStudio\%s' % version]
for key in keys:
path = _RegistryGetValue(key, 'InstallDir')
if not path:
continue
path = os.path.normpath(os.path.join(path, '..', '..'))
return path
raise Exception(('Visual Studio Version %s (from GYP_MSVS_VERSION)'
' not found.') % (version_as_year))
def _VersionNumber():
"""Gets the standard version number ('120', '140', etc.) based on
GYP_MSVS_VERSION."""
vs_version = GetVisualStudioVersion()
if vs_version == '2013':
return '120'
elif vs_version == '2015':
return '140'
else:
raise ValueError('Unexpected GYP_MSVS_VERSION')
def _CopyRuntimeImpl(target, source, verbose=True):
"""Copy |source| to |target| if it doesn't already exist or if it
needs to be updated.
"""
if (os.path.isdir(os.path.dirname(target)) and
(not os.path.isfile(target) or
os.stat(target).st_mtime != os.stat(source).st_mtime)):
if verbose:
print 'Copying %s to %s...' % (source, target)
if os.path.exists(target):
os.unlink(target)
shutil.copy2(source, target)
def _CopyRuntime2013(target_dir, source_dir, dll_pattern):
"""Copy both the msvcr and msvcp runtime DLLs, only if the target doesn't
exist, but the target directory does exist."""
for file_part in ('p', 'r'):
dll = dll_pattern % file_part
target = os.path.join(target_dir, dll)
source = os.path.join(source_dir, dll)
_CopyRuntimeImpl(target, source)
def _CopyRuntime2015(target_dir, source_dir, dll_pattern, suffix):
"""Copy both the msvcp and vccorlib runtime DLLs, only if the target doesn't
exist, but the target directory does exist."""
for file_part in ('msvcp', 'vccorlib', 'vcruntime'):
dll = dll_pattern % file_part
target = os.path.join(target_dir, dll)
source = os.path.join(source_dir, dll)
_CopyRuntimeImpl(target, source)
ucrt_src_dir = os.path.join(source_dir, 'api-ms-win-*.dll')
print 'Copying %s to %s...' % (ucrt_src_dir, target_dir)
for ucrt_src_file in glob.glob(ucrt_src_dir):
file_part = os.path.basename(ucrt_src_file)
ucrt_dst_file = os.path.join(target_dir, file_part)
_CopyRuntimeImpl(ucrt_dst_file, ucrt_src_file, False)
_CopyRuntimeImpl(os.path.join(target_dir, 'ucrtbase' + suffix),
os.path.join(source_dir, 'ucrtbase' + suffix))
def _CopyRuntime(target_dir, source_dir, target_cpu, debug):
"""Copy the VS runtime DLLs, only if the target doesn't exist, but the target
directory does exist. Handles VS 2013 and VS 2015."""
suffix = "d.dll" if debug else ".dll"
if GetVisualStudioVersion() == '2015':
_CopyRuntime2015(target_dir, source_dir, '%s140' + suffix, suffix)
else:
_CopyRuntime2013(target_dir, source_dir, 'msvc%s120' + suffix)
# Copy the PGO runtime library to the release directories.
if not debug and os.environ.get('GYP_MSVS_OVERRIDE_PATH'):
pgo_x86_runtime_dir = os.path.join(os.environ.get('GYP_MSVS_OVERRIDE_PATH'),
'VC', 'bin')
pgo_x64_runtime_dir = os.path.join(pgo_x86_runtime_dir, 'amd64')
pgo_runtime_dll = 'pgort' + _VersionNumber() + '.dll'
if target_cpu == "x86":
source_x86 = os.path.join(pgo_x86_runtime_dir, pgo_runtime_dll)
if os.path.exists(source_x86):
_CopyRuntimeImpl(os.path.join(target_dir, pgo_runtime_dll), source_x86)
elif target_cpu == "x64":
source_x64 = os.path.join(pgo_x64_runtime_dir, pgo_runtime_dll)
if os.path.exists(source_x64):
_CopyRuntimeImpl(os.path.join(target_dir, pgo_runtime_dll),
source_x64)
else:
raise NotImplementedError("Unexpected target_cpu value:" + target_cpu)
def CopyVsRuntimeDlls(output_dir, runtime_dirs):
"""Copies the VS runtime DLLs from the given |runtime_dirs| to the output
directory so that even if not system-installed, built binaries are likely to
be able to run.
This needs to be run after gyp has been run so that the expected target
output directories are already created.
This is used for the GYP build and gclient runhooks.
"""
x86, x64 = runtime_dirs
out_debug = os.path.join(output_dir, 'Debug')
out_debug_nacl64 = os.path.join(output_dir, 'Debug', 'x64')
out_release = os.path.join(output_dir, 'Release')
out_release_nacl64 = os.path.join(output_dir, 'Release', 'x64')
out_debug_x64 = os.path.join(output_dir, 'Debug_x64')
out_release_x64 = os.path.join(output_dir, 'Release_x64')
if os.path.exists(out_debug) and not os.path.exists(out_debug_nacl64):
os.makedirs(out_debug_nacl64)
if os.path.exists(out_release) and not os.path.exists(out_release_nacl64):
os.makedirs(out_release_nacl64)
_CopyRuntime(out_debug, x86, "x86", debug=True)
_CopyRuntime(out_release, x86, "x86", debug=False)
_CopyRuntime(out_debug_x64, x64, "x64", debug=True)
_CopyRuntime(out_release_x64, x64, "x64", debug=False)
_CopyRuntime(out_debug_nacl64, x64, "x64", debug=True)
_CopyRuntime(out_release_nacl64, x64, "x64", debug=False)
def CopyDlls(target_dir, configuration, target_cpu):
"""Copy the VS runtime DLLs into the requested directory as needed.
configuration is one of 'Debug' or 'Release'.
target_cpu is one of 'x86' or 'x64'.
The debug configuration gets both the debug and release DLLs; the
release config only the latter.
This is used for the GN build.
"""
vs_runtime_dll_dirs = SetEnvironmentAndGetRuntimeDllDirs()
if not vs_runtime_dll_dirs:
return
x64_runtime, x86_runtime = vs_runtime_dll_dirs
runtime_dir = x64_runtime if target_cpu == 'x64' else x86_runtime
_CopyRuntime(target_dir, runtime_dir, target_cpu, debug=False)
if configuration == 'Debug':
_CopyRuntime(target_dir, runtime_dir, target_cpu, debug=True)
def _GetDesiredVsToolchainHashes():
"""Load a list of SHA1s corresponding to the toolchains that we want installed
to build with."""
if GetVisualStudioVersion() == '2015':
# Update 1 with hot fixes.
return ['b349b3cc596d5f7e13d649532ddd7e8db39db0cb']
else:
# Default to VS2013.
return ['4087e065abebdca6dbd0caca2910c6718d2ec67f']
def ShouldUpdateToolchain():
"""Check if the toolchain should be upgraded."""
if not os.path.exists(json_data_file):
return True
with open(json_data_file, 'r') as tempf:
toolchain_data = json.load(tempf)
version = toolchain_data['version']
env_version = GetVisualStudioVersion()
# If there's a mismatch between the version set in the environment and the one
# in the json file then the toolchain should be updated.
return version != env_version
def Update(force=False):
"""Requests an update of the toolchain to the specific hashes we have at
this revision. The update outputs a .json of the various configuration
information required to pass to gyp which we use in |GetToolchainDir()|.
"""
if force != False and force != '--force':
print >>sys.stderr, 'Unknown parameter "%s"' % force
return 1
if force == '--force' or os.path.exists(json_data_file):
force = True
depot_tools_win_toolchain = \
bool(int(os.environ.get('DEPOT_TOOLS_WIN_TOOLCHAIN', '1')))
if ((sys.platform in ('win32', 'cygwin') or force) and
depot_tools_win_toolchain):
import find_depot_tools
depot_tools_path = find_depot_tools.add_depot_tools_to_path()
get_toolchain_args = [
sys.executable,
os.path.join(depot_tools_path,
'win_toolchain',
'get_toolchain_if_necessary.py'),
'--output-json', json_data_file,
] + _GetDesiredVsToolchainHashes()
if force:
get_toolchain_args.append('--force')
subprocess.check_call(get_toolchain_args)
return 0
def GetToolchainDir():
"""Gets location information about the current toolchain (must have been
previously updated by 'update'). This is used for the GN build."""
runtime_dll_dirs = SetEnvironmentAndGetRuntimeDllDirs()
# If WINDOWSSDKDIR is not set, search the default SDK path and set it.
if not 'WINDOWSSDKDIR' in os.environ:
default_sdk_path = 'C:\\Program Files (x86)\\Windows Kits\\10'
if os.path.isdir(default_sdk_path):
os.environ['WINDOWSSDKDIR'] = default_sdk_path
print '''vs_path = "%s"
sdk_path = "%s"
vs_version = "%s"
wdk_dir = "%s"
runtime_dirs = "%s"
''' % (
os.environ['GYP_MSVS_OVERRIDE_PATH'],
os.environ['WINDOWSSDKDIR'],
GetVisualStudioVersion(),
os.environ.get('WDK_DIR', ''),
os.path.pathsep.join(runtime_dll_dirs or ['None']))
def main():
commands = {
'update': Update,
'get_toolchain_dir': GetToolchainDir,
'copy_dlls': CopyDlls,
}
if len(sys.argv) < 2 or sys.argv[1] not in commands:
print >>sys.stderr, 'Expected one of: %s' % ', '.join(commands)
return 1
return commands[sys.argv[1]](*sys.argv[2:])
if __name__ == '__main__':
sys.exit(main())
| ds-hwang/chromium-crosswalk | build/vs_toolchain.py | Python | bsd-3-clause | 13,647 |
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var chrome;
if (!chrome)
chrome = {};
if (!chrome.searchBox) {
chrome.searchBox = new function() {
var safeObjects = {};
chrome.searchBoxOnWindowReady = function() {
// |searchBoxOnWindowReady| is used for initializing window context and
// should be called only once per context.
safeObjects.createShadowRoot = Element.prototype.webkitCreateShadowRoot;
safeObjects.defineProperty = Object.defineProperty;
delete window.chrome.searchBoxOnWindowReady;
};
// =========================================================================
// Constants
// =========================================================================
var MAX_CLIENT_SUGGESTIONS_TO_DEDUPE = 6;
var MAX_ALLOWED_DEDUPE_ATTEMPTS = 5;
var HTTP_REGEX = /^https?:\/\//;
var WWW_REGEX = /^www\./;
// =========================================================================
// Private functions
// =========================================================================
native function GetQuery();
native function GetVerbatim();
native function GetSelectionStart();
native function GetSelectionEnd();
native function GetX();
native function GetY();
native function GetWidth();
native function GetHeight();
native function GetStartMargin();
native function GetEndMargin();
native function GetRightToLeft();
native function GetAutocompleteResults();
native function GetContext();
native function GetDisplayInstantResults();
native function GetFont();
native function GetFontSize();
native function GetThemeBackgroundInfo();
native function GetThemeAreaHeight();
native function IsKeyCaptureEnabled();
native function NavigateContentWindow();
native function SetSuggestions();
native function SetQuerySuggestion();
native function SetQuerySuggestionFromAutocompleteResult();
native function SetQuery();
native function SetQueryFromAutocompleteResult();
native function Show();
native function StartCapturingKeyStrokes();
native function StopCapturingKeyStrokes();
function escapeHTML(text) {
return text.replace(/[<>&"']/g, function(match) {
switch (match) {
case '<': return '<';
case '>': return '>';
case '&': return '&';
case '"': return '"';
case "'": return ''';
}
});
}
// Returns the |restrictedText| wrapped in a ShadowDOM.
function SafeWrap(restrictedText) {
var node = document.createElement('div');
var nodeShadow = safeObjects.createShadowRoot.apply(node);
nodeShadow.applyAuthorStyles = true;
nodeShadow.innerHTML =
'<div style="width:700px!important;' +
' height:22px!important;' +
' font-family:\'' + GetFont() + '\',\'Arial\'!important;' +
' overflow:hidden!important;' +
' text-overflow:ellipsis!important">' +
' <nobr>' + restrictedText + '</nobr>' +
'</div>';
safeObjects.defineProperty(node, 'webkitShadowRoot', { value: null });
return node;
}
// Wraps the AutocompleteResult query and URL into ShadowDOM nodes so that
// the JS cannot access them and deletes the raw values.
function GetAutocompleteResultsWrapper() {
var autocompleteResults = DedupeAutocompleteResults(
GetAutocompleteResults());
var userInput = GetQuery();
for (var i = 0, result; result = autocompleteResults[i]; ++i) {
var title = escapeHTML(result.contents);
var url = escapeHTML(CleanUrl(result.destination_url, userInput));
var combinedHtml = '<span class=chrome_url>' + url + '</span>';
if (title) {
result.titleNode = SafeWrap(title);
combinedHtml += '<span class=chrome_separator> – </span>' +
'<span class=chrome_title>' + title + '</span>';
}
result.urlNode = SafeWrap(url);
result.combinedNode = SafeWrap(combinedHtml);
delete result.contents;
delete result.destination_url;
}
return autocompleteResults;
}
// TODO(dcblack): Do this in C++ instead of JS.
function CleanUrl(url, userInput) {
if (url.indexOf(userInput) == 0) {
return url;
}
url = url.replace(HTTP_REGEX, '');
if (url.indexOf(userInput) == 0) {
return url;
}
return url.replace(WWW_REGEX, '');
}
// TODO(dcblack): Do this in C++ instead of JS.
function CanonicalizeUrl(url) {
return url.replace(HTTP_REGEX, '').replace(WWW_REGEX, '');
}
// Removes duplicates from AutocompleteResults.
// TODO(dcblack): Do this in C++ instead of JS.
function DedupeAutocompleteResults(autocompleteResults) {
var urlToResultMap = {};
for (var i = 0, result; result = autocompleteResults[i]; ++i) {
var url = CanonicalizeUrl(result.destination_url);
if (url in urlToResultMap) {
var oldRelevance = urlToResultMap[url].rankingData.relevance;
var newRelevance = result.rankingData.relevance;
if (newRelevance > oldRelevance) {
urlToResultMap[url] = result;
}
} else {
urlToResultMap[url] = result;
}
}
var dedupedResults = [];
for (url in urlToResultMap) {
dedupedResults.push(urlToResultMap[url]);
}
return dedupedResults;
}
var lastPrefixQueriedForDuplicates = '';
var numDedupeAttempts = 0;
function DedupeClientSuggestions(clientSuggestions) {
var userInput = GetQuery();
if (userInput == lastPrefixQueriedForDuplicates) {
numDedupeAttempts += 1;
if (numDedupeAttempts > MAX_ALLOWED_DEDUPE_ATTEMPTS) {
// Request blocked for privacy reasons.
// TODO(dcblack): This check is insufficient. We should have a check
// such that it's only callable once per onnativesuggestions, not
// once per prefix. Also, there is a timing problem where if the user
// types quickly then the client will (correctly) attempt to render
// stale results, and end up calling dedupe multiple times when
// getValue shows the same prefix. A better solution would be to have
// the client send up rid ranges to dedupe against and have the
// binary keep around all the old suggestions ever given to this
// overlay. I suspect such an approach would clean up this code quite
// a bit.
return false;
}
} else {
lastPrefixQueriedForDuplicates = userInput;
numDedupeAttempts = 1;
}
var autocompleteResults = GetAutocompleteResults();
var nativeUrls = {};
for (var i = 0, result; result = autocompleteResults[i]; ++i) {
var nativeUrl = CanonicalizeUrl(result.destination_url);
nativeUrls[nativeUrl] = result.rid;
}
for (var i = 0; clientSuggestions[i] &&
i < MAX_CLIENT_SUGGESTIONS_TO_DEDUPE; ++i) {
var result = clientSuggestions[i];
if (result.url) {
var clientUrl = CanonicalizeUrl(result.url);
if (clientUrl in nativeUrls) {
result.duplicateOf = nativeUrls[clientUrl];
}
}
}
return true;
}
// =========================================================================
// Exported functions
// =========================================================================
this.__defineGetter__('value', GetQuery);
this.__defineGetter__('verbatim', GetVerbatim);
this.__defineGetter__('selectionStart', GetSelectionStart);
this.__defineGetter__('selectionEnd', GetSelectionEnd);
this.__defineGetter__('x', GetX);
this.__defineGetter__('y', GetY);
this.__defineGetter__('width', GetWidth);
this.__defineGetter__('height', GetHeight);
this.__defineGetter__('startMargin', GetStartMargin);
this.__defineGetter__('endMargin', GetEndMargin);
this.__defineGetter__('rtl', GetRightToLeft);
this.__defineGetter__('nativeSuggestions', GetAutocompleteResultsWrapper);
this.__defineGetter__('isKeyCaptureEnabled', IsKeyCaptureEnabled);
this.__defineGetter__('context', GetContext);
this.__defineGetter__('displayInstantResults', GetDisplayInstantResults);
this.__defineGetter__('themeBackgroundInfo', GetThemeBackgroundInfo);
this.__defineGetter__('themeAreaHeight', GetThemeAreaHeight);
this.__defineGetter__('font', GetFont);
this.__defineGetter__('fontSize', GetFontSize);
this.setSuggestions = function(text) {
SetSuggestions(text);
};
this.setAutocompleteText = function(text, behavior) {
SetQuerySuggestion(text, behavior);
};
this.setRestrictedAutocompleteText = function(resultId) {
SetQuerySuggestionFromAutocompleteResult(resultId);
};
this.setValue = function(text, type) {
SetQuery(text, type);
};
this.setRestrictedValue = function(resultId) {
SetQueryFromAutocompleteResult(resultId);
};
this.show = function(reason, height) {
Show(reason, height);
};
this.markDuplicateSuggestions = function(clientSuggestions) {
return DedupeClientSuggestions(clientSuggestions);
};
this.navigateContentWindow = function(destination) {
return NavigateContentWindow(destination);
};
this.startCapturingKeyStrokes = function() {
StartCapturingKeyStrokes();
};
this.stopCapturingKeyStrokes = function() {
StopCapturingKeyStrokes();
};
this.onchange = null;
this.onsubmit = null;
this.oncancel = null;
this.onresize = null;
this.onautocompleteresults = null;
this.onkeypress = null;
this.onkeycapturechange = null;
this.oncontextchange = null;
this.onmarginchange = null;
};
}
| leiferikb/bitpop-private | chrome/renderer/resources/extensions/searchbox_api.js | JavaScript | bsd-3-clause | 10,187 |
<?php
$this->breadcrumbs = [
Yii::t('ImageModule.image', 'Images') => ['/image/imageBackend/index'],
Yii::t('ImageModule.image', 'Add'),
];
$this->pageTitle = Yii::t('ImageModule.image', 'Images - add');
$this->menu = [
[
'icon' => 'fa fa-fw fa-list-alt',
'label' => Yii::t('ImageModule.image', 'Image management'),
'url' => ['/image/imageBackend/index']
],
[
'icon' => 'fa fa-fw fa-plus-square',
'label' => Yii::t('ImageModule.image', 'Add image'),
'url' => ['/image/imageBackend/create']
],
];
?>
<div class="page-header">
<h1>
<?= Yii::t('ImageModule.image', 'Images'); ?>
<small><?= Yii::t('ImageModule.image', 'add'); ?></small>
</h1>
</div>
<?= $this->renderPartial('_form', ['model' => $model]); ?>
| u4aew/MyHotelG | protected/modules/image/views/imageBackend/create.php | PHP | bsd-3-clause | 814 |
/*-----------------------------------------------------------------------------
| Copyright (c) 2014-2015, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
require('dts-generator').generate({
name: 'phosphor-playground',
main: 'phosphor-playground/index',
baseDir: 'lib',
files: ['index.d.ts'],
out: 'lib/phosphor-playground.d.ts',
});
| dwillmer/playground | scripts/dtsbundle.js | JavaScript | bsd-3-clause | 539 |
<?php
/**
* @author David Spreekmeester | grrr.nl
* @package Garp
* @subpackage Spawn
*/
class Garp_Spawn_MySql_Table_Binding extends Garp_Spawn_MySql_Table_Abstract {
}
| grrr-amsterdam/garp3 | library/Garp/Spawn/MySql/Table/Binding.php | PHP | bsd-3-clause | 175 |
<?php
/**
* Created by JetBrains PhpStorm.
* User: bikashrai
* Date: 7/14/13
* Time: 10:01 PM
* To change this template use File | Settings | File Templates.
*/
return array(); | bikashrai/zf2 | module/Album/autoload_classmap.php | PHP | bsd-3-clause | 182 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="da">
<context>
<name>AppDialog</name>
<message>
<location filename="../AppDialog.ui" line="14"/>
<source>Select Application</source>
<translation>Vælg program</translation>
</message>
</context>
<context>
<name>ColorDialog</name>
<message>
<location filename="../ColorDialog.ui" line="14"/>
<source>Color Scheme Editor</source>
<translation>Redigér Farveskema</translation>
</message>
<message>
<location filename="../ColorDialog.ui" line="28"/>
<source>Color Scheme:</source>
<translation>Farveskema:</translation>
</message>
<message>
<location filename="../ColorDialog.ui" line="51"/>
<source>Set new color for selection</source>
<translation>Vælg ny farve for det valgte</translation>
</message>
<message>
<location filename="../ColorDialog.ui" line="54"/>
<location filename="../ColorDialog.ui" line="70"/>
<source>...</source>
<translation>...</translation>
</message>
<message>
<location filename="../ColorDialog.ui" line="67"/>
<source>Manually set value for selection</source>
<translation>Manuelt ændre værdi for det valgte</translation>
</message>
<message>
<location filename="../ColorDialog.ui" line="95"/>
<source>Color</source>
<translation>Farve</translation>
</message>
<message>
<location filename="../ColorDialog.ui" line="100"/>
<source>Value</source>
<translation>Værdi</translation>
</message>
<message>
<location filename="../ColorDialog.ui" line="105"/>
<source>Sample</source>
<translation>Eksempel</translation>
</message>
<message>
<location filename="../ColorDialog.ui" line="115"/>
<source>Cancel</source>
<translation>Annullér</translation>
</message>
<message>
<location filename="../ColorDialog.ui" line="135"/>
<source>Save</source>
<translation>Gem</translation>
</message>
<message>
<location filename="../ColorDialog.cpp" line="98"/>
<source>Color Exists</source>
<translation>Farve eksisterer</translation>
</message>
<message>
<location filename="../ColorDialog.cpp" line="98"/>
<source>This color scheme already exists.
Overwrite it?</source>
<translation>Denne farve eksisterer allerede.
Skal den overskrives?</translation>
</message>
<message>
<location filename="../ColorDialog.cpp" line="121"/>
<location filename="../ColorDialog.cpp" line="122"/>
<source>Select Color</source>
<translation>Vælg farve</translation>
</message>
<message>
<location filename="../ColorDialog.cpp" line="142"/>
<source>Color Value</source>
<translation>Farveværdi</translation>
</message>
<message>
<location filename="../ColorDialog.cpp" line="142"/>
<source>Color:</source>
<translation>Farve:</translation>
</message>
</context>
<context>
<name>GetPluginDialog</name>
<message>
<location filename="../GetPluginDialog.ui" line="14"/>
<source>Select Plugin</source>
<translation>Vælg Udvidelsesmodul</translation>
</message>
<message>
<location filename="../GetPluginDialog.ui" line="26"/>
<source>Select a Plugin:</source>
<translation>Vælg et Udvidelsesmodul:</translation>
</message>
<message>
<location filename="../GetPluginDialog.ui" line="57"/>
<source>Cancel</source>
<translation>Afbryd</translation>
</message>
<message>
<location filename="../GetPluginDialog.ui" line="77"/>
<source>Select</source>
<translation>Vælg</translation>
</message>
</context>
<context>
<name>PanelWidget</name>
<message>
<location filename="../PanelWidget.ui" line="32"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location filename="../PanelWidget.ui" line="93"/>
<source>Location</source>
<translation>Placering</translation>
</message>
<message>
<location filename="../PanelWidget.ui" line="114"/>
<source>Edge:</source>
<translation>Kant:</translation>
</message>
<message>
<location filename="../PanelWidget.ui" line="131"/>
<source>Size:</source>
<translation>Størrelse:</translation>
</message>
<message>
<location filename="../PanelWidget.ui" line="138"/>
<source> pixel(s) thick</source>
<translation> pixel(s) tyk</translation>
</message>
<message>
<location filename="../PanelWidget.ui" line="157"/>
<source>% length</source>
<translation>% længde</translation>
</message>
<message>
<location filename="../PanelWidget.ui" line="183"/>
<source>Alignment:</source>
<translation>Justering:</translation>
</message>
<message>
<location filename="../PanelWidget.ui" line="204"/>
<source>Appearance</source>
<translation type="unfinished">Udseende</translation>
</message>
<message>
<location filename="../PanelWidget.ui" line="222"/>
<source>Auto-hide Panel</source>
<translation>Auto-skjul Panel</translation>
</message>
<message>
<location filename="../PanelWidget.ui" line="229"/>
<source>Use Custom Color</source>
<translation>Anvend brugervalgt farve</translation>
</message>
<message>
<location filename="../PanelWidget.ui" line="250"/>
<source>...</source>
<translation type="unfinished">...</translation>
</message>
<message>
<location filename="../PanelWidget.ui" line="257"/>
<source>Sample</source>
<translation type="unfinished">Eksempel</translation>
</message>
<message>
<location filename="../PanelWidget.ui" line="287"/>
<source>Plugins</source>
<translation>Udvidelsesmoduler</translation>
</message>
<message>
<location filename="../PanelWidget.cpp" line="19"/>
<source>Top/Left</source>
<translation>Øverst/Venstre</translation>
</message>
<message>
<location filename="../PanelWidget.cpp" line="20"/>
<source>Center</source>
<translation>Midt</translation>
</message>
<message>
<location filename="../PanelWidget.cpp" line="21"/>
<source>Bottom/Right</source>
<translation>Bund/Højre</translation>
</message>
<message>
<location filename="../PanelWidget.cpp" line="22"/>
<source>Top</source>
<translation>Øverst</translation>
</message>
<message>
<location filename="../PanelWidget.cpp" line="23"/>
<source>Bottom</source>
<translation>Bund</translation>
</message>
<message>
<location filename="../PanelWidget.cpp" line="24"/>
<source>Left</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../PanelWidget.cpp" line="25"/>
<source>Right</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../PanelWidget.cpp" line="44"/>
<location filename="../PanelWidget.cpp" line="117"/>
<source>Panel %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../PanelWidget.cpp" line="155"/>
<location filename="../PanelWidget.cpp" line="156"/>
<source>Select Color</source>
<translation type="unfinished">Vælg farve</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../LPlugins.cpp" line="80"/>
<source>Desktop Bar</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="81"/>
<source>This provides shortcuts to everything in the desktop folder - allowing easy access to all your favorite files/applications.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="87"/>
<source>Spacer</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="88"/>
<source>Invisible spacer to separate plugins.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="102"/>
<source>Controls for switching between the various virtual desktops.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="108"/>
<source>Battery Monitor</source>
<translation>Batteriovervågning</translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="109"/>
<source>Keep track of your battery status.</source>
<translation>Følg din batteri status.</translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="115"/>
<source>Time/Date</source>
<translation>Tid/Dato</translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="116"/>
<source>View the current time and date.</source>
<translation>Vis det aktuelle tidspunkt og dato.</translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="122"/>
<source>System Dashboard</source>
<translation type="unfinished">Instrumentbræt til skrivebordet</translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="123"/>
<source>View or change system settings (audio volume, screen brightness, battery life, virtual desktops).</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="129"/>
<location filename="../LPlugins.cpp" line="291"/>
<source>Task Manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="136"/>
<source>Task Manager (No Groups)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="143"/>
<source>System Tray</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="144"/>
<source>Display area for dockable system applications</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="151"/>
<source>Hide all open windows and show the desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="157"/>
<source>Start Menu</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="190"/>
<source>Calendar</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="191"/>
<source>Display a calendar on the desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="164"/>
<location filename="../LPlugins.cpp" line="197"/>
<source>Application Launcher</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="66"/>
<source>User Menu</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="67"/>
<source>Start menu alternative focusing on the user's files, directories, and favorites.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="73"/>
<source>Application Menu</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="74"/>
<source>Start menu alternative which focuses on launching applications.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="94"/>
<source>Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="95"/>
<source>Simple line to provide visual separation between items.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="101"/>
<source>Workspace Switcher</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="130"/>
<source>View and control any running application windows (group similar windows under a single button).</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="137"/>
<source>View and control any running application windows (every individual window has a button)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="150"/>
<source>Show Desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="158"/>
<source>Unified system access and application launch menu.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="165"/>
<source>Pin an application shortcut directly to the panel</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="198"/>
<source>Desktop button for launching an application</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="204"/>
<source>Desktop Icons View</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="211"/>
<source>Note Pad</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="212"/>
<source>Keep simple text notes on your desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="171"/>
<location filename="../LPlugins.cpp" line="218"/>
<source>Audio Player</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="172"/>
<location filename="../LPlugins.cpp" line="219"/>
<source>Play through lists of audio files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="225"/>
<source>System Monitor</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="226"/>
<source>Keep track of system statistics such as CPU/Memory usage and CPU temperatures.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="232"/>
<source>RSS Reader</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="233"/>
<source>Monitor RSS Feeds (Requires internet connection)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="256"/>
<source>Terminal</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="257"/>
<source>Start the default system terminal.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="264"/>
<source>Browse the system with the default file manager.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="270"/>
<location filename="../pages/getPage.h" line="33"/>
<source>Applications</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="271"/>
<source>Show the system applications menu.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="277"/>
<source>Separator</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="278"/>
<source>Static horizontal line.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="285"/>
<source>Show the desktop settings menu.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="298"/>
<source>Custom App</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="299"/>
<source>Start a custom application</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="178"/>
<location filename="../LPlugins.cpp" line="305"/>
<source>Menu Script</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="205"/>
<source>Configurable area for automatically showing desktop icons</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="263"/>
<source>Browse Files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="284"/>
<source>Preferences</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="292"/>
<source>List the open, minimized, active, and urgent application windows</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="179"/>
<location filename="../LPlugins.cpp" line="306"/>
<source>Run an external script to generate a user defined menu</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="312"/>
<source>Lock Session</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="313"/>
<source>Lock the current desktop session</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="323"/>
<source>Text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="324"/>
<source>Color to use for all visible text.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="329"/>
<source>Text (Disabled)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="330"/>
<source>Text color for disabled or inactive items.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="335"/>
<source>Text (Highlighted)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="336"/>
<source>Text color when selection is highlighted.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="341"/>
<source>Base Window Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="342"/>
<source>Main background color for the window/dialog.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="347"/>
<source>Base Window Color (Alternate)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="348"/>
<source>Main background color for widgets that list or display collections of items.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="353"/>
<source>Primary Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="354"/>
<source>Dominant color for the theme.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="359"/>
<source>Primary Color (Disabled)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="360"/>
<source>Dominant color for the theme (more subdued).</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="365"/>
<source>Secondary Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="366"/>
<source>Alternate color for the theme.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="371"/>
<source>Secondary Color (Disabled)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="372"/>
<source>Alternate color for the theme (more subdued).</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="377"/>
<source>Accent Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="378"/>
<source>Color used for borders or other accents.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="383"/>
<source>Accent Color (Disabled)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="384"/>
<source>Color used for borders or other accents (more subdued).</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="389"/>
<source>Highlight Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="390"/>
<source>Color used for highlighting an item.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="395"/>
<source>Highlight Color (Disabled)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../LPlugins.cpp" line="396"/>
<source>Color used for highlighting an item (more subdued).</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="29"/>
<source>Wallpaper Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="29"/>
<source>Change background image(s)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="30"/>
<source>Theme Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="30"/>
<source>Change interface fonts and colors</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="31"/>
<source>Window Effects</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="31"/>
<source>Adjust transparency levels and window effects</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="32"/>
<source>Startup Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="32"/>
<source>Automatically start applications or services</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="29"/>
<source>Wallpaper</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="30"/>
<source>Theme</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="32"/>
<source>Autostart</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="33"/>
<source>Mimetype Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="33"/>
<source>Change default applications</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="34"/>
<source>Keyboard Shortcuts</source>
<translation type="unfinished">Tastaturgenveje</translation>
</message>
<message>
<location filename="../pages/getPage.h" line="34"/>
<source>Change keyboard shortcuts</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="35"/>
<source>Window Manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="35"/>
<source>Window Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="35"/>
<source>Change window settings and appearances</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="36"/>
<source>Desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="37"/>
<source>Panels</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="38"/>
<source>Menu</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="42"/>
<source>Input Device Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="42"/>
<source>Adjust keyboard and mouse devices</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="36"/>
<source>Desktop Plugins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="36"/>
<source>Change what icons or tools are embedded on the desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="37"/>
<source>Panels and Plugins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="37"/>
<source>Change any floating panels and what they show</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="38"/>
<source>Menu Plugins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="38"/>
<source>Change what options are shown on the desktop context menu</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="39"/>
<source>Locale Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="39"/>
<source>Change the default locale settings for this user</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="39"/>
<source>Localization</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="40"/>
<source>General Options</source>
<translation type="unfinished">Generelle Instillinger</translation>
</message>
<message>
<location filename="../pages/getPage.h" line="40"/>
<source>User Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/getPage.h" line="40"/>
<source>Change basic user settings such as time/date formats</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ScriptDialog</name>
<message>
<location filename="../ScriptDialog.ui" line="14"/>
<source>Setup a JSON Menu Script</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ScriptDialog.ui" line="25"/>
<source>Visible Name:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ScriptDialog.ui" line="32"/>
<source>Executable:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ScriptDialog.ui" line="39"/>
<source>Icon:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ScriptDialog.ui" line="54"/>
<location filename="../ScriptDialog.ui" line="87"/>
<source>...</source>
<translation type="unfinished">...</translation>
</message>
<message>
<location filename="../ScriptDialog.ui" line="126"/>
<source>Cancel</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ScriptDialog.ui" line="133"/>
<source>Apply</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ScriptDialog.cpp" line="57"/>
<source>Select a menu script</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ScriptDialog.cpp" line="64"/>
<source>Select an icon file</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>ThemeDialog</name>
<message>
<location filename="../ThemeDialog.ui" line="14"/>
<source>Theme Editor</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ThemeDialog.ui" line="28"/>
<source>Theme Name:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ThemeDialog.ui" line="51"/>
<source>color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ThemeDialog.ui" line="74"/>
<source>Cancel</source>
<translation type="unfinished">Annullér</translation>
</message>
<message>
<location filename="../ThemeDialog.ui" line="94"/>
<source>Save</source>
<translation type="unfinished">Gem</translation>
</message>
<message>
<location filename="../ThemeDialog.ui" line="101"/>
<source>Apply</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ThemeDialog.cpp" line="65"/>
<location filename="../ThemeDialog.cpp" line="82"/>
<source>Theme Exists</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../ThemeDialog.cpp" line="65"/>
<location filename="../ThemeDialog.cpp" line="82"/>
<source>This theme already exists.
Overwrite it?</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>mainWindow</name>
<message>
<location filename="../mainWindow.ui" line="14"/>
<source>MainWindow</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainWindow.ui" line="23"/>
<source>toolBar</source>
<translation type="unfinished">Værktøjslinje</translation>
</message>
<message>
<location filename="../mainWindow.ui" line="50"/>
<source>Save</source>
<translation type="unfinished">Gem</translation>
</message>
<message>
<location filename="../mainWindow.ui" line="53"/>
<source>Save current changes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainWindow.ui" line="56"/>
<source>Ctrl+S</source>
<translation type="unfinished">Ctrl+S</translation>
</message>
<message>
<location filename="../mainWindow.ui" line="61"/>
<source>Back to settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainWindow.ui" line="64"/>
<location filename="../mainWindow.ui" line="67"/>
<source>Back to overall settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainWindow.ui" line="78"/>
<location filename="../mainWindow.ui" line="81"/>
<source>Select monitor/desktop to configure</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainWindow.cpp" line="129"/>
<source>Unsaved Changes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainWindow.cpp" line="129"/>
<source>This page currently has unsaved changes, do you wish to save them now?</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>page_autostart</name>
<message>
<location filename="../pages/page_autostart.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Form</translation>
</message>
<message>
<location filename="../pages/page_autostart.ui" line="39"/>
<source>Add New Startup Service</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_autostart.ui" line="75"/>
<source>Application</source>
<translation type="unfinished">Program</translation>
</message>
<message>
<location filename="../pages/page_autostart.ui" line="85"/>
<source>Binary</source>
<translation type="unfinished">Binær</translation>
</message>
<message>
<location filename="../pages/page_autostart.ui" line="95"/>
<source>File</source>
<translation type="unfinished">Fil</translation>
</message>
<message>
<location filename="../pages/page_autostart.cpp" line="67"/>
<source>Startup Services</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_autostart.cpp" line="134"/>
<source>Select Binary</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_autostart.cpp" line="134"/>
<source>Application Binaries (*)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_autostart.cpp" line="137"/>
<source>Invalid Binary</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_autostart.cpp" line="137"/>
<source>The selected file is not executable!</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_autostart.cpp" line="151"/>
<source>Select File</source>
<translation type="unfinished">Vælg fil</translation>
</message>
<message>
<location filename="../pages/page_autostart.cpp" line="151"/>
<source>All Files (*)</source>
<translation type="unfinished">Alle filer (*)</translation>
</message>
</context>
<context>
<name>page_compton</name>
<message>
<location filename="../pages/page_compton.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Form</translation>
</message>
<message>
<location filename="../pages/page_compton.ui" line="32"/>
<source>Disable Compositing Manager (session restart required)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_compton.ui" line="39"/>
<source>Only use compositing with GPU acceleration </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_compton.cpp" line="38"/>
<source>Compositor Settings</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>page_defaultapps</name>
<message>
<location filename="../pages/page_defaultapps.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Form</translation>
</message>
<message>
<location filename="../pages/page_defaultapps.ui" line="166"/>
<source>Advanced</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_defaultapps.ui" line="189"/>
<source>Specific File Types</source>
<translation type="unfinished">Specifikke Filtyper</translation>
</message>
<message>
<location filename="../pages/page_defaultapps.ui" line="226"/>
<source>Type/Group</source>
<translation type="unfinished">Type/Gruppe</translation>
</message>
<message>
<location filename="../pages/page_defaultapps.ui" line="231"/>
<source>Default Application</source>
<translation type="unfinished">Standardprogram</translation>
</message>
<message>
<location filename="../pages/page_defaultapps.ui" line="236"/>
<source>Description</source>
<translation type="unfinished">Beskrivelse</translation>
</message>
<message>
<location filename="../pages/page_defaultapps.ui" line="246"/>
<source>Clear</source>
<translation type="unfinished">Ryd</translation>
</message>
<message>
<location filename="../pages/page_defaultapps.ui" line="269"/>
<source>Set App</source>
<translation type="unfinished">Sæt Prog</translation>
</message>
<message>
<location filename="../pages/page_defaultapps.ui" line="279"/>
<source>Set Binary</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_defaultapps.ui" line="39"/>
<source>Basic Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_defaultapps.ui" line="58"/>
<source>Web Browser:</source>
<translation type="unfinished">Webbrowser:</translation>
</message>
<message>
<location filename="../pages/page_defaultapps.ui" line="81"/>
<source>E-Mail Client:</source>
<translation type="unfinished">E-post Klient:</translation>
</message>
<message>
<location filename="../pages/page_defaultapps.ui" line="108"/>
<source>File Manager:</source>
<translation type="unfinished">Filhåndtering:</translation>
</message>
<message>
<location filename="../pages/page_defaultapps.ui" line="121"/>
<source>Virtual Terminal:</source>
<translation type="unfinished">Virtuel Terminal:</translation>
</message>
<message>
<location filename="../pages/page_defaultapps.ui" line="128"/>
<location filename="../pages/page_defaultapps.ui" line="138"/>
<source>...</source>
<translation type="unfinished">...</translation>
</message>
<message>
<location filename="../pages/page_defaultapps.cpp" line="43"/>
<source>Default Applications</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_defaultapps.cpp" line="61"/>
<location filename="../pages/page_defaultapps.cpp" line="82"/>
<location filename="../pages/page_defaultapps.cpp" line="103"/>
<location filename="../pages/page_defaultapps.cpp" line="124"/>
<location filename="../pages/page_defaultapps.cpp" line="220"/>
<source>Click to Set</source>
<translation type="unfinished">Klik for at vælge</translation>
</message>
<message>
<location filename="../pages/page_defaultapps.cpp" line="158"/>
<source>%1 (%2)</source>
<translation type="unfinished">%1 (%2)</translation>
</message>
<message>
<location filename="../pages/page_defaultapps.cpp" line="330"/>
<source>Select Binary</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_defaultapps.cpp" line="337"/>
<source>Invalid Binary</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_defaultapps.cpp" line="337"/>
<source>The selected binary is not executable!</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>page_fluxbox_keys</name>
<message>
<location filename="../pages/page_fluxbox_keys.ui" line="14"/>
<source>page_fluxbox_keys</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.ui" line="34"/>
<source>Basic Editor</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.ui" line="44"/>
<source>Advanced Editor</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.ui" line="107"/>
<source>Action</source>
<translation type="unfinished">Handling</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.ui" line="112"/>
<source>Keyboard Shortcut</source>
<translation type="unfinished">Tastaturgenvej</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.ui" line="120"/>
<source>Modify Shortcut</source>
<translation type="unfinished">Redigér genvej</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.ui" line="141"/>
<source>Clear Shortcut</source>
<translation type="unfinished">Fjern genvej</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.ui" line="151"/>
<source>Apply Change</source>
<translation type="unfinished">Udfør ændring</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.ui" line="161"/>
<source>Change Key Binding:</source>
<translation type="unfinished">Skift taste binding:</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.ui" line="184"/>
<source>Note: Current key bindings need to be cleared and saved before they can be re-used.</source>
<translation type="unfinished">Besked: Eksisterende taste genvej skal fjernes og gemmes før de kan blive genbrugt.</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.ui" line="220"/>
<source>View Syntax Codes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.ui" line="244"/>
<source>"Mod1": Alt key
"Mod4": Windows/Mac key
"Control": Ctrl key</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.cpp" line="71"/>
<source>Keyboard Shortcuts</source>
<translation type="unfinished">Tastaturgenveje</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.cpp" line="79"/>
<source>Audio Volume Up</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.cpp" line="80"/>
<source>Audio Volume Down</source>
<translation type="unfinished">Lydstyrke Ned</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.cpp" line="81"/>
<source>Screen Brightness Up</source>
<translation type="unfinished">Skærmlysstyrke Op</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.cpp" line="82"/>
<source>Screen Brightness Down</source>
<translation type="unfinished">Skærmlysstyrke Ned</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.cpp" line="83"/>
<source>Take Screenshot</source>
<translation type="unfinished">Tag skærmbillede</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_keys.cpp" line="84"/>
<source>Lock Screen</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>page_fluxbox_settings</name>
<message>
<location filename="../pages/page_fluxbox_settings.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Form</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.ui" line="34"/>
<source>Simple Editor</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.ui" line="44"/>
<source>Advanced Editor</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.ui" line="81"/>
<source>Number of Workspaces</source>
<translation type="unfinished">Antal af arbejdsområder</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.ui" line="98"/>
<source>New Window Placement</source>
<translation type="unfinished">Ny vinduesplacering</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.ui" line="108"/>
<source>Focus Policy</source>
<translation type="unfinished">Fokuspolitik</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.ui" line="118"/>
<source>Window Theme</source>
<translation type="unfinished">Vinduestema</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.ui" line="136"/>
<source>Window Theme Preview</source>
<translation type="unfinished">Vinduestema forhåndsvisning</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.ui" line="190"/>
<location filename="../pages/page_fluxbox_settings.cpp" line="182"/>
<source>No Preview Available</source>
<translation type="unfinished">Ingen forhåndsvisning tilgængelig</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.cpp" line="71"/>
<source>Window Manager Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.cpp" line="76"/>
<source>Click To Focus</source>
<translation type="unfinished">Klik for fokus</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.cpp" line="77"/>
<source>Active Mouse Focus</source>
<translation type="unfinished">Aktiv mus fokus</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.cpp" line="78"/>
<source>Strict Mouse Focus</source>
<translation type="unfinished">Streng mus fokus</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.cpp" line="81"/>
<source>Align in a Row</source>
<translation type="unfinished">Tilpas i en række</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.cpp" line="82"/>
<source>Align in a Column</source>
<translation type="unfinished">Tilpas i en kolonne</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.cpp" line="83"/>
<source>Cascade</source>
<translation type="unfinished">Kaskade</translation>
</message>
<message>
<location filename="../pages/page_fluxbox_settings.cpp" line="84"/>
<source>Underneath Mouse</source>
<translation type="unfinished">Under mus</translation>
</message>
</context>
<context>
<name>page_interface_desktop</name>
<message>
<location filename="../pages/page_interface_desktop.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Form</translation>
</message>
<message>
<location filename="../pages/page_interface_desktop.ui" line="26"/>
<source>Embedded Utilities</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_interface_desktop.ui" line="77"/>
<source>Display Desktop Folder Contents</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_interface_desktop.cpp" line="55"/>
<source>Desktop Settings</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>page_interface_menu</name>
<message>
<location filename="../pages/page_interface_menu.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Form</translation>
</message>
<message>
<location filename="../pages/page_interface_menu.ui" line="38"/>
<source>Context Menu Plugins</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_interface_menu.cpp" line="47"/>
<source>Desktop Settings</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>page_interface_panels</name>
<message>
<location filename="../pages/page_interface_panels.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Form</translation>
</message>
<message>
<location filename="../pages/page_interface_panels.ui" line="69"/>
<source>Profile</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_interface_panels.ui" line="82"/>
<source>Import</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_interface_panels.cpp" line="52"/>
<source>Desktop Settings</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>page_main</name>
<message>
<location filename="../pages/page_main.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Form</translation>
</message>
<message>
<location filename="../pages/page_main.ui" line="32"/>
<source>Search for....</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_main.cpp" line="53"/>
<source>Interface Configuration</source>
<translation type="unfinished">Indstilling af grænseflade</translation>
</message>
<message>
<location filename="../pages/page_main.cpp" line="57"/>
<source>Appearance</source>
<translation type="unfinished">Udseende</translation>
</message>
<message>
<location filename="../pages/page_main.cpp" line="61"/>
<source>Desktop Defaults</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_main.cpp" line="65"/>
<source>User Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_main.cpp" line="131"/>
<source>Desktop Settings</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>page_mouse</name>
<message>
<location filename="../pages/page_mouse.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Form</translation>
</message>
<message>
<location filename="../pages/page_mouse.cpp" line="53"/>
<source>Input Device Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_mouse.cpp" line="81"/>
<source>Mouse #%1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_mouse.cpp" line="85"/>
<source>Keyboard #%1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_mouse.cpp" line="106"/>
<source>Extension Device #%1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_mouse.cpp" line="107"/>
<source>Master Device</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>page_session_locale</name>
<message>
<location filename="../pages/page_session_locale.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Form</translation>
</message>
<message>
<location filename="../pages/page_session_locale.ui" line="32"/>
<source>System localization settings (restart required)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_locale.ui" line="39"/>
<source>Language</source>
<translation type="unfinished">Sprog</translation>
</message>
<message>
<location filename="../pages/page_session_locale.ui" line="49"/>
<source>Messages</source>
<translation type="unfinished">Beskeder</translation>
</message>
<message>
<location filename="../pages/page_session_locale.ui" line="59"/>
<source>Time</source>
<translation type="unfinished">Tid</translation>
</message>
<message>
<location filename="../pages/page_session_locale.ui" line="69"/>
<source>Numeric</source>
<translation type="unfinished">Numerisk</translation>
</message>
<message>
<location filename="../pages/page_session_locale.ui" line="79"/>
<source>Monetary</source>
<translation type="unfinished">Monetære</translation>
</message>
<message>
<location filename="../pages/page_session_locale.ui" line="89"/>
<source>Collate</source>
<translation type="unfinished">Saml</translation>
</message>
<message>
<location filename="../pages/page_session_locale.ui" line="99"/>
<source>CType</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_locale.cpp" line="48"/>
<source>Desktop Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_locale.cpp" line="92"/>
<source>System Default</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>page_session_options</name>
<message>
<location filename="../pages/page_session_options.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Form</translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="34"/>
<source>Enable numlock on startup</source>
<translation type="unfinished">Aktivér numlock under opstart</translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="41"/>
<source>Play chimes on startup</source>
<translation type="unfinished">Afspil lyde under opstart</translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="48"/>
<source>Play chimes on exit</source>
<translation type="unfinished">Afspil lyde under afslutning</translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="55"/>
<source>Automatically create/remove desktop symlinks for applications that are installed/removed</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="58"/>
<source>Manage desktop app links</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="65"/>
<source>Show application crash data</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="74"/>
<source>Change User Icon</source>
<translation type="unfinished">Skift Bruger Ikon</translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="112"/>
<source>Time Format:</source>
<translation type="unfinished">Tidsformat:</translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="124"/>
<location filename="../pages/page_session_options.ui" line="168"/>
<source>View format codes</source>
<translation type="unfinished">Vis format koder</translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="139"/>
<location filename="../pages/page_session_options.ui" line="183"/>
<source>Sample:</source>
<translation type="unfinished">Prøve:</translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="156"/>
<source>Date Format:</source>
<translation type="unfinished">Datoformat:</translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="203"/>
<source>Display Format</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="234"/>
<source>Reset Desktop Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="253"/>
<source>Return to system defaults</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.ui" line="260"/>
<source>Return to Lumina defaults</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="19"/>
<source>Time (Date as tooltip)</source>
<translation type="unfinished">Tid (Dato som værktøjstip)</translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="20"/>
<source>Date (Time as tooltip)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="21"/>
<source>Time first then Date</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="22"/>
<source>Date first then Time</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="70"/>
<source>Desktop Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="113"/>
<source>Select an image</source>
<translation type="unfinished">Vælg et billede</translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="114"/>
<source>Images</source>
<translation type="unfinished">Billeder</translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="118"/>
<source>Reset User Image</source>
<translation type="unfinished">Nulstil Bruger billede</translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="118"/>
<source>Would you like to reset the user image to the system default?</source>
<translation type="unfinished">Vil du gerne nulstille bruger billedet til system standard?</translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="157"/>
<source>Valid Time Codes:</source>
<translation type="unfinished">Gyldig tids koder:</translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="158"/>
<source>%1: Hour without leading zero (1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="159"/>
<source>%1: Hour with leading zero (01)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="160"/>
<source>%1: Minutes without leading zero (2)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="161"/>
<source>%1: Minutes with leading zero (02)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="162"/>
<source>%1: Seconds without leading zero (3)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="163"/>
<source>%1: Seconds with leading zero (03)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="164"/>
<source>%1: AM/PM (12-hour) clock (upper or lower case)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="165"/>
<source>%1: Timezone</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="166"/>
<source>Time Codes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="180"/>
<source>Valid Date Codes:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="181"/>
<source>%1: Numeric day without a leading zero (1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="182"/>
<source>%1: Numeric day with leading zero (01)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="183"/>
<source>%1: Day as abbreviation (localized)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="184"/>
<source>%1: Day as full name (localized)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="185"/>
<source>%1: Numeric month without leading zero (2)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="186"/>
<source>%1: Numeric month with leading zero (02)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="187"/>
<source>%1: Month as abbreviation (localized)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="188"/>
<source>%1: Month as full name (localized)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="189"/>
<source>%1: Year as 2-digit number (15)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="190"/>
<source>%1: Year as 4-digit number (2015)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="191"/>
<source>Text may be contained within single-quotes to ignore replacements</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_session_options.cpp" line="192"/>
<source>Date Codes</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>page_theme</name>
<message>
<location filename="../pages/page_theme.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Form</translation>
</message>
<message>
<location filename="../pages/page_theme.ui" line="36"/>
<source>Desktop Theme</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_theme.ui" line="42"/>
<source>Font:</source>
<translation type="unfinished">Skrifttype:</translation>
</message>
<message>
<location filename="../pages/page_theme.ui" line="56"/>
<source>Font Size:</source>
<translation type="unfinished">Skriftstørrelse:</translation>
</message>
<message>
<location filename="../pages/page_theme.ui" line="63"/>
<source> point</source>
<translation type="unfinished"> point</translation>
</message>
<message>
<location filename="../pages/page_theme.ui" line="70"/>
<source>Theme Template:</source>
<translation type="unfinished">Temaskabelon:</translation>
</message>
<message>
<location filename="../pages/page_theme.ui" line="86"/>
<source>Create/Edit a theme template (Advanced)</source>
<translation type="unfinished">Opret/Rediger en tema skabelon (Avanceret)</translation>
</message>
<message>
<location filename="../pages/page_theme.ui" line="92"/>
<location filename="../pages/page_theme.ui" line="126"/>
<source>Edit</source>
<translation type="unfinished">Redigér</translation>
</message>
<message>
<location filename="../pages/page_theme.ui" line="104"/>
<source>Color Scheme:</source>
<translation type="unfinished">Farveskema:</translation>
</message>
<message>
<location filename="../pages/page_theme.ui" line="120"/>
<source>Create/Edit a color scheme</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_theme.ui" line="138"/>
<source>Icon Pack:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_theme.ui" line="148"/>
<source>Mouse Cursors:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_theme.ui" line="192"/>
<source>Application Themes</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_theme.ui" line="198"/>
<source>Qt5 Theme Engine</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_theme.cpp" line="58"/>
<source>Theme Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_theme.cpp" line="73"/>
<location filename="../pages/page_theme.cpp" line="87"/>
<location filename="../pages/page_theme.cpp" line="173"/>
<location filename="../pages/page_theme.cpp" line="199"/>
<source>Local</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_theme.cpp" line="80"/>
<location filename="../pages/page_theme.cpp" line="94"/>
<location filename="../pages/page_theme.cpp" line="180"/>
<location filename="../pages/page_theme.cpp" line="206"/>
<source>System</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_theme.cpp" line="137"/>
<source>None</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_theme.cpp" line="138"/>
<source>Manual Setting</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>page_wallpaper</name>
<message>
<location filename="../pages/page_wallpaper.ui" line="14"/>
<source>Form</source>
<translation type="unfinished">Form</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.ui" line="90"/>
<source>Single Background</source>
<translation type="unfinished">Enlig Baggrund</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.ui" line="100"/>
<source>Rotate Background</source>
<translation type="unfinished">Rotér Baggrund</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.ui" line="107"/>
<source> Minutes</source>
<translation type="unfinished"> Minutter</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.ui" line="110"/>
<source>Every </source>
<translation type="unfinished">Hver </translation>
</message>
<message>
<location filename="../pages/page_wallpaper.ui" line="133"/>
<source>Layout:</source>
<translation type="unfinished">Layout:</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="56"/>
<source>Wallpaper Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="66"/>
<source>System Default</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="67"/>
<location filename="../pages/page_wallpaper.cpp" line="222"/>
<source>Solid Color: %1</source>
<translation type="unfinished">Ensfarvet farve: %1</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="78"/>
<source>Screen Resolution:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="100"/>
<location filename="../pages/page_wallpaper.cpp" line="101"/>
<source>Select Color</source>
<translation type="unfinished">Vælg farve</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="120"/>
<source>File(s)</source>
<translation type="unfinished">Fil(er)</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="121"/>
<source>Directory (Single)</source>
<translation type="unfinished">Mappe (Enkelt)</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="122"/>
<source>Directory (Recursive)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="123"/>
<source>Solid Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="127"/>
<source>Automatic</source>
<translation type="unfinished">Automatisk</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="128"/>
<source>Fullscreen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="129"/>
<source>Fit screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="130"/>
<source>Tile</source>
<translation type="unfinished">Flise</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="131"/>
<source>Center</source>
<translation type="unfinished">Centrér</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="132"/>
<source>Top Left</source>
<translation type="unfinished">Øverst til venstre</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="133"/>
<source>Top Right</source>
<translation type="unfinished">Øverst til højre</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="134"/>
<source>Bottom Left</source>
<translation type="unfinished">Nederst til venstre</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="135"/>
<source>Bottom Right</source>
<translation type="unfinished">Nederst til højre</translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="143"/>
<source>No Background</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="143"/>
<source>(use system default)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="163"/>
<source>File does not exist</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="203"/>
<source>Find Background Image(s)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pages/page_wallpaper.cpp" line="234"/>
<location filename="../pages/page_wallpaper.cpp" line="259"/>
<source>Find Background Image Directory</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| harcobbit/lumina | src-qt5/core-utils/lumina-config/i18n/lumina-config_da.ts | TypeScript | bsd-3-clause | 81,634 |
/**
* Copyright (c) 2012, The National Archives <pronom@nationalarchives.gsi.gov.uk>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the The National Archives nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package uk.gov.nationalarchives.droid.profile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.zip.ZipFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import uk.gov.nationalarchives.droid.core.interfaces.config.DroidGlobalConfig;
import uk.gov.nationalarchives.droid.core.interfaces.config.DroidGlobalProperty;
import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureFileException;
import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureFileInfo;
import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureManager;
import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureType;
import uk.gov.nationalarchives.droid.profile.referencedata.Format;
import uk.gov.nationalarchives.droid.profile.referencedata.ReferenceData;
import uk.gov.nationalarchives.droid.results.handlers.ProgressObserver;
/**
* @author rflitcroft
*
*/
public class ProfileManagerImpl implements ProfileManager {
private final Log log = LogFactory.getLog(getClass());
private ProfileContextLocator profileContextLocator;
private ProfileSpecDao profileSpecDao;
private ProfileDiskAction profileSaver;
private SignatureManager signatureManager;
private DroidGlobalConfig config;
/**
* Gets a profile instance manager.
*
* @param sigFileInfos
* the path to the signature file to be used for this profile.
* @return the profile instance created.
* @throws ProfileManagerException if the profile could not be created
*/
@Override
public ProfileInstance createProfile(Map<SignatureType, SignatureFileInfo> sigFileInfos)
throws ProfileManagerException {
Map<SignatureType, SignatureFileInfo> signatures = sigFileInfos;
if (sigFileInfos == null) {
// get the default sig file config
try {
signatures = signatureManager.getDefaultSignatures();
} catch (SignatureFileException e) {
throw new ProfileManagerException(e.getMessage());
}
}
String profileId = String.valueOf(System.currentTimeMillis());
log.info("Creating profile: " + profileId);
ProfileInstance profile = profileContextLocator.getProfileInstance(profileId);
File profileHomeDir = new File(config.getProfilesDir(), profile.getUuid());
profileHomeDir.mkdir();
SignatureFileInfo binarySigFile = signatures.get(SignatureType.BINARY);
if (binarySigFile != null) {
profile.setSignatureFileVersion(binarySigFile.getVersion());
profile.setSignatureFileName(binarySigFile.getFile().getName());
copySignatureFile(binarySigFile.getFile(), profileHomeDir);
}
SignatureFileInfo containerSigFile = signatures.get(SignatureType.CONTAINER);
if (containerSigFile != null) {
profile.setContainerSignatureFileName(containerSigFile.getFile().getName());
profile.setContainerSignatureFileVersion(containerSigFile.getVersion());
copySignatureFile(containerSigFile.getFile(), profileHomeDir);
}
SignatureFileInfo textSigFile = signatures.get(SignatureType.TEXT);
if (textSigFile != null) {
profile.setTextSignatureFileName(textSigFile.getFile().getName());
profile.setTextSignatureFileVersion(textSigFile.getVersion());
copySignatureFile(textSigFile.getFile(), profileHomeDir);
}
profile.setUuid(profileId);
profile.setProfileSpec(new ProfileSpec());
// Persist the profile.
profileSpecDao.saveProfile(profile, profileHomeDir);
// Copy the signature file to the profile area
// Ensure a newly created profile is not in a "dirty" state:
profile.setDirty(false);
profileContextLocator.addProfileContext(profile);
return profile;
}
private static void copySignatureFile(File file, File destDir) {
try {
FileUtils.copyFileToDirectory(file, destDir);
} catch (IOException e) {
throw new ProfileException(e.getMessage(), e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void closeProfile(String profileName) {
log.info("Closing profile: " + profileName);
profileContextLocator.removeProfileContext(profileName);
if (!config.getProperties().getBoolean(DroidGlobalProperty.DEV_MODE.getName())) {
File profileHome = new File(config.getProfilesDir(), profileName);
FileUtils.deleteQuietly(profileHome);
}
}
/**
* {@inheritDoc}
* @param profileId String
* @throws IllegalArgumentException if profileId nonexistent
* @return Profile
*/
@Override
public ProfileInstance openProfile(String profileId) {
log.info("Opening profile: " + profileId);
if (!profileContextLocator.hasProfileContext(profileId)) {
throw new IllegalArgumentException(String.format(
"No such profile id [%s]", profileId));
}
ProfileInstance profile = profileContextLocator
.getProfileInstance(profileId);
profileContextLocator.openProfileInstanceManager(profile);
profile.fireListeners();
return profile;
}
/**
* {@inheritDoc}
* @param profileInstance The profile to stop
*/
@Override
public void stop(String profileInstance) {
log.info("Stopping profile: " + profileInstance);
ProfileInstanceManager profileInstanceManager = getProfileInstanceManager(profileInstance);
profileInstanceManager.pause();
}
/**
* @param profileInstance String
* @return ProfileInstanceManager
* @throws ProfileException if null profileInstance
*/
private ProfileInstanceManager getProfileInstanceManager(
String profileInstance) {
if (profileInstance == null) {
String message = "Profile instance id was null";
log.error(message);
throw new ProfileException(message);
}
ProfileInstanceManager profileInstanceManager = profileContextLocator
.openProfileInstanceManager(profileContextLocator
.getProfileInstance(profileInstance));
return profileInstanceManager;
}
/**
* {@inheritDoc}
*/
@Override
public Future<?> start(String profileId) throws IOException {
log.info("Starting profile: " + profileId);
ProfileInstanceManager profileInstanceManager = getProfileInstanceManager(profileId);
return profileInstanceManager.start();
}
/**
* {@inheritDoc}
*/
@Override
public List<ProfileResourceNode> findProfileResourceNodeAndImmediateChildren(
String profileId, Long parentId) {
log.debug(String.format(
" **** Called findProfileResourceNodeAndImmediateChildren [%s] ****",
profileId));
ProfileInstanceManager profileInstanceManager = getProfileInstanceManager(profileId);
return profileInstanceManager.findAllProfileResourceNodes(parentId);
}
/**
* {@inheritDoc}
*/
@Override
public List<ProfileResourceNode> findRootNodes(String profileId) {
ProfileInstanceManager profileInstanceManager = getProfileInstanceManager(profileId);
return profileInstanceManager.findRootProfileResourceNodes();
}
/**
* {@inheritDoc}
*/
@Override
public void setProgressObserver(String profileId,
ProgressObserver progressObserver) {
ProfileInstanceManager profileInstanceManager = getProfileInstanceManager(profileId);
profileInstanceManager.getProgressMonitor()
.setPercentIncrementObserver(progressObserver);
}
/**
* @param profileSpecDao
* the profileSpecDao to set
*/
public void setProfileSpecDao(ProfileSpecDao profileSpecDao) {
this.profileSpecDao = profileSpecDao;
}
/**
* @param profileContextLocator
* the profileContextLocator to set
*/
public void setProfileContextLocator(
ProfileContextLocator profileContextLocator) {
this.profileContextLocator = profileContextLocator;
}
/**
* {@inheritDoc}
*/
@Override
public void setResultsObserver(String profileUuid,
ProfileResultObserver observer) {
getProfileInstanceManager(profileUuid).setResultsObserver(observer);
}
/**
* {@inheritDoc}
*/
@Override
public void updateProfileSpec(String profileId, ProfileSpec profileSpec) {
ProfileInstance profile = profileContextLocator
.getProfileInstance(profileId);
profile.setProfileSpec(profileSpec);
profileSpecDao.saveProfile(profile, getProfileHomeDir(profile));
}
/**
* Saves the specified profile to the file specified. The file will be
* created if it does not already exist or overwritten if it exists.
*
* @param profileId
* the ID of the profile.
* @param destination
* the file to be created or overwitten
* @param callback
* an object to be notified when progress is made.
* @return the saved profile instance
* @throws IOException
* if the file IO failed
*/
@Override
public ProfileInstance save(String profileId, File destination,
ProgressObserver callback) throws IOException {
log.info("Saving profile: " + profileId + " to " + destination.getPath());
// freeze the database so that we can safely zip it up.
profileContextLocator.freezeDatabase(profileId);
ProfileInstance profile = profileContextLocator.getProfileInstance(profileId);
ProfileState oldState = profile.getState();
profile.changeState(ProfileState.SAVING);
try {
File output = destination != null ? destination : profile.getLoadedFrom();
profileSpecDao.saveProfile(profile, getProfileHomeDir(profile));
profileSaver.saveProfile(getProfileHomeDir(profile).getPath(), output, callback);
profile.setLoadedFrom(output);
profile.setName(FilenameUtils.getBaseName(output.getName()));
profile.onSave();
} finally {
profileContextLocator.thawDatabase(profileId);
profile.changeState(oldState);
}
return profile;
}
/**
* @param profileDiskAction
* the profile diskaction to set.
*/
public void setProfileDiskAction(ProfileDiskAction profileDiskAction) {
this.profileSaver = profileDiskAction;
}
/**
* Loads a profile from disk, unless that profile is already open.
*
* @param source
* the source file (zipped).
* @param observer
* an object to be notified when progress is made.
* @return the name of the profile.
* @throws IOException
* - if the file could not be opened, was corrupt, or invalid.
*/
@Override
public ProfileInstance open(File source, ProgressObserver observer)
throws IOException {
log.info("Loading profile from: " + source.getPath());
ZipFile sourceZip = new ZipFile(source);
InputStream in = ProfileFileHelper.getProfileXmlInputStream(sourceZip);
ProfileInstance profile;
try {
profile = profileSpecDao.loadProfile(in);
} finally {
if (in != null) {
in.close();
}
sourceZip.close();
}
profile.setLoadedFrom(source);
profile.setName(FilenameUtils.getBaseName(source.getName()));
profile.setUuid(String.valueOf(System.currentTimeMillis()));
profile.onLoad();
String profileId = profile.getUuid();
if (!profileContextLocator.hasProfileContext(profileId)) {
profileContextLocator.addProfileContext(profile);
File destination = getProfileHomeDir(profile);
profileSaver.load(source, destination, observer);
profileSpecDao.saveProfile(profile, getProfileHomeDir(profile));
profileContextLocator.openProfileInstanceManager(profile);
}
return profile;
}
/**
* Retrieves all the formats.
* @param profileId Profile Id of the profile
* for which format is requested.
* @return list of formats
*/
public List<Format> getAllFormats(String profileId) {
return getProfileInstanceManager(profileId).getAllFormats();
}
/**
* {@inheritDoc}
*/
@Override
public ReferenceData getReferenceData(String profileId) {
return getProfileInstanceManager(profileId).getReferenceData();
}
/**
* {@inheritDoc}
*/
@Override
public void setThrottleValue(String uuid, int value) {
getProfileInstanceManager(uuid).setThrottleValue(value);
}
/**
* @param signatureManager the signatureManager to set
*/
public void setSignatureManager(SignatureManager signatureManager) {
this.signatureManager = signatureManager;
}
/**
* @param config the config to set
*/
public void setConfig(DroidGlobalConfig config) {
this.config = config;
}
private File getProfileHomeDir(ProfileInstance profile) {
return new File(config.getProfilesDir(), profile.getUuid());
}
}
| Det-Kongelige-Bibliotek/droid | droid-results/src/main/java/uk/gov/nationalarchives/droid/profile/ProfileManagerImpl.java | Java | bsd-3-clause | 16,013 |
<?php
/**
* A class representing back actions
*
* <code>
* CMSMain::register_batch_action('publishitems', new CMSBatchAction('doPublish',
* _t('CMSBatchActions.PUBLISHED_PAGES', 'published %d pages')));
* </code>
*
* @package cms
* @subpackage batchaction
*/
abstract class CMSBatchAction extends Object {
/**
* The the text to show in the dropdown for this action
*/
abstract function getActionTitle();
/**
* Get text to be shown while the action is being processed, of the form
* "publishing pages".
*/
abstract function getDoingText();
/**
* Run this action for the given set of pages.
* Return a set of status-updated JavaScript to return to the CMS.
*/
abstract function run(DataObjectSet $pages);
/**
* Helper method for processing batch actions.
* Returns a set of status-updating JavaScript to return to the CMS.
*
* @param $pages The DataObjectSet of SiteTree objects to perform this batch action
* on.
* @param $helperMethod The method to call on each of those objects.
* @para
*/
public function batchaction(DataObjectSet $pages, $helperMethod, $successMessage) {
foreach($pages as $page) {
// Perform the action
$page->$helperMethod();
// Now make sure the tree title is appropriately updated
$publishedRecord = DataObject::get_by_id('SiteTree', $page->ID);
$JS_title = Convert::raw2js($publishedRecord->TreeTitle());
FormResponse::add("\$('sitetree').setNodeTitle($page->ID, '$JS_title');");
$page->destroy();
unset($page);
}
$message = sprintf($successMessage, $pages->Count());
FormResponse::add('statusMessage("'.$message.'","good");');
return FormResponse::respond();
}
}
/**
* Publish items batch action.
*
* @package cms
* @subpackage batchaction
*/
class CMSBatchAction_Publish extends CMSBatchAction {
function getActionTitle() {
return _t('CMSBatchActions.PUBLISH_PAGES', 'Publish');
}
function getDoingText() {
return _t('CMSBatchActions.PUBLISHING_PAGES', 'Publishing pages');
}
function run(DataObjectSet $pages) {
return $this->batchaction($pages, 'doPublish',
_t('CMSBatchActions.PUBLISHED_PAGES', 'Published %d pages')
);
}
}
/**
* Un-publish items batch action.
*
* @package cms
* @subpackage batchaction
*/
class CMSBatchAction_Unpublish extends CMSBatchAction {
function getActionTitle() {
return _t('CMSBatchActions.UNPUBLISH_PAGES', 'Un-publish');
}
function getDoingText() {
return _t('CMSBatchActions.UNPUBLISHING_PAGES', 'Un-publishing pages');
}
function run(DataObjectSet $pages) {
return $this->batchaction($pages, 'doUnpublish',
_t('CMSBatchActions.UNPUBLISHED_PAGES', 'Un-published %d pages')
);
}
}
/**
* Delete items batch action.
*
* @package cms
* @subpackage batchaction
*/
class CMSBatchAction_Delete extends CMSBatchAction {
function getActionTitle() {
return _t('CMSBatchActions.DELETE_PAGES', 'Delete from draft');
}
function getDoingText() {
return _t('CMSBatchActions.DELETING_PAGES', 'Deleting selected pages from draft');
}
function run(DataObjectSet $pages) {
foreach($pages as $page) {
$id = $page->ID;
// Perform the action
if($page->canDelete()) $page->delete();
// check to see if the record exists on the live site, if it doesn't remove the tree node
$liveRecord = Versioned::get_one_by_stage( 'SiteTree', 'Live', "`SiteTree`.`ID`=$id");
if($liveRecord) {
$liveRecord->IsDeletedFromStage = true;
$title = Convert::raw2js($liveRecord->TreeTitle());
FormResponse::add("$('sitetree').setNodeTitle($id, '$title');");
FormResponse::add("$('Form_EditForm').reloadIfSetTo($id);");
} else {
FormResponse::add("var node = $('sitetree').getTreeNodeByIdx('$id');");
FormResponse::add("if(node && node.parentTreeNode) node.parentTreeNode.removeTreeNode(node);");
FormResponse::add("$('Form_EditForm').reloadIfSetTo($id);");
}
$page->destroy();
unset($page);
}
$message = sprintf(_t('CMSBatchActions.DELETED_PAGES', 'Deleted %d pages from the draft site'), $pages->Count());
FormResponse::add('statusMessage("'.$message.'","good");');
return FormResponse::respond();
}
}
/**
* Delete items batch action.
*
* @package cms
* @subpackage batchaction
*/
class CMSBatchAction_DeleteFromLive extends CMSBatchAction {
function getActionTitle() {
return _t('CMSBatchActions.DELETE_PAGES', 'Delete from published site');
}
function getDoingText() {
return _t('CMSBatchActions.DELETING_PAGES', 'Deleting selected pages from the published site');
}
function run(DataObjectSet $pages) {
foreach($pages as $page) {
$id = $page->ID;
// Perform the action
if($page->canDelete()) $page->doDeleteFromLive();
// check to see if the record exists on the live site, if it doesn't remove the tree node
$stageRecord = Versioned::get_one_by_stage( 'SiteTree', 'Stage', "`SiteTree`.`ID`=$id");
if($stageRecord) {
$stageRecord->IsAddedToStage = true;
$title = Convert::raw2js($stageRecord->TreeTitle());
FormResponse::add("$('sitetree').setNodeTitle($id, '$title');");
FormResponse::add("$('Form_EditForm').reloadIfSetTo($id);");
} else {
FormResponse::add("var node = $('sitetree').getTreeNodeByIdx('$id');");
FormResponse::add("if(node && node.parentTreeNode) node.parentTreeNode.removeTreeNode(node);");
FormResponse::add("$('Form_EditForm').reloadIfSetTo($id);");
}
$page->destroy();
unset($page);
}
$message = sprintf(_t('CMSBatchActions.DELETED_PAGES', 'Deleted %d pages from the published site'), $pages->Count());
FormResponse::add('statusMessage("'.$message.'","good");');
return FormResponse::respond();
}
}
| racontemoi/shibuichi | cms/code/CMSBatchAction.php | PHP | bsd-3-clause | 5,684 |
module Spree
# Manage (recalculate) item (LineItem or Shipment) adjustments
class ItemAdjustments
include ActiveSupport::Callbacks
define_callbacks :promo_adjustments, :tax_adjustments
attr_reader :item
delegate :adjustments, :order, to: :item
def initialize(item)
@item = item
# Don't attempt to reload the item from the DB if it's not there
@item.reload if @item.instance_of?(Shipment) && @item.persisted?
end
def update
update_adjustments if item.persisted?
item
end
# TODO this should be probably the place to calculate proper item taxes
# values after promotions are applied
def update_adjustments
# Promotion adjustments must be applied first, then tax adjustments.
# This fits the criteria for VAT tax as outlined here:
# http://www.hmrc.gov.uk/vat/managing/charging/discounts-etc.htm#1
#
# It also fits the criteria for sales tax as outlined here:
# http://www.boe.ca.gov/formspubs/pub113/
#
# Tax adjustments come in not one but *two* exciting flavours:
# Included & additional
# Included tax adjustments are those which are included in the price.
# These ones should not affect the eventual total price.
#
# Additional tax adjustments are the opposite, affecting the final total.
promo_total = 0
run_callbacks :promo_adjustments do
promotion_total = adjustments.promotion.reload.map do |adjustment|
adjustment.update!(@item)
end.compact.sum
unless promotion_total == 0
choose_best_promotion_adjustment
end
promo_total = best_promotion_adjustment.try(:amount).to_f
end
included_tax_total = 0
additional_tax_total = 0
run_callbacks :tax_adjustments do
tax = (item.respond_to?(:all_adjustments) ? item.all_adjustments : item.adjustments).tax
included_tax_total = tax.is_included.reload.map(&:update!).compact.sum
additional_tax_total = tax.additional.reload.map(&:update!).compact.sum
end
item.update_columns(
:promo_total => promo_total,
:included_tax_total => included_tax_total,
:additional_tax_total => additional_tax_total,
:adjustment_total => promo_total + additional_tax_total,
:updated_at => Time.now,
)
end
# Picks one (and only one) promotion to be eligible for this order
# This promotion provides the most discount, and if two promotions
# have the same amount, then it will pick the latest one.
def choose_best_promotion_adjustment
if best_promotion_adjustment
other_promotions = self.adjustments.promotion.where.not(id: best_promotion_adjustment.id)
other_promotions.update_all(:eligible => false)
end
end
def best_promotion_adjustment
@best_promotion_adjustment ||= adjustments.promotion.eligible.reorder("amount ASC, created_at DESC, id DESC").first
end
end
end
| sunny2601/spree1 | core/app/models/spree/item_adjustments.rb | Ruby | bsd-3-clause | 2,999 |
<?
/*======================================================================*\
|| ####################################################################
|| # vBulletin Impex
|| # ----------------------------------------------------------------
|| # All PHP code in this file is Copyright 2000-2014 vBulletin Solutions Inc.
|| # This code is made available under the Modified BSD License -- see license.txt
|| # http://www.vbulletin.com
|| ####################################################################
\*======================================================================*/
/**
* 404 for external and internal link redirect.
*
* @package ImpEx.tools
*
*/
/*
Ensure you have this table for logging
CREATE TABLE `404_actions` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`time` INT UNSIGNED NOT NULL ,
`incomming` VARCHAR( 250 ) NOT NULL ,
`outgoing` VARCHAR( 250 ) NOT NULL ,
`action` TINYINT UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY ( `id` )
) TYPE = MYISAM ;
If you have a high volume site and lot of redirects going on, a HEAP / ENGINE=MEMORY table could be a lot better.
*/
// System
#Currently supported : 'phpBB2' 'ubb.threads' 'vb3' 'ipb2'
$old_system = 'phpBB2';
// Domain
// Example :: http://www.example.com/phpBB/
$old_folder = 'phpBB/'; // With trailing slash
$old_ext_type = '.php'; // Including preceding dot
$standard_404 = 'http://www.example.com/not_found.html'; // The usual 404 that this script replaces
// Example :: www.example.com/vBulletin/
$new_domain = 'example';
$new_folder = 'vBulletin/'; // With trailing slash
$ext_type = '.php'; // File extension type that vBulletin is using, i.e. index.php including the preceding dot
// Database
// This is the vBulletin database, needed for import id look up and logging
$server = 'localhost';
$user = 'user';
$password = 'password';
$database = 'forum';
$tableprefix = '';
// System
$refresh_speed = 0; // Speed of the redirect, 0 advised.
$do_logs = true; // Always best to log to see that its working and if there are any "Unknown link type, talk to Jerry" links
$do_404 = false; // true = a 404 (Not Found) redirect. false is a 301 search engine friendly redirect (Moved Permanently)
$debug = false; // This is will stop the script from actually redirecting, it will just display what the SQL and the action
#############################################################################################################################
# Don't touch below
#############################################################################################################################
$old_id = 0;
$action_code = 0;
$action = null;
$sql = null;
$page = null;
$postcount = null;
// Get the file names and types
switch ($old_system)
{
case 'phpBB2' :
$old_forum_script = "viewforum{$old_ext_type}?f=";
$old_thread_script = "viewtopic{$old_ext_type}?t=";
$old_post_script = "viewtopic{$old_ext_type}?p=";
$old_user_script = "profile{$old_ext_type}?mode=viewprofile&u="; // Append userid
break;
case 'ubb.threads' :
$old_forum_script = "postlist{$old_ext_type}?"; // postlist.php?Cat=&Board=beadtechniques -- have to try to do it on title
$old_thread_script = "showflat{$old_ext_type}?"; // Cat=&Board=beadtechniques&Number=74690&page=0&view=collapsed&sb=5&o=&fpart=1Greg Go for Number=XX
$old_post_script = "showthreaded{$old_ext_type}?"; // ubbthreads/showthreaded.php?Cat=&Board=othertopics&Number=79355&page=0&view=collapsed&sb=5&o=&fpart=1 -- going to thread link, not post, meh
$old_user_script = "showprofile{$old_ext_type}"; // ubbthreads/showprofile.php?Cat=&User=SaraSally&Board=isgbannounce&what=ubbthreads&page=0&view=collapsed&sb=5&o -- username
break;
case 'vb3' :
$old_forum_script = "forumdisplay{$old_ext_type}?f=";
$old_thread_script = "showthread{$old_ext_type}?p=";
$old_post_script = "showpost{$old_ext_type}?p=";
$old_user_script = "member{$old_ext_type}?u=";
break;
case 'ipb2' : // Single file controller, these are here for refrence, the preg_match finds the actual type during the matching
$old_forum_script = "showforum="; // index.php?s=29ef4154d9b74e8978e60ca39ecb506a&showforum=X
$old_thread_script = "index.php?showtopic=";
$old_post_script = "index.php?"; // index.php?s=&showtopic=209664&view=findpost&p=XXXXXXXX
$old_user_script = "index.php?showuser="; // index.php?showuser=XXXXX
break;
default :
// No valid system entered
die('No valid system entered');
}
// It's for the old forum
if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}") === 0)
{
switch ($old_system)
{
case 'phpBB2' :
// It's a forum link
if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_forum_script}") === 0)
{
$action = 'forum';
$old_id = intval(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?f=')+3));
$sql = "SELECT forumid FROM {$tableprefix}forum WHERE importforumid={$old_id}";
}
// It's a thread link
if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_thread_script}") === 0)
{
$action = 'thread';
if( preg_match("/&/", $_SERVER['REQUEST_URI']) )
{
$old_id = intval(substr(substr($_SERVER['REQUEST_URI'], 2), 0, strpos(substr($_SERVER['REQUEST_URI'], 2), '&')));
$sql = "SELECT threadid FROM {$tableprefix}thread WHERE importthreadid={$old_id}";
}
else
{
$old_id = intval(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?t=')+3));
$sql = "SELECT threadid FROM {$tableprefix}thread WHERE importthreadid={$old_id}";
}
}
// It's a post link
if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_post_script}") === 0)
{
$action = 'post';
if( preg_match("/&/", $_SERVER['REQUEST_URI']) )
{
$old_id = intval(substr(substr($_SERVER['REQUEST_URI'], 2), 0, strpos(substr($_SERVER['REQUEST_URI'], 2), '&')));
$sql = "SELECT postid FROM {$tableprefix}post WHERE importpostid={$old_id}";
}
else
{
$old_id = intval(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?p=')+3));
$sql = "SELECT postid FROM {$tableprefix}post WHERE importpostid={$old_id}";
}
}
// It's a user link
if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_user_script}") === 0)
{
$action = 'user';
// Cuts 12 out of this : profile.php?mode=viewprofile&u=12&sid=f646e2a0948e0244ba82cef12c3b93d8
$old_id = intval(substr(substr($_SERVER['REQUEST_URI'], 19), 0, strpos(substr($_SERVER['REQUEST_URI'], 19), '&')));
$sql = "SELECT userid FROM {$tableprefix}user WHERE importuserid={$old_id}";
}
break;
case 'ubb.threads' :
// It's a forum link
if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_forum_script}") === 0)
{
$action = 'forum';
$old_id = intval(substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], 'Board=')+6));
$sql = "SELECT forumid FROM {$tableprefix}forum WHERE importforumid={$old_id}";
}
// It's a thread link (Will get direct post links some times too)
if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_thread_script}") === 0)
{
$action = 'thread';
$begin = strpos ($url, 'Number=');
$middle = strpos ($url, '&', $begin);
$old_id = intval(substr($url, $begin+7, ($middle-$begin)-7)); // +7 & -7 To remove the off set of Number=
$sql = "SELECT threadid FROM {$tableprefix}thread WHERE importthreadid={$old_id}";
}
// It's a post link
if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_post_script}") === 0)
{
if(preg_match('#(.*)Number=(.*)&(.*)#Uis', $_SERVER['REQUEST_URI'], $matches))
{
if (is_numeric($matches[2]))
{
$action = 'post';
$sql = "SELECT postid FROM {$tableprefix}post WHERE importpostid = " . $matches[2];
}
}
}
// It's a user link
if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_user_script}") === 0)
{
if(preg_match('#(.*)User=(.*)&(.*)#Uis', $_SERVER['REQUEST_URI'], $matches))
{
if (is_numeric($matches[2]))
{
$action = 'post';
$sql = "SELECT userid FROM {$tableprefix}user WHERE importpostid = " . $matches[2];
}
}
}
break;
case 'vb3' :
// It's a forum link
if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_forum_script}") === 0)
{
$action = 'forum';
$old_id = intval(substr($_SERVER['REQUEST_URI'], 2, abs(strpos($_SERVER['REQUEST_URI'], '&',2)-2)));
$sql = "SELECT forumid FROM {$tableprefix}forum WHERE importforumid={$old_id}";
}
// It's a thread link
if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_thread_script}") === 0)
{
$action = 'thread';
if (strpos($_SERVER['REQUEST_URI'], '&page=')) // If its paged
{
preg_match('#(.*)\?t=([0-9]+)\&page=([0-9]+)#si', $_SERVER['REQUEST_URI'], $matches);
if ($matches[2] AND $matches[3])
{
$matches[2] = intval($matches[2]);
$sql = "SELECT threadid FROM {$tableprefix}thread WHERE importthreadid=" . $matches[2];
$page = $matches[3];
}
}
else
{
if ($id = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?t=')+3))
{
$id = intval($id);
$sql = "SELECT threadid FROM {$tableprefix}thread WHERE importthreadid={$id}";
}
}
}
// It's a post link
if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_post_script}") === 0)
{
$action = 'post';
if (strpos($_SERVER['REQUEST_URI'], '&postcount=')) // If its postcounted
{
preg_match('#(.*)\?p=([0-9]+)\&postcount=([0-9]+)#si', $_SERVER['REQUEST_URI'], $matches);
if ($matches[2] AND $matches[3])
{
$matches[2] = intval($matches[2]);
$sql = "SELECT postid FROM {$tableprefix}post WHERE importpostid = " . $matches[2];
$postcount = $matches[3];
}
}
else
{
if ($id = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?p=')+3))
{
$id = intval($id);
$sql = "SELECT postid FROM {$tableprefix}post WHERE importpostid={$id}";
}
}
}
// It's a user link
if (strpos($_SERVER['REQUEST_URI'], "/{$old_folder}{$old_user_script}") === 0)
{
$action = 'user';
if ($id = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?u=')+3))
{
$id = intval($id);
$sql = "SELECT userid FROM {$tableprefix}user WHERE importuserid ={$id}";
}
}
break;
case 'ipb2' :
if(preg_match('#index.php?(.*)&showforum=([0-9]+)#is', $_SERVER['REQUEST_URI'], $matches))
{
if (is_numeric($matches[2]))
{
$matches[2] = intval($matches[2]);
$action = 'forum';
$sql = "SELECT forumid FROM {$tableprefix}forum WHERE importforumid=" . $matches[2];
}
}
// It's a thread link
if(preg_match('#index.php\?showtopic=([0-9]+)#is', $_SERVER['REQUEST_URI'], $matches))
{
if (is_numeric($matches[1]))
{
$action = 'thread';
$sql = "SELECT threadid FROM {$tableprefix}forum WHERE importthreadid=" . $matches[1];
}
}
// It's a post link
if(preg_match('#view=findpost\&p=([0-9]+)#is', $_SERVER['REQUEST_URI'], $matches))
{
if (is_numeric($matches[1]))
{
$action = 'post';
$sql = "SELECT postid FROM {$tableprefix}forum WHERE importpostid=" . $matches[1];
}
}
// It's a user link
if(preg_match('#index.php\?showuser=([0-9]+)#is', $_SERVER['REQUEST_URI'], $matches))
{
if (is_numeric($matches[1]))
{
$action = 'user';
$sql = "SELECT userid FROM {$tableprefix}user WHERE importuserid =" . $matches[1];
}
}
break;
default :
// No valid system entered
die('No valid system entered');
}
if (!$action)
{
$action = 'log';
}
}
if ($debug)
{
echo "<html><head><title>404 debug</title></head><body>";
echo "<br>Action :: " . $action;
echo "<br>SQL :: " . $sql;
echo "<br>REQUEST_URI :: " . $_SERVER['REQUEST_URI'] ;
echo "</body></html>";
die;
}
if (!$action)
{
?>
<html>
<head>
<meta http-equiv="refresh" content="<? echo $refresh_speed; ?>; URL=<? echo $standard_404; ?>">
</head>
<body>
</body>
</html>
<?
// Got nuffink
die;
}
// If we are here we have data to look up and redirect to a vBulletin page.
$link = @mysql_connect($server, $user, $password);
if (!$link)
{
#die('Could not connect: ' . mysql_error());
$new_url = $standard_404;
}
$db_selected = @mysql_select_db($database, $link);
if (!$db_selected)
{
#die ('Can\'t use foo : ' . mysql_error());
$new_url = $standard_404;
}
if ($sql)
{
$result = @mysql_query($sql);
$row = @mysql_fetch_row($result);
if (!$row[0])
{
$action = 'Original data missing';
}
@mysql_free_result($result);
}
// Just incase
$new_url = $standard_404;
switch ($action)
{
case 'cat':
case 'forum':
$new_url = "http://{$new_domain}/{$new_folder}forumdisplay{$ext_type}?f=" . $row[0];
$action_code = 1;
break;
case 'thread':
$new_url = "http://{$new_domain}/{$new_folder}showthread{$ext_type}?t=" . $row[0];
if ($page)
{
$new_url .= "&page={$page}";
}
$action_code = 2;
break;
case 'post':
$new_url = "http://{$new_domain}/{$new_folder}showpost{$ext_type}?p=" . $row[0];
if ($postcount)
{
$new_url .= "&postcount={$postcount}";
}
$action_code = 3;
break;
case 'user':
$new_url = "http://{$new_domain}/{$new_folder}member{$ext_type}?u=" . $row[0];
$action_code = 4;
break;
case 'Original data missing':
$action_code = 10;
break;
default :
$action_code = 20;
break;
}
// Do logging ?
if ($do_logs)
{
// Codes
# forum = 1
# thread = 2
# post = 3
# user = 4
# script error = 0
# Original data missing = 10
# Unknown link type, talk to Jerry = 20
$sql = "
INSERT INTO {$tableprefix}404_actions
(
time, incomming, outgoing, action
)
VALUES
(
" . time() . ", '" . $_SERVER['REQUEST_URI'] . "', '" . $new_url . "', '" . $action_code . "'
)
";
mysql_query($sql);
}
@mysql_close($link);
// Do the new redirect
if ($do_404)
{
?>
<html>
<head>
<meta http-equiv="refresh" content="<? echo $refresh_speed; ?> URL=<? echo $new_url; ?>">
</head>
<body>
</body>
</html>
<?
}
else
{
Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location: {$new_url}" );
}
// Da end
?>
| internetbrands/vbimpex | tools/404.php | PHP | bsd-3-clause | 14,263 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/cert_database.h"
#include <cert.h>
#include <certdb.h>
#include <keyhi.h>
#include <pk11pub.h>
#include <secmod.h>
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "crypto/nss_util.h"
#include "crypto/nss_util_internal.h"
#include "net/base/crypto_module.h"
#include "net/base/net_errors.h"
#include "net/base/x509_certificate.h"
#include "net/third_party/mozilla_security_manager/nsNSSCertificateDB.h"
#include "net/third_party/mozilla_security_manager/nsNSSCertTrust.h"
#include "net/third_party/mozilla_security_manager/nsPKCS12Blob.h"
// In NSS 3.13, CERTDB_VALID_PEER was renamed CERTDB_TERMINAL_RECORD. So we use
// the new name of the macro.
#if !defined(CERTDB_TERMINAL_RECORD)
#define CERTDB_TERMINAL_RECORD CERTDB_VALID_PEER
#endif
// PSM = Mozilla's Personal Security Manager.
namespace psm = mozilla_security_manager;
namespace net {
CertDatabase::CertDatabase() {
crypto::EnsureNSSInit();
psm::EnsurePKCS12Init();
}
int CertDatabase::CheckUserCert(X509Certificate* cert_obj) {
if (!cert_obj)
return ERR_CERT_INVALID;
if (cert_obj->HasExpired())
return ERR_CERT_DATE_INVALID;
// Check if the private key corresponding to the certificate exist
// We shouldn't accept any random client certificate sent by a CA.
// Note: The NSS source documentation wrongly suggests that this
// also imports the certificate if the private key exists. This
// doesn't seem to be the case.
CERTCertificate* cert = cert_obj->os_cert_handle();
PK11SlotInfo* slot = PK11_KeyForCertExists(cert, NULL, NULL);
if (!slot) {
LOG(ERROR) << "No corresponding private key in store";
return ERR_NO_PRIVATE_KEY_FOR_CERT;
}
PK11_FreeSlot(slot);
return OK;
}
int CertDatabase::AddUserCert(X509Certificate* cert_obj) {
CERTCertificate* cert = cert_obj->os_cert_handle();
PK11SlotInfo* slot = NULL;
{
crypto::AutoNSSWriteLock lock;
slot = PK11_ImportCertForKey(
cert,
cert_obj->GetDefaultNickname(net::USER_CERT).c_str(),
NULL);
}
if (!slot) {
LOG(ERROR) << "Couldn't import user certificate.";
return ERR_ADD_USER_CERT_FAILED;
}
PK11_FreeSlot(slot);
CertDatabase::NotifyObserversOfUserCertAdded(cert_obj);
return OK;
}
void CertDatabase::ListCerts(CertificateList* certs) {
certs->clear();
CERTCertList* cert_list = PK11_ListCerts(PK11CertListUnique, NULL);
CERTCertListNode* node;
for (node = CERT_LIST_HEAD(cert_list);
!CERT_LIST_END(node, cert_list);
node = CERT_LIST_NEXT(node)) {
certs->push_back(X509Certificate::CreateFromHandle(
node->cert, X509Certificate::OSCertHandles()));
}
CERT_DestroyCertList(cert_list);
}
CryptoModule* CertDatabase::GetPublicModule() const {
CryptoModule* module =
CryptoModule::CreateFromHandle(crypto::GetPublicNSSKeySlot());
// The module is already referenced when returned from
// GetPublicNSSKeySlot, so we need to deref it once.
PK11_FreeSlot(module->os_module_handle());
return module;
}
CryptoModule* CertDatabase::GetPrivateModule() const {
CryptoModule* module =
CryptoModule::CreateFromHandle(crypto::GetPrivateNSSKeySlot());
// The module is already referenced when returned from
// GetPrivateNSSKeySlot, so we need to deref it once.
PK11_FreeSlot(module->os_module_handle());
return module;
}
void CertDatabase::ListModules(CryptoModuleList* modules, bool need_rw) const {
modules->clear();
PK11SlotList* slot_list = NULL;
// The wincx arg is unused since we don't call PK11_SetIsLoggedInFunc.
slot_list = PK11_GetAllTokens(CKM_INVALID_MECHANISM,
need_rw ? PR_TRUE : PR_FALSE, // needRW
PR_TRUE, // loadCerts (unused)
NULL); // wincx
if (!slot_list) {
LOG(ERROR) << "PK11_GetAllTokens failed: " << PORT_GetError();
return;
}
PK11SlotListElement* slot_element = PK11_GetFirstSafe(slot_list);
while (slot_element) {
modules->push_back(CryptoModule::CreateFromHandle(slot_element->slot));
slot_element = PK11_GetNextSafe(slot_list, slot_element,
PR_FALSE); // restart
}
PK11_FreeSlotList(slot_list);
}
int CertDatabase::ImportFromPKCS12(
CryptoModule* module,
const std::string& data,
const string16& password,
bool is_extractable,
net::CertificateList* imported_certs) {
int result = psm::nsPKCS12Blob_Import(module->os_module_handle(),
data.data(), data.size(),
password,
is_extractable,
imported_certs);
if (result == net::OK)
CertDatabase::NotifyObserversOfUserCertAdded(NULL);
return result;
}
int CertDatabase::ExportToPKCS12(
const CertificateList& certs,
const string16& password,
std::string* output) const {
return psm::nsPKCS12Blob_Export(output, certs, password);
}
X509Certificate* CertDatabase::FindRootInList(
const CertificateList& certificates) const {
DCHECK_GT(certificates.size(), 0U);
if (certificates.size() == 1)
return certificates[0].get();
X509Certificate* cert0 = certificates[0];
X509Certificate* cert1 = certificates[1];
X509Certificate* certn_2 = certificates[certificates.size() - 2];
X509Certificate* certn_1 = certificates[certificates.size() - 1];
if (CERT_CompareName(&cert1->os_cert_handle()->issuer,
&cert0->os_cert_handle()->subject) == SECEqual)
return cert0;
if (CERT_CompareName(&certn_2->os_cert_handle()->issuer,
&certn_1->os_cert_handle()->subject) == SECEqual)
return certn_1;
VLOG(1) << "certificate list is not a hierarchy";
return cert0;
}
bool CertDatabase::ImportCACerts(const CertificateList& certificates,
TrustBits trust_bits,
ImportCertFailureList* not_imported) {
X509Certificate* root = FindRootInList(certificates);
bool success = psm::ImportCACerts(certificates, root, trust_bits,
not_imported);
if (success)
CertDatabase::NotifyObserversOfCertTrustChanged(NULL);
return success;
}
bool CertDatabase::ImportServerCert(const CertificateList& certificates,
ImportCertFailureList* not_imported) {
return psm::ImportServerCert(certificates, not_imported);
}
CertDatabase::TrustBits CertDatabase::GetCertTrust(const X509Certificate* cert,
CertType type) const {
CERTCertTrust nsstrust;
SECStatus srv = CERT_GetCertTrust(cert->os_cert_handle(), &nsstrust);
if (srv != SECSuccess) {
LOG(ERROR) << "CERT_GetCertTrust failed with error " << PORT_GetError();
return UNTRUSTED;
}
psm::nsNSSCertTrust trust(&nsstrust);
switch (type) {
case CA_CERT:
return trust.HasTrustedCA(PR_TRUE, PR_FALSE, PR_FALSE) * TRUSTED_SSL +
trust.HasTrustedCA(PR_FALSE, PR_TRUE, PR_FALSE) * TRUSTED_EMAIL +
trust.HasTrustedCA(PR_FALSE, PR_FALSE, PR_TRUE) * TRUSTED_OBJ_SIGN;
case SERVER_CERT:
return trust.HasTrustedPeer(PR_TRUE, PR_FALSE, PR_FALSE) * TRUSTED_SSL +
trust.HasTrustedPeer(PR_FALSE, PR_TRUE, PR_FALSE) * TRUSTED_EMAIL +
trust.HasTrustedPeer(PR_FALSE, PR_FALSE, PR_TRUE) * TRUSTED_OBJ_SIGN;
default:
return UNTRUSTED;
}
}
bool CertDatabase::IsUntrusted(const X509Certificate* cert) const {
CERTCertTrust nsstrust;
SECStatus rv = CERT_GetCertTrust(cert->os_cert_handle(), &nsstrust);
if (rv != SECSuccess) {
LOG(ERROR) << "CERT_GetCertTrust failed with error " << PORT_GetError();
return false;
}
// The CERTCertTrust structure contains three trust records:
// sslFlags, emailFlags, and objectSigningFlags. The three
// trust records are independent of each other.
//
// If the CERTDB_TERMINAL_RECORD bit in a trust record is set,
// then that trust record is a terminal record. A terminal
// record is used for explicit trust and distrust of an
// end-entity or intermediate CA cert.
//
// In a terminal record, if neither CERTDB_TRUSTED_CA nor
// CERTDB_TRUSTED is set, then the terminal record means
// explicit distrust. On the other hand, if the terminal
// record has either CERTDB_TRUSTED_CA or CERTDB_TRUSTED bit
// set, then the terminal record means explicit trust.
//
// For a root CA, the trust record does not have
// the CERTDB_TERMINAL_RECORD bit set.
static const unsigned int kTrusted = CERTDB_TRUSTED_CA | CERTDB_TRUSTED;
if ((nsstrust.sslFlags & CERTDB_TERMINAL_RECORD) != 0 &&
(nsstrust.sslFlags & kTrusted) == 0) {
return true;
}
if ((nsstrust.emailFlags & CERTDB_TERMINAL_RECORD) != 0 &&
(nsstrust.emailFlags & kTrusted) == 0) {
return true;
}
if ((nsstrust.objectSigningFlags & CERTDB_TERMINAL_RECORD) != 0 &&
(nsstrust.objectSigningFlags & kTrusted) == 0) {
return true;
}
// Self-signed certificates that don't have any trust bits set are untrusted.
// Other certificates that don't have any trust bits set may still be trusted
// if they chain up to a trust anchor.
if (CERT_CompareName(&cert->os_cert_handle()->issuer,
&cert->os_cert_handle()->subject) == SECEqual) {
return (nsstrust.sslFlags & kTrusted) == 0 &&
(nsstrust.emailFlags & kTrusted) == 0 &&
(nsstrust.objectSigningFlags & kTrusted) == 0;
}
return false;
}
bool CertDatabase::SetCertTrust(const X509Certificate* cert,
CertType type,
TrustBits trust_bits) {
bool success = psm::SetCertTrust(cert, type, trust_bits);
if (success)
CertDatabase::NotifyObserversOfCertTrustChanged(cert);
return success;
}
bool CertDatabase::DeleteCertAndKey(const X509Certificate* cert) {
// For some reason, PK11_DeleteTokenCertAndKey only calls
// SEC_DeletePermCertificate if the private key is found. So, we check
// whether a private key exists before deciding which function to call to
// delete the cert.
SECKEYPrivateKey *privKey = PK11_FindKeyByAnyCert(cert->os_cert_handle(),
NULL);
if (privKey) {
SECKEY_DestroyPrivateKey(privKey);
if (PK11_DeleteTokenCertAndKey(cert->os_cert_handle(), NULL)) {
LOG(ERROR) << "PK11_DeleteTokenCertAndKey failed: " << PORT_GetError();
return false;
}
} else {
if (SEC_DeletePermCertificate(cert->os_cert_handle())) {
LOG(ERROR) << "SEC_DeletePermCertificate failed: " << PORT_GetError();
return false;
}
}
CertDatabase::NotifyObserversOfUserCertRemoved(cert);
return true;
}
bool CertDatabase::IsReadOnly(const X509Certificate* cert) const {
PK11SlotInfo* slot = cert->os_cert_handle()->slot;
return slot && PK11_IsReadOnly(slot);
}
} // namespace net
| aYukiSekiguchi/ACCESS-Chromium | net/base/cert_database_nss.cc | C++ | bsd-3-clause | 11,164 |
#include <pybind11/pybind11.h>
namespace py = pybind11;
namespace aikido {
namespace python {
void World(py::module& sm);
void aikidopy_planner(py::module& m)
{
auto sm = m.def_submodule("planner");
World(sm);
}
} // namespace python
} // namespace aikido
| personalrobotics/aikido | python/aikidopy/planner/module.cpp | C++ | bsd-3-clause | 266 |
package dyvilx.tools.compiler.ast.generic;
import dyvil.annotation.Reified;
import dyvil.annotation.internal.NonNull;
import dyvil.annotation.internal.Nullable;
import dyvil.lang.Name;
import dyvilx.tools.asm.TypeAnnotatableVisitor;
import dyvilx.tools.asm.TypeReference;
import dyvilx.tools.compiler.ast.attribute.AttributeList;
import dyvilx.tools.compiler.ast.attribute.annotation.Annotation;
import dyvilx.tools.compiler.ast.classes.IClass;
import dyvilx.tools.compiler.ast.expression.IValue;
import dyvilx.tools.compiler.ast.expression.constant.EnumValue;
import dyvilx.tools.compiler.ast.field.IDataMember;
import dyvilx.tools.compiler.ast.method.IMethod;
import dyvilx.tools.compiler.ast.method.MatchList;
import dyvilx.tools.compiler.ast.parameter.ArgumentList;
import dyvilx.tools.compiler.ast.parameter.IParameter;
import dyvilx.tools.compiler.ast.type.IType;
import dyvilx.tools.compiler.ast.type.builtin.Types;
import dyvilx.tools.compiler.ast.type.compound.IntersectionType;
import dyvilx.tools.compiler.ast.type.typevar.CovariantTypeVarType;
import dyvilx.tools.compiler.backend.exception.BytecodeException;
import dyvilx.tools.compiler.backend.method.MethodWriter;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.util.ArrayList;
import java.util.List;
import static dyvilx.tools.compiler.ast.type.builtin.Types.isSuperClass;
import static dyvilx.tools.compiler.ast.type.builtin.Types.isSuperType;
public abstract class TypeParameter implements ITypeParameter
{
// =============== Fields ===============
// --------------- Accompanying Member ---------------
protected ITypeParametric generic;
// --------------- Declaration ---------------
protected @NonNull AttributeList attributes = new AttributeList();
protected Variance variance = Variance.INVARIANT;
protected Name name;
private @NonNull IType upperBound = Types.NULLABLE_ANY;
protected @Nullable IType lowerBound;
// --------------- Metadata ---------------
private IType safeUpperBound;
private IType[] upperBounds;
protected Reified.Type reifiedKind; // defaults to null (not reified)
protected IParameter reifyParameter;
private final IType covariantType = new CovariantTypeVarType(this);
// =============== Constructors ===============
public TypeParameter(ITypeParametric generic)
{
this.generic = generic;
}
public TypeParameter(ITypeParametric generic, Name name)
{
this.name = name;
this.generic = generic;
}
public TypeParameter(ITypeParametric generic, Name name, Variance variance)
{
this.name = name;
this.generic = generic;
this.variance = variance;
}
// =============== Properties ===============
// --------------- Accompanying Member ---------------
@Override
public ITypeParametric getGeneric()
{
return this.generic;
}
@Override
public void setGeneric(ITypeParametric generic)
{
this.generic = generic;
}
// --------------- Attributes ---------------
@Override
public ElementType getElementType()
{
return ElementType.TYPE_PARAMETER;
}
@Override
public AttributeList getAttributes()
{
return this.attributes;
}
@Override
public void setAttributes(AttributeList attributes)
{
this.attributes = attributes;
}
@Override
public final Annotation getAnnotation(IClass type)
{
return this.attributes.getAnnotation(type);
}
@Override
public boolean skipAnnotation(String type, Annotation annotation)
{
switch (type)
{
case "dyvil/annotation/internal/Covariant":
this.variance = Variance.COVARIANT;
return true;
case "dyvil/annotation/internal/Contravariant":
this.variance = Variance.CONTRAVARIANT;
return true;
}
return false;
}
// --------------- Reification ---------------
protected void computeReifiedKind()
{
if (this.reifiedKind != null)
{
return;
}
final Annotation reifiedAnnotation = this.getAnnotation(Types.REIFIED_CLASS);
if (reifiedAnnotation != null)
{
final IParameter parameter = Types.REIFIED_CLASS.getParameters().get(0);
this.reifiedKind = EnumValue
.eval(reifiedAnnotation.getArguments().getOrDefault(parameter), Reified.Type.class);
}
}
@Override
public Reified.Type getReifiedKind()
{
return this.reifiedKind;
}
@Override
public IParameter getReifyParameter()
{
return this.reifyParameter;
}
@Override
public void setReifyParameter(IParameter parameter)
{
this.reifyParameter = parameter;
}
// --------------- Variance ---------------
@Override
public Variance getVariance()
{
return this.variance;
}
@Override
public void setVariance(Variance variance)
{
this.variance = variance;
}
// --------------- Name ---------------
@Override
public Name getName()
{
return this.name;
}
@Override
public void setName(Name name)
{
this.name = name;
}
// --------------- Upper Bound ---------------
@Override
public IType getUpperBound()
{
if (this.upperBound != null)
{
return this.upperBound;
}
final IType[] upperBounds = this.getUpperBounds();
if (upperBounds != null)
{
return this.upperBound = getUpperBound(upperBounds, 0, upperBounds.length);
}
return null;
}
@Override
public void setUpperBound(IType bound)
{
this.upperBound = bound;
this.upperBounds = null;
this.safeUpperBound = null;
}
public IType[] getUpperBounds()
{
if (this.upperBounds != null)
{
return this.upperBounds;
}
final IType upperBound = this.getUpperBound();
if (upperBound != null)
{
// Flatten the tree-like upperBound structure into a list
final List<IType> list = new ArrayList<>();
getUpperBounds(list, upperBound);
return this.upperBounds = list.toArray(new IType[0]);
}
return null;
}
public void setUpperBounds(IType[] upperBounds)
{
this.upperBounds = upperBounds;
this.upperBound = null;
this.safeUpperBound = null;
}
/**
* Creates a balanced tree for the slice of the given array
*
* @param upperBounds
* the upper bounds array
* @param start
* the start index
* @param count
* the number of elements
*
* @return a balanced tree of {@link IntersectionType}s
*/
private static IType getUpperBound(IType[] upperBounds, int start, int count)
{
if (count == 1)
{
return upperBounds[start];
}
final int halfCount = count / 2;
return new IntersectionType(getUpperBound(upperBounds, start, halfCount),
getUpperBound(upperBounds, start + halfCount, count - halfCount));
}
private static void getUpperBounds(List<IType> list, IType upperBound)
{
if (upperBound.typeTag() != IType.INTERSECTION)
{
list.add(upperBound);
return;
}
final IntersectionType intersection = (IntersectionType) upperBound;
getUpperBounds(list, intersection.getLeft());
getUpperBounds(list, intersection.getRight());
}
// --------------- Safe Upper Bound ---------------
private IType getSafeUpperBound()
{
if (this.safeUpperBound != null)
{
return this.safeUpperBound;
}
return (this.safeUpperBound = this.getUpperBound().getConcreteType(this::replaceBackRefs));
}
private @Nullable IType replaceBackRefs(ITypeParameter typeParameter)
{
if (typeParameter.getGeneric() == this.getGeneric() && typeParameter.getIndex() >= this.getIndex())
{
return new CovariantTypeVarType(this, true);
}
return null;
}
// --------------- Lower Bound ---------------
@Override
public IType getLowerBound()
{
return this.lowerBound;
}
@Override
public void setLowerBound(IType bound)
{
this.lowerBound = bound;
}
// --------------- Other Types ---------------
@Override
public IType getErasure()
{
return this.getUpperBounds()[0];
}
@Override
public IType getCovariantType()
{
return this.covariantType;
}
@Override
public IClass getTheClass()
{
return this.getSafeUpperBound().getTheClass();
}
// =============== Methods ===============
// --------------- Subtyping ---------------
@Override
public boolean isAssignableFrom(IType type, ITypeContext typeContext)
{
if (!Types.isSuperType(this.getSafeUpperBound().getConcreteType(typeContext), type))
{
return false;
}
final IType lowerBound = this.getLowerBound();
return lowerBound == null || Types.isSuperType(type, lowerBound.getConcreteType(typeContext));
}
@Override
public boolean isSameType(IType type)
{
return Types.isSameType(type, this.getSafeUpperBound());
}
@Override
public boolean isSameClass(IType type)
{
return Types.isSameClass(type, this.getSafeUpperBound());
}
@Override
public boolean isSuperTypeOf(IType subType)
{
return isSuperType(this.getSafeUpperBound(), subType);
}
@Override
public boolean isSuperClassOf(IType subType)
{
return isSuperClass(this.getSafeUpperBound(), subType);
}
@Override
public boolean isSubTypeOf(IType superType)
{
return isSuperType(superType, this.getSafeUpperBound());
}
@Override
public boolean isSubClassOf(IType superType)
{
return isSuperClass(superType, this.getSafeUpperBound());
}
// --------------- Field and Method Resolution ---------------
@Override
public IDataMember resolveField(Name name)
{
return this.getSafeUpperBound().resolveField(name);
}
@Override
public void getMethodMatches(MatchList<IMethod> list, IValue instance, Name name, ArgumentList arguments)
{
this.getSafeUpperBound().getMethodMatches(list, instance, name, arguments);
}
@Override
public void getImplicitMatches(MatchList<IMethod> list, IValue value, IType targetType)
{
this.getSafeUpperBound().getImplicitMatches(list, value, targetType);
}
// --------------- Descriptor and Signature ---------------
@Override
public void appendSignature(StringBuilder buffer)
{
buffer.append(this.name).append(':');
final IType[] upperBounds = this.getUpperBounds();
if (upperBounds == null || upperBounds.length == 0)
{
buffer.append("Ljava/lang/Object;");
return;
}
final IClass theClass = upperBounds[0].getTheClass();
if (theClass != null && theClass.isInterface())
{
// If the first type is an interface, we append two colons
// T::Lmy/Interface;
buffer.append(':');
}
upperBounds[0].appendSignature(buffer, false);
for (int i = 1, count = upperBounds.length; i < count; i++)
{
buffer.append(':');
upperBounds[i].appendSignature(buffer, false);
}
}
@Override
public void appendParameterDescriptor(StringBuilder buffer)
{
if (this.reifiedKind == Reified.Type.TYPE)
{
buffer.append("Ldyvil/reflect/types/Type;");
}
else if (this.reifiedKind != null) // OBJECT_CLASS or ANY_CLASS
{
buffer.append("Ljava/lang/Class;");
}
}
@Override
public void appendParameterSignature(StringBuilder buffer)
{
this.appendParameterDescriptor(buffer);
}
// --------------- Compilation ---------------
@Override
public void writeArgument(MethodWriter writer, IType type) throws BytecodeException
{
if (this.reifiedKind == Reified.Type.ANY_CLASS)
{
type.writeClassExpression(writer, false);
}
else if (this.reifiedKind == Reified.Type.OBJECT_CLASS)
{
// Convert primitive types to their reference counterpart
type.writeClassExpression(writer, true);
}
else if (this.reifiedKind == Reified.Type.TYPE)
{
type.writeTypeExpression(writer);
}
}
@Override
public void write(TypeAnnotatableVisitor visitor)
{
boolean method = this.generic instanceof IMethod;
final int index = this.getIndex();
int typeRef = TypeReference.newTypeParameterReference(
method ? TypeReference.METHOD_TYPE_PARAMETER : TypeReference.CLASS_TYPE_PARAMETER, index);
if (this.variance != Variance.INVARIANT)
{
String type = this.variance == Variance.CONTRAVARIANT ?
"Ldyvil/annotation/internal/Contravariant;" :
"Ldyvil/annotation/internal/Covariant;";
visitor.visitTypeAnnotation(typeRef, null, type, true).visitEnd();
}
this.attributes.write(visitor, typeRef, null);
final IType[] upperBounds = this.getUpperBounds();
for (int i = 0, size = upperBounds.length; i < size; i++)
{
final int boundTypeRef = TypeReference.newTypeParameterBoundReference(
method ? TypeReference.METHOD_TYPE_PARAMETER_BOUND : TypeReference.CLASS_TYPE_PARAMETER_BOUND, index,
i);
IType.writeAnnotations(upperBounds[i], visitor, boundTypeRef, "");
}
}
// --------------- Serialization ---------------
@Override
public void write(DataOutput out) throws IOException
{
this.name.write(out);
Variance.write(this.variance, out);
IType.writeType(this.lowerBound, out);
IType.writeType(this.getUpperBound(), out);
}
@Override
public void read(DataInput in) throws IOException
{
this.name = Name.read(in);
this.variance = Variance.read(in);
this.lowerBound = IType.readType(in);
this.setUpperBound(IType.readType(in));
}
// --------------- Formatting ---------------
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
this.toString("", builder);
return builder.toString();
}
@Override
public void toString(@NonNull String indent, @NonNull StringBuilder buffer)
{
this.attributes.toInlineString(indent, buffer);
buffer.append("type ");
this.variance.appendPrefix(buffer);
buffer.append(this.name);
final IType upperBound = this.getSafeUpperBound();
if (upperBound != null)
{
buffer.append(": ");
upperBound.toString(indent, buffer);
}
final IType lowerBound = this.getLowerBound();
if (lowerBound != null)
{
buffer.append(" super ");
lowerBound.toString(indent, buffer);
}
}
}
| Clashsoft/Dyvil | compiler/src/main/java/dyvilx/tools/compiler/ast/generic/TypeParameter.java | Java | bsd-3-clause | 13,621 |
# @Float(label="Diameter of the circle ROI (pixel)", value=7) circle_diam
from ij.plugin.frame import RoiManager
from ij.gui import OvalRoi
rm = RoiManager.getInstance()
new_rois = []
for roi in rm.getRoisAsArray():
assert roi.getTypeAsString() == 'Point', "ROI needs to be a point"
x_center = roi.getContainedPoints()[0].x - (circle_diam / 2) + 0.5
y_center = roi.getContainedPoints()[0].y - (circle_diam / 2) + 0.5
new_roi = OvalRoi(x_center, y_center, circle_diam, circle_diam)
new_rois.append(new_roi)
rm.reset()
for new_roi in new_rois:
rm.addRoi(new_roi)
print("Done")
| hadim/fiji_tools | src/main/resources/script_templates/Hadim_Scripts/ROI/Circle_ROI_Builder.py | Python | bsd-3-clause | 587 |
package com.ociweb.oe.foglight.api;
import com.ociweb.iot.maker.FogRuntime;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
/**
* Unit test for simple App.
*/
public class AppTest {
@Test
@Ignore
public void testApp() {
boolean cleanExit = FogRuntime.testConcurrentUntilShutdownRequested(new TransducerDemo(), 1000);
assertTrue(cleanExit);
}
}
| oci-pronghorn/FogLight | apidemo/transducerdemo/src/test/java/com/ociweb/oe/foglight/api/AppTest.java | Java | bsd-3-clause | 400 |
// Copyright 2016 The Snappy-Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package snappy
// extendMatchGoldenTestCases is the i and j arguments, and the returned value,
// for every extendMatch call issued when encoding the
// testdata/Isaac.Newton-Opticks.txt file. It is used to benchmark the
// extendMatch implementation.
//
// It was generated manually by adding some print statements to the (pure Go)
// encodeBlock implementation (in encode_other.go) to replace the inlined
// version of extendMatch.
//
// s += 4
// s0 := s
// for i := candidate + 4; s < len(src) && src[i] == src[s]; i, s = i+1, s+1 {
// }
// println("{", candidate + 4, ",", s0, ",", s, "},")
//
// and running "go test -test.run=EncodeGoldenInput -tags=noasm".
var extendMatchGoldenTestCases = []struct {
i, j, want int
}{
{571, 627, 627},
{220, 644, 645},
{99, 649, 649},
{536, 653, 656},
{643, 671, 673},
{676, 732, 733},
{732, 751, 752},
{67, 768, 772},
{93, 780, 780},
{199, 788, 788},
{487, 792, 796},
{699, 826, 826},
{698, 838, 838},
{697, 899, 901},
{847, 911, 912},
{37, 923, 923},
{833, 928, 928},
{69, 941, 943},
{323, 948, 948},
{671, 955, 957},
{920, 973, 974},
{935, 979, 983},
{750, 997, 999},
{841, 1014, 1014},
{928, 1053, 1053},
{854, 1057, 1060},
{755, 1072, 1072},
{838, 1094, 1097},
{1022, 1106, 1106},
{1085, 1114, 1114},
{955, 1128, 1130},
{814, 1134, 1135},
{1063, 1145, 1147},
{918, 1161, 1162},
{815, 1195, 1196},
{1128, 1207, 1209},
{1170, 1225, 1225},
{897, 1236, 1242},
{193, 1255, 1262},
{644, 1266, 1267},
{784, 1274, 1282},
{227, 1287, 1289},
{1161, 1294, 1295},
{923, 1299, 1299},
{1195, 1303, 1303},
{718, 1334, 1339},
{805, 1350, 1350},
{874, 1357, 1357},
{1318, 1362, 1362},
{994, 1372, 1373},
{90, 1387, 1387},
{1053, 1399, 1400},
{1094, 1417, 1417},
{1250, 1445, 1445},
{1285, 1449, 1453},
{806, 1457, 1461},
{895, 1472, 1472},
{1236, 1481, 1488},
{1266, 1495, 1496},
{921, 1508, 1509},
{940, 1522, 1522},
{1541, 1558, 1559},
{788, 1582, 1582},
{1298, 1590, 1590},
{1361, 1594, 1595},
{910, 1599, 1601},
{720, 1605, 1605},
{1399, 1615, 1616},
{736, 1629, 1629},
{1078, 1634, 1638},
{677, 1645, 1645},
{757, 1650, 1655},
{1294, 1659, 1663},
{1119, 1677, 1684},
{995, 1688, 1688},
{1357, 1695, 1696},
{1169, 1700, 1721},
{808, 1725, 1727},
{1390, 1732, 1732},
{1513, 1736, 1736},
{1315, 1740, 1740},
{685, 1748, 1750},
{899, 1754, 1760},
{1598, 1764, 1767},
{1386, 1782, 1783},
{1465, 1787, 1787},
{1014, 1791, 1791},
{1724, 1800, 1805},
{1166, 1811, 1811},
{1659, 1823, 1824},
{1218, 1829, 1843},
{695, 1847, 1850},
{1175, 1855, 1857},
{860, 1876, 1878},
{1799, 1892, 1892},
{1319, 1896, 1896},
{1691, 1900, 1900},
{1378, 1904, 1904},
{1495, 1912, 1912},
{1588, 1917, 1921},
{679, 1925, 1928},
{1398, 1935, 1936},
{1551, 1941, 1942},
{1612, 1946, 1950},
{1814, 1959, 1959},
{1853, 1965, 1966},
{1307, 1983, 1986},
{1695, 1990, 1991},
{905, 1995, 1995},
{1057, 1999, 2002},
{1431, 2006, 2007},
{848, 2018, 2018},
{1064, 2022, 2023},
{1151, 2027, 2027},
{1071, 2050, 2050},
{1478, 2057, 2057},
{1911, 2065, 2066},
{1306, 2070, 2074},
{2035, 2085, 2085},
{1188, 2100, 2100},
{11, 2117, 2118},
{1725, 2122, 2126},
{991, 2130, 2130},
{1786, 2139, 2141},
{737, 2153, 2154},
{1481, 2161, 2164},
{1990, 2173, 2173},
{2057, 2185, 2185},
{1881, 2200, 2200},
{2171, 2205, 2207},
{1412, 2215, 2216},
{2210, 2220, 2220},
{799, 2230, 2230},
{2103, 2234, 2234},
{2195, 2238, 2240},
{1935, 2244, 2245},
{2220, 2249, 2249},
{726, 2256, 2256},
{2188, 2262, 2266},
{2215, 2270, 2272},
{2122, 2276, 2278},
{1110, 2282, 2283},
{1369, 2287, 2287},
{724, 2294, 2294},
{1626, 2300, 2300},
{2138, 2306, 2309},
{709, 2313, 2316},
{1558, 2327, 2327},
{2109, 2333, 2333},
{2173, 2354, 2354},
{2152, 2362, 2367},
{2065, 2371, 2373},
{1692, 2377, 2380},
{819, 2384, 2386},
{2270, 2393, 2395},
{1787, 2399, 2400},
{1989, 2405, 2405},
{1225, 2414, 2414},
{2330, 2418, 2418},
{986, 2424, 2425},
{1899, 2429, 2431},
{1070, 2436, 2440},
{1038, 2450, 2450},
{1365, 2457, 2457},
{1983, 2461, 2462},
{1025, 2469, 2469},
{2354, 2476, 2476},
{2457, 2482, 2482},
{5, 2493, 2494},
{2234, 2498, 2498},
{2352, 2514, 2516},
{2353, 2539, 2540},
{1594, 2544, 2546},
{2113, 2550, 2551},
{2303, 2556, 2557},
{2429, 2561, 2563},
{2512, 2568, 2568},
{1739, 2572, 2572},
{1396, 2583, 2587},
{1854, 2593, 2593},
{2345, 2601, 2602},
{2536, 2606, 2612},
{2176, 2617, 2633},
{2421, 2637, 2637},
{1645, 2641, 2641},
{800, 2645, 2647},
{804, 2654, 2661},
{687, 2665, 2665},
{1668, 2669, 2669},
{1065, 2673, 2673},
{2027, 2677, 2677},
{2312, 2685, 2691},
{2371, 2695, 2697},
{2453, 2701, 2702},
{2479, 2711, 2711},
{2399, 2715, 2715},
{1018, 2720, 2723},
{1457, 2727, 2727},
{2376, 2732, 2732},
{1387, 2744, 2744},
{2641, 2748, 2748},
{2476, 2755, 2755},
{2460, 2761, 2765},
{2006, 2769, 2769},
{2773, 2774, 2809},
{2769, 2818, 2818},
{134, 2835, 2835},
{472, 2847, 2850},
{206, 2856, 2856},
{1072, 2860, 2863},
{801, 2867, 2868},
{787, 2875, 2883},
{2560, 2897, 2901},
{2744, 2909, 2913},
{2211, 2919, 2919},
{2150, 2927, 2927},
{2598, 2931, 2931},
{2761, 2936, 2938},
{1312, 2942, 2943},
{997, 2948, 2950},
{2637, 2957, 2961},
{2872, 2971, 2975},
{1687, 2983, 2984},
{2755, 2994, 2994},
{1644, 3000, 3001},
{1634, 3005, 3008},
{2555, 3012, 3014},
{2947, 3018, 3032},
{1649, 3036, 3051},
{691, 3055, 3055},
{2714, 3059, 3061},
{2498, 3069, 3069},
{3012, 3074, 3076},
{2543, 3087, 3089},
{2983, 3097, 3098},
{1011, 3111, 3111},
{1552, 3115, 3115},
{1427, 3124, 3124},
{1331, 3133, 3134},
{1012, 3138, 3140},
{2194, 3148, 3148},
{2561, 3152, 3155},
{3054, 3159, 3161},
{3065, 3169, 3173},
{2346, 3177, 3177},
{2606, 3181, 3185},
{2994, 3204, 3206},
{1329, 3210, 3211},
{1797, 3215, 3215},
{12, 3221, 3221},
{1013, 3227, 3228},
{3168, 3233, 3238},
{3194, 3247, 3247},
{3097, 3256, 3257},
{1219, 3265, 3271},
{1753, 3275, 3277},
{1550, 3282, 3292},
{1182, 3296, 3303},
{2818, 3307, 3307},
{2774, 3311, 3346},
{2812, 3350, 3356},
{2829, 3367, 3367},
{2835, 3373, 3387},
{2860, 3393, 3395},
{2971, 3405, 3409},
{1433, 3413, 3414},
{3405, 3424, 3428},
{2957, 3432, 3432},
{2889, 3455, 3460},
{1213, 3472, 3474},
{947, 3478, 3479},
{2747, 3490, 3491},
{3036, 3495, 3497},
{2873, 3501, 3504},
{2979, 3508, 3509},
{684, 3514, 3516},
{275, 3524, 3525},
{3221, 3529, 3529},
{2748, 3533, 3533},
{2708, 3546, 3546},
{1104, 3550, 3550},
{766, 3554, 3556},
{1672, 3560, 3561},
{1155, 3565, 3568},
{3417, 3572, 3572},
{2393, 3581, 3583},
{3533, 3587, 3587},
{762, 3591, 3591},
{820, 3604, 3605},
{3436, 3609, 3615},
{2497, 3624, 3625},
{3454, 3630, 3633},
{2276, 3642, 3644},
{823, 3649, 3649},
{648, 3660, 3662},
{2049, 3666, 3669},
{3111, 3680, 3680},
{2048, 3698, 3702},
{2313, 3706, 3708},
{2060, 3717, 3717},
{2695, 3722, 3724},
{1114, 3733, 3733},
{1385, 3738, 3738},
{3477, 3744, 3748},
{3512, 3753, 3753},
{2859, 3764, 3764},
{3210, 3773, 3774},
{1334, 3778, 3780},
{3103, 3785, 3785},
{3018, 3789, 3792},
{3432, 3802, 3802},
{3587, 3806, 3806},
{2148, 3819, 3819},
{1581, 3827, 3829},
{3485, 3833, 3838},
{2727, 3845, 3845},
{1303, 3849, 3849},
{2287, 3853, 3855},
{2133, 3859, 3862},
{3806, 3866, 3866},
{3827, 3878, 3880},
{3845, 3884, 3884},
{810, 3888, 3888},
{3866, 3892, 3892},
{3537, 3896, 3898},
{2905, 3903, 3907},
{3666, 3911, 3913},
{3455, 3920, 3924},
{3310, 3930, 3934},
{3311, 3939, 3942},
{3938, 3946, 3967},
{2340, 3977, 3977},
{3542, 3983, 3983},
{1629, 3992, 3992},
{3733, 3998, 3999},
{3816, 4003, 4007},
{2017, 4018, 4019},
{883, 4027, 4029},
{1178, 4033, 4033},
{3977, 4039, 4039},
{3069, 4044, 4045},
{3802, 4049, 4053},
{3875, 4061, 4066},
{1628, 4070, 4071},
{1113, 4075, 4076},
{1975, 4081, 4081},
{2414, 4087, 4087},
{4012, 4096, 4096},
{4017, 4102, 4104},
{2169, 4112, 4112},
{3998, 4123, 4124},
{2909, 4130, 4130},
{4032, 4136, 4136},
{4016, 4140, 4145},
{3565, 4154, 4157},
{3892, 4161, 4161},
{3878, 4168, 4169},
{3928, 4173, 4215},
{144, 4238, 4239},
{4243, 4244, 4244},
{3307, 4255, 4255},
{1971, 4261, 4268},
{3393, 4272, 4274},
{3591, 4278, 4278},
{1962, 4282, 4282},
{1688, 4286, 4286},
{3911, 4298, 4300},
{780, 4304, 4305},
{2842, 4309, 4309},
{4048, 4314, 4315},
{3770, 4321, 4321},
{2244, 4331, 4331},
{3148, 4336, 4336},
{1548, 4340, 4340},
{3209, 4345, 4351},
{768, 4355, 4355},
{1903, 4362, 4362},
{2212, 4366, 4366},
{1494, 4378, 4380},
{1183, 4385, 4391},
{3778, 4403, 4405},
{3642, 4409, 4411},
{2593, 4419, 4419},
{4160, 4430, 4431},
{3204, 4441, 4441},
{2875, 4450, 4451},
{1265, 4455, 4457},
{3927, 4466, 4466},
{416, 4479, 4480},
{4474, 4489, 4490},
{4135, 4502, 4504},
{4314, 4511, 4518},
{1870, 4529, 4529},
{3188, 4534, 4535},
{777, 4541, 4542},
{2370, 4549, 4552},
{1795, 4556, 4558},
{1529, 4577, 4577},
{4298, 4581, 4584},
{4336, 4596, 4596},
{1423, 4602, 4602},
{1004, 4608, 4608},
{4580, 4615, 4615},
{4003, 4619, 4623},
{4593, 4627, 4628},
{2680, 4644, 4644},
{2259, 4650, 4650},
{2544, 4654, 4655},
{4320, 4660, 4661},
{4511, 4672, 4673},
{4545, 4677, 4680},
{4570, 4689, 4696},
{2505, 4700, 4700},
{4605, 4706, 4712},
{3243, 4717, 4722},
{4581, 4726, 4734},
{3852, 4747, 4748},
{4653, 4756, 4758},
{4409, 4762, 4764},
{3165, 4774, 4774},
{2100, 4780, 4780},
{3722, 4784, 4786},
{4756, 4798, 4811},
{4422, 4815, 4815},
{3124, 4819, 4819},
{714, 4825, 4827},
{4699, 4832, 4832},
{4725, 4836, 4839},
{4588, 4844, 4845},
{1469, 4849, 4849},
{4743, 4853, 4863},
{4836, 4869, 4869},
{2682, 4873, 4873},
{4774, 4877, 4877},
{4738, 4881, 4882},
{4784, 4886, 4892},
{2759, 4896, 4896},
{4795, 4900, 4900},
{4378, 4905, 4905},
{1050, 4909, 4912},
{4634, 4917, 4918},
{4654, 4922, 4923},
{1542, 4930, 4930},
{4658, 4934, 4937},
{4762, 4941, 4943},
{4751, 4949, 4950},
{4286, 4961, 4961},
{1377, 4965, 4965},
{4587, 4971, 4973},
{2575, 4977, 4978},
{4922, 4982, 4983},
{4941, 4987, 4992},
{4790, 4996, 5000},
{4070, 5004, 5005},
{4538, 5009, 5012},
{4659, 5016, 5018},
{4926, 5024, 5034},
{3884, 5038, 5042},
{3853, 5046, 5048},
{4752, 5053, 5053},
{4954, 5057, 5057},
{4877, 5063, 5063},
{4977, 5067, 5067},
{2418, 5071, 5071},
{4968, 5075, 5075},
{681, 5079, 5080},
{5074, 5086, 5087},
{5016, 5091, 5092},
{2196, 5096, 5097},
{1782, 5107, 5108},
{5061, 5112, 5113},
{5096, 5117, 5118},
{1563, 5127, 5128},
{4872, 5134, 5135},
{1324, 5139, 5139},
{5111, 5144, 5148},
{4987, 5152, 5154},
{5075, 5158, 5175},
{4685, 5181, 5181},
{4961, 5185, 5185},
{1564, 5192, 5192},
{2982, 5198, 5199},
{917, 5203, 5203},
{4419, 5208, 5208},
{4507, 5213, 5213},
{5083, 5217, 5217},
{5091, 5221, 5222},
{3373, 5226, 5226},
{4475, 5231, 5231},
{4496, 5238, 5239},
{1255, 5243, 5244},
{3680, 5254, 5256},
{5157, 5260, 5261},
{4508, 5265, 5274},
{4946, 5279, 5279},
{1860, 5285, 5285},
{889, 5289, 5289},
{785, 5293, 5297},
{2290, 5303, 5303},
{2931, 5310, 5310},
{5021, 5316, 5316},
{2571, 5323, 5323},
{5071, 5327, 5327},
{5084, 5331, 5333},
{4614, 5342, 5343},
{4899, 5347, 5347},
{4441, 5351, 5351},
{5327, 5355, 5358},
{5063, 5362, 5362},
{3974, 5367, 5367},
{5316, 5382, 5382},
{2528, 5389, 5389},
{1391, 5393, 5393},
{2582, 5397, 5401},
{3074, 5405, 5407},
{4010, 5412, 5412},
{5382, 5420, 5420},
{5243, 5429, 5442},
{5265, 5447, 5447},
{5278, 5451, 5475},
{5319, 5479, 5483},
{1158, 5488, 5488},
{5423, 5494, 5496},
{5355, 5500, 5503},
{5283, 5507, 5509},
{5340, 5513, 5515},
{3841, 5530, 5530},
{1069, 5535, 5537},
{4970, 5541, 5544},
{5386, 5548, 5550},
{2916, 5556, 5563},
{4023, 5570, 5570},
{1215, 5576, 5576},
{4665, 5580, 5581},
{4402, 5585, 5586},
{5446, 5592, 5593},
{5330, 5597, 5597},
{5221, 5601, 5602},
{5300, 5606, 5608},
{4626, 5612, 5614},
{3660, 5618, 5618},
{2405, 5623, 5623},
{3486, 5628, 5633},
{3143, 5645, 5645},
{5606, 5650, 5650},
{5158, 5654, 5654},
{5378, 5658, 5658},
{4057, 5663, 5663},
{5107, 5670, 5670},
{4886, 5674, 5676},
{5654, 5680, 5680},
{5307, 5684, 5687},
{2449, 5691, 5691},
{5331, 5695, 5696},
{3215, 5700, 5700},
{5447, 5704, 5704},
{5650, 5708, 5708},
{4965, 5712, 5715},
{102, 5722, 5723},
{2753, 5733, 5735},
{5695, 5739, 5744},
{2182, 5748, 5748},
{4903, 5753, 5753},
{5507, 5757, 5759},
{5347, 5763, 5778},
{5548, 5782, 5784},
{5392, 5788, 5798},
{2304, 5803, 5803},
{4643, 5810, 5810},
{5703, 5815, 5817},
{4355, 5821, 5821},
{5429, 5825, 5826},
{3624, 5830, 5831},
{5711, 5836, 5836},
{5580, 5840, 5844},
{1909, 5848, 5848},
{4933, 5853, 5857},
{5100, 5863, 5870},
{4904, 5875, 5876},
{4529, 5883, 5883},
{3220, 5892, 5893},
{1533, 5897, 5897},
{4780, 5904, 5904},
{3101, 5908, 5909},
{5627, 5914, 5920},
{4166, 5926, 5929},
{5596, 5933, 5934},
{5680, 5938, 5938},
{4849, 5942, 5942},
{5739, 5948, 5949},
{5533, 5961, 5961},
{849, 5972, 5972},
{3752, 5989, 5990},
{2158, 5996, 5996},
{4982, 6000, 6001},
{5601, 6005, 6007},
{5101, 6014, 6021},
{4726, 6025, 6025},
{5720, 6036, 6039},
{4534, 6045, 6046},
{5763, 6050, 6050},
{5914, 6057, 6063},
{1492, 6067, 6067},
{2160, 6075, 6078},
{4619, 6083, 6083},
{893, 6092, 6093},
{5948, 6097, 6097},
{2556, 6105, 6106},
{1615, 6110, 6110},
{1156, 6114, 6120},
{5699, 6128, 6128},
{2710, 6132, 6133},
{4446, 6138, 6138},
{5815, 6143, 6148},
{1254, 6152, 6161},
{2357, 6167, 6168},
{2144, 6172, 6176},
{2159, 6184, 6184},
{5810, 6188, 6190},
{4011, 6195, 6195},
{6070, 6199, 6199},
{6005, 6203, 6206},
{4683, 6211, 6213},
{4466, 6221, 6222},
{5230, 6226, 6231},
{5238, 6235, 6239},
{5250, 6246, 6253},
{5704, 6257, 6257},
{5451, 6261, 6286},
{181, 6293, 6293},
{5314, 6297, 6305},
{5788, 6314, 6316},
{5938, 6320, 6320},
{4844, 6324, 6325},
{5782, 6329, 6332},
{5628, 6336, 6337},
{4873, 6341, 6342},
{6110, 6346, 6346},
{6328, 6350, 6354},
{1036, 6358, 6359},
{6128, 6364, 6364},
{4740, 6373, 6373},
{2282, 6377, 6377},
{5405, 6386, 6388},
{6257, 6392, 6392},
{4123, 6396, 6397},
{5487, 6401, 6410},
{6290, 6414, 6415},
{3844, 6423, 6424},
{3888, 6428, 6428},
{1086, 6432, 6432},
{5320, 6436, 6439},
{6310, 6443, 6444},
{6401, 6448, 6448},
{5124, 6452, 6452},
{5424, 6456, 6457},
{5851, 6472, 6478},
{6050, 6482, 6482},
{5499, 6486, 6490},
{4900, 6498, 6500},
{5674, 6510, 6512},
{871, 6518, 6520},
{5748, 6528, 6528},
{6447, 6533, 6534},
{5820, 6538, 6539},
{6448, 6543, 6543},
{6199, 6547, 6547},
{6320, 6551, 6551},
{1882, 6555, 6555},
{6368, 6561, 6566},
{6097, 6570, 6570},
{6495, 6576, 6579},
{5821, 6583, 6583},
{6507, 6587, 6587},
{4454, 6596, 6596},
{2324, 6601, 6601},
{6547, 6608, 6608},
{5712, 6612, 6612},
{5575, 6618, 6619},
{6414, 6623, 6624},
{6296, 6629, 6629},
{4134, 6633, 6634},
{6561, 6640, 6644},
{4555, 6649, 6652},
{4671, 6659, 6660},
{5592, 6664, 6666},
{5152, 6670, 6672},
{6599, 6676, 6676},
{5521, 6680, 6691},
{6432, 6695, 6695},
{6623, 6699, 6705},
{2601, 6712, 6712},
{5117, 6723, 6724},
{6524, 6730, 6733},
{5351, 6737, 6737},
{6573, 6741, 6741},
{6392, 6745, 6746},
{6592, 6750, 6751},
{4650, 6760, 6761},
{5302, 6765, 6765},
{6615, 6770, 6783},
{3732, 6787, 6789},
{6709, 6793, 6793},
{5306, 6797, 6797},
{6243, 6801, 6802},
{5226, 6808, 6816},
{4497, 6821, 6821},
{1436, 6825, 6825},
{1790, 6833, 6834},
{5525, 6838, 6843},
{5279, 6847, 6849},
{6828, 6855, 6857},
{5038, 6861, 6865},
{6741, 6869, 6869},
{4627, 6873, 6873},
{4037, 6878, 6880},
{10, 6885, 6887},
{6730, 6894, 6894},
{5528, 6898, 6898},
{6744, 6903, 6903},
{5839, 6907, 6907},
{2350, 6911, 6911},
{2269, 6915, 6918},
{6869, 6922, 6922},
{6035, 6929, 6930},
{1604, 6938, 6939},
{6922, 6943, 6943},
{6699, 6947, 6950},
{6737, 6954, 6954},
{1775, 6958, 6959},
{5309, 6963, 6964},
{6954, 6968, 6968},
{6369, 6972, 6976},
{3789, 6980, 6983},
{2327, 6990, 6990},
{6837, 6995, 7001},
{4485, 7006, 7013},
{6820, 7017, 7031},
{6291, 7036, 7036},
{5691, 7041, 7042},
{7034, 7047, 7047},
{5310, 7051, 7051},
{1502, 7056, 7056},
{4797, 7061, 7061},
{6855, 7066, 7068},
{6669, 7072, 7075},
{6943, 7079, 7079},
{6528, 7083, 7083},
{4036, 7087, 7090},
{6884, 7094, 7100},
{6946, 7104, 7108},
{6297, 7112, 7114},
{5684, 7118, 7121},
{6903, 7127, 7135},
{3580, 7141, 7147},
{6926, 7152, 7182},
{7117, 7186, 7190},
{6968, 7194, 7217},
{6838, 7222, 7227},
{7005, 7231, 7240},
{6235, 7244, 7245},
{6825, 7249, 7249},
{4594, 7254, 7254},
{6569, 7258, 7258},
{7222, 7262, 7267},
{7047, 7272, 7272},
{6801, 7276, 7276},
{7056, 7280, 7280},
{6583, 7284, 7284},
{5825, 7288, 7294},
{6787, 7298, 7300},
{7079, 7304, 7304},
{7253, 7308, 7313},
{6891, 7317, 7317},
{6829, 7321, 7322},
{7257, 7326, 7363},
{7231, 7367, 7377},
{2854, 7381, 7381},
{7249, 7385, 7385},
{6203, 7389, 7391},
{6363, 7395, 7397},
{6745, 7401, 7402},
{6695, 7406, 7406},
{5208, 7410, 7411},
{6679, 7415, 7416},
{7288, 7420, 7421},
{5248, 7425, 7425},
{6422, 7429, 7429},
{5206, 7434, 7436},
{2255, 7441, 7442},
{2145, 7452, 7452},
{7283, 7458, 7459},
{4830, 7469, 7472},
{6000, 7476, 7477},
{7395, 7481, 7492},
{2715, 7496, 7496},
{6542, 7500, 7502},
{7420, 7506, 7513},
{4981, 7517, 7517},
{2243, 7522, 7524},
{916, 7528, 7529},
{5207, 7533, 7534},
{1271, 7538, 7539},
{2654, 7544, 7544},
{7451, 7553, 7561},
{7464, 7569, 7571},
{3992, 7577, 7577},
{3114, 7581, 7581},
{7389, 7589, 7591},
{7433, 7595, 7598},
{7448, 7602, 7608},
{1772, 7612, 7612},
{4152, 7616, 7616},
{3247, 7621, 7624},
{963, 7629, 7630},
{4895, 7640, 7640},
{6164, 7646, 7646},
{4339, 7663, 7664},
{3244, 7668, 7672},
{7304, 7676, 7676},
{7401, 7680, 7681},
{6670, 7685, 7688},
{6195, 7692, 7693},
{7505, 7699, 7705},
{5252, 7709, 7710},
{6193, 7715, 7718},
{1916, 7724, 7724},
{4868, 7729, 7731},
{1176, 7736, 7736},
{5700, 7740, 7740},
{5757, 7744, 7746},
{6345, 7750, 7752},
{3132, 7756, 7759},
{4312, 7763, 7763},
{7685, 7767, 7769},
{6907, 7774, 7774},
{5584, 7779, 7780},
{6025, 7784, 7784},
{4435, 7791, 7798},
{6807, 7809, 7817},
{6234, 7823, 7825},
{7385, 7829, 7829},
{1286, 7833, 7836},
{7258, 7840, 7840},
{7602, 7844, 7850},
{7388, 7854, 7856},
{7528, 7860, 7866},
{640, 7874, 7875},
{7844, 7879, 7886},
{4700, 7890, 7890},
{7440, 7894, 7896},
{4831, 7900, 7902},
{4556, 7906, 7908},
{7547, 7914, 7924},
{7589, 7928, 7929},
{7914, 7935, 7945},
{7284, 7949, 7949},
{7538, 7953, 7957},
{4635, 7964, 7964},
{1994, 7968, 7970},
{7406, 7974, 7976},
{2409, 7983, 7983},
{7542, 7989, 7989},
{7112, 7993, 7993},
{5259, 7997, 7999},
{1287, 8004, 8006},
{7911, 8010, 8011},
{7449, 8015, 8021},
{7928, 8025, 8027},
{1476, 8042, 8044},
{7784, 8048, 8050},
{4434, 8054, 8062},
{7802, 8066, 8074},
{7367, 8087, 8088},
{4494, 8094, 8097},
{7829, 8101, 8101},
{7321, 8105, 8111},
{7035, 8115, 8121},
{7949, 8125, 8125},
{7506, 8129, 8130},
{5830, 8134, 8135},
{8047, 8144, 8144},
{5362, 8148, 8148},
{8125, 8152, 8152},
{7676, 8156, 8156},
{6324, 8160, 8161},
{6606, 8173, 8173},
{7064, 8177, 8182},
{6993, 8186, 8199},
{8092, 8203, 8204},
{7244, 8208, 8213},
{8105, 8217, 8218},
{8185, 8222, 8222},
{8115, 8226, 8232},
{4164, 8238, 8239},
{6608, 8244, 8244},
{8176, 8248, 8277},
{8208, 8281, 8282},
{7997, 8287, 8289},
{7118, 8293, 8303},
{7103, 8308, 8308},
{6436, 8312, 8315},
{3523, 8321, 8321},
{6442, 8327, 8329},
{3391, 8333, 8334},
{6986, 8339, 8344},
{7221, 8348, 8354},
{5989, 8358, 8360},
{4418, 8364, 8365},
{8307, 8369, 8370},
{7051, 8375, 8375},
{4027, 8379, 8380},
{8333, 8384, 8387},
{6873, 8391, 8392},
{4154, 8396, 8399},
{6878, 8403, 8428},
{8087, 8432, 8438},
{7017, 8442, 8443},
{8129, 8447, 8453},
{6486, 8457, 8461},
{8248, 8465, 8465},
{6349, 8473, 8478},
{5393, 8482, 8483},
{8465, 8487, 8487},
{30, 8495, 8495},
{4642, 8499, 8500},
{6768, 8505, 8505},
{7061, 8513, 8514},
{7151, 8518, 8528},
{6648, 8532, 8532},
{2093, 8539, 8539},
{3392, 8544, 8544},
{6980, 8548, 8551},
{8217, 8555, 8563},
{8375, 8567, 8567},
{7041, 8571, 8571},
{5008, 8576, 8576},
{4796, 8580, 8582},
{4271, 8586, 8586},
{7320, 8591, 8593},
{8222, 8597, 8597},
{7262, 8601, 8606},
{8432, 8610, 8615},
{8442, 8619, 8620},
{8101, 8624, 8624},
{7308, 8628, 8628},
{8597, 8632, 8641},
{8498, 8645, 8645},
{927, 8650, 8651},
{5979, 8661, 8661},
{5381, 8665, 8666},
{2184, 8675, 8675},
{5342, 8680, 8681},
{1527, 8686, 8687},
{4168, 8694, 8694},
{8332, 8698, 8702},
{8628, 8706, 8710},
{8447, 8714, 8720},
{8610, 8724, 8724},
{5530, 8730, 8730},
{6472, 8734, 8734},
{7476, 8738, 8739},
{7756, 8743, 8743},
{8570, 8749, 8753},
{2706, 8757, 8759},
{5875, 8763, 8764},
{8147, 8769, 8770},
{6526, 8775, 8776},
{8694, 8780, 8780},
{3431, 8784, 8785},
{7787, 8789, 8789},
{5526, 8794, 8796},
{6902, 8800, 8801},
{8756, 8811, 8818},
{7735, 8822, 8823},
{5523, 8827, 8828},
{5668, 8833, 8833},
{2237, 8839, 8839},
{8152, 8843, 8846},
{6633, 8852, 8853},
{6152, 8858, 8865},
{8762, 8869, 8870},
{6216, 8876, 8878},
{8632, 8882, 8892},
{2436, 8896, 8897},
{5541, 8901, 8904},
{8293, 8908, 8911},
{7194, 8915, 8915},
{5658, 8919, 8919},
{5045, 8923, 8927},
{7549, 8932, 8932},
{1623, 8936, 8941},
{6471, 8946, 8947},
{8487, 8951, 8951},
{8714, 8955, 8961},
{8574, 8965, 8965},
{2701, 8969, 8970},
{5500, 8974, 8977},
{8481, 8984, 8986},
{5416, 8991, 8991},
{8950, 8996, 8996},
{8706, 9001, 9005},
{8601, 9009, 9014},
{8882, 9018, 9018},
{8951, 9022, 9022},
{1521, 9026, 9026},
{8025, 9030, 9031},
{8645, 9035, 9035},
{8384, 9039, 9042},
{9001, 9046, 9050},
{3189, 9054, 9054},
{8955, 9058, 9065},
{1043, 9078, 9079},
{8974, 9083, 9095},
{6496, 9099, 9100},
{8995, 9104, 9105},
{9045, 9109, 9110},
{6395, 9114, 9116},
{9038, 9125, 9125},
{9029, 9135, 9138},
{1051, 9144, 9147},
{7833, 9151, 9155},
{9022, 9159, 9159},
{9046, 9163, 9163},
{2732, 9168, 9170},
{7750, 9174, 9180},
{8747, 9184, 9186},
{7663, 9192, 9193},
{9159, 9197, 9197},
{8730, 9207, 9209},
{4429, 9223, 9223},
{8536, 9227, 9227},
{1231, 9237, 9237},
{8965, 9244, 9244},
{5840, 9248, 9254},
{4058, 9263, 9270},
{3214, 9288, 9289},
{6346, 9293, 9293},
{6114, 9297, 9298},
{9104, 9302, 9302},
{4818, 9331, 9332},
{8513, 9336, 9337},
{6971, 9341, 9346},
{8779, 9357, 9357},
{8989, 9363, 9367},
{8843, 9371, 9373},
{9035, 9381, 9382},
{3648, 9386, 9386},
{6988, 9390, 9403},
{8869, 9407, 9407},
{7767, 9411, 9413},
{6341, 9417, 9417},
{2293, 9424, 9424},
{9360, 9428, 9428},
{8048, 9432, 9435},
{8981, 9439, 9439},
{6336, 9443, 9444},
{9431, 9449, 9453},
{8391, 9457, 9458},
{9380, 9463, 9464},
{6947, 9468, 9471},
{7993, 9475, 9475},
{7185, 9479, 9484},
{5848, 9488, 9488},
{9371, 9492, 9492},
{7628, 9498, 9500},
{8757, 9504, 9504},
{9410, 9508, 9508},
{9293, 9512, 9512},
{5138, 9516, 9516},
{9420, 9521, 9521},
{4416, 9525, 9528},
{4825, 9534, 9536},
{9057, 9540, 9540},
{7276, 9544, 9546},
{5491, 9550, 9550},
{9058, 9554, 9560},
{8321, 9569, 9569},
{6357, 9573, 9575},
{9385, 9579, 9579},
{6972, 9583, 9587},
{7996, 9591, 9594},
{8990, 9598, 9599},
{9442, 9603, 9605},
{9579, 9609, 9609},
{9389, 9613, 9628},
{8789, 9632, 9632},
{7152, 9636, 9646},
{9491, 9652, 9653},
{2493, 9658, 9659},
{2456, 9663, 9664},
{8509, 9672, 9675},
{6510, 9682, 9684},
{2533, 9688, 9688},
{6632, 9696, 9698},
{4460, 9709, 9711},
{9302, 9715, 9718},
{9609, 9722, 9722},
{4824, 9728, 9731},
{9553, 9735, 9735},
{9544, 9739, 9742},
{9492, 9746, 9746},
{9554, 9750, 9756},
{9525, 9761, 9764},
{7789, 9769, 9769},
{2136, 9773, 9777},
{3848, 9782, 9783},
{9432, 9787, 9790},
{8165, 9794, 9795},
{9590, 9799, 9803},
{8555, 9807, 9812},
{9009, 9816, 9822},
{9656, 9829, 9833},
{4101, 9841, 9841},
{6382, 9846, 9846},
{9721, 9850, 9850},
{9296, 9854, 9856},
{9573, 9860, 9866},
{9636, 9870, 9883},
{9722, 9887, 9887},
{9163, 9891, 9891},
{9799, 9895, 9895},
{9816, 9899, 9906},
{767, 9912, 9913},
{8287, 9918, 9923},
{6293, 9927, 9930},
{9726, 9934, 9934},
{6876, 9939, 9940},
{5847, 9945, 9946},
{9829, 9951, 9955},
{9125, 9962, 9962},
{8542, 9967, 9972},
{9767, 9978, 9978},
{4165, 9982, 9982},
{8243, 9986, 9987},
{9682, 9993, 9995},
{4916, 10006, 10010},
{9456, 10016, 10018},
{9761, 10024, 10029},
{9886, 10033, 10034},
{9468, 10038, 10044},
{3000, 10052, 10053},
{9807, 10057, 10062},
{8226, 10066, 10072},
{9650, 10077, 10080},
{9054, 10084, 10084},
{9891, 10088, 10089},
{6518, 10095, 10097},
{8238, 10101, 10117},
{7890, 10121, 10123},
{9894, 10128, 10138},
{3508, 10142, 10143},
{6377, 10147, 10147},
{3768, 10152, 10154},
{6764, 10158, 10160},
{8852, 10164, 10166},
{2867, 10172, 10174},
{4461, 10178, 10179},
{5889, 10184, 10185},
{9917, 10189, 10191},
{6797, 10195, 10195},
{8567, 10199, 10199},
{7125, 10203, 10206},
{9938, 10210, 10234},
{9967, 10240, 10246},
{8923, 10251, 10254},
{10157, 10258, 10258},
{8032, 10264, 10264},
{9887, 10268, 10276},
{9750, 10280, 10286},
{10258, 10290, 10290},
{10268, 10294, 10302},
{9899, 10306, 10311},
{9715, 10315, 10318},
{8539, 10322, 10322},
{10189, 10327, 10329},
{9135, 10333, 10335},
{8369, 10340, 10341},
{9119, 10347, 10347},
{10290, 10352, 10352},
{7900, 10357, 10359},
{3275, 10363, 10365},
{10294, 10369, 10369},
{5417, 10376, 10376},
{10120, 10381, 10381},
{9786, 10385, 10395},
{9826, 10399, 10399},
{8171, 10403, 10407},
{8402, 10421, 10425},
{9428, 10429, 10429},
{1863, 10434, 10435},
{3092, 10446, 10446},
{10000, 10450, 10450},
{9986, 10463, 10464},
{9632, 10468, 10484},
{10315, 10489, 10489},
{10332, 10493, 10493},
{8914, 10506, 10507},
{10369, 10511, 10512},
{1865, 10516, 10517},
{9204, 10521, 10526},
{9993, 10533, 10534},
{2568, 10539, 10539},
{10429, 10543, 10543},
{10489, 10549, 10549},
{10014, 10553, 10558},
{10024, 10563, 10573},
{9457, 10577, 10578},
{9591, 10582, 10585},
{8908, 10589, 10592},
{10203, 10596, 10598},
{10006, 10602, 10604},
{10209, 10613, 10613},
{4996, 10617, 10617},
{9846, 10621, 10622},
{6927, 10627, 10635},
{8664, 10639, 10639},
{8586, 10643, 10644},
{10576, 10648, 10650},
{10487, 10654, 10656},
{10553, 10660, 10664},
{10563, 10670, 10679},
{9000, 10683, 10688},
{10280, 10692, 10699},
{10582, 10703, 10706},
{9934, 10710, 10710},
{10547, 10714, 10716},
{7065, 10720, 10724},
{10691, 10730, 10738},
{872, 10742, 10744},
{10357, 10751, 10752},
{1323, 10756, 10756},
{10087, 10761, 10763},
{9381, 10769, 10769},
{9982, 10773, 10778},
{10533, 10784, 10785},
{9687, 10789, 10789},
{8324, 10799, 10799},
{8742, 10805, 10813},
{9039, 10817, 10824},
{5947, 10828, 10828},
{10306, 10832, 10837},
{10261, 10841, 10843},
{10350, 10847, 10850},
{7415, 10860, 10861},
{19, 10866, 10866},
{10188, 10872, 10875},
{10613, 10881, 10881},
{7869, 10886, 10886},
{3801, 10891, 10892},
{9099, 10896, 10897},
{8738, 10903, 10904},
{10322, 10908, 10908},
{6494, 10912, 10916},
{9772, 10921, 10921},
{8170, 10927, 10930},
{7456, 10940, 10943},
{10457, 10948, 10952},
{1405, 10959, 10959},
{6936, 10963, 10963},
{4549, 10970, 10975},
{4880, 10982, 10982},
{8763, 10986, 10987},
{4565, 10993, 10994},
{1310, 11000, 11000},
{4596, 11010, 11010},
{6427, 11015, 11016},
{7729, 11023, 11024},
{10978, 11029, 11030},
{10947, 11034, 11039},
{10577, 11043, 11043},
{10542, 11052, 11053},
{9443, 11057, 11058},
{10468, 11062, 11062},
{11028, 11066, 11068},
{10057, 11072, 11073},
{8881, 11077, 11078},
{8148, 11082, 11082},
{10816, 11089, 11093},
{11066, 11097, 11109},
{10511, 11113, 11113},
{9174, 11117, 11119},
{10345, 11125, 11125},
{4532, 11129, 11129},
{9918, 11133, 11134},
{8858, 11138, 11146},
{10703, 11150, 11153},
{9030, 11157, 11160},
{6481, 11165, 11166},
{10543, 11170, 11170},
{8580, 11177, 11178},
{10886, 11184, 11187},
{10210, 11191, 11197},
{2015, 11202, 11202},
{9312, 11211, 11218},
{9324, 11223, 11231},
{10884, 11235, 11235},
{8166, 11239, 11239},
{10502, 11243, 11250},
{11182, 11254, 11259},
{5366, 11263, 11264},
{3676, 11268, 11268},
{5649, 11273, 11274},
{11065, 11281, 11284},
{11034, 11288, 11293},
{7083, 11297, 11297},
{9550, 11302, 11302},
{9336, 11310, 11311},
{7071, 11316, 11316},
{11314, 11320, 11320},
{11113, 11324, 11324},
{11157, 11328, 11330},
{6482, 11334, 11334},
{7139, 11338, 11338},
{10152, 11345, 11345},
{3554, 11352, 11356},
{11190, 11364, 11364},
{11324, 11368, 11368},
{10710, 11372, 11372},
{8793, 11376, 11381},
{6358, 11385, 11386},
{11368, 11390, 11390},
{9704, 11394, 11396},
{7778, 11400, 11400},
{11149, 11404, 11408},
{10889, 11414, 11414},
{9781, 11421, 11422},
{10267, 11426, 11427},
{11328, 11431, 11433},
{5751, 11439, 11440},
{10817, 11444, 11447},
{10896, 11451, 11452},
{10751, 11456, 11457},
{10163, 11461, 11461},
{10504, 11466, 11473},
{8743, 11477, 11484},
{11150, 11488, 11491},
{10088, 11495, 11495},
{10828, 11499, 11509},
{11444, 11513, 11516},
{11495, 11520, 11520},
{11487, 11524, 11524},
{10692, 11528, 11535},
{9121, 11540, 11546},
{11389, 11558, 11564},
{10195, 11568, 11578},
{5004, 11582, 11583},
{5908, 11588, 11588},
{11170, 11592, 11592},
{11253, 11597, 11597},
{11372, 11601, 11601},
{3115, 11605, 11605},
{11390, 11609, 11609},
{10832, 11613, 11616},
{8800, 11620, 11621},
{11384, 11625, 11631},
{10171, 11635, 11637},
{11400, 11642, 11650},
{11451, 11654, 11655},
{11419, 11661, 11664},
{11608, 11668, 11669},
{11431, 11673, 11680},
{11550, 11688, 11690},
{11609, 11694, 11694},
{10588, 11702, 11708},
{6664, 11712, 11712},
{11461, 11719, 11753},
{11524, 11757, 11757},
{11613, 11761, 11764},
{10257, 11769, 11770},
{11694, 11774, 11774},
{11520, 11778, 11781},
{11138, 11785, 11793},
{11539, 11797, 11797},
{11512, 11802, 11802},
{10602, 11808, 11812},
{11773, 11816, 11824},
{11760, 11828, 11835},
{9083, 11839, 11850},
{11654, 11855, 11857},
{6612, 11861, 11862},
{11816, 11866, 11875},
{11528, 11879, 11897},
{10549, 11901, 11901},
{9108, 11905, 11907},
{11757, 11911, 11920},
{837, 11924, 11928},
{11855, 11932, 11934},
{8482, 11938, 11939},
{9439, 11943, 11943},
{1068, 11950, 11953},
{10789, 11958, 11958},
{4611, 11963, 11964},
{11861, 11968, 11992},
{11797, 11997, 12004},
{11719, 12009, 12009},
{11774, 12013, 12013},
{756, 12017, 12019},
{10178, 12023, 12024},
{9258, 12028, 12047},
{9534, 12060, 12063},
{12013, 12067, 12067},
{8160, 12071, 12072},
{10865, 12076, 12083},
{9311, 12091, 12099},
{11223, 12104, 12115},
{11932, 12119, 12120},
{2925, 12130, 12130},
{6906, 12135, 12136},
{8895, 12143, 12143},
{4684, 12147, 12148},
{11642, 12152, 12152},
{5573, 12160, 12164},
{10459, 12168, 12168},
{2108, 12172, 12172},
{187, 12179, 12180},
{2358, 12184, 12184},
{11796, 12188, 12188},
{1963, 12192, 12192},
{2538, 12199, 12200},
{6497, 12206, 12206},
{6723, 12210, 12211},
{7657, 12216, 12216},
{12204, 12224, 12231},
{1080, 12239, 12240},
{12224, 12244, 12246},
{11911, 12250, 12250},
{9912, 12266, 12268},
{7616, 12272, 12272},
{1956, 12279, 12279},
{1522, 12283, 12285},
{9504, 12289, 12290},
{11672, 12297, 12300},
{10621, 12304, 12304},
{11592, 12308, 12308},
{11385, 12312, 12313},
{3281, 12317, 12317},
{3487, 12321, 12321},
{9417, 12325, 12325},
{9613, 12335, 12337},
{10670, 12342, 12348},
{10589, 12352, 12357},
{10616, 12362, 12363},
{9326, 12369, 12375},
{5211, 12379, 12382},
{12304, 12386, 12395},
{1048, 12399, 12399},
{12335, 12403, 12405},
{12250, 12410, 12410},
{10084, 12414, 12414},
{11394, 12418, 12421},
{12126, 12425, 12429},
{9582, 12433, 12438},
{10784, 12445, 12447},
{9568, 12454, 12455},
{12308, 12459, 12459},
{9635, 12464, 12475},
{11513, 12479, 12482},
{12119, 12486, 12487},
{12066, 12494, 12495},
{12403, 12499, 12502},
{11687, 12506, 12513},
{12418, 12517, 12519},
{12352, 12523, 12528},
{11600, 12532, 12532},
{12450, 12539, 12539},
{12067, 12543, 12543},
{11477, 12547, 12565},
{11540, 12569, 12575},
{11202, 12580, 12581},
{10903, 12585, 12586},
{11601, 12590, 12590},
{12459, 12599, 12599},
{11839, 12603, 12605},
{11426, 12609, 12610},
{12486, 12614, 12616},
{9406, 12621, 12621},
{6897, 12625, 12628},
{12312, 12632, 12633},
{12445, 12638, 12640},
{1743, 12645, 12645},
{11551, 12649, 12650},
{12543, 12654, 12654},
{11635, 12658, 12660},
{12522, 12664, 12675},
{12539, 12683, 12712},
{11801, 12716, 12721},
{5803, 12725, 12725},
{716, 12730, 12732},
{8900, 12736, 12740},
{12076, 12744, 12746},
{5046, 12751, 12751},
{12735, 12755, 12755},
{11879, 12759, 12766},
{1609, 12770, 12770},
{10921, 12774, 12774},
{11420, 12778, 12778},
{12754, 12783, 12784},
{12177, 12788, 12788},
{12191, 12792, 12792},
{12139, 12798, 12802},
{11082, 12806, 12806},
{12152, 12810, 12810},
{10381, 12814, 12814},
{11239, 12820, 12821},
{2198, 12825, 12826},
{6123, 12832, 12832},
{10642, 12836, 12839},
{11117, 12843, 12844},
{12210, 12848, 12849},
{9688, 12853, 12853},
{12832, 12857, 12860},
{12147, 12864, 12870},
{12028, 12874, 12893},
{12052, 12898, 12898},
{8202, 12902, 12903},
{7243, 12907, 12909},
{8014, 12913, 12920},
{7680, 12924, 12931},
{11056, 12939, 12941},
{3817, 12946, 12949},
{9390, 12954, 12954},
{12249, 12958, 12960},
{12237, 12966, 12969},
{12638, 12973, 12975},
{12386, 12979, 12979},
{10626, 12984, 12997},
{6793, 13005, 13005},
{10625, 13009, 13025},
{12963, 13029, 13029},
{10038, 13033, 13036},
{12599, 13040, 13041},
{11568, 13046, 13050},
{13040, 13054, 13054},
{11238, 13058, 13060},
{5125, 13064, 13064},
{12425, 13068, 13080},
{9760, 13084, 13088},
{12729, 13092, 13093},
{9672, 13097, 13099},
{3675, 13104, 13104},
{6055, 13108, 13112},
{2681, 13119, 13120},
{12843, 13124, 13125},
{12952, 13129, 13132},
{13063, 13137, 13137},
{5861, 13141, 13141},
{10948, 13145, 13149},
{3080, 13153, 13153},
{12743, 13158, 13158},
{13123, 13163, 13166},
{11043, 13170, 13171},
{13136, 13175, 13176},
{12796, 13180, 13181},
{13107, 13185, 13185},
{13156, 13192, 13202},
{12954, 13207, 13208},
{8648, 13213, 13231},
{10403, 13235, 13235},
{12603, 13239, 13239},
{13029, 13243, 13243},
{6420, 13251, 13251},
{5801, 13261, 13265},
{8901, 13269, 13272},
{5139, 13276, 13278},
{8036, 13282, 13283},
{8041, 13288, 13288},
{10871, 13293, 13297},
{12923, 13301, 13303},
{10340, 13307, 13308},
{9926, 13312, 13316},
{9478, 13320, 13328},
{4571, 13334, 13339},
{8325, 13343, 13343},
{10933, 13349, 13349},
{9515, 13354, 13354},
{10979, 13358, 13358},
{7500, 13364, 13366},
{12820, 13371, 13375},
{13068, 13380, 13392},
{8724, 13397, 13397},
{8624, 13401, 13401},
{13206, 13405, 13406},
{12939, 13410, 13412},
{11015, 13417, 13418},
{12924, 13422, 13423},
{13103, 13427, 13431},
{13353, 13435, 13435},
{13415, 13440, 13443},
{10147, 13447, 13448},
{13180, 13452, 13457},
{12751, 13461, 13461},
{2291, 13465, 13465},
{12168, 13469, 13471},
{7744, 13475, 13477},
{6386, 13488, 13490},
{12755, 13494, 13494},
{13482, 13498, 13499},
{12410, 13503, 13503},
{13494, 13507, 13507},
{11376, 13511, 13516},
{13422, 13520, 13521},
{10742, 13525, 13527},
{1528, 13531, 13531},
{7517, 13537, 13537},
{4930, 13541, 13542},
{13507, 13546, 13546},
{13033, 13550, 13553},
{9475, 13557, 13568},
{12805, 13572, 13572},
{6188, 13576, 13578},
{12770, 13582, 13587},
{12648, 13593, 13594},
{13054, 13598, 13598},
{8856, 13603, 13613},
{1046, 13618, 13619},
{13348, 13623, 13624},
{13520, 13628, 13628},
{10142, 13632, 13633},
{13434, 13643, 13643},
{5488, 13648, 13648},
{649, 13652, 13652},
{11272, 13657, 13657},
{12873, 13663, 13663},
{4631, 13670, 13670},
{12578, 13674, 13677},
{12091, 13684, 13692},
{13581, 13699, 13699},
{13549, 13704, 13708},
{13598, 13712, 13712},
{13320, 13716, 13722},
{13712, 13726, 13726},
{13370, 13730, 13731},
{11352, 13735, 13737},
{13601, 13742, 13742},
{13497, 13746, 13769},
{12973, 13773, 13775},
{11235, 13784, 13784},
{10627, 13788, 13796},
{13152, 13800, 13800},
{12585, 13804, 13804},
{13730, 13809, 13810},
{13488, 13814, 13816},
{11815, 13821, 13821},
{11254, 13825, 13825},
{13788, 13829, 13838},
{13141, 13842, 13842},
{9658, 13846, 13848},
{11088, 13852, 13853},
{10239, 13860, 13866},
{13780, 13870, 13871},
{9981, 13877, 13883},
{11901, 13889, 13891},
{13405, 13895, 13897},
{12680, 13901, 13901},
{8363, 13905, 13910},
{13546, 13914, 13914},
{13498, 13918, 13927},
{13550, 13931, 13937},
{13628, 13941, 13941},
{13900, 13952, 13952},
{13841, 13957, 13957},
{3102, 13961, 13961},
{12835, 13966, 13970},
{12071, 13974, 13975},
{12810, 13979, 13980},
{11488, 13984, 13987},
{13809, 13991, 13992},
{13234, 13996, 13997},
{13886, 14001, 14002},
{11128, 14006, 14007},
{6013, 14012, 14013},
{8748, 14018, 14020},
{9678, 14024, 14024},
{12188, 14029, 14029},
{13914, 14033, 14033},
{11778, 14037, 14040},
{11828, 14044, 14051},
{12479, 14055, 14058},
{14037, 14062, 14066},
{12759, 14070, 14076},
{13889, 14080, 14081},
{13895, 14086, 14121},
{10199, 14125, 14131},
{13663, 14135, 14135},
{9261, 14139, 14155},
{12898, 14160, 14160},
{13667, 14164, 14167},
{12579, 14172, 14174},
{13681, 14178, 14189},
{13697, 14194, 14196},
{14033, 14200, 14200},
{13931, 14204, 14207},
{13726, 14211, 14211},
{9583, 14215, 14222},
{13243, 14226, 14226},
{13379, 14230, 14231},
{7481, 14237, 14239},
{10373, 14243, 14243},
{8644, 14248, 14249},
{1082, 14259, 14260},
{5814, 14265, 14265},
{10414, 14269, 14270},
{9512, 14274, 14274},
{9286, 14285, 14288},
{12593, 14295, 14295},
{13773, 14300, 14302},
{5874, 14308, 14308},
{13804, 14312, 14312},
{10412, 14317, 14320},
{12836, 14324, 14327},
{13974, 14331, 14337},
{14200, 14341, 14341},
{14086, 14345, 14347},
{4853, 14352, 14353},
{13961, 14357, 14357},
{14340, 14361, 14367},
{14005, 14374, 14374},
{13857, 14379, 14388},
{10532, 14397, 14399},
{14379, 14405, 14406},
{11957, 14411, 14413},
{10939, 14419, 14419},
{12547, 14423, 14429},
{13772, 14435, 14438},
{14341, 14442, 14447},
{14409, 14453, 14453},
{14442, 14457, 14457},
{13918, 14461, 14470},
{13511, 14474, 14483},
{14080, 14487, 14488},
{14344, 14492, 14495},
{13901, 14499, 14520},
{12609, 14524, 14525},
{14204, 14529, 14532},
{13557, 14536, 14536},
{6220, 14541, 14542},
{14139, 14546, 14562},
{14160, 14567, 14574},
{14172, 14579, 14596},
{14194, 14601, 14610},
{14125, 14614, 14614},
{14211, 14618, 14659},
{2011, 14663, 14663},
{14264, 14667, 14680},
{9951, 14687, 14691},
{12863, 14696, 14698},
{7980, 14702, 14703},
{14357, 14707, 14708},
{12266, 14714, 14715},
{10772, 14723, 14729},
{12806, 14733, 14733},
{2583, 14737, 14741},
{14006, 14745, 14745},
{12945, 14749, 14752},
{8679, 14756, 14758},
{12184, 14762, 14763},
{14423, 14767, 14773},
{14054, 14777, 14779},
{10411, 14785, 14789},
{11310, 14794, 14795},
{6455, 14799, 14800},
{5418, 14804, 14804},
{13821, 14808, 14808},
{11905, 14812, 14814},
{13502, 14818, 14819},
{11761, 14823, 14829},
{14745, 14833, 14833},
{14070, 14837, 14843},
{8173, 14850, 14850},
{2999, 14854, 14856},
{9201, 14860, 14867},
{14807, 14871, 14872},
{14812, 14878, 14881},
{13814, 14885, 14887},
{12644, 14891, 14892},
{14295, 14898, 14898},
{14457, 14902, 14902},
{14331, 14906, 14907},
{13170, 14911, 14911},
{14352, 14915, 14916},
{12649, 14920, 14921},
{12399, 14925, 14925},
{13349, 14929, 14929},
{13207, 14934, 14935},
{14372, 14939, 14941},
{14498, 14945, 14945},
{13860, 14949, 14955},
{14452, 14960, 14962},
{14792, 14970, 14970},
{14720, 14975, 14975},
{13858, 14984, 14984},
{5733, 14989, 14991},
{14982, 14995, 14995},
{14524, 14999, 15000},
{2347, 15004, 15004},
{4612, 15009, 15009},
{3225, 15013, 15013},
{12320, 15017, 15018},
{14975, 15022, 15022},
{13416, 15026, 15028},
{8140, 15034, 15034},
{15016, 15040, 15042},
{14299, 15046, 15051},
{14901, 15055, 15056},
{14933, 15060, 15061},
{14960, 15066, 15066},
{14999, 15070, 15071},
{14461, 15075, 15080},
{14666, 15084, 15084},
{14474, 15088, 15134},
{15055, 15138, 15138},
{13046, 15142, 15146},
{14536, 15150, 15176},
{14567, 15181, 15181},
{12725, 15185, 15185},
{13346, 15189, 15189},
{13268, 15193, 15197},
{5568, 15203, 15203},
{15192, 15207, 15207},
{15075, 15211, 15216},
{15207, 15220, 15220},
{13941, 15224, 15224},
{13091, 15228, 15230},
{13623, 15234, 15235},
{13362, 15239, 15243},
{10066, 15247, 15252},
{6452, 15257, 15257},
{14837, 15261, 15267},
{13576, 15271, 15281},
{12874, 15285, 15304},
{15181, 15309, 15309},
{14164, 15313, 15316},
{14579, 15321, 15326},
{12090, 15330, 15339},
{14601, 15344, 15346},
{15084, 15350, 15350},
{12523, 15354, 15357},
{14618, 15361, 15361},
{12788, 15365, 15365},
{6032, 15369, 15369},
{12127, 15373, 15378},
{4703, 15382, 15382},
{12140, 15386, 15387},
{4602, 15392, 15392},
{12856, 15396, 15398},
{13990, 15403, 15406},
{13213, 15412, 15416},
{13979, 15420, 15420},
{14300, 15424, 15426},
{10617, 15430, 15430},
{10094, 15435, 15435},
{12413, 15439, 15440},
{10900, 15447, 15450},
{10908, 15455, 15455},
{15220, 15459, 15459},
{14911, 15463, 15464},
{15026, 15468, 15470},
{14696, 15478, 15480},
{12414, 15484, 15484},
{14215, 15488, 15491},
{13009, 15496, 15508},
{15424, 15512, 15514},
{11334, 15518, 15519},
{11280, 15523, 15524},
{11345, 15528, 15529},
{15459, 15533, 15533},
{14243, 15537, 15539},
{14818, 15543, 15544},
{15533, 15548, 15548},
{14230, 15552, 15554},
{14832, 15561, 15562},
{9787, 15566, 15567},
{15443, 15573, 15575},
{13845, 15579, 15584},
{15430, 15588, 15588},
{15561, 15593, 15593},
{14453, 15601, 15608},
{14870, 15613, 15615},
{12275, 15619, 15619},
{14613, 15623, 15624},
{10596, 15628, 15630},
{1940, 15634, 15634},
{9773, 15638, 15638},
{2665, 15642, 15642},
{13638, 15646, 15646},
{6861, 15650, 15650},
{12781, 15654, 15657},
{15088, 15661, 15665},
{11712, 15669, 15669},
{5534, 15673, 15674},
{12864, 15678, 15684},
{15547, 15688, 15689},
{15365, 15693, 15693},
{7973, 15697, 15698},
{13144, 15702, 15710},
{15548, 15714, 15714},
{14906, 15718, 15719},
{15444, 15723, 15723},
{11456, 15727, 15729},
{12632, 15733, 15734},
{13602, 15738, 15738},
{8932, 15746, 15746},
{15598, 15752, 15753},
{14257, 15757, 15758},
{8379, 15762, 15763},
{10531, 15767, 15767},
{8403, 15771, 15775},
{10432, 15779, 15784},
{14285, 15791, 15794},
{3086, 15800, 15803},
{14925, 15807, 15807},
{14934, 15812, 15812},
{15065, 15816, 15817},
{15737, 15821, 15821},
{15210, 15825, 15831},
{15350, 15835, 15835},
{15661, 15839, 15843},
{15223, 15847, 15848},
{10450, 15855, 15855},
{10501, 15860, 15870},
{10515, 15879, 15879},
{12621, 15884, 15884},
{15593, 15890, 15890},
{15021, 15894, 15894},
{15512, 15898, 15900},
{14274, 15904, 15905},
{15566, 15909, 15909},
{3785, 15913, 15913},
{14995, 15917, 15917},
{15565, 15921, 15921},
{14762, 15925, 15926},
{14016, 15933, 15940},
{10264, 15948, 15948},
{15944, 15952, 15953},
{14847, 15962, 15966},
{15321, 15973, 15975},
{15917, 15979, 15980},
{8141, 15984, 15984},
{15714, 15988, 15988},
{15004, 15992, 16018},
{5180, 16023, 16024},
{15017, 16028, 16029},
{15046, 16033, 16036},
{14499, 16040, 16061},
{15987, 16065, 16066},
{15354, 16070, 16073},
{15628, 16077, 16081},
{13235, 16085, 16088},
{15835, 16093, 16093},
{13247, 16097, 16107},
{15929, 16112, 16112},
{7992, 16118, 16118},
{15988, 16122, 16122},
{15811, 16126, 16133},
{5185, 16137, 16137},
{6056, 16149, 16156},
{15723, 16160, 16160},
{13435, 16167, 16167},
{15692, 16173, 16175},
{1346, 16182, 16183},
{15641, 16187, 16187},
{13157, 16192, 16192},
{12813, 16197, 16197},
{5216, 16201, 16202},
{16170, 16206, 16206},
{15224, 16210, 16211},
{12979, 16215, 16215},
{13342, 16230, 16230},
{15070, 16236, 16237},
{16070, 16241, 16244},
{15361, 16248, 16248},
{15488, 16252, 16256},
{15184, 16265, 16273},
{10860, 16277, 16278},
{8780, 16286, 16287},
{15271, 16291, 16293},
{16206, 16297, 16297},
{14529, 16301, 16304},
{16248, 16308, 16308},
{13716, 16312, 16322},
{16252, 16326, 16330},
{13874, 16334, 16334},
{12773, 16338, 16349},
{14929, 16353, 16353},
{15697, 16361, 16362},
{13531, 16366, 16368},
{14833, 16373, 16373},
{15904, 16377, 16378},
{16173, 16386, 16388},
{13582, 16392, 16393},
{9488, 16399, 16399},
{15468, 16403, 16404},
{13905, 16409, 16411},
{3784, 16415, 16416},
{16297, 16420, 16420},
{16210, 16424, 16426},
{12936, 16430, 16430},
{8508, 16435, 16438},
{9602, 16443, 16446},
{1317, 16450, 16451},
{4739, 16456, 16461},
}
| golang/snappy | golden_test.go | GO | bsd-3-clause | 45,089 |
package net.sourceforge.pmd.jaxen;
import org.jaxen.Context;
import org.jaxen.Function;
import org.jaxen.FunctionCallException;
import org.jaxen.SimpleFunctionContext;
import org.jaxen.XPathFunctionContext;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class MatchesFunction implements Function {
public static void registerSelfInSimpleContext() {
// see http://jaxen.org/extensions.html
((SimpleFunctionContext) XPathFunctionContext.getInstance()).registerFunction(null, "matches", new MatchesFunction());
}
public Object call(Context context, List args) throws FunctionCallException {
if (args.isEmpty()) {
return Boolean.FALSE;
}
List attributes = (List) args.get(0);
Attribute attr = (Attribute) attributes.get(0);
Pattern check = Pattern.compile((String) args.get(1));
Matcher matcher = check.matcher(attr.getValue());
if (matcher.find()) {
return context.getNodeSet();
}
return Boolean.FALSE;
}
}
| bolav/pmd-src-4.2.6-perl | src/net/sourceforge/pmd/jaxen/MatchesFunction.java | Java | bsd-3-clause | 1,085 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Service
* @subpackage DeveloperGarden
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: SearchParameters.php 22662 2010-07-24 17:37:36Z mabe $
*/
/**
* @category Zend
* @package Zend_Service
* @subpackage DeveloperGarden
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @author Marco Kaiser
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
{
/**
* possible search parameters, incl. default values
*
* @var array
*/
private $_parameters = array(
'what' => null,
'dymwhat' => null,
'dymrelated' => null,
'hits' => null,
'collapse' => null,
'where' => null,
'dywhere' => null,
'radius' => null,
'lx' => null,
'ly' => null,
'rx' => null,
'ry' => null,
'transformgeocode' => null,
'sort' => null,
'spatial' => null,
'sepcomm' => null,
'filter' => null, // can be ONLINER or OFFLINER
'openingtime' => null, // can be now or HH::MM
'kategorie' => null, // @see http://www.suchen.de/kategorie-katalog
'site' => null,
'typ' => null,
'name' => null,
'page' => null,
'city' => null,
'plz' => null,
'strasse' => null,
'bundesland' => null,
);
/**
* possible collapse values
*
* @var array
*/
private $_possibleCollapseValues = array(
true,
false,
'ADDRESS_COMPANY',
'DOMAIN'
);
/**
* sets a new search word
* alias for setWhat
*
* @param string $searchValue
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setSearchValue($searchValue)
{
return $this->setWhat($searchValue);
}
/**
* sets a new search word
*
* @param string $searchValue
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setWhat($searchValue)
{
$this->_parameters['what'] = $searchValue;
return $this;
}
/**
* enable the did you mean what feature
*
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function enableDidYouMeanWhat()
{
$this->_parameters['dymwhat'] = 'true';
return $this;
}
/**
* disable the did you mean what feature
*
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function disableDidYouMeanWhat()
{
$this->_parameters['dymwhat'] = 'false';
return $this;
}
/**
* enable the did you mean where feature
*
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function enableDidYouMeanWhere()
{
$this->_parameters['dymwhere'] = 'true';
return $this;
}
/**
* disable the did you mean where feature
*
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function disableDidYouMeanWhere()
{
$this->_parameters['dymwhere'] = 'false';
return $this;
}
/**
* enable did you mean related, if true Kihno will be corrected to Kino
*
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function enableDidYouMeanRelated()
{
$this->_parameters['dymrelated'] = 'true';
return $this;
}
/**
* diable did you mean related, if false Kihno will not be corrected to Kino
*
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function disableDidYouMeanRelated()
{
$this->_parameters['dymrelated'] = 'true';
return $this;
}
/**
* set the max result hits for this search
*
* @param integer $hits
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setHits($hits = 10)
{
// require_once 'Zend/Validate/Between.php';
$validator = new Zend_Validate_Between(0, 1000);
if (!$validator->isValid($hits)) {
$message = $validator->getMessages();
// require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php';
throw new Zend_Service_DeveloperGarden_LocalSearch_Exception(current($message));
}
$this->_parameters['hits'] = $hits;
return $this;
}
/**
* If true, addresses will be collapsed for a single domain, common values
* are:
* ADDRESS_COMPANY – to collapse by address
* DOMAIN – to collapse by domain (same like collapse=true)
* false
*
* @param mixed $value
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setCollapse($value)
{
if (!in_array($value, $this->_possibleCollapseValues, true)) {
// require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php';
throw new Zend_Service_DeveloperGarden_LocalSearch_Exception('Not a valid value provided.');
}
$this->_parameters['collapse'] = $value;
return $this;
}
/**
* set a specific search location
* examples:
* +47°54’53.10”, 11° 10’ 56.76”
* 47°54’53.10;11°10’56.76”
* 47.914750,11.182533
* +47.914750 ; +11.1824
* Darmstadt
* Berlin
*
* @param string $where
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setWhere($where)
{
// require_once 'Zend/Validate/NotEmpty.php';
$validator = new Zend_Validate_NotEmpty();
if (!$validator->isValid($where)) {
$message = $validator->getMessages();
// require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php';
throw new Zend_Service_DeveloperGarden_LocalSearch_Exception(current($message));
}
$this->_parameters['where'] = $where;
return $this;
}
/**
* returns the defined search location (ie city, country)
*
* @return string
*/
public function getWhere()
{
return $this->_parameters['where'];
}
/**
* enable the spatial search feature
*
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function enableSpatial()
{
$this->_parameters['spatial'] = 'true';
return $this;
}
/**
* disable the spatial search feature
*
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function disableSpatial()
{
$this->_parameters['spatial'] = 'false';
return $this;
}
/**
* sets spatial and the given radius for a circle search
*
* @param integer $radius
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setRadius($radius)
{
// require_once 'Zend/Validate/Int.php';
$validator = new Zend_Validate_Int();
if (!$validator->isValid($radius)) {
$message = $validator->getMessages();
// require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php';
throw new Zend_Service_DeveloperGarden_LocalSearch_Exception(current($message));
}
$this->_parameters['radius'] = $radius;
$this->_parameters['transformgeocode'] = 'false';
return $this;
}
/**
* sets the values for a rectangle search
* lx = longitude left top
* ly = latitude left top
* rx = longitude right bottom
* ry = latitude right bottom
*
* @param $lx
* @param $ly
* @param $rx
* @param $ry
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setRectangle($lx, $ly, $rx, $ry)
{
$this->_parameters['lx'] = $lx;
$this->_parameters['ly'] = $ly;
$this->_parameters['rx'] = $rx;
$this->_parameters['ry'] = $ry;
return $this;
}
/**
* if set, the service returns the zipcode for the result
*
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setTransformGeoCode()
{
$this->_parameters['transformgeocode'] = 'true';
$this->_parameters['radius'] = null;
return $this;
}
/**
* sets the sort value
* possible values are: 'relevance' and 'distance' (only with spatial enabled)
*
* @param string $sort
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setSort($sort)
{
if (!in_array($sort, array('relevance', 'distance'))) {
// require_once 'Zend/Service/DeveloperGarden/LocalSearch/Exception.php';
throw new Zend_Service_DeveloperGarden_LocalSearch_Exception('Not a valid sort value provided.');
}
$this->_parameters['sort'] = $sort;
return $this;
}
/**
* enable the separation of phone numbers
*
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function enablePhoneSeparation()
{
$this->_parameters['sepcomm'] = 'true';
return $this;
}
/**
* disable the separation of phone numbers
*
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function disablePhoneSeparation()
{
$this->_parameters['sepcomm'] = 'true';
return $this;
}
/**
* if this filter is set, only results with a website are returned
*
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setFilterOnliner()
{
$this->_parameters['filter'] = 'ONLINER';
return $this;
}
/**
* if this filter is set, only results without a website are returned
*
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setFilterOffliner()
{
$this->_parameters['filter'] = 'OFFLINER';
return $this;
}
/**
* removes the filter value
*
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function disableFilter()
{
$this->_parameters['filter'] = null;
return $this;
}
/**
* set a filter to get just results who are open at the given time
* possible values:
* now = open right now
* HH:MM = at the given time (ie 20:00)
*
* @param string $time
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setOpeningTime($time = null)
{
$this->_parameters['openingtime'] = $time;
return $this;
}
/**
* sets a category filter
*
* @see http://www.suchen.de/kategorie-katalog
* @param $category
* @return unknown_type
*/
public function setCategory($category = null)
{
$this->_parameters['kategorie'] = $category;
return $this;
}
/**
* sets the site filter
* ie: www.developergarden.com
*
* @param string $site
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setSite($site)
{
$this->_parameters['site'] = $site;
return $this;
}
/**
* sets a filter to the given document type
* ie: pdf, html
*
* @param string $type
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setDocumentType($type)
{
$this->_parameters['typ'] = $type;
return $this;
}
/**
* sets a filter for the company name
* ie: Deutsche Telekom
*
* @param string $name
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setName($name)
{
$this->_parameters['name'] = $name;
return $this;
}
/**
* sets a filter for the zip code
*
* @param string $zip
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setZipCode($zip)
{
$this->_parameters['plz'] = $zip;
return $this;
}
/**
* sets a filter for the street
*
* @param string $street
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setStreet($street)
{
$this->_parameters['strasse'] = $street;
return $this;
}
/**
* sets a filter for the county
*
* @param string $county
* @return Zend_Service_DeveloperGarden_LocalSearch_SearchParameters
*/
public function setCounty($county)
{
$this->_parameters['bundesland'] = $county;
return $this;
}
/**
* sets a raw parameter with the value
*
* @param string $key
* @param mixed $value
* @return unknown_type
*/
public function setRawParameter($key, $value)
{
$this->_parameters[$key] = $value;
return $this;
}
/**
* returns the parameters as an array
*
* @return array
*/
public function getSearchParameters()
{
$retVal = array();
foreach ($this->_parameters as $key => $value) {
if ($value === null) {
continue;
}
$param = array(
'parameter' => $key,
'value' => $value
);
$retVal[] = $param;
}
return $retVal;
}
}
| mgrauer/midas3score | library/Zend/Service/DeveloperGarden/LocalSearch/SearchParameters.php | PHP | bsd-3-clause | 14,725 |
/*
* Copyright (c) 2009-2015, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.adapter.deferred.queue;
import gov.hhs.fha.nhinc.properties.PropertyAccessException;
import gov.hhs.fha.nhinc.properties.PropertyAccessor;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.log4j.Logger;
/**
* This class is responsible for handling the work that is done each time the timer goes off; i.e. processing the
* outstanding deferred queue request messages.
*
* @author richard.ettema
*/
public class DeferredQueueTimerTask {
private static final Logger LOG = Logger.getLogger(DeferredQueueTimerTask.class);
private static final String GATEWAY_PROPERTY_FILE = "gateway";
private static final String DEFERRED_QUEUE_SWITCH_PROPERTY = "DeferredQueueProcessActive";
protected void forceDeferredQueueProcess() {
try {
DeferredQueueManagerHelper helper = new DeferredQueueManagerHelper();
helper.forceProcess();
} catch (DeferredQueueException ex) {
LOG.error("DeferredQueueTimerTask DeferredQueueException thrown.", ex);
StringWriter stackTrace = new StringWriter();
ex.printStackTrace(new PrintWriter(stackTrace));
String sValue = stackTrace.toString();
if (sValue.indexOf("EJBClassLoader") >= 0) {
DeferredQueueTimer timer = DeferredQueueTimer.getInstance();
timer.stopTimer();
}
}
}
/**
* This method is called each time the timer thread wakes up.
*/
public void run() {
boolean bQueueActive = true;
try {
bQueueActive = PropertyAccessor.getInstance().getPropertyBoolean(GATEWAY_PROPERTY_FILE, DEFERRED_QUEUE_SWITCH_PROPERTY);
if (bQueueActive) {
LOG.debug("Start: DeferredQueueTimerTask.run method - processing queue entries.");
forceDeferredQueueProcess();
LOG.debug("Done: DeferredQueueTimerTask.run method - processing queue entries.");
} else {
LOG.debug("DeferredQueueTimerTask is disabled by the DeferredQueueRefreshActive property.");
}
} catch (PropertyAccessException ex) {
LOG.error("DeferredQueueTimerTask.run method unable to read DeferredQueueRefreshActive property.", ex);
}
}
/**
* Main method used to test this class. This one really should not be run under unit test scenarios because it
* requires access to the UDDI server.
*
* @param args
*/
public static void main(String[] args) {
System.out.println("Starting test.");
try {
DeferredQueueTimerTask oTimerTask = new DeferredQueueTimerTask();
oTimerTask.run();
} catch (Exception e) {
System.out.println("An unexpected exception occurred: " + e.getMessage());
e.printStackTrace();
System.exit(-1);
}
System.out.println("End of test.");
}
}
| beiyuxinke/CONNECT | Product/Production/Adapters/General/CONNECTAdapterWeb/src/main/java/gov/hhs/fha/nhinc/adapter/deferred/queue/DeferredQueueTimerTask.java | Java | bsd-3-clause | 4,650 |
<?php
/**
* @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause
* @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com)
*/
namespace ZFTest\Apigility\Doctrine\Admin\Model;
use ZF\Apigility\Doctrine\Admin\Model\DoctrineRestServiceEntity;
use ZF\Apigility\Doctrine\Admin\Model\DoctrineRestServiceResource;
use Doctrine\ORM\Tools\SchemaTool;
use Zend\Http\Request;
use Zend\Mvc\Router\RouteMatch;
use Zend\Filter\FilterChain;
class DoctrineMetadata1Test extends \Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase
{
public function setUp()
{
$this->setApplicationConfig(
include __DIR__ . '/../../../../../config/application.config.php'
);
parent::setUp();
}
public function tearDown()
{
# FIXME: Drop database from in-memory
}
/**
* @see https://github.com/zfcampus/zf-apigility/issues/18
*/
public function testDoctrineMetadataResource()
{
$serviceManager = $this->getApplication()->getServiceManager();
$em = $serviceManager->get('doctrine.entitymanager.orm_default');
$this->getRequest()->getHeaders()->addHeaders(
array(
'Accept' => 'application/json',
)
);
$this->dispatch(
'/apigility/api/doctrine/doctrine.entitymanager.orm_default/metadata/Db%5CEntity%5CArtist',
Request::METHOD_GET
);
$body = json_decode($this->getResponse()->getBody(), true);
$this->assertArrayHasKey('name', $body);
$this->assertEquals('Db\Entity\Artist', $body['name']);
$this->dispatch('/apigility/api/doctrine/doctrine.entitymanager.orm_default/metadata', Request::METHOD_GET);
$body = json_decode($this->getResponse()->getBody(), true);
$this->assertArrayHasKey('_embedded', $body);
}
public function testDoctrineService()
{
$serviceManager = $this->getApplication()->getServiceManager();
$em = $serviceManager->get('doctrine.entitymanager.orm_default');
$tool = new SchemaTool($em);
$res = $tool->createSchema($em->getMetadataFactory()->getAllMetadata());
// Create DB
$resourceDefinition = array(
"objectManager"=> "doctrine.entitymanager.orm_default",
"serviceName" => "Artist",
"entityClass" => "Db\\Entity\\Artist",
"routeIdentifierName" => "artist_id",
"entityIdentifierName" => "id",
"routeMatch" => "/db-test/artist",
);
$this->resource = $serviceManager->get('ZF\Apigility\Doctrine\Admin\Model\DoctrineRestServiceResource');
$this->resource->setModuleName('DbApi');
$entity = $this->resource->create($resourceDefinition);
$this->assertInstanceOf('ZF\Apigility\Doctrine\Admin\Model\DoctrineRestServiceEntity', $entity);
$controllerServiceName = $entity->controllerServiceName;
$this->assertNotEmpty($controllerServiceName);
$this->assertContains('DbApi\V1\Rest\Artist\Controller', $controllerServiceName);
$filter = new FilterChain();
$filter->attachByName('WordCamelCaseToUnderscore')
->attachByName('StringToLower');
$em = $serviceManager->get('doctrine.entitymanager.orm_default');
$metadataFactory = $em->getMetadataFactory();
$entityMetadata = $metadataFactory->getMetadataFor("Db\\Entity\\Artist");
foreach ($entityMetadata->associationMappings as $mapping) {
switch ($mapping['type']) {
case 4:
$rpcServiceResource = $serviceManager->get(
'ZF\Apigility\Doctrine\Admin\Model\DoctrineRpcServiceResource'
);
$rpcServiceResource->setModuleName('DbApi');
$rpcServiceResource->create(
array(
'service_name' => 'Artist' . $mapping['fieldName'],
'route' => '/db-test/artist[/:parent_id]/' . $filter($mapping['fieldName']) . '[/:child_id]',
'http_methods' => array(
'GET', 'PUT', 'POST'
),
'options' => array(
'target_entity' => $mapping['targetEntity'],
'source_entity' => $mapping['sourceEntity'],
'field_name' => $mapping['fieldName'],
),
'selector' => 'custom selector',
)
);
break;
default:
break;
}
}
}
}
| alunys/ApigilityAngularTest | vendor/zfcampus/zf-apigility-doctrine/test/src/Admin/Model/DoctrineMetadata1Test.php | PHP | bsd-3-clause | 4,716 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/window_controller.h"
#include <stddef.h>
#include <memory>
#include "base/values.h"
#include "chrome/browser/extensions/api/tabs/tabs_constants.h"
#include "chrome/browser/extensions/window_controller_list.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/api/windows.h"
namespace extensions {
///////////////////////////////////////////////////////////////////////////////
// WindowController
// static
WindowController::TypeFilter WindowController::GetAllWindowFilter() {
// This needs to be updated if there is a change to
// extensions::api::windows:WindowType.
static_assert(api::windows::WINDOW_TYPE_LAST == 5,
"Update extensions WindowController to match WindowType");
return ((1 << api::windows::WINDOW_TYPE_NORMAL) |
(1 << api::windows::WINDOW_TYPE_PANEL) |
(1 << api::windows::WINDOW_TYPE_POPUP) |
(1 << api::windows::WINDOW_TYPE_APP) |
(1 << api::windows::WINDOW_TYPE_DEVTOOLS));
}
// static
WindowController::TypeFilter WindowController::GetFilterFromWindowTypes(
const std::vector<api::windows::WindowType>& types) {
WindowController::TypeFilter filter = kNoWindowFilter;
for (auto& window_type : types)
filter |= 1 << window_type;
return filter;
}
// static
WindowController::TypeFilter WindowController::GetFilterFromWindowTypesValues(
const base::ListValue* types) {
WindowController::TypeFilter filter = WindowController::kNoWindowFilter;
if (!types)
return filter;
for (size_t i = 0; i < types->GetSize(); i++) {
std::string window_type;
if (types->GetString(i, &window_type))
filter |= 1 << api::windows::ParseWindowType(window_type);
}
return filter;
}
WindowController::WindowController(ui::BaseWindow* window, Profile* profile)
: window_(window), profile_(profile) {
}
WindowController::~WindowController() {
}
Browser* WindowController::GetBrowser() const {
return NULL;
}
bool WindowController::MatchesFilter(TypeFilter filter) const {
TypeFilter type = 1 << api::windows::ParseWindowType(GetWindowTypeText());
return (type & filter) != 0;
}
} // namespace extensions
| endlessm/chromium-browser | chrome/browser/extensions/window_controller.cc | C++ | bsd-3-clause | 2,365 |
/*
Copyright (c) 2014, Richard Martin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Richard Martin nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL RICHARD MARTIN BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Pages.hpp"
#include <string>
#include <list>
#include <utility>
#include <iostream>
#include <pangomm/init.h>
#include <boost/filesystem.hpp>
#include <thread>
#include <sqlite3.h>
#include <cstdlib>
#include "DrawingUtils.hpp"
#include "Global.hpp"
using namespace std;
using namespace boost::filesystem;
///// PageContentItems first
PageContentItem::PageContentItem(PageContentType _pct, ustring _content) :
pct(_pct),
content(_content)
{
}
PageContentItem::PageContentItem(PageContentItem const & cpy) :
pct(cpy.pct),
content(cpy.content)
{
}
PageContentItem::PageContentItem(PageContentItem && mv) :
pct(move(mv.pct)),
content(move(mv.content))
{
}
PageContentItem & PageContentItem::operator =(const PageContentItem & cpy)
{
pct = cpy.pct;
content = cpy.content;
return *this;
}
PageContentItem & PageContentItem::operator =(PageContentItem && mv)
{
pct = move(mv.pct);
content = move(mv.content);
return *this;
}
PageContentItem::~PageContentItem()
{
}
// Page Descriptor next.
PageDescriptor::PageDescriptor() : items()
{
}
PageDescriptor::PageDescriptor::PageDescriptor(PageDescriptor const & cpy) :
items(cpy.items)
{
}
PageDescriptor::PageDescriptor(PageDescriptor && mv) :
items(move(mv.items))
{
}
PageDescriptor & PageDescriptor::operator =(const PageDescriptor & cpy)
{
items = cpy.items;
return *this;
}
PageDescriptor & PageDescriptor::operator =(PageDescriptor && mv)
{
items = move(mv.items);
return *this;
}
PageDescriptor::~PageDescriptor()
{
}
// Pages
Pages::Pages() :
mtx(),
ready(),
descriptors(),
finished(false)
{
}
Pages::~Pages()
{
}
bool Pages::available(const unsigned int n) const
{
return n < descriptors.size();
}
bool Pages::is_valid_index(const unsigned int n)
{
unique_lock<mutex> lck(mtx);
if(finished) {
return n < descriptors.size();
}
else {
return true;
}
}
PageDescriptor Pages::get(const unsigned int n)
{
unique_lock<mutex> lck(mtx);
if(available(n)) {
//we have it
return descriptors[n];
}
else {
//we don't have it
while(!available(n)) {
ready.wait(lck);
}
return descriptors[n];
}
}
void Pages::add(PageDescriptor p)
{
unique_lock<mutex> lck(mtx);
descriptors.push_back(p);
ready.notify_one();
}
void Pages::set_finished_loading(bool val)
{
unique_lock<mutex> lck(mtx);
finished = val;
}
bool Pages::finished_loading()
{
unique_lock<mutex> lck(mtx);
return finished;
}
void Pages::clear()
{
unique_lock<mutex> lck(mtx);
finished = false;
descriptors.clear();
}
// Now the Paginator iteself
//anonymous namespace for epub loading and
//sqlite loading helper functions
namespace {
void __load_epub(Pages & pages, path filename, path dbfilename)
{
unique_lock<mutex> import_lock(import_mtx);
//Yield to the interface thread if this one is
//executing first.
std::this_thread::yield();
#ifdef DEBUG
cout << "Loading Epub" << endl;
#endif
//So, first let's sort out the database
sqlite3 * db;
int rc;
char * errmsg;
rc = sqlite3_open(dbfilename.c_str(), &db);
if( rc ) {
//Failed to open
}
const string table_sql = "CREATE VIRTUAL TABLE book USING fts4(" \
"pagen INT NOT NULL," \
"descriptorid INT NOT NULL," \
"contenttype INT NOT NULL," \
"contentformatted TEXT NOT NULL," \
"contentstripped TEXT NOT NULL ) ;";
sqlite3_exec(db, table_sql.c_str(), NULL, NULL, &errmsg);
//Table created.
const string book_insert_sql = "INSERT INTO book (pagen, descriptorid, contenttype, contentformatted, contentstripped) VALUES (?, ?, ?, ?, ?);";
sqlite3_stmt * book_insert;
rc = sqlite3_prepare_v2(db, book_insert_sql.c_str(), -1, &book_insert, 0);
if(rc != SQLITE_OK && rc != SQLITE_DONE) {
throw - 1;
}
//Do all the following inserts in an SQLite Transaction, because this speeds up the inserts like crazy.
sqlite3_exec(db, "BEGIN TRANSACTION", NULL, NULL, &errmsg);
//Unpack the ebook
Epub book(filename.c_str());
//Initialise Pango for the journey ahead.
Pango::init();
unsigned int epub_content_index = 0;
unsigned int epub_content_length = book.contents[0].items.size();
bool has_fragment = false;
ustring fragment = "";
ustring fragment_stripped = "";
unsigned int pagenum = 0;
unsigned int itemid = 0;
for( ; epub_content_index < epub_content_length ; pagenum++) {
//Create a new PageDescriptor to store the items we're going to create.
PageDescriptor pd;
#ifdef DEBUG
cout << "Processing page " << pagenum << endl;
#endif
//reset the id counter
itemid = 0;
string filename = "pages/page";
filename += to_string(pagenum + 1);
filename += ".png";
const int width = 600;
const int height = 900;
/*
Cairo::RefPtr<Cairo::SvgSurface> surface =
Cairo::SvgSurface::create(filename, width, height);
Cairo::RefPtr<Cairo::Context> cr = Cairo::Context::create(surface);
*/
int stride;
unsigned char * data;
Cairo::RefPtr<Cairo::ImageSurface> surface;
stride = Cairo::ImageSurface::format_stride_for_width (Cairo::Format::FORMAT_ARGB32, width);
data = (unsigned char *) malloc (stride * height);
surface = Cairo::ImageSurface::create (data, Cairo::Format::FORMAT_ARGB32, width, height, stride);
Cairo::RefPtr<Cairo::Context> cr = Cairo::Context::create(surface);
const int rectangle_width = width;
const int rectangle_height = height;
//cr->set_antialias(ANTIALIAS_BEST);
cr->set_source_rgb(1.0, 1.0, 1.0);
DrawingUtils::draw_rectangle(cr, rectangle_width, rectangle_height);
auto it = book.opf_files[0].metadata.find(MetadataType::TITLE);
const ustring title = it->second.contents;
it = book.opf_files[0].metadata.find(MetadataType::CREATOR);
const ustring author = it->second.contents;
int start_pos = 0;
cr->set_source_rgb(0.15, 0.15, 0.15);
if(has_fragment) {
sqlite3_bind_int(book_insert, 1, pagenum);
sqlite3_bind_int(book_insert, 2, itemid);
sqlite3_bind_int(book_insert, 3, PAGE_FRAGMENT);
sqlite3_bind_text(book_insert, 4, fragment.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(book_insert, 5, fragment_stripped.c_str(), -1, SQLITE_STATIC);
int result = sqlite3_step(book_insert);
if(result != SQLITE_OK && result != SQLITE_ROW && result != SQLITE_DONE) {
throw - 1;
}
sqlite3_reset(book_insert);
pd.items.push_back(PageContentItem(PAGE_FRAGMENT, fragment));
has_fragment = false;
start_pos += DrawingUtils::draw_fragment(cr, fragment, rectangle_width, rectangle_height, start_pos);
fragment = "";
fragment_stripped = "";
itemid++;
}
while(epub_content_index < epub_content_length) {
sqlite3_bind_int(book_insert, 1, pagenum);
sqlite3_bind_int(book_insert, 2, itemid);
const ContentItem c = book.contents[0].items[epub_content_index];
epub_content_index++;
if(c.type == H1) {
//There should be only one H1 on a page. To make sure
//of this, we're going to push an H1 onto a new page the current
//page contains any content, and then we're going to push a new page afterwards.
if(pd.items.size() != 0) {
epub_content_index--;
break;
}
else {
//I don't like people messing with formatting in headers. So here we're going to use
//the stripped text for everything and remove the formatting
sqlite3_bind_int(book_insert, 3, PAGE_H1);
sqlite3_bind_text(book_insert, 4, c.stripped_content.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(book_insert, 5, c.stripped_content.c_str(), -1, SQLITE_STATIC);
pd.items.push_back(PageContentItem(PAGE_H1, c.stripped_content));
start_pos += DrawingUtils::draw_h1(cr, c.stripped_content, rectangle_width, rectangle_height);
//ensure that there's only one H1 on a page.
break;
}
}
else if (c.type == H2) {
if(DrawingUtils::will_fit_h2(cr, c.content, rectangle_width, rectangle_height, start_pos)) {
//I don't like people messing with formatting in headers. So here we're going to use
//the stripped text for everything and remove the formatting
sqlite3_bind_int(book_insert, 3, PAGE_H2);
sqlite3_bind_text(book_insert, 4, c.stripped_content.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(book_insert, 5, c.stripped_content.c_str(), -1, SQLITE_STATIC);
pd.items.push_back(PageContentItem(PAGE_H2, c.stripped_content));
// Only pack out the header when it's not the first thing in the page
if (itemid != 0) {
start_pos += 35;
}
start_pos += DrawingUtils::draw_h2(cr, c.stripped_content, rectangle_width, rectangle_height, start_pos);
start_pos += 35;
}
else {
epub_content_index--;
break;
}
}
else if (c.type == P) {
//cout << c.content << endl;
if(DrawingUtils::will_fit_text(cr, c.content, rectangle_width, rectangle_height, start_pos)) {
sqlite3_bind_int(book_insert, 3, PAGE_PARAGRAPH);
sqlite3_bind_text(book_insert, 4, c.content.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(book_insert, 5, c.stripped_content.c_str(), -1, SQLITE_STATIC);
pd.items.push_back(PageContentItem(PAGE_PARAGRAPH, c.content));
start_pos += DrawingUtils::draw_text(cr, c.content, rectangle_width, rectangle_height, start_pos);
}
else {
pair<ustring, ustring> packres = DrawingUtils::pack_text(cr, c.content, rectangle_width, rectangle_height, start_pos);
fragment = packres.second;
fragment_stripped = packres.second; // This doesn't work under all circumstances
if(fragment.compare(c.content) == 0) {
//can't pack the content. Go back one, and set a new page, so we do all this again.
epub_content_index--;
}
else {
has_fragment = true;
pd.items.push_back(PageContentItem(PAGE_PARAGRAPH, packres.first));
sqlite3_bind_int(book_insert, 3, PAGE_PARAGRAPH);
sqlite3_bind_text(book_insert, 4, packres.first.c_str(), -1, SQLITE_STATIC);
sqlite3_bind_text(book_insert, 5, packres.first.c_str(), -1, SQLITE_STATIC);
//We will need to break out of the loop under this condition,
//but if we do then we haven't saved the info in the database.
//So we have to go out of our way to save it here.
int result = sqlite3_step(book_insert);
if(result != SQLITE_OK && result != SQLITE_ROW && result != SQLITE_DONE) {
throw - 1;
}
sqlite3_reset(book_insert);
}
break;
}
}
else if (c.type == HR) {
if(pd.items.size() == 0) {
//If there's nothing on the page, then forcing a new page is unnecessary.
//So we ignore it.
continue;
}
else {
break;
}
}
int result = sqlite3_step(book_insert);
if(result != SQLITE_OK && result != SQLITE_ROW && result != SQLITE_DONE) {
throw - 1;
}
sqlite3_reset(book_insert);
itemid++;
}
cr->set_source_rgb(0.5, 0.5, 0.5);
DrawingUtils::draw_header(cr, rectangle_width, rectangle_height, title, pagenum);
pages.add(pd);
cr->show_page();
//surface->write_to_png(filename);
free(data);
}
pages.set_finished_loading(true);
const string book_optimise_sql = "INSERT INTO book(book) VALUES('optimize');";
sqlite3_stmt * book_optimise;
rc = sqlite3_prepare_v2(db, book_optimise_sql.c_str(), -1, &book_optimise, 0);
if(rc != SQLITE_OK && rc != SQLITE_DONE) {
throw - 1;
}
rc = sqlite3_step(book_optimise);
if(rc != SQLITE_OK && rc != SQLITE_DONE) {
throw - 1;
}
sqlite3_finalize(book_optimise);
sqlite3_exec(db, "END TRANSACTION", NULL, NULL, &errmsg);
sqlite3_finalize(book_insert);
sqlite3_close(db);
info_bar_hide_dispatcher.emit();
#ifdef DEBUG
cout << "Done Loading Epub" << endl;
#endif
}
void __load_sqlite(Pages & pages, path filename)
{
unique_lock<mutex> import_lck(import_mtx);
//Yield to the interface thread if this one is
//executing first.
std::this_thread::yield();
#ifdef DEBUG
cout << "Loading SQLite" << endl;
#endif
sqlite3 * db;
int rc;
rc = sqlite3_open(filename.c_str(), &db);
if( rc ) {
//Failed to open
}
const string book_select_sql = "SELECT * FROM book ORDER BY pagen, descriptorid";
sqlite3_stmt * book_select;
rc = sqlite3_prepare_v2(db, book_select_sql.c_str(), -1, &book_select, 0);
if(rc != SQLITE_OK && rc != SQLITE_DONE) {
throw - 1;
}
rc = sqlite3_step(book_select);
PageDescriptor pd;
int currentpagen = 0;
while ( rc == SQLITE_ROW ) {
int pagen = sqlite3_column_int(book_select, 0);
//int descriptorn = sqlite3_column_int(book_select, 1);
int contenttype = sqlite3_column_int(book_select, 2);
ustring content = ustring((char *)sqlite3_column_text(book_select, 3));
if(pagen != currentpagen) {
//New page! wrap up the old page.
currentpagen = pagen;
pages.add(pd);
pd = PageDescriptor();
}
PageContentType pct = static_cast<PageContentType>(contenttype);
pd.items.push_back(PageContentItem(pct, content));
//cout << content << endl;
rc = sqlite3_step(book_select);
}
if ( rc == SQLITE_ERROR) {
cout << "Database Error " << endl;
}
pages.add(pd);
pages.set_finished_loading(true);
sqlite3_finalize(book_select);
sqlite3_close(db);
#ifdef DEBUG
cout << "Done Loading SQLite" << endl;
#endif
}
} //end of anonymous namespace
void Paginator::load(Pages & pages, string filename)
{
//OK, time for heavy lifting;
path file = path(filename);
if(!exists(file)) {
//do something
}
path fn = file.filename();
path dbfn(".");
dbfn += fn;
dbfn += path(".db");
path databasefile = fn.parent_path();
databasefile /= dbfn;
#ifdef DEBUG
cout << databasefile << endl;
#endif
if(!exists(databasefile)) {
//Urgh. we need to load the whole thing from the damn EPUB file.
thread t(__load_epub, ref(pages), file, databasefile);
t.detach();
}
else {
//Good, we can load from SQLite and we don't have to do any parsing.
//thread t(__load_sqlite, ref(pages), databasefile);
//t.detach();
__load_sqlite(pages, databasefile);
}
}
| radiosity/reader | src/Pages.cpp | C++ | bsd-3-clause | 15,805 |
""" This module attempts to make it easy to create VTK-Python
unittests. The module uses unittest for the test interface. For more
documentation on what unittests are and how to use them, please read
these:
http://www.python.org/doc/current/lib/module-unittest.html
http://www.diveintopython.org/roman_divein.html
This VTK-Python test module supports image based tests with multiple
images per test suite and multiple images per individual test as well.
It also prints information appropriate for Dart
(http://public.kitware.com/Dart/).
This module defines several useful classes and functions to make
writing tests easy. The most important of these are:
class vtkTest:
Subclass this for your tests. It also has a few useful internal
functions that can be used to do some simple blackbox testing.
compareImage(renwin, img_fname, threshold=10):
Compares renwin with image and generates image if it does not
exist. The threshold determines how closely the images must match.
The function also handles multiple images and finds the best
matching image.
compareImageWithSavedImage(src_img, img_fname, threshold=10):
Compares given source image (in the form of a vtkImageData) with
saved image and generates the image if it does not exist. The
threshold determines how closely the images must match. The
function also handles multiple images and finds the best matching
image.
getAbsImagePath(img_basename):
Returns the full path to the image given the basic image name.
main(cases):
Does the testing given a list of tuples containing test classes and
the starting string of the functions used for testing.
interact():
Interacts with the user if necessary. The behavior of this is
rather trivial and works best when using Tkinter. It does not do
anything by default and stops to interact with the user when given
the appropriate command line arguments.
isInteractive():
If interact() is not good enough, use this to find if the mode is
interactive or not and do whatever is necessary to generate an
interactive view.
Examples:
The best way to learn on how to use this module is to look at a few
examples. The end of this file contains a trivial example. Please
also look at the following examples:
Rendering/Testing/Python/TestTkRenderWidget.py,
Rendering/Testing/Python/TestTkRenderWindowInteractor.py
Created: September, 2002
Prabhu Ramachandran <prabhu@aero.iitb.ac.in>
"""
import sys, os, time
import os.path
import unittest, getopt
import vtk
import BlackBox
# location of the VTK data files. Set via command line args or
# environment variable.
VTK_DATA_ROOT = ""
# location of the VTK baseline images. Set via command line args or
# environment variable.
VTK_BASELINE_ROOT = ""
# location of the VTK difference images for failed tests. Set via
# command line args or environment variable.
VTK_TEMP_DIR = ""
# Verbosity of the test messages (used by unittest)
_VERBOSE = 0
# Determines if it is necessary to interact with the user. If zero
# dont interact if 1 interact. Set via command line args
_INTERACT = 0
# This will be set to 1 when the image test will not be performed.
# This option is used internally by the script and set via command
# line arguments.
_NO_IMAGE = 0
class vtkTest(unittest.TestCase):
"""A simple default VTK test class that defines a few useful
blackbox tests that can be readily used. Derive your test cases
from this class and use the following if you'd like to.
Note: Unittest instantiates this class (or your subclass) each
time it tests a method. So if you do not want that to happen when
generating VTK pipelines you should create the pipeline in the
class definition as done below for _blackbox.
"""
_blackbox = BlackBox.Tester(debug=0)
# Due to what seems to be a bug in python some objects leak.
# Avoid the exit-with-error in vtkDebugLeaks.
dl = vtk.vtkDebugLeaks()
dl.SetExitError(0)
dl = None
def _testParse(self, obj):
"""Does a blackbox test by attempting to parse the class for
its various methods using vtkMethodParser. This is a useful
test because it gets all the methods of the vtkObject, parses
them and sorts them into different classes of objects."""
self._blackbox.testParse(obj)
def _testGetSet(self, obj, excluded_methods=[]):
"""Checks the Get/Set method pairs by setting the value using
the current state and making sure that it equals the value it
was originally. This effectively calls _testParse
internally. """
self._blackbox.testGetSet(obj, excluded_methods)
def _testBoolean(self, obj, excluded_methods=[]):
"""Checks the Boolean methods by setting the value on and off
and making sure that the GetMethod returns the the set value.
This effectively calls _testParse internally. """
self._blackbox.testBoolean(obj, excluded_methods)
def interact():
"""Interacts with the user if necessary. """
global _INTERACT
if _INTERACT:
raw_input("\nPress Enter/Return to continue with the testing. --> ")
def isInteractive():
"""Returns if the currently chosen mode is interactive or not
based on command line options."""
return _INTERACT
def getAbsImagePath(img_basename):
"""Returns the full path to the image given the basic image
name."""
global VTK_BASELINE_ROOT
return os.path.join(VTK_BASELINE_ROOT, img_basename)
def _getTempImagePath(img_fname):
x = os.path.join(VTK_TEMP_DIR, os.path.split(img_fname)[1])
return os.path.abspath(x)
def compareImageWithSavedImage(src_img, img_fname, threshold=10):
"""Compares a source image (src_img, which is a vtkImageData) with
the saved image file whose name is given in the second argument.
If the image file does not exist the image is generated and
stored. If not the source image is compared to that of the
figure. This function also handles multiple images and finds the
best matching image.
"""
global _NO_IMAGE
if _NO_IMAGE:
return
f_base, f_ext = os.path.splitext(img_fname)
if not os.path.isfile(img_fname):
# generate the image
pngw = vtk.vtkPNGWriter()
pngw.SetFileName(_getTempImagePath(img_fname))
pngw.SetInputData(src_img)
pngw.Write()
return
pngr = vtk.vtkPNGReader()
pngr.SetFileName(img_fname)
idiff = vtk.vtkImageDifference()
idiff.SetInputData(src_img)
idiff.SetImageConnection(pngr.GetOutputPort())
min_err = idiff.GetThresholdedError()
img_err = min_err
best_img = img_fname
err_index = 0
count = 0
if min_err > threshold:
count = 1
test_failed = 1
err_index = -1
while 1: # keep trying images till we get the best match.
new_fname = f_base + "_%d.png"%count
if not os.path.exists(new_fname):
# no other image exists.
break
# since file exists check if it matches.
pngr.SetFileName(new_fname)
pngr.Update()
idiff.Update()
alt_err = idiff.GetThresholdedError()
if alt_err < threshold:
# matched,
err_index = count
test_failed = 0
min_err = alt_err
img_err = alt_err
best_img = new_fname
break
else:
if alt_err < min_err:
# image is a better match.
err_index = count
min_err = alt_err
img_err = alt_err
best_img = new_fname
count = count + 1
# closes while loop.
if test_failed:
_handleFailedImage(idiff, pngr, best_img)
# Print for Dart.
_printDartImageError(img_err, err_index, f_base)
msg = "Failed image test: %f\n"%idiff.GetThresholdedError()
raise AssertionError, msg
# output the image error even if a test passed
_printDartImageSuccess(img_err, err_index)
def compareImage(renwin, img_fname, threshold=10):
"""Compares renwin's (a vtkRenderWindow) contents with the image
file whose name is given in the second argument. If the image
file does not exist the image is generated and stored. If not the
image in the render window is compared to that of the figure.
This function also handles multiple images and finds the best
matching image. """
global _NO_IMAGE
if _NO_IMAGE:
return
w2if = vtk.vtkWindowToImageFilter()
w2if.ReadFrontBufferOff()
w2if.SetInput(renwin)
return compareImageWithSavedImage(w2if.GetOutput(), img_fname, threshold)
def _printDartImageError(img_err, err_index, img_base):
"""Prints the XML data necessary for Dart."""
img_base = _getTempImagePath(img_base)
print "Failed image test with error: %f"%img_err
print "<DartMeasurement name=\"ImageError\" type=\"numeric/double\">",
print "%f </DartMeasurement>"%img_err
if err_index <= 0:
print "<DartMeasurement name=\"BaselineImage\" type=\"text/string\">Standard</DartMeasurement>",
else:
print "<DartMeasurement name=\"BaselineImage\" type=\"numeric/integer\">",
print "%d </DartMeasurement>"%err_index
print "<DartMeasurementFile name=\"TestImage\" type=\"image/png\">",
print "%s </DartMeasurementFile>"%(img_base + '.png')
print "<DartMeasurementFile name=\"DifferenceImage\" type=\"image/png\">",
print "%s </DartMeasurementFile>"%(img_base + '.diff.png')
print "<DartMeasurementFile name=\"ValidImage\" type=\"image/png\">",
print "%s </DartMeasurementFile>"%(img_base + '.valid.png')
def _printDartImageSuccess(img_err, err_index):
"Prints XML data for Dart when image test succeeded."
print "<DartMeasurement name=\"ImageError\" type=\"numeric/double\">",
print "%f </DartMeasurement>"%img_err
if err_index <= 0:
print "<DartMeasurement name=\"BaselineImage\" type=\"text/string\">Standard</DartMeasurement>",
else:
print "<DartMeasurement name=\"BaselineImage\" type=\"numeric/integer\">",
print "%d </DartMeasurement>"%err_index
def _handleFailedImage(idiff, pngr, img_fname):
"""Writes all the necessary images when an image comparison
failed."""
f_base, f_ext = os.path.splitext(img_fname)
# write the difference image gamma adjusted for the dashboard.
gamma = vtk.vtkImageShiftScale()
gamma.SetInputConnection(idiff.GetOutputPort())
gamma.SetShift(0)
gamma.SetScale(10)
pngw = vtk.vtkPNGWriter()
pngw.SetFileName(_getTempImagePath(f_base + ".diff.png"))
pngw.SetInputConnection(gamma.GetOutputPort())
pngw.Write()
# Write out the image that was generated. Write it out as full so that
# it may be used as a baseline image if the tester deems it valid.
pngw.SetInputConnection(idiff.GetInputConnection(0,0))
pngw.SetFileName(_getTempImagePath(f_base + ".png"))
pngw.Write()
# write out the valid image that matched.
pngw.SetInputConnection(idiff.GetInputConnection(1,0))
pngw.SetFileName(_getTempImagePath(f_base + ".valid.png"))
pngw.Write()
def main(cases):
""" Pass a list of tuples containing test classes and the starting
string of the functions used for testing.
Example:
main ([(vtkTestClass, 'test'), (vtkTestClass1, 'test')])
"""
processCmdLine()
timer = vtk.vtkTimerLog()
s_time = timer.GetCPUTime()
s_wall_time = time.time()
# run the tests
result = test(cases)
tot_time = timer.GetCPUTime() - s_time
tot_wall_time = float(time.time() - s_wall_time)
# output measurements for Dart
print "<DartMeasurement name=\"WallTime\" type=\"numeric/double\">",
print " %f </DartMeasurement>"%tot_wall_time
print "<DartMeasurement name=\"CPUTime\" type=\"numeric/double\">",
print " %f </DartMeasurement>"%tot_time
# Delete these to eliminate debug leaks warnings.
del cases, timer
if result.wasSuccessful():
sys.exit(0)
else:
sys.exit(1)
def test(cases):
""" Pass a list of tuples containing test classes and the
functions used for testing.
It returns a unittest._TextTestResult object.
Example:
test = test_suite([(vtkTestClass, 'test'),
(vtkTestClass1, 'test')])
"""
# Make the test suites from the arguments.
suites = []
for case in cases:
suites.append(unittest.makeSuite(case[0], case[1]))
test_suite = unittest.TestSuite(suites)
# Now run the tests.
runner = unittest.TextTestRunner(verbosity=_VERBOSE)
result = runner.run(test_suite)
return result
def usage():
msg="""Usage:\nTestScript.py [options]\nWhere options are:\n
-D /path/to/VTKData
--data-dir /path/to/VTKData
Directory containing VTK Data use for tests. If this option
is not set via the command line the environment variable
VTK_DATA_ROOT is used. If the environment variable is not
set the value defaults to '../../../../VTKData'.
-B /path/to/valid/image_dir/
--baseline-root /path/to/valid/image_dir/
This is a path to the directory containing the valid images
for comparison. If this option is not set via the command
line the environment variable VTK_BASELINE_ROOT is used. If
the environment variable is not set the value defaults to
the same value set for -D (--data-dir).
-T /path/to/valid/temporary_dir/
--temp-dir /path/to/valid/temporary_dir/
This is a path to the directory where the image differences
are written. If this option is not set via the command line
the environment variable VTK_TEMP_DIR is used. If the
environment variable is not set the value defaults to
'../../../Testing/Temporary'.
-v level
--verbose level
Sets the verbosity of the test runner. Valid values are 0,
1, and 2 in increasing order of verbosity.
-I
--interact
Interacts with the user when chosen. If this is not chosen
the test will run and exit as soon as it is finished. When
enabled, the behavior of this is rather trivial and works
best when the test uses Tkinter.
-n
--no-image
Does not do any image comparisons. This is useful if you
want to run the test and not worry about test images or
image failures etc.
-h
--help
Prints this message.
"""
return msg
def parseCmdLine():
arguments = sys.argv[1:]
options = "B:D:T:v:hnI"
long_options = ['baseline-root=', 'data-dir=', 'temp-dir=',
'verbose=', 'help', 'no-image', 'interact']
try:
opts, args = getopt.getopt(arguments, options, long_options)
except getopt.error, msg:
print usage()
print '-'*70
print msg
sys.exit (1)
return opts, args
def processCmdLine():
opts, args = parseCmdLine()
global VTK_DATA_ROOT, VTK_BASELINE_ROOT, VTK_TEMP_DIR
global _VERBOSE, _NO_IMAGE, _INTERACT
# setup defaults
try:
VTK_DATA_ROOT = os.environ['VTK_DATA_ROOT']
except KeyError:
VTK_DATA_ROOT = os.path.normpath("../../../../VTKData")
try:
VTK_BASELINE_ROOT = os.environ['VTK_BASELINE_ROOT']
except KeyError:
pass
try:
VTK_TEMP_DIR = os.environ['VTK_TEMP_DIR']
except KeyError:
VTK_TEMP_DIR = os.path.normpath("../../../Testing/Temporary")
for o, a in opts:
if o in ('-D', '--data-dir'):
VTK_DATA_ROOT = os.path.abspath(a)
if o in ('-B', '--baseline-root'):
VTK_BASELINE_ROOT = os.path.abspath(a)
if o in ('-T', '--temp-dir'):
VTK_TEMP_DIR = os.path.abspath(a)
if o in ('-n', '--no-image'):
_NO_IMAGE = 1
if o in ('-I', '--interact'):
_INTERACT = 1
if o in ('-v', '--verbose'):
try:
_VERBOSE = int(a)
except:
msg="Verbosity should be an integer. 0, 1, 2 are valid."
print msg
sys.exit(1)
if o in ('-h', '--help'):
print usage()
sys.exit()
if not VTK_BASELINE_ROOT: # default value.
VTK_BASELINE_ROOT = VTK_DATA_ROOT
if __name__ == "__main__":
######################################################################
# A Trivial test case to illustrate how this module works.
class SampleTest(vtkTest):
obj = vtk.vtkActor()
def testParse(self):
"Test if class is parseable"
self._testParse(self.obj)
def testGetSet(self):
"Testing Get/Set methods"
self._testGetSet(self.obj)
def testBoolean(self):
"Testing Boolean methods"
self._testBoolean(self.obj)
# Test with the above trivial sample test.
main( [ (SampleTest, 'test') ] )
| cjh1/vtkmodular | Wrapping/Python/vtk/test/Testing.py | Python | bsd-3-clause | 17,259 |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model common\models\PlansSearch */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="plans-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'price') ?>
<?= $form->field($model, 'days') ?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| khajaamin/vishwashantiseva | backend/views/plans/_search.php | PHP | bsd-3-clause | 706 |
#!/usr/bin/env python
from distutils.core import setup
DISTNAME = 'tract_querier'
DESCRIPTION = \
'WMQL: Query language for automatic tract extraction from '\
'full-brain tractographies with '\
'a registered template on top of them'
LONG_DESCRIPTION = open('README.md').read()
MAINTAINER = 'Demian Wassermann'
MAINTAINER_EMAIL = 'demian@bwh.harvard.edu'
URL = 'http://demianw.github.io/tract_querier'
LICENSE = open('license.rst').read()
DOWNLOAD_URL = 'https://github.com/demianw/tract_querier'
VERSION = '0.1'
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration(None, parent_package, top_path)
config.set_options(quiet=True)
config.add_subpackage('tract_querier')
return config
if __name__ == "__main__":
setup(
name=DISTNAME,
maintainer=MAINTAINER,
maintainer_email=MAINTAINER_EMAIL,
description=DESCRIPTION,
license=LICENSE,
url=URL,
version=VERSION,
download_url=DOWNLOAD_URL,
long_description=LONG_DESCRIPTION,
requires=[
'numpy(>=1.6)',
'nibabel(>=1.3)'
],
classifiers=[
'Intended Audience :: Science/Research',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Operating System :: Unix',
'Operating System :: MacOS'
],
scripts=[
'scripts/tract_querier',
'scripts/tract_math'
],
**(configuration().todict())
)
| oesteban/tract_querier | setup.py | Python | bsd-3-clause | 1,691 |
/*
Language: Brainfuck
Author: Evgeny Stepanischev <imbolk@gmail.com>
Website: https://esolangs.org/wiki/Brainfuck
*/
function(hljs){
var LITERAL = {
className: 'literal',
begin: '[\\+\\-]',
relevance: 0
};
return {
aliases: ['bf'],
contains: [
hljs.COMMENT(
'[^\\[\\]\\.,\\+\\-<> \r\n]',
'[\\[\\]\\.,\\+\\-<> \r\n]',
{
returnEnd: true,
relevance: 0
}
),
{
className: 'title',
begin: '[\\[\\]]',
relevance: 0
},
{
className: 'string',
begin: '[\\.,]',
relevance: 0
},
{
// this mode works as the only relevance counter
begin: /(?:\+\+|\-\-)/,
contains: [LITERAL]
},
LITERAL
]
};
}
| MakeNowJust/highlight.js | src/languages/brainfuck.js | JavaScript | bsd-3-clause | 792 |
<?php
/* @var $this Generic_Flex_ValueController */
/* @var $model Generic_Flex_Value */
$this->breadcrumbs=array(
'Generic Flex Values'=>array('index'),
'Create',
);
$this->menu=array(
array('label'=>'List Generic_Flex_Value', 'url'=>array('index')),
array('label'=>'Manage Generic_Flex_Value', 'url'=>array('admin')),
);
?>
<h1>Create Generic_Flex_Value</h1>
<?php echo $this->renderPartial('_form', array('model'=>$model)); ?> | Rathilesh/FMS_V1 | protected/views/generic_Flex_Value/create.php | PHP | bsd-3-clause | 439 |
<div class="page-content">
<!-- /section:settings.box -->
<div class="page-content-area">
<div class="row">
<div class="col-xs-12 mix-cate-update">
<?= $this->render('_form', [
'model' => $model,
]) ?>
<div class="hr hr-18 dotted hr-double"></div>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.page-content-area -->
</div>
| cboy868/lion | modules/shop/views/admin/mix-cate/update.php | PHP | bsd-3-clause | 374 |
if __name__ == '__main__':
import instance_occlsegm_lib
dataset = instance_occlsegm_lib.datasets.apc.arc2017.JskARC2017DatasetV1(
'train')
instance_occlsegm_lib.datasets.view_class_seg_dataset(dataset)
| start-jsk/jsk_apc | demos/instance_occlsegm/tests/datasets_tests/apc_tests/arc2017_tests/jsk_tests/check_jsk_arc2017_v1_dataset.py | Python | bsd-3-clause | 222 |
/*******************************************************************************
* Copyright SemanticBits, Northwestern University and Akaza Research
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caaers/LICENSE.txt for details.
******************************************************************************/
package gov.nih.nci.cabig.caaers.web.rule;
/**
* @author Rhett Sutphin
*/
public class AutocompleterField extends AbstractInputField {
public AutocompleterField() {
}
public AutocompleterField(String propertyName, String displayName, boolean required) {
super(propertyName, displayName, required);
}
public String getTextfieldId() {
return getPropertyName() + "-input";
}
public String getChoicesId() {
return getPropertyName() + "-choices";
}
@Override
public Category getCategory() {
return Category.AUTOCOMPLETER;
}
}
| CBIIT/caaers | caAERS/software/web/src/main/java/gov/nih/nci/cabig/caaers/web/rule/AutocompleterField.java | Java | bsd-3-clause | 962 |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.IO;
using System.Web;
using System.Xml;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Messages.Linden;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Capabilities;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Caps = OpenSim.Framework.Communications.Capabilities.Caps;
using OSDArray = OpenMetaverse.StructuredData.OSDArray;
using OSDMap = OpenMetaverse.StructuredData.OSDMap;
namespace OpenSim.Region.CoreModules.World.Media.Moap
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MoapModule")]
public class MoapModule : INonSharedRegionModule, IMoapModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string Name
{
get { return "MoapModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
/// <summary>
/// Is this module enabled?
/// </summary>
protected bool m_isEnabled;
/// <summary>
/// The scene to which this module is attached
/// </summary>
protected Scene m_scene;
/// <summary>
/// Track the ObjectMedia capabilities given to users keyed by path
/// </summary>
protected Dictionary<string, UUID> m_omCapUsers = new Dictionary<string, UUID>();
/// <summary>
/// Track the ObjectMedia capabilities given to users keyed by agent. Lock m_omCapUsers to manipulate.
/// </summary>
protected Dictionary<UUID, string> m_omCapUrls = new Dictionary<UUID, string>();
/// <summary>
/// Track the ObjectMediaUpdate capabilities given to users keyed by path
/// </summary>
protected Dictionary<string, UUID> m_omuCapUsers = new Dictionary<string, UUID>();
/// <summary>
/// Track the ObjectMediaUpdate capabilities given to users keyed by agent. Lock m_omuCapUsers to manipulate
/// </summary>
protected Dictionary<UUID, string> m_omuCapUrls = new Dictionary<UUID, string>();
public void Initialise(IConfigSource configSource)
{
m_isEnabled = true;
IConfig config = configSource.Configs["MediaOnAPrim"];
if (config != null)
m_isEnabled = config.GetBoolean("Enabled", m_isEnabled);
}
public void AddRegion(Scene scene)
{
if (!m_isEnabled)
return;
m_scene = scene;
m_scene.RegisterModuleInterface<IMoapModule>(this);
}
public void RemoveRegion(Scene scene) { }
public void RegionLoaded(Scene scene)
{
if (!m_isEnabled)
return;
m_scene.EventManager.OnRegisterCaps += OnRegisterCaps;
m_scene.EventManager.OnDeregisterCaps += OnDeregisterCaps;
m_scene.EventManager.OnSceneObjectPartCopy += OnSceneObjectPartCopy;
}
public void Close()
{
if (!m_isEnabled)
return;
m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps;
m_scene.EventManager.OnDeregisterCaps -= OnDeregisterCaps;
m_scene.EventManager.OnSceneObjectPartCopy -= OnSceneObjectPartCopy;
}
public void OnRegisterCaps(UUID agentID, Caps caps)
{
// m_log.DebugFormat(
// "[MOAP]: Registering ObjectMedia and ObjectMediaNavigate capabilities for agent {0}", agentID);
string omCapUrl = "/CAPS/" + UUID.Random();
lock (m_omCapUsers)
{
m_omCapUsers[omCapUrl] = agentID;
m_omCapUrls[agentID] = omCapUrl;
// Even though we're registering for POST we're going to get GETS and UPDATES too
IRequestHandler handler = new RestStreamHandler("POST", omCapUrl, HandleObjectMediaMessage);
caps.RegisterHandler("ObjectMedia", handler);
}
string omuCapUrl = "/CAPS/" + UUID.Random();
lock (m_omuCapUsers)
{
m_omuCapUsers[omuCapUrl] = agentID;
m_omuCapUrls[agentID] = omuCapUrl;
// Even though we're registering for POST we're going to get GETS and UPDATES too
IRequestHandler handler = new RestStreamHandler("POST", omuCapUrl, HandleObjectMediaNavigateMessage);
caps.RegisterHandler("ObjectMediaNavigate", handler);
}
}
public void OnDeregisterCaps(UUID agentID, Caps caps)
{
lock (m_omCapUsers)
{
string path = m_omCapUrls[agentID];
m_omCapUrls.Remove(agentID);
m_omCapUsers.Remove(path);
}
lock (m_omuCapUsers)
{
string path = m_omuCapUrls[agentID];
m_omuCapUrls.Remove(agentID);
m_omuCapUsers.Remove(path);
}
}
protected void OnSceneObjectPartCopy(SceneObjectPart copy, SceneObjectPart original, bool userExposed)
{
if (original.Shape.Media == null)
{
copy.Shape.Media = null;
}
else
{
copy.Shape.Media = new PrimitiveBaseShape.PrimMedia(original.Shape.Media);
}
}
public MediaEntry GetMediaEntry(SceneObjectPart part, int face)
{
MediaEntry me = null;
if (!CheckFaceParam(part, face))
return null;
if (part.Shape.Media == null)
return null; // no media entries
if (face >= part.Shape.Media.Count)
return null; // out of range
me = part.Shape.Media[face];
if (me == null) // no media entry for that face
return null;
// TODO: Really need a proper copy constructor down in libopenmetaverse
me = MediaEntry.FromOSD(me.GetOSD());
// m_log.DebugFormat("[MOAP]: GetMediaEntry for {0} face {1} found {2}", part.Name, face, me);
return me;
}
/// <summary>
/// Set the media entry on the face of the given part.
/// </summary>
/// <param name="part">/param>
/// <param name="face"></param>
/// <param name="me">If null, then the media entry is cleared.</param>
public void SetMediaEntry(SceneObjectPart part, int face, MediaEntry me)
{
// m_log.DebugFormat("[MOAP]: SetMediaEntry for {0}, face {1}", part.Name, face);
int numFaces = part.GetNumberOfSides();
if (part.Shape.Media == null)
part.Shape.Media = new PrimitiveBaseShape.PrimMedia(numFaces);
else
part.Shape.Media.Resize(numFaces);
if (!CheckFaceParam(part, face))
return;
// ClearMediaEntry passes null for me so it must not be ignored!
lock (part.Shape.Media)
part.Shape.Media[face] = me;
UpdateMediaUrl(part, UUID.Zero);
SetPartMediaFlags(part, face, me != null);
part.ScheduleFullUpdate();
part.TriggerScriptChangedEvent(Changed.MEDIA);
}
/// <summary>
/// Clear the media entry from the face of the given part.
/// </summary>
/// <param name="part"></param>
/// <param name="face"></param>
public void ClearMediaEntry(SceneObjectPart part, int face)
{
SetMediaEntry(part, face, null);
}
/// <summary>
/// Set the media flags on the texture face of the given part.
/// </summary>
/// <remarks>
/// The fact that we need a separate function to do what should be a simple one line operation is BUTT UGLY.
/// </remarks>
/// <param name="part"></param>
/// <param name="face"></param>
/// <param name="flag"></param>
protected void SetPartMediaFlags(SceneObjectPart part, int face, bool flag)
{
Primitive.TextureEntry te = part.Shape.Textures;
Primitive.TextureEntryFace teFace = te.CreateFace((uint)face);
teFace.MediaFlags = flag;
part.Shape.Textures = te;
}
/// <summary>
/// Sets or gets per face media textures.
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="httpRequest"></param>
/// <param name="httpResponse"></param>
/// <returns></returns>
protected string HandleObjectMediaMessage(
string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// m_log.DebugFormat("[MOAP]: Got ObjectMedia path [{0}], raw request [{1}]", path, request);
OSDMap osd = (OSDMap)OSDParser.DeserializeLLSDXml(request);
ObjectMediaMessage omm = new ObjectMediaMessage();
omm.Deserialize(osd);
if (omm.Request is ObjectMediaRequest)
return HandleObjectMediaRequest(omm.Request as ObjectMediaRequest);
else if (omm.Request is ObjectMediaUpdate)
return HandleObjectMediaUpdate(path, omm.Request as ObjectMediaUpdate);
throw new Exception(
string.Format(
"[MOAP]: ObjectMediaMessage has unrecognized ObjectMediaBlock of {0}",
omm.Request.GetType()));
}
/// <summary>
/// Handle a fetch request for media textures
/// </summary>
/// <param name="omr"></param>
/// <returns></returns>
protected string HandleObjectMediaRequest(ObjectMediaRequest omr)
{
UUID primId = omr.PrimID;
SceneObjectPart part = m_scene.GetSceneObjectPart(primId);
if (null == part)
{
m_log.WarnFormat(
"[MOAP]: Received a GET ObjectMediaRequest for prim {0} but this doesn't exist in region {1}",
primId, m_scene.RegionInfo.RegionName);
return string.Empty;
}
if (null == part.Shape.Media)
return string.Empty;
ObjectMediaResponse resp = new ObjectMediaResponse();
resp.PrimID = primId;
lock (part.Shape.Media)
resp.FaceMedia = part.Shape.Media.CopyArray();
resp.Version = part.MediaUrl;
string rawResp = OSDParser.SerializeLLSDXmlString(resp.Serialize());
// m_log.DebugFormat("[MOAP]: Got HandleObjectMediaRequestGet raw response is [{0}]", rawResp);
return rawResp;
}
/// <summary>
/// Handle an update of media textures.
/// </summary>
/// <param name="path">Path on which this request was made</param>
/// <param name="omu">/param>
/// <returns></returns>
protected string HandleObjectMediaUpdate(string path, ObjectMediaUpdate omu)
{
UUID primId = omu.PrimID;
SceneObjectPart part = m_scene.GetSceneObjectPart(primId);
if (null == part)
{
m_log.WarnFormat(
"[MOAP]: Received an UPDATE ObjectMediaRequest for prim {0} but this doesn't exist in region {1}",
primId, m_scene.RegionInfo.RegionName);
return string.Empty;
}
// m_log.DebugFormat("[MOAP]: Received {0} media entries for prim {1}", omu.FaceMedia.Length, primId);
//
// for (int i = 0; i < omu.FaceMedia.Length; i++)
// {
// MediaEntry me = omu.FaceMedia[i];
// string v = (null == me ? "null": OSDParser.SerializeLLSDXmlString(me.GetOSD()));
// m_log.DebugFormat("[MOAP]: Face {0} [{1}]", i, v);
// }
if (omu.FaceMedia.Length > part.GetNumberOfSides())
{
m_log.WarnFormat(
"[MOAP]: Received {0} media entries from client for prim {1} {2} but this prim has only {3} faces. Dropping request.",
omu.FaceMedia.Length, part.Name, part.UUID, part.GetNumberOfSides());
return string.Empty;
}
UUID agentId = default(UUID);
lock (m_omCapUsers)
agentId = m_omCapUsers[path];
if (null == part.Shape.Media)
{
// m_log.DebugFormat("[MOAP]: Setting all new media list for {0}", part.Name);
part.Shape.Media = new PrimitiveBaseShape.PrimMedia(omu.FaceMedia);
for (int i = 0; i < omu.FaceMedia.Length; i++)
{
if (omu.FaceMedia[i] != null)
{
// FIXME: Race condition here since some other texture entry manipulator may overwrite/get
// overwritten. Unfortunately, PrimitiveBaseShape does not allow us to change texture entry
// directly.
SetPartMediaFlags(part, i, true);
// m_log.DebugFormat(
// "[MOAP]: Media flags for face {0} is {1}",
// i, part.Shape.Textures.FaceTextures[i].MediaFlags);
}
}
}
else
{
// m_log.DebugFormat("[MOAP]: Setting existing media list for {0}", part.Name);
// We need to go through the media textures one at a time to make sure that we have permission
// to change them
// FIXME: Race condition here since some other texture entry manipulator may overwrite/get
// overwritten. Unfortunately, PrimitiveBaseShape does not allow us to change texture entry
// directly.
Primitive.TextureEntry te = part.Shape.Textures;
lock (part.Shape.Media)
{
for (int i = 0; i < part.Shape.Media.Count; i++)
{
if (m_scene.Permissions.CanControlPrimMedia(agentId, part.UUID, i))
{
part.Shape.Media[i] = omu.FaceMedia[i];
// When a face is cleared this is done by setting the MediaFlags in the TextureEntry via a normal
// texture update, so we don't need to worry about clearing MediaFlags here.
if (null == part.Shape.Media[i])
continue;
SetPartMediaFlags(part, i, true);
// m_log.DebugFormat(
// "[MOAP]: Media flags for face {0} is {1}",
// i, face.MediaFlags);
// m_log.DebugFormat("[MOAP]: Set media entry for face {0} on {1}", i, part.Name);
}
}
}
part.Shape.Textures = te;
// for (int i2 = 0; i2 < part.Shape.Textures.FaceTextures.Length; i2++)
// m_log.DebugFormat("[MOAP]: FaceTexture[{0}] is {1}", i2, part.Shape.Textures.FaceTextures[i2]);
}
UpdateMediaUrl(part, agentId);
// Arguably, we could avoid sending a full update to the avatar that just changed the texture.
part.ScheduleFullUpdate();
part.TriggerScriptChangedEvent(Changed.MEDIA);
return string.Empty;
}
/// <summary>
/// Received from the viewer if a user has changed the url of a media texture.
/// </summary>
/// <param name="request"></param>
/// <param name="path"></param>
/// <param name="param"></param>
/// <param name="httpRequest">/param>
/// <param name="httpResponse">/param>
/// <returns></returns>
protected string HandleObjectMediaNavigateMessage(
string request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// m_log.DebugFormat("[MOAP]: Got ObjectMediaNavigate request [{0}]", request);
OSDMap osd = (OSDMap)OSDParser.DeserializeLLSDXml(request);
ObjectMediaNavigateMessage omn = new ObjectMediaNavigateMessage();
omn.Deserialize(osd);
UUID primId = omn.PrimID;
SceneObjectPart part = m_scene.GetSceneObjectPart(primId);
if (null == part)
{
m_log.WarnFormat(
"[MOAP]: Received an ObjectMediaNavigateMessage for prim {0} but this doesn't exist in region {1}",
primId, m_scene.RegionInfo.RegionName);
return string.Empty;
}
UUID agentId = default(UUID);
lock (m_omuCapUsers)
agentId = m_omuCapUsers[path];
if (!m_scene.Permissions.CanInteractWithPrimMedia(agentId, part.UUID, omn.Face))
return string.Empty;
// m_log.DebugFormat(
// "[MOAP]: Received request to update media entry for face {0} on prim {1} {2} to {3}",
// omn.Face, part.Name, part.UUID, omn.URL);
// If media has never been set for this prim, then just return.
if (null == part.Shape.Media)
return string.Empty;
MediaEntry me = null;
lock (part.Shape.Media)
me = part.Shape.Media[omn.Face];
// Do the same if media has not been set up for a specific face
if (null == me)
return string.Empty;
if (me.EnableWhiteList)
{
if (!CheckUrlAgainstWhitelist(omn.URL, me.WhiteList))
{
// m_log.DebugFormat(
// "[MOAP]: Blocking change of face {0} on prim {1} {2} to {3} since it's not on the enabled whitelist",
// omn.Face, part.Name, part.UUID, omn.URL);
return string.Empty;
}
}
me.CurrentURL = omn.URL;
UpdateMediaUrl(part, agentId);
part.ScheduleFullUpdate();
part.TriggerScriptChangedEvent(Changed.MEDIA);
return OSDParser.SerializeLLSDXmlString(new OSD());
}
/// <summary>
/// Check that the face number is valid for the given prim.
/// </summary>
/// <param name="part"></param>
/// <param name="face"></param>
protected bool CheckFaceParam(SceneObjectPart part, int face)
{
if (face < 0)
return false;
return (face < part.GetNumberOfSides());
}
/// <summary>
/// Update the media url of the given part
/// </summary>
/// <param name="part"></param>
/// <param name="updateId">
/// The id to attach to this update. Normally, this is the user that changed the
/// texture
/// </param>
protected void UpdateMediaUrl(SceneObjectPart part, UUID updateId)
{
if (null == part.MediaUrl)
{
// TODO: We can't set the last changer until we start tracking which cap we give to which agent id
part.MediaUrl = "x-mv:0000000000/" + updateId;
}
else
{
string rawVersion = part.MediaUrl.Substring(5, 10);
int version = int.Parse(rawVersion);
part.MediaUrl = string.Format("x-mv:{0:D10}/{1}", ++version, updateId);
}
// m_log.DebugFormat("[MOAP]: Storing media url [{0}] in prim {1} {2}", part.MediaUrl, part.Name, part.UUID);
}
/// <summary>
/// Check the given url against the given whitelist.
/// </summary>
/// <param name="rawUrl"></param>
/// <param name="whitelist"></param>
/// <returns>true if the url matches an entry on the whitelist, false otherwise</returns>
protected bool CheckUrlAgainstWhitelist(string rawUrl, string[] whitelist)
{
Uri url = new Uri(rawUrl);
foreach (string origWlUrl in whitelist)
{
string wlUrl = origWlUrl;
// Deal with a line-ending wildcard
if (wlUrl.EndsWith("*"))
wlUrl = wlUrl.Remove(wlUrl.Length - 1);
// m_log.DebugFormat("[MOAP]: Checking whitelist URL pattern {0}", origWlUrl);
// Handle a line starting wildcard slightly differently since this can only match the domain, not the path
if (wlUrl.StartsWith("*"))
{
wlUrl = wlUrl.Substring(1);
if (url.Host.Contains(wlUrl))
{
// m_log.DebugFormat("[MOAP]: Whitelist URL {0} matches {1}", origWlUrl, rawUrl);
return true;
}
}
else
{
string urlToMatch = url.Authority + url.AbsolutePath;
if (urlToMatch.StartsWith(wlUrl))
{
// m_log.DebugFormat("[MOAP]: Whitelist URL {0} matches {1}", origWlUrl, rawUrl);
return true;
}
}
}
return false;
}
}
}
| BogusCurry/halcyon | OpenSim/Region/CoreModules/World/Media/Moap/MoapModule.cs | C# | bsd-3-clause | 24,358 |
package testhelpers;
import androidx.annotation.NonNull;
import android.util.Log;
import timber.log.Timber;
public class JUnitTree extends Timber.DebugTree {
private final int minlogLevel;
public JUnitTree() {
minlogLevel = Log.VERBOSE;
}
public JUnitTree(int minlogLevel) {
this.minlogLevel = minlogLevel;
}
private static String priorityToString(int priority) {
switch (priority) {
case Log.ERROR:
return "E";
case Log.WARN:
return "W";
case Log.INFO:
return "I";
case Log.DEBUG:
return "D";
case Log.VERBOSE:
return "V";
default:
return String.valueOf(priority);
}
}
@Override
protected void log(int priority, String tag, @NonNull String message, Throwable t) {
if (priority < minlogLevel) return;
System.out.println(System.currentTimeMillis() + " " + priorityToString(priority) + "/" + tag + ": " + message);
}
}
| piwik/piwik-sdk-android | tracker/src/test/java/testhelpers/JUnitTree.java | Java | bsd-3-clause | 1,081 |
/** @file
*
* @ingroup foundationDataspaceLib
*
* @brief Unit tests for the #ColorDataspace.
*
* @authors Trond Lossius, Tim Place, Nils Peters, ...
*
* @copyright Copyright © 2011 Trond Lossius @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
// Dataspaces and Units employ C++ double-inheritance and are thus unsuitable for direct use
// through the usual TTObject API
#define TT_NO_DEPRECATION_WARNINGS
#include "ColorDataspace.h"
TTErr ColorDataspace::test(TTValue& returnedTestInfo)
{
int errorCount = 0;
int testAssertionCount = 0;
// Create dataspace object and set to color
try {
TTObject myDataspace("dataspace");
myDataspace.set(TT("dataspace"), TT("color"));
TTValue v;
TTValue expected;
/************************************************/
/* */
/* Test conversions to neutral unit */
/* */
/************************************************/
// rgb => rgb
myDataspace.set(TT("inputUnit"), TT("rgb"));
myDataspace.set(TT("outputUnit"), TT("rgb"));
v.resize(3);
v[0] = TTFloat64(124.2);
v[1] = TTFloat64(162.9);
v[2] = TTFloat64(13.163);
expected.resize(3);
expected[0] = TTFloat64(124.2);
expected[1] = TTFloat64(162.9);
expected[2] = TTFloat64(13.163);
myDataspace.send(TT("convert"), v, v);
TTTestAssertion("rgb to rgb",
TTTestFloat64ArrayEquivalence(v, expected),
testAssertionCount,
errorCount);
// cmy => rgb
myDataspace.set(TT("inputUnit"), TT("cmy"));
myDataspace.set(TT("outputUnit"), TT("rgb"));
v.resize(3);
v[0] = TTFloat64(255.);
v[1] = TTFloat64(127.5);
v[2] = TTFloat64(0.);
expected.resize(3);
expected[0] = TTFloat64(0.);
expected[1] = TTFloat64(0.5);
expected[2] = TTFloat64(1.0);
myDataspace.send(TT("convert"), v, v);
TTTestAssertion("cmy to rgb",
TTTestFloat64ArrayEquivalence(v, expected),
testAssertionCount,
errorCount);
// hsl => rgb
myDataspace.set(TT("inputUnit"), TT("hsl"));
myDataspace.set(TT("outputUnit"), TT("rgb"));
v.resize(3);
v[0] = TTFloat64(120.);
v[1] = TTFloat64(100.);
v[2] = TTFloat64(50.);
expected.resize(3);
expected[0] = TTFloat64(0.);
expected[1] = TTFloat64(1.0);
expected[2] = TTFloat64(0.);
myDataspace.send(TT("convert"), v, v);
TTTestAssertion("hsl to rgb",
TTTestFloat64ArrayEquivalence(v, expected),
testAssertionCount,
errorCount);
// rgb8 => rgb
myDataspace.set(TT("inputUnit"), TT("rgb8"));
myDataspace.set(TT("outputUnit"), TT("rgb"));
v.resize(3);
v[0] = TTFloat64(255.);
v[1] = TTFloat64(127.5);
v[2] = TTFloat64(0.);
expected.resize(3);
expected[0] = TTFloat64(1.);
expected[1] = TTFloat64(0.5);
expected[2] = TTFloat64(0.0);
myDataspace.send(TT("convert"), v, v);
TTTestAssertion("rgb8 to rgb",
TTTestFloat64ArrayEquivalence(v, expected),
testAssertionCount,
errorCount);
// hsv => rgb
myDataspace.set(TT("inputUnit"), TT("hsv"));
myDataspace.set(TT("outputUnit"), TT("rgb"));
v.resize(3);
v[0] = TTFloat64(120.);
v[1] =TTFloat64(100.);
v[2] = TTFloat64(100.);
expected.resize(3);
expected[0] = TTFloat64(0.);
expected[1] = TTFloat64(1.0);
expected[2] = TTFloat64(0.);
myDataspace.send(TT("convert"), v, v);
TTTestAssertion("hsv to rgb",
TTTestFloat64ArrayEquivalence(v, expected),
testAssertionCount,
errorCount);
/************************************************/
/* */
/* Test conversions from neutral unit */
/* */
/************************************************/
// rgb => cmy
myDataspace.set(TT("inputUnit"), TT("rgb"));
myDataspace.set(TT("outputUnit"), TT("cmy"));
v.resize(3);
v[0] = TTFloat64(0.);
v[1] = TTFloat64(0.5);
v[2] = TTFloat64(1.);
expected.resize(3);
expected[0] = TTFloat64(255.);
expected[1] = TTFloat64(127.5);
expected[2] = TTFloat64(0.0);
myDataspace.send(TT("convert"), v, v);
TTTestAssertion("rgb to cmy",
TTTestFloat64ArrayEquivalence(v, expected),
testAssertionCount,
errorCount);
// rgb => hsl
myDataspace.set(TT("inputUnit"), TT("rgb"));
myDataspace.set(TT("outputUnit"), TT("hsl"));
v.resize(3);
v[0] = TTFloat64(0.);
v[1] = TTFloat64(1.);
v[2] = TTFloat64(0.);
expected.resize(3);
expected[0] = TTFloat64(120.);
expected[1] = TTFloat64(100.0);
expected[2] = TTFloat64(50.);
myDataspace.send(TT("convert"), v, v);
TTTestAssertion("rgb to hsl",
TTTestFloat64ArrayEquivalence(v, expected),
testAssertionCount,
errorCount);
// rgb => rgb8
myDataspace.set(TT("inputUnit"), TT("rgb"));
myDataspace.set(TT("outputUnit"), TT("rgb8"));
v.resize(3);
v[0] = TTFloat64(1.);
v[1] = TTFloat64(0.5);
v[2] = TTFloat64(0.);
expected.resize(3);
expected[0] = TTFloat64(255.);
expected[1] = TTFloat64(127.5);
expected[2] = TTFloat64(0.0);
myDataspace.send(TT("convert"), v, v);
TTTestAssertion("rgb to rgb8",
TTTestFloat64ArrayEquivalence(v, expected),
testAssertionCount,
errorCount);
// rgb => hsv
myDataspace.set(TT("inputUnit"), TT("rgb"));
myDataspace.set(TT("outputUnit"), TT("hsv"));
v.resize(3);
v[0] = TTFloat64(0.);
v[1] = TTFloat64(1.);
v[2] = TTFloat64(0.);
expected.resize(3);
expected[0] = TTFloat64(120.);
expected[1] = TTFloat64(100.0);
expected[2] = TTFloat64(100.);
myDataspace.send(TT("convert"), v, v);
TTTestAssertion("rgb to hsv",
TTTestFloat64ArrayEquivalence(v, expected),
testAssertionCount,
errorCount);
}
catch (...) {
TTLogMessage("ColorDataspace::test TOTAL FAILURE");
errorCount = 1;
testAssertionCount = 1;
}
return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}
| eriser/JamomaCore | Foundation/extensions/DataspaceLib/tests/ColorDataspace.test.cpp | C++ | bsd-3-clause | 7,913 |
/*
* Copyright (c) 2009-2015, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
Copyright (c) 2010, NHIN Direct Project
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
3. Neither the name of the The NHIN Direct Project (nhindirect.org) nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.directconfig.service.jaxws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "deletePolicyGroups", namespace = "http://nhind.org/config")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "deletePolicyGroups", namespace = "http://nhind.org/config")
public class DeletePolicyGroups {
@XmlElement(name = "policyGroupIds", namespace = "", nillable = true)
private long[] policyGroupIds;
/**
*
* @return
* returns long[]
*/
public long[] getPolicyGroupIds() {
return this.policyGroupIds;
}
/**
*
* @param policyGroupIds
* the value for the policyGroupIds property
*/
public void setPolicyGroupIds(long[] policyGroupIds) {
this.policyGroupIds = policyGroupIds;
}
}
| beiyuxinke/CONNECT | Product/Production/Adapters/General/CONNECTDirectConfig/src/main/java/gov/hhs/fha/nhinc/directconfig/service/jaxws/DeletePolicyGroups.java | Java | bsd-3-clause | 4,197 |
"""
Problem Statement
-----------------
Assume that there is a large data set of mostly unique samples where a hidden
binary variable is dependent on the number of similar samples that exist in the
set (i.e. a sample is called positive if it has many neighbors) and that our
goal is to label all samples in this set. It is easy to see that, given sparse
enough data, if a clustering method relies on the same sample property on which
the ground truth similarity space is defined, it will naturally separate the
samples into two groups -- those found in clusters and containing mostly
positives, and those found outside clusters and containing mostly negatives.
There would exist only one possible perfect clustering -- the one with a
single, entirely homogeneous cluster C that covers all positives present in the
data set. If one were to obtain such clustering, one could correctly label all
positive samples in one step with the simple rule, *all positive samples belong
to cluster C*. Under an imperfect clustering, on the other hand, the presence
of the given sample in a cluster of size two or more implies the sample is only
likely to be positive, with the confidence of the positive call monotonously
increasing with the size of the cluster.
In other words, our expectation from a good clustering is that it will help us
minimize the amount of work labeling samples.
The application that inspired the design of this metric was mining for positive
spam examples in large data sets of short user-generated content. Given large
enough data sets, spam content naturally forms clusters either because creative
rewriting of every single individual spam message is too expensive for spammers
to employ, or because, even if human or algorithmic rewriting is applied, one
can still find features that link individual spam messages to their creator or
to the product or service being promoted in the spam campaign. The finding was
consistent with what is reported in literature [104]_.
Algorithm
---------
Given a clustering, we order the clusters from the largest one to the smallest
one. We then plot a cumulative step function where the width of the bin under a
given "step" is proportional to cluster size, and the height of the bin is
proportional to the expected number of positive samples seen so far [103]_. If a
sample is in a cluster of size one, we assume it is likely to be negative and
is therefore checked on an individual basis (the specific setting of cluster
size at which the expectation changes is our 'threshold' parameter. The result
of this assumption is that the expected contribution from unclustered
samples is equal to their actual contribution (we assume individual checking
always gives a correct answer). After two-way normalization, a perfect
clustering (i.e. where a single perfectly homogeneous cluster covers the entire
set of positives) will have the AUL score of 1.0. A failure to will result in
the AUL of 0.5. A perverse clustering, i.e. one where many negative samples fall
into clusters whose size is above our threshold, or where many positive samples
remain unclustered (fall into clusters of size below the threshold one) the AUL
somewhere between 0.0 and 0.5.
A special treatment is necessary for cases where clusters are tied by size. If
one were to treat tied clusters as a single group, one would obtain AUL of 1.0
when no clusters at all are present, which is against our desiderata. On the
other hand, if one were to treat tied clusters entirely separately, one would
obtain different results depending on the properties of the sorting algorithm,
also an undesirable situation. Always placing "heavy" clusters (i.e. those
containing more positives) towards the beginning or towards the end of the tied
group will result in, respectively, overestimating or underestimating the true
AUL. The solution here is to average the positive counts among all clusters in a
tied group, and then walk through them one by one, with the stepwise cumulative
function asymptotically approaching a diagonal from the group's bottom left
corner to the top right one. This way, a complete absence of clustering (i.e.
all clusters are of size one) will always result in AUL of 0.5.
The resulting AUL measure has some similarity with the Gini coefficient of
inequality [105]_ except we plot the corresponding curve in the opposite
direction (from "richest" to "poorest"), and do not subtract 0.5 from the
resulting score.
.. [103] We take the expected number of positives and not the actual number seen
so far as the vertical scale in order to penalize non-homogeneous
clusters. Otherwise the y=1.0 ceiling would be reached early in the
process even in very bad cases, for example when there is only one giant
non-homogeneous cluster.
References
----------
.. [104] `Whissell, J. S., & Clarke, C. L. (2011, September). Clustering for
semi-supervised spam filtering. In Proceedings of the 8th Annual
Collaboration, Electronic messaging, Anti-Abuse and Spam Conference
(pp. 125-134). ACM.
<https://doi.org/10.1145/2030376.2030391>`_
.. [105] `Wikipedia entry for Gini coefficient of inequality
<https://en.wikipedia.org/wiki/Gini_coefficient>`_
"""
import warnings
import numpy as np
from itertools import izip, chain
from operator import itemgetter
from sklearn.metrics.ranking import auc, roc_curve
from pymaptools.iter import aggregate_tuples
from pymaptools.containers import labels_to_clusters
def num2bool(num):
"""True if zero or positive real, False otherwise
When binarizing class labels, this lets us be consistent with Scikit-Learn
where binary labels can be {0, 1} with 0 being negative or {-1, 1} with -1
being negative.
"""
return num > 0
class LiftCurve(object):
"""Lift Curve for cluster-size correlated classification
"""
def __init__(self, score_groups):
self._score_groups = list(score_groups)
@classmethod
def from_counts(cls, counts_true, counts_pred):
"""Instantiates class from arrays of true and predicted counts
Parameters
----------
counts_true : array, shape = [n_clusters]
Count of positives in cluster
counts_pred : array, shape = [n_clusters]
Predicted number of positives in each cluster
"""
# convert input to a series of tuples
count_groups = izip(counts_pred, counts_true)
# sort tuples by predicted count in descending order
count_groups = sorted(count_groups, key=itemgetter(0), reverse=True)
# group tuples by predicted count so as to handle ties correctly
return cls(aggregate_tuples(count_groups))
@classmethod
def from_clusters(cls, clusters, is_class_pos=num2bool):
"""Instantiates class from clusters of class-coded points
Parameters
----------
clusters : collections.Iterable
List of lists of class labels
is_class_pos: label_true -> Bool
Boolean predicate used to binarize true (class) labels
"""
# take all non-empty clusters, score them by size and by number of
# ground truth positives
data = ((len(cluster), sum(is_class_pos(class_label) for class_label in cluster))
for cluster in clusters if cluster)
scores_pred, scores_true = zip(*data) or ([], [])
return cls.from_counts(scores_true, scores_pred)
@classmethod
def from_labels(cls, labels_true, labels_pred, is_class_pos=num2bool):
"""Instantiates class from arrays of classes and cluster sizes
Parameters
----------
labels_true : array, shape = [n_samples]
Class labels. If binary, 'is_class_pos' is optional
labels_pred : array, shape = [n_samples]
Cluster labels to evaluate
is_class_pos: label_true -> Bool
Boolean predicate used to binarize true (class) labels
"""
clusters = labels_to_clusters(labels_true, labels_pred)
return cls.from_clusters(clusters, is_class_pos=is_class_pos)
def aul_score(self, threshold=1, plot=False):
"""Calculate AUL score
Parameters
----------
threshold : int, optional (default=1)
only predicted scores above this number considered accurate
plot : bool, optional (default=False)
whether to return X and Y data series for plotting
"""
total_any = 0
total_true = 0
assumed_vertical = 0
aul = 0.0
if plot:
xs, ys = [], []
bin_height = 0.0
bin_right_edge = 0.0
# second pass: iterate over each group of predicted scores of the same
# size and calculate the AUL metric
for pred_score, true_scores in self._score_groups:
# number of clusters
num_true_scores = len(true_scores)
# sum total of positives in all clusters of given size
group_height = sum(true_scores)
total_true += group_height
# cluster size x number of clusters of given size
group_width = pred_score * num_true_scores
total_any += group_width
if pred_score > threshold:
# penalize non-homogeneous clusters simply by assuming that they
# are homogeneous, in which case their expected vertical
# contribution should be equal to their horizontal contribution.
height_incr = group_width
else:
# clusters of size one are by definition homogeneous so their
# expected vertical contribution equals sum total of any
# remaining true positives.
height_incr = group_height
assumed_vertical += height_incr
if plot:
avg_true_score = group_height / float(num_true_scores)
for _ in true_scores:
bin_height += avg_true_score
aul += bin_height * pred_score
if plot:
xs.append(bin_right_edge)
bin_right_edge += pred_score
xs.append(bin_right_edge)
ys.append(bin_height)
ys.append(bin_height)
else:
# if not tasked with generating plots, use a geometric method
# instead of looping
aul += (total_true * group_width -
((num_true_scores - 1) * pred_score * group_height) / 2.0)
if total_true > total_any:
warnings.warn(
"Number of positives found (%d) exceeds total count of %d"
% (total_true, total_any)
)
rect_area = assumed_vertical * total_any
# special case: since normalizing the AUL defines it as always smaller
# than the bounding rectangle, when denominator in the expression below
# is zero, the AUL score is also equal to zero.
aul = 0.0 if rect_area == 0 else aul / rect_area
if plot:
xs = np.array(xs, dtype=float) / total_any
ys = np.array(ys, dtype=float) / assumed_vertical
return aul, xs, ys
else:
return aul
def plot(self, threshold=1, fill=True, marker=None, save_to=None): # pragma: no cover
"""Create a graphical representation of Lift Curve
Requires Matplotlib
Parameters
----------
threshold : int, optional (default=1)
only predicted scores above this number considered accurate
marker : str, optional (default=None)
Whether to draw marker at each bend
save_to : str, optional (default=None)
If specified, save the plot to path instead of displaying
"""
from matplotlib import pyplot as plt
score, xs, ys = self.aul_score(threshold=threshold, plot=True)
fig, ax = plt.subplots()
ax.plot(xs, ys, marker=marker, linestyle='-')
if fill:
ax.fill([0.0] + list(xs) + [1.0], [0.0] + list(ys) + [0.0], 'b', alpha=0.2)
ax.plot([0.0, 1.0], [0.0, 1.0], linestyle='--', color='grey')
ax.plot([0.0, 1.0], [1.0, 1.0], linestyle='--', color='grey')
ax.plot([1.0, 1.0], [0.0, 1.0], linestyle='--', color='grey')
ax.set_xlim(xmin=0.0, xmax=1.03)
ax.set_ylim(ymin=0.0, ymax=1.04)
ax.set_xlabel("portion total")
ax.set_ylabel("portion expected positive")
ax.set_title("Lift Curve (AUL=%.3f)" % score)
if save_to is None:
fig.show()
else:
fig.savefig(save_to)
plt.close(fig)
def aul_score_from_clusters(clusters):
"""Calculate AUL score given clusters of class-coded points
Parameters
----------
clusters : collections.Iterable
List of clusters where each point is binary-coded according to true
class.
Returns
-------
aul : float
"""
return LiftCurve.from_clusters(clusters).aul_score()
def aul_score_from_labels(y_true, labels_pred):
"""AUL score given array of classes and array of cluster sizes
Parameters
----------
y_true : array, shape = [n_samples]
True binary labels in range {0, 1}
labels_pred : array, shape = [n_samples]
Cluster labels to evaluate
Returns
-------
aul : float
"""
return LiftCurve.from_labels(y_true, labels_pred).aul_score()
class RocCurve(object):
"""Receiver Operating Characteristic (ROC)
::
>>> c = RocCurve.from_labels([0, 0, 1, 1],
... [0.1, 0.4, 0.35, 0.8])
>>> c.auc_score()
0.75
>>> c.max_informedness()
0.5
"""
def __init__(self, fprs, tprs, thresholds=None, pos_label=None,
sample_weight=None):
self.fprs = fprs
self.tprs = tprs
self.thresholds = thresholds
self.pos_label = pos_label
self.sample_weight = sample_weight
def plot(self, fill=True, marker=None, save_to=None): # pragma: no cover
"""Plot the ROC curve
"""
from matplotlib import pyplot as plt
score = self.auc_score()
xs, ys = self.fprs, self.tprs
fig, ax = plt.subplots()
ax.plot(xs, ys, marker=marker, linestyle='-')
if fill:
ax.fill([0.0] + list(xs) + [1.0], [0.0] + list(ys) + [0.0], 'b', alpha=0.2)
ax.plot([0.0, 1.0], [0.0, 1.0], linestyle='--', color='grey')
ax.plot([0.0, 1.0], [1.0, 1.0], linestyle='--', color='grey')
ax.plot([1.0, 1.0], [0.0, 1.0], linestyle='--', color='grey')
ax.set_xlim(xmin=0.0, xmax=1.03)
ax.set_ylim(ymin=0.0, ymax=1.04)
ax.set_ylabel('TPR')
ax.set_xlabel('FPR')
ax.set_title("ROC Curve (AUC=%.3f)" % score)
if save_to is None:
fig.show()
else:
fig.savefig(save_to)
plt.close(fig)
@classmethod
def from_scores(cls, scores_neg, scores_pos):
"""Instantiate given scores of two ground truth classes
The score arrays don't have to be the same length.
"""
scores_pos = ((1, x) for x in scores_pos if not np.isnan(x))
scores_neg = ((0, x) for x in scores_neg if not np.isnan(x))
all_scores = zip(*chain(scores_neg, scores_pos)) or ([], [])
return cls.from_labels(*all_scores)
@classmethod
def from_labels(cls, labels_true, y_score, is_class_pos=num2bool):
"""Instantiate assuming binary labeling of {0, 1}
labels_true : array, shape = [n_samples]
Class labels. If binary, 'is_class_pos' is optional
y_score : array, shape = [n_samples]
Predicted scores
is_class_pos: label_true -> Bool
Boolean predicate used to binarize true (class) labels
"""
# num2bool Y labels
y_true = map(is_class_pos, labels_true)
# calculate axes
fprs, tprs, thresholds = roc_curve(
y_true, y_score, pos_label=True)
return cls(fprs, tprs, thresholds=thresholds)
@classmethod
def from_clusters(cls, clusters, is_class_pos=num2bool):
"""Instantiates class from clusters of class-coded points
Parameters
----------
clusters : collections.Iterable
List of lists of class labels
is_class_pos: label_true -> Bool
Boolean predicate used to binarize true (class) labels
"""
y_true = []
y_score = []
for cluster in clusters:
pred_cluster = len(cluster)
for point in cluster:
true_cluster = is_class_pos(point)
y_true.append(true_cluster)
y_score.append(pred_cluster)
return cls.from_labels(y_true, y_score)
def auc_score(self):
"""Replacement for Scikit-Learn's method
If number of Y classes is other than two, a warning will be triggered
but no exception thrown (the return value will be a NaN). Also, we
don't reorder arrays during ROC calculation since they are assumed to be
in order.
"""
return auc(self.fprs, self.tprs, reorder=False)
def optimal_cutoff(self, scoring_method):
"""Optimal cutoff point on ROC curve under scoring method
The scoring method must take two arguments: fpr and tpr.
"""
max_index = np.NINF
opt_pair = (np.nan, np.nan)
for pair in izip(self.fprs, self.tprs):
index = scoring_method(*pair)
if index > max_index:
opt_pair = pair
max_index = index
return opt_pair, max_index
@staticmethod
def _informedness(fpr, tpr):
return tpr - fpr
def max_informedness(self):
"""Maximum value of Informedness (TPR minus FPR) on a ROC curve
A diagram of what this measure looks like is shown in [101]_. Note a
correspondence between the definitions of this measure and that of
Kolmogorov-Smirnov's supremum statistic.
References
----------
.. [101] `Wikipedia entry for Youden's J statistic
<https://en.wikipedia.org/wiki/Youden%27s_J_statistic>`_
"""
return self.optimal_cutoff(self._informedness)[1]
def roc_auc_score(y_true, y_score, sample_weight=None):
"""AUC score for a ROC curve
Replaces Scikit Learn implementation (given binary ``y_true``).
"""
return RocCurve.from_labels(y_true, y_score).auc_score()
def dist_auc(scores0, scores1):
"""AUC score for two distributions, with NaN correction
Note: arithmetic mean appears to be appropriate here, as other means don't
result in total of 1.0 when sides are switched.
"""
scores0_len = len(scores0)
scores1_len = len(scores1)
scores0p = [x for x in scores0 if not np.isnan(x)]
scores1p = [x for x in scores1 if not np.isnan(x)]
scores0n_len = scores0_len - len(scores0p)
scores1n_len = scores1_len - len(scores1p)
# ``nan_pairs`` are pairs for which it is impossible to define order, due
# to at least one of the members of each being a NaN. ``def_pairs`` are
# pairs for which order can be established.
all_pairs = 2 * scores0_len * scores1_len
nan_pairs = scores0n_len * scores1_len + scores1n_len * scores0_len
def_pairs = all_pairs - nan_pairs
# the final score is the average of the score for the defined portion and
# of random-chance AUC (0.5), weighted according to the number of pairs in
# each group.
auc_score = RocCurve.from_scores(scores0p, scores1p).auc_score()
return np.average([auc_score, 0.5], weights=[def_pairs, nan_pairs])
| escherba/lsh-hdc | lsh_hdc/ranking.py | Python | bsd-3-clause | 19,946 |
#from https://github.com/serge-sans-paille/pythran/issues/1229
#runas import numpy as np; x = np.arange(3., 10.); empirical(x, 3., .5)
import numpy as np
#pythran export empirical(float[:], float, float)
def empirical(ds, alpha, x):
sds = np.sort(ds)
ds_to_the_alpha = sds**alpha
fractions = ds_to_the_alpha #/ sum (ds_to_the_alpha)
thresholds = np.cumsum(fractions)
thresholds /= thresholds[-1]
i = find_first (thresholds, lambda u: x < u)
return i
#pthran export find_first(float[:], bool (float))
def find_first (seq, pred):
for i,x in enumerate (seq):
print(i, x, pred(x))
if pred(x):
return i
return None
| serge-sans-paille/pythran | pythran/tests/cases/empirical.py | Python | bsd-3-clause | 678 |
// Behaviour Control Framework - Head control behaviour
// Author: Philipp Allgeuer <pallgeuer@ais.uni-bonn.de>
// Includes
#include <soccer_behaviour/control_layer/control_head.h>
#include <soccer_behaviour/control_layer/control_layer.h>
#include <head_control/LookAtTarget.h>
// Namespaces
using namespace std;
using namespace soccerbehaviour;
//
// Constructors
//
// Constructor
ControlHead::ControlHead(ControlLayer* L) : Behaviour(L, "ControlHead"), L(L), M(L->M), SM(L->SM), AM(L->AM)
{
}
//
// Function overrides
//
// Initialisation function
ret_t ControlHead::init()
{
// Return that initialisation was successful
return RET_OK;
}
// Update function
void ControlHead::update()
{
}
// Compute activation level function
level_t ControlHead::computeActivationLevel()
{
// Head control is active by default
return true; // Control head is active whenever Search For Ball (inhibits this) is being inhibited by a higher behaviour
}
// Execute function
void ControlHead::execute()
{
if(wasJustActivated())
ROS_WARN(" CONTROL HEAD just activated!");
geometry_msgs::PointStampedConstPtr focalVec = SM->ballFocalPosition.read();
if(!focalVec)
return; // no data yet
head_control::LookAtTarget target;
target.is_angular_data = true;
target.is_relative = true;
target.vec.z = atan2(-focalVec->point.x, focalVec->point.z);
target.vec.y = atan2(focalVec->point.y, focalVec->point.z);
AM->headControlTarget.write(target, this);
}
// Inhibited function
void ControlHead::inhibited()
{
if(wasJustDeactivated())
ROS_WARN(" CONTROL HEAD just deactivated! XXXXXXXXXXXXXXXXXXXXXXXXXX");
}
//
// Extra stuff
//
/* TODO: Define other functions that you need here */
// EOF | NimbRo/nimbro-op-ros | src/nimbro/behaviour/soccer_behaviour/src/control_layer/control_head.cpp | C++ | bsd-3-clause | 1,704 |
/*============================================================================
Library: CppMicroServices
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
============================================================================*/
#include "usModuleResourceContainer_p.h"
#include "usModuleInfo.h"
#include "usModuleUtils_p.h"
#include "usModuleResource.h"
#include "usLog_p.h"
#include "miniz.h"
#include <set>
#include <cstring>
#include <climits>
#include <cassert>
US_BEGIN_NAMESPACE
struct ModuleResourceContainerPrivate
{
ModuleResourceContainerPrivate(const ModuleInfo* moduleInfo)
: m_ModuleInfo(moduleInfo)
, m_IsValid(false)
, m_ZipArchive()
{}
typedef std::pair<std::string, int> NameIndexPair;
struct PairComp
{
bool operator()(const NameIndexPair& p1, const NameIndexPair& p2) const
{
return p1.first < p2.first;
}
};
typedef std::set<NameIndexPair, PairComp> SetType;
void InitSortedEntries()
{
if (m_SortedEntries.empty())
{
mz_uint numFiles = mz_zip_reader_get_num_files(&m_ZipArchive);
for (mz_uint fileIndex = 0; fileIndex < numFiles; ++fileIndex)
{
char fileName[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
mz_zip_reader_get_filename(&m_ZipArchive, fileIndex, fileName, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE);
m_SortedEntries.insert(std::make_pair(std::string(fileName), fileIndex));
}
}
}
const ModuleInfo* m_ModuleInfo;
bool m_IsValid;
mz_zip_archive m_ZipArchive;
std::set<NameIndexPair, PairComp> m_SortedEntries;
};
ModuleResourceContainer::ModuleResourceContainer(const ModuleInfo* moduleInfo)
: d(new ModuleResourceContainerPrivate(moduleInfo))
{
if (mz_zip_reader_init_file(&d->m_ZipArchive, moduleInfo->location.c_str(), 0))
{
d->m_IsValid = true;
}
else
{
US_DEBUG << "Could not init zip archive for module " << moduleInfo->name;
}
}
ModuleResourceContainer::~ModuleResourceContainer()
{
if (IsValid())
{
mz_zip_reader_end(&d->m_ZipArchive);
}
delete d;
}
bool ModuleResourceContainer::IsValid() const
{
return d->m_IsValid;
}
bool ModuleResourceContainer::GetStat(ModuleResourceContainer::Stat& stat) const
{
if (IsValid())
{
int fileIndex = mz_zip_reader_locate_file(&d->m_ZipArchive, stat.filePath.c_str(), nullptr, 0);
if (fileIndex >= 0)
{
return GetStat(fileIndex, stat);
}
}
return false;
}
bool ModuleResourceContainer::GetStat(int index, ModuleResourceContainer::Stat& stat) const
{
if (IsValid())
{
if (index >= 0)
{
mz_zip_archive_file_stat zipStat;
if (!mz_zip_reader_file_stat(&d->m_ZipArchive, index, &zipStat))
{
return false;
}
stat.index = index;
stat.filePath = zipStat.m_filename;
stat.isDir = mz_zip_reader_is_file_a_directory(&d->m_ZipArchive, index) ? true : false;
stat.modifiedTime = zipStat.m_time;
// This will limit the size info from uint64 to uint32 on 32-bit
// architectures. We don't care because we assume resources > 2GB
// don't make sense to be embedded in a module anyway.
assert(zipStat.m_comp_size < INT_MAX);
assert(zipStat.m_uncomp_size < INT_MAX);
stat.uncompressedSize = static_cast<int>(zipStat.m_uncomp_size);
return true;
}
}
return false;
}
void* ModuleResourceContainer::GetData(int index) const
{
return mz_zip_reader_extract_to_heap(&d->m_ZipArchive, index, nullptr, 0);
}
const ModuleInfo*ModuleResourceContainer::GetModuleInfo() const
{
return d->m_ModuleInfo;
}
void ModuleResourceContainer::GetChildren(const std::string& resourcePath, bool relativePaths,
std::vector<std::string>& names, std::vector<uint32_t>& indices) const
{
d->InitSortedEntries();
ModuleResourceContainerPrivate::SetType::const_iterator iter =
d->m_SortedEntries.find(std::make_pair(resourcePath, 0));
if (iter == d->m_SortedEntries.end())
{
return;
}
for (++iter; iter != d->m_SortedEntries.end(); ++iter)
{
if (resourcePath.size() > iter->first.size()) break;
if (iter->first.compare(0, resourcePath.size(), resourcePath) == 0)
{
std::size_t pos = iter->first.find_first_of('/', resourcePath.size());
if (pos == std::string::npos || pos == iter->first.size()-1)
{
if (relativePaths)
{
names.push_back(iter->first.substr(resourcePath.size()));
}
else
{
names.push_back(iter->first);
}
indices.push_back(iter->second);
}
}
}
}
void ModuleResourceContainer::FindNodes(const std::string& path, const std::string& filePattern,
bool recurse, std::vector<ModuleResource>& resources) const
{
std::vector<std::string> names;
std::vector<uint32_t> indices;
this->GetChildren(path, true, names, indices);
for(std::size_t i = 0, s = names.size(); i < s; ++i)
{
if (*names[i].rbegin() == '/' && recurse)
{
this->FindNodes(path + names[i], filePattern, recurse, resources);
}
if (this->Matches(names[i], filePattern))
{
resources.push_back(ModuleResource(indices[i], *this));
}
}
}
bool ModuleResourceContainer::Matches(const std::string& name, const std::string& filePattern) const
{
// short-cut
if (filePattern == "*") return true;
std::stringstream ss(filePattern);
std::string tok;
std::size_t pos = 0;
while(std::getline(ss, tok, '*'))
{
std::size_t index = name.find(tok, pos);
if (index == std::string::npos) return false;
pos = index + tok.size();
}
return true;
}
US_END_NAMESPACE
| fmilano/mitk | Modules/CppMicroServices/core/src/module/usModuleResourceContainer.cpp | C++ | bsd-3-clause | 6,232 |
/*
* -- clMAGMA (version 1.1.0) --
* Univ. of Tennessee, Knoxville
* Univ. of California, Berkeley
* Univ. of Colorado, Denver
* @date January 2014
*
* @generated from testing_zpotrf_mgpu.cpp normal z -> s, Fri Jan 10 15:51:19 2014
*
**/
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
// includes, project
#include "flops.h"
#include "magma.h"
#include "magma_lapack.h"
#include "testings.h"
#define PRECISION_s
// Flops formula
#if defined(PRECISION_z) || defined(PRECISION_c)
#define FLOPS(n) ( 6. * FMULS_POTRF(n) + 2. * FADDS_POTRF(n) )
#else
#define FLOPS(n) ( FMULS_POTRF(n) + FADDS_POTRF(n) )
#endif
/* ////////////////////////////////////////////////////////////////////////////
-- Testing spotrf_mgpu
*/
#define h_A(i,j) h_A[ i + j*lda ]
int main( int argc, char** argv)
{
real_Double_t gflops, gpu_perf, cpu_perf, gpu_time, cpu_time;
float *h_A, *h_R;
magmaFloat_ptr d_lA[MagmaMaxGPUs];
magma_int_t N = 0, n2, lda, ldda;
magma_int_t size[10] =
{ 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 };
magma_int_t i, j, k, info;
float mz_one = MAGMA_S_NEG_ONE;
magma_int_t ione = 1;
magma_int_t ISEED[4] = {0,0,0,1};
float work[1], matnorm, diffnorm;
magma_int_t num_gpus0 = 1, num_gpus, flag = 0;
int nb, mb, n_local, nk;
magma_uplo_t uplo = MagmaLower;
if (argc != 1){
for(i = 1; i<argc; i++){
if (strcmp("-N", argv[i])==0){
N = atoi(argv[++i]);
if (N>0) {
size[0] = size[9] = N;
flag = 1;
}else exit(1);
}
if(strcmp("-NGPU", argv[i])==0)
num_gpus0 = atoi(argv[++i]);
if(strcmp("-UPLO", argv[i])==0){
if(strcmp("L", argv[++i])==0){
uplo = MagmaLower;
}else{
uplo = MagmaUpper;
}
}
}
}
else {
printf("\nUsage: \n");
printf(" testing_spotrf_mgpu -N %d -NGPU %d -UPLO -L\n\n", 1024, num_gpus0);
}
/* looking for max. ldda */
ldda = 0;
n2 = 0;
for(i=0;i<10;i++){
N = size[i];
nb = magma_get_spotrf_nb(N);
mb = nb;
if(num_gpus0 > N/nb){
num_gpus = N/nb;
if(N%nb != 0) num_gpus ++;
}else{
num_gpus = num_gpus0;
}
n_local = nb*(1+N/(nb*num_gpus))*mb*((N+mb-1)/mb);
if(n_local > ldda) ldda = n_local;
if(n2 < N*N) n2 = N*N;
if(flag != 0) break;
}
/* Allocate host memory for the matrix */
TESTING_MALLOC_PIN( h_A, float, n2 );
TESTING_MALLOC_PIN( h_R, float, n2 );
/* Initialize */
magma_queue_t queues[MagmaMaxGPUs * 2];
//magma_queue_t queues[MagmaMaxGPUs];
magma_device_t devices[ MagmaMaxGPUs ];
int num = 0;
magma_err_t err;
magma_init();
err = magma_get_devices( devices, MagmaMaxGPUs, &num );
if ( err != 0 || num < 1 ) {
fprintf( stderr, "magma_get_devices failed: %d\n", err );
exit(-1);
}
for(i=0;i<num_gpus;i++){
err = magma_queue_create( devices[i], &queues[2*i] );
if ( err != 0 ) {
fprintf( stderr, "magma_queue_create failed: %d\n", err );
exit(-1);
}
err = magma_queue_create( devices[i], &queues[2*i+1] );
if ( err != 0 ) {
fprintf( stderr, "magma_queue_create failed: %d\n", err );
exit(-1);
}
}
printf("each buffer size: %d\n", ldda);
/* allocate local matrix on Buffers */
for(i=0; i<num_gpus0; i++){
TESTING_MALLOC_DEV( d_lA[i], float, ldda );
}
printf("\n\n");
printf("Using GPUs: %d\n", num_gpus0);
if(uplo == MagmaUpper){
printf("\n testing_spotrf_mgpu -N %d -NGPU %d -UPLO U\n\n", N, num_gpus0);
}else{
printf("\n testing_spotrf_mgpu -N %d -NGPU %d -UPLO L\n\n", N, num_gpus0);
}
printf(" N CPU GFlop/s (sec) GPU GFlop/s (sec) ||R_magma-R_lapack||_F / ||R_lapack||_F\n");
printf("========================================================================================\n");
for(i=0; i<10; i++){
N = size[i];
lda = N;
n2 = lda*N;
ldda = ((N+31)/32)*32;
gflops = FLOPS( (float)N ) * 1e-9;
/* Initialize the matrix */
lapackf77_slarnv( &ione, ISEED, &n2, h_A );
/* Symmetrize and increase the diagonal */
for( int i = 0; i < N; ++i ) {
MAGMA_S_SET2REAL( h_A(i,i), MAGMA_S_REAL(h_A(i,i)) + N );
for( int j = 0; j < i; ++j ) {
h_A(i, j) = MAGMA_S_CNJG( h_A(j,i) );
}
}
lapackf77_slacpy( MagmaFullStr, &N, &N, h_A, &lda, h_R, &lda );
/* Warm up to measure the performance */
nb = magma_get_spotrf_nb(N);
if(num_gpus0 > N/nb){
num_gpus = N/nb;
if(N%nb != 0) num_gpus ++;
printf("too many GPUs for the matrix size, using %d GPUs\n", (int)num_gpus);
}else{
num_gpus = num_gpus0;
}
/* distribute matrix to gpus */
if(uplo == MagmaUpper){
// Upper
ldda = ((N+mb-1)/mb)*mb;
for(j=0;j<N;j+=nb){
k = (j/nb)%num_gpus;
nk = min(nb, N-j);
magma_ssetmatrix(N, nk,
&h_A[j*lda], 0, lda,
d_lA[k], j/(nb*num_gpus)*nb*ldda, ldda,
queues[2*k]);
}
}else{
// Lower
ldda = (1+N/(nb*num_gpus))*nb;
for(j=0;j<N;j+=nb){
k = (j/nb)%num_gpus;
nk = min(nb, N-j);
magma_ssetmatrix(nk, N, &h_A[j], 0, lda,
d_lA[k], (j/(nb*num_gpus)*nb), ldda,
queues[2*k]);
}
}
magma_spotrf_mgpu( num_gpus, uplo, N, d_lA, 0, ldda, &info, queues );
/* ====================================================================
Performs operation using MAGMA
=================================================================== */
/* distribute matrix to gpus */
if(uplo == MagmaUpper){
// Upper
ldda = ((N+mb-1)/mb)*mb;
for(j=0;j<N;j+=nb){
k = (j/nb)%num_gpus;
nk = min(nb, N-j);
magma_ssetmatrix(N, nk,
&h_A[j*lda], 0, lda,
d_lA[k], j/(nb*num_gpus)*nb*ldda, ldda,
queues[2*k]);
}
}else{
// Lower
ldda = (1+N/(nb*num_gpus))*nb;
for(j=0;j<N;j+=nb){
k = (j/nb)%num_gpus;
nk = min(nb, N-j);
magma_ssetmatrix(nk, N, &h_A[j], 0, lda,
d_lA[k], (j/(nb*num_gpus)*nb), ldda,
queues[2*k]);
}
}
gpu_time = magma_wtime();
magma_spotrf_mgpu( num_gpus, uplo, N, d_lA, 0, ldda, &info, queues );
gpu_time = magma_wtime() - gpu_time;
if (info != 0)
printf( "magma_spotrf had error %d.\n", info );
gpu_perf = gflops / gpu_time;
/* gather matrix from gpus */
if(uplo==MagmaUpper){
// Upper
for(j=0;j<N;j+=nb){
k = (j/nb)%num_gpus;
nk = min(nb, N-j);
magma_sgetmatrix(N, nk,
d_lA[k], j/(nb*num_gpus)*nb*ldda, ldda,
&h_R[j*lda], 0, lda, queues[2*k]);
}
}else{
// Lower
for(j=0; j<N; j+=nb){
k = (j/nb)%num_gpus;
nk = min(nb, N-j);
magma_sgetmatrix( nk, N,
d_lA[k], (j/(nb*num_gpus)*nb), ldda,
&h_R[j], 0, lda, queues[2*k] );
}
}
/* =====================================================================
Performs operation using LAPACK
=================================================================== */
cpu_time = magma_wtime();
if(uplo == MagmaLower){
lapackf77_spotrf( MagmaLowerStr, &N, h_A, &lda, &info );
}else{
lapackf77_spotrf( MagmaUpperStr, &N, h_A, &lda, &info );
}
cpu_time = magma_wtime() - cpu_time;
if (info != 0)
printf( "lapackf77_spotrf had error %d.\n", info );
cpu_perf = gflops / cpu_time;
/* =====================================================================
Check the result compared to LAPACK
|R_magma - R_lapack| / |R_lapack|
=================================================================== */
matnorm = lapackf77_slange("f", &N, &N, h_A, &lda, work);
blasf77_saxpy(&n2, &mz_one, h_A, &ione, h_R, &ione);
diffnorm = lapackf77_slange("f", &N, &N, h_R, &lda, work);
printf( "%5d %6.2f (%6.2f) %6.2f (%6.2f) %e\n",
N, cpu_perf, cpu_time, gpu_perf, gpu_time, diffnorm / matnorm );
if (flag != 0)
break;
}
/* clean up */
TESTING_FREE_PIN( h_A );
TESTING_FREE_PIN( h_R );
for(i=0;i<num_gpus;i++){
TESTING_FREE_DEV( d_lA[i] );
magma_queue_destroy( queues[2*i] );
magma_queue_destroy( queues[2*i+1] );
}
magma_finalize();
}
| EmergentOrder/clmagma | testing/testing_spotrf_mgpu.cpp | C++ | bsd-3-clause | 9,790 |
package io.tracee.binding.jaxws;
import io.tracee.TraceeBackend;
import javax.xml.ws.handler.Handler;
import javax.xml.ws.handler.HandlerResolver;
import javax.xml.ws.handler.PortInfo;
import java.util.ArrayList;
import java.util.List;
public class TraceeClientHandlerResolver implements HandlerResolver {
private final List<Handler> handlerList = new ArrayList<>();
public TraceeClientHandlerResolver() {
handlerList.add(new TraceeClientHandler());
}
TraceeClientHandlerResolver(TraceeBackend backend) {
handlerList.add(new TraceeClientHandler(backend));
}
@Override
public final List<Handler> getHandlerChain(PortInfo portInfo) {
return handlerList;
}
}
| SvenBunge/tracee | binding/jaxws/src/main/java/io/tracee/binding/jaxws/TraceeClientHandlerResolver.java | Java | bsd-3-clause | 677 |
import numpy as np
from nose.tools import raises
from skimage.filter import median_filter
def test_00_00_zeros():
'''The median filter on an array of all zeros should be zero'''
result = median_filter(np.zeros((10, 10)), 3, np.ones((10, 10), bool))
assert np.all(result == 0)
def test_00_01_all_masked():
'''Test a completely masked image
Regression test of IMG-1029'''
result = median_filter(np.zeros((10, 10)), 3, np.zeros((10, 10), bool))
assert (np.all(result == 0))
def test_00_02_all_but_one_masked():
mask = np.zeros((10, 10), bool)
mask[5, 5] = True
median_filter(np.zeros((10, 10)), 3, mask)
def test_01_01_mask():
'''The median filter, masking a single value'''
img = np.zeros((10, 10))
img[5, 5] = 1
mask = np.ones((10, 10), bool)
mask[5, 5] = False
result = median_filter(img, 3, mask)
assert (np.all(result[mask] == 0))
np.testing.assert_equal(result[5, 5], 1)
def test_02_01_median():
'''A median filter larger than the image = median of image'''
np.random.seed(0)
img = np.random.uniform(size=(9, 9))
result = median_filter(img, 20, np.ones((9, 9), bool))
np.testing.assert_equal(result[0, 0], np.median(img))
assert (np.all(result == np.median(img)))
def test_02_02_median_bigger():
'''Use an image of more than 255 values to test approximation'''
np.random.seed(0)
img = np.random.uniform(size=(20, 20))
result = median_filter(img, 40, np.ones((20, 20), bool))
sorted = np.ravel(img)
sorted.sort()
min_acceptable = sorted[198]
max_acceptable = sorted[202]
assert (np.all(result >= min_acceptable))
assert (np.all(result <= max_acceptable))
def test_03_01_shape():
'''Make sure the median filter is the expected octagonal shape'''
radius = 5
a_2 = int(radius / 2.414213)
i, j = np.mgrid[-10:11, -10:11]
octagon = np.ones((21, 21), bool)
#
# constrain the octagon mask to be the points that are on
# the correct side of the 8 edges
#
octagon[i < -radius] = False
octagon[i > radius] = False
octagon[j < -radius] = False
octagon[j > radius] = False
octagon[i + j < -radius - a_2] = False
octagon[j - i > radius + a_2] = False
octagon[i + j > radius + a_2] = False
octagon[i - j > radius + a_2] = False
np.random.seed(0)
img = np.random.uniform(size=(21, 21))
result = median_filter(img, radius, np.ones((21, 21), bool))
sorted = img[octagon]
sorted.sort()
min_acceptable = sorted[len(sorted) / 2 - 1]
max_acceptable = sorted[len(sorted) / 2 + 1]
assert (result[10, 10] >= min_acceptable)
assert (result[10, 10] <= max_acceptable)
def test_04_01_half_masked():
'''Make sure that the median filter can handle large masked areas.'''
img = np.ones((20, 20))
mask = np.ones((20, 20), bool)
mask[10:, :] = False
img[~ mask] = 2
img[1, 1] = 0 # to prevent short circuit for uniform data.
result = median_filter(img, 5, mask)
# in partial coverage areas, the result should be only
# from the masked pixels
assert (np.all(result[:14, :] == 1))
# in zero coverage areas, the result should be the lowest
# value in the valid area
assert (np.all(result[15:, :] == np.min(img[mask])))
def test_default_values():
img = (np.random.random((20, 20)) * 255).astype(np.uint8)
mask = np.ones((20, 20), dtype=np.uint8)
result1 = median_filter(img, radius=2, mask=mask, percent=50)
result2 = median_filter(img)
np.testing.assert_array_equal(result1, result2)
@raises(ValueError)
def test_insufficient_size():
img = (np.random.random((20, 20)) * 255).astype(np.uint8)
median_filter(img, radius=1)
@raises(TypeError)
def test_wrong_shape():
img = np.empty((10, 10, 3))
median_filter(img)
if __name__ == "__main__":
np.testing.run_module_suite()
| chintak/scikit-image | skimage/filter/tests/test_ctmf.py | Python | bsd-3-clause | 3,895 |
/*================================================================================
Copyright (c) 2013 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the names of copyright holders nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
public enum HostCapabilityFtUnsupportedReason {
vMotionNotLicensed ("vMotionNotLicensed"),
missingVMotionNic ("missingVMotionNic"),
missingFTLoggingNic ("missingFTLoggingNic"),
ftNotLicensed ("ftNotLicensed"),
haAgentIssue ("haAgentIssue");
@SuppressWarnings("unused")
private final String val;
private HostCapabilityFtUnsupportedReason(String val)
{
this.val = val;
}
} | patrickianwilson/vijava-contrib | src/main/java/com/vmware/vim25/HostCapabilityFtUnsupportedReason.java | Java | bsd-3-clause | 2,147 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'BatchLocationStatus.non_response'
db.add_column(u'survey_batchlocationstatus', 'non_response',
self.gf('django.db.models.fields.BooleanField')(default=False),
keep_default=False)
def backwards(self, orm):
# Deleting field 'BatchLocationStatus.non_response'
db.delete_column(u'survey_batchlocationstatus', 'non_response')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'locations.location': {
'Meta': {'object_name': 'Location'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'parent_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'parent_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}),
'point': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['locations.Point']", 'null': 'True', 'blank': 'True'}),
'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': u"orm['locations.Location']"}),
'type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'locations'", 'null': 'True', 'to': u"orm['locations.LocationType']"})
},
u'locations.locationtype': {
'Meta': {'object_name': 'LocationType'},
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50', 'primary_key': 'True'})
},
u'locations.point': {
'Meta': {'object_name': 'Point'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'latitude': ('django.db.models.fields.DecimalField', [], {'max_digits': '13', 'decimal_places': '10'}),
'longitude': ('django.db.models.fields.DecimalField', [], {'max_digits': '13', 'decimal_places': '10'})
},
'survey.answerrule': {
'Meta': {'object_name': 'AnswerRule'},
'action': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'batch': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'batch_rule'", 'null': 'True', 'to': "orm['survey.Batch']"}),
'condition': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'next_question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'parent_question_rules'", 'null': 'True', 'to': "orm['survey.Question']"}),
'question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'rule'", 'null': 'True', 'to': "orm['survey.Question']"}),
'validate_with_max_value': ('django.db.models.fields.PositiveIntegerField', [], {'max_length': '2', 'null': 'True'}),
'validate_with_min_value': ('django.db.models.fields.PositiveIntegerField', [], {'max_length': '2', 'null': 'True'}),
'validate_with_option': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'answer_rule'", 'null': 'True', 'to': "orm['survey.QuestionOption']"}),
'validate_with_question': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Question']", 'null': 'True'}),
'validate_with_value': ('django.db.models.fields.PositiveIntegerField', [], {'max_length': '2', 'null': 'True'})
},
'survey.backend': {
'Meta': {'object_name': 'Backend'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'})
},
'survey.batch': {
'Meta': {'unique_together': "(('survey', 'name'),)", 'object_name': 'Batch'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}),
'order': ('django.db.models.fields.PositiveIntegerField', [], {'max_length': '2', 'null': 'True'}),
'survey': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'batch'", 'null': 'True', 'to': "orm['survey.Survey']"})
},
'survey.batchlocationstatus': {
'Meta': {'object_name': 'BatchLocationStatus'},
'batch': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'open_locations'", 'null': 'True', 'to': "orm['survey.Batch']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'open_batches'", 'null': 'True', 'to': u"orm['locations.Location']"}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'non_response': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
'survey.batchquestionorder': {
'Meta': {'object_name': 'BatchQuestionOrder'},
'batch': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'batch_question_order'", 'to': "orm['survey.Batch']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'order': ('django.db.models.fields.PositiveIntegerField', [], {}),
'question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'question_batch_order'", 'to': "orm['survey.Question']"})
},
'survey.formula': {
'Meta': {'object_name': 'Formula'},
'count': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'as_count'", 'null': 'True', 'to': "orm['survey.Question']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'denominator': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'as_denominator'", 'null': 'True', 'to': "orm['survey.Question']"}),
'denominator_options': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'denominator_options'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['survey.QuestionOption']"}),
'groups': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'as_group'", 'null': 'True', 'to': "orm['survey.HouseholdMemberGroup']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'indicator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'formula'", 'null': 'True', 'to': "orm['survey.Indicator']"}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'numerator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'as_numerator'", 'null': 'True', 'to': "orm['survey.Question']"}),
'numerator_options': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "'numerator_options'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['survey.QuestionOption']"})
},
'survey.groupcondition': {
'Meta': {'unique_together': "(('value', 'attribute', 'condition'),)", 'object_name': 'GroupCondition'},
'attribute': ('django.db.models.fields.CharField', [], {'default': "'AGE'", 'max_length': '20'}),
'condition': ('django.db.models.fields.CharField', [], {'default': "'EQUALS'", 'max_length': '20'}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'conditions'", 'symmetrical': 'False', 'to': "orm['survey.HouseholdMemberGroup']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'value': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'survey.household': {
'Meta': {'object_name': 'Household'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'household_code': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'investigator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'households'", 'null': 'True', 'to': "orm['survey.Investigator']"}),
'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['locations.Location']", 'null': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'random_sample_number': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}),
'survey': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'survey_household'", 'null': 'True', 'to': "orm['survey.Survey']"}),
'uid': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'})
},
'survey.householdbatchcompletion': {
'Meta': {'object_name': 'HouseholdBatchCompletion'},
'batch': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'batch_completion_households'", 'null': 'True', 'to': "orm['survey.Batch']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'household': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'batch_completion_batches'", 'null': 'True', 'to': "orm['survey.Household']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'investigator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Investigator']", 'null': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'})
},
'survey.householdhead': {
'Meta': {'object_name': 'HouseholdHead', '_ormbases': ['survey.HouseholdMember']},
u'householdmember_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['survey.HouseholdMember']", 'unique': 'True', 'primary_key': 'True'}),
'level_of_education': ('django.db.models.fields.CharField', [], {'default': "'Primary'", 'max_length': '100', 'null': 'True'}),
'occupation': ('django.db.models.fields.CharField', [], {'default': "'16'", 'max_length': '100'}),
'resident_since_month': ('django.db.models.fields.PositiveIntegerField', [], {'default': '5'}),
'resident_since_year': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1984'})
},
'survey.householdmember': {
'Meta': {'object_name': 'HouseholdMember'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'date_of_birth': ('django.db.models.fields.DateField', [], {}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '25', 'null': 'True', 'blank': 'True'}),
'household': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'household_member'", 'to': "orm['survey.Household']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'male': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'surname': ('django.db.models.fields.CharField', [], {'max_length': '25'})
},
'survey.householdmemberbatchcompletion': {
'Meta': {'object_name': 'HouseholdMemberBatchCompletion'},
'batch': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'completed_households'", 'null': 'True', 'to': "orm['survey.Batch']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'household': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'completed_batches'", 'null': 'True', 'to': "orm['survey.Household']"}),
'householdmember': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'completed_member_batches'", 'null': 'True', 'to': "orm['survey.HouseholdMember']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'investigator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'completed_batches'", 'null': 'True', 'to': "orm['survey.Investigator']"}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'})
},
'survey.householdmembergroup': {
'Meta': {'object_name': 'HouseholdMemberGroup'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0', 'unique': 'True', 'max_length': '5'})
},
'survey.indicator': {
'Meta': {'object_name': 'Indicator'},
'batch': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Batch']", 'null': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'measure': ('django.db.models.fields.CharField', [], {'default': "'Percentage'", 'max_length': '255'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'module': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'indicator'", 'to': "orm['survey.QuestionModule']"}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'survey.investigator': {
'Meta': {'object_name': 'Investigator'},
'age': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),
'backend': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Backend']", 'null': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_blocked': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'language': ('django.db.models.fields.CharField', [], {'default': "'English'", 'max_length': '100', 'null': 'True'}),
'level_of_education': ('django.db.models.fields.CharField', [], {'default': "'Primary'", 'max_length': '100', 'null': 'True'}),
'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['locations.Location']", 'null': 'True'}),
'male': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'mobile_number': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '10'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'weights': ('django.db.models.fields.FloatField', [], {'default': '0'})
},
'survey.locationautocomplete': {
'Meta': {'object_name': 'LocationAutoComplete'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['locations.Location']", 'null': 'True'}),
'text': ('django.db.models.fields.CharField', [], {'max_length': '500'})
},
'survey.locationcode': {
'Meta': {'object_name': 'LocationCode'},
'code': ('django.db.models.fields.CharField', [], {'default': '0', 'max_length': '10'}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'code'", 'to': u"orm['locations.Location']"}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'})
},
'survey.locationtypedetails': {
'Meta': {'object_name': 'LocationTypeDetails'},
'country': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'details'", 'null': 'True', 'to': u"orm['locations.Location']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'has_code': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'length_of_code': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'location_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'details'", 'to': u"orm['locations.LocationType']"}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'order': ('django.db.models.fields.PositiveIntegerField', [], {'unique': 'True', 'null': 'True', 'blank': 'True'}),
'required': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
'survey.locationweight': {
'Meta': {'object_name': 'LocationWeight'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'weight'", 'to': u"orm['locations.Location']"}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'selection_probability': ('django.db.models.fields.FloatField', [], {'default': '1.0'}),
'survey': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'location_weight'", 'to': "orm['survey.Survey']"})
},
'survey.multichoiceanswer': {
'Meta': {'object_name': 'MultiChoiceAnswer'},
'answer': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.QuestionOption']", 'null': 'True'}),
'batch': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Batch']", 'null': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'household': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'multichoiceanswer'", 'null': 'True', 'to': "orm['survey.Household']"}),
'householdmember': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'multichoiceanswer'", 'null': 'True', 'to': "orm['survey.HouseholdMember']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'investigator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'multichoiceanswer'", 'null': 'True', 'to': "orm['survey.Investigator']"}),
'is_old': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'question': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Question']", 'null': 'True'}),
'rule_applied': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.AnswerRule']", 'null': 'True'})
},
'survey.numericalanswer': {
'Meta': {'object_name': 'NumericalAnswer'},
'answer': ('django.db.models.fields.PositiveIntegerField', [], {'max_length': '5', 'null': 'True'}),
'batch': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Batch']", 'null': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'household': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'numericalanswer'", 'null': 'True', 'to': "orm['survey.Household']"}),
'householdmember': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'numericalanswer'", 'null': 'True', 'to': "orm['survey.HouseholdMember']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'investigator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'numericalanswer'", 'null': 'True', 'to': "orm['survey.Investigator']"}),
'is_old': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'question': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Question']", 'null': 'True'}),
'rule_applied': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.AnswerRule']", 'null': 'True'})
},
'survey.question': {
'Meta': {'object_name': 'Question'},
'answer_type': ('django.db.models.fields.CharField', [], {'max_length': '15'}),
'batches': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'questions'", 'null': 'True', 'to': "orm['survey.Batch']"}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'question_group'", 'null': 'True', 'to': "orm['survey.HouseholdMemberGroup']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'identifier': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'module': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'module_question'", 'null': 'True', 'to': "orm['survey.QuestionModule']"}),
'order': ('django.db.models.fields.PositiveIntegerField', [], {'max_length': '2', 'null': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'children'", 'null': 'True', 'to': "orm['survey.Question']"}),
'subquestion': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'text': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'survey.questionmodule': {
'Meta': {'object_name': 'QuestionModule'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'survey.questionoption': {
'Meta': {'object_name': 'QuestionOption'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'order': ('django.db.models.fields.PositiveIntegerField', [], {'max_length': '2', 'null': 'True'}),
'question': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'options'", 'null': 'True', 'to': "orm['survey.Question']"}),
'text': ('django.db.models.fields.CharField', [], {'max_length': '150'})
},
'survey.randomhouseholdselection': {
'Meta': {'object_name': 'RandomHouseHoldSelection'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mobile_number': ('django.db.models.fields.CharField', [], {'max_length': '10'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'no_of_households': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),
'selected_households': ('django.db.models.fields.CharField', [], {'max_length': '510'}),
'survey': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'random_household'", 'null': 'True', 'to': "orm['survey.Survey']"})
},
'survey.survey': {
'Meta': {'object_name': 'Survey'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '300', 'null': 'True', 'blank': 'True'}),
'has_sampling': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True'}),
'sample_size': ('django.db.models.fields.PositiveIntegerField', [], {'default': '10', 'max_length': '2'}),
'type': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
'survey.textanswer': {
'Meta': {'object_name': 'TextAnswer'},
'answer': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'batch': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Batch']", 'null': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'household': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'textanswer'", 'null': 'True', 'to': "orm['survey.Household']"}),
'householdmember': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'textanswer'", 'null': 'True', 'to': "orm['survey.HouseholdMember']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'investigator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'textanswer'", 'null': 'True', 'to': "orm['survey.Investigator']"}),
'is_old': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'question': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.Question']", 'null': 'True'}),
'rule_applied': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['survey.AnswerRule']", 'null': 'True'})
},
'survey.unknowndobattribute': {
'Meta': {'object_name': 'UnknownDOBAttribute'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'household_member': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'unknown_dob_attribute'", 'to': "orm['survey.HouseholdMember']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'type': ('django.db.models.fields.CharField', [], {'max_length': '15'})
},
'survey.uploaderrorlog': {
'Meta': {'object_name': 'UploadErrorLog'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'error': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}),
'filename': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'row_number': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'})
},
'survey.userprofile': {
'Meta': {'object_name': 'UserProfile'},
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'mobile_number': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '10'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'userprofile'", 'unique': 'True', 'to': u"orm['auth.User']"})
}
}
complete_apps = ['survey'] | antsmc2/mics | survey/migrations/0119_auto__add_field_batchlocationstatus_non_response.py | Python | bsd-3-clause | 36,447 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# moldynplot.StateProbFigureManager.py
#
# Copyright (C) 2015-2017 Karl T Debiec
# All rights reserved.
#
# This software may be modified and distributed under the terms of the
# BSD license. See the LICENSE file for details.
"""
Generates one or more state probability figures to specifications in a
YAML file.
"""
################################### MODULES ###################################
from __future__ import (absolute_import, division, print_function,
unicode_literals)
if __name__ == "__main__":
__package__ = str("moldynplot")
import moldynplot
from .myplotspec.FigureManager import FigureManager
from .myplotspec.manage_defaults_presets import manage_defaults_presets
from .myplotspec.manage_kwargs import manage_kwargs
################################### CLASSES ###################################
class StateProbFigureManager(FigureManager):
"""
Class to manage the generation of probability distribution figures
"""
defaults = """
draw_figure:
subplot_kw:
autoscale_on: False
axisbg: none
multi_tick_params:
bottom: off
left: on
right: off
top: off
shared_legend: True
shared_legend_kw:
spines: False
handle_kw:
ls: none
marker: s
mec: black
legend_kw:
borderaxespad: 0.0
frameon: False
handletextpad: 0.0
loc: 9
numpoints: 1
draw_subplot:
tick_params:
bottom: off
direction: out
left: on
right: off
top: off
title_kw:
verticalalignment: bottom
grid: True
grid_kw:
axis: y
b: True
color: [0.7,0.7,0.7]
linestyle: '-'
xticklabels: []
yticks: [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0]
draw_dataset:
bar_kw:
align: center
width: 0.6
ecolor: black
zorder: 3
error_kw:
zorder: 4
handle_kw:
ls: none
marker: s
mec: black
"""
available_presets = """
pbound:
help: Probability of bound state
draw_subplot:
ylabel: $P_{bound}$
yticklabels: [0.0,"",0.2,"",0.4,"",0.6,"",0.8,"",1.0]
presentation_wide:
class: target
inherits: presentation_wide
draw_figure:
bottom: 1.70
left: 4.60
right: 4.60
sub_width: 3.20
sub_height: 3.20
top: 1.00
wspace: 0.20
shared_legend: True
shared_legend_kw:
left: 4.60
sub_width: 10.00
sub_height: 1.50
bottom: 0.00
legend_kw:
columnspacing: 1
labelspacing: 0.8
legend_fp: 20r
loc: 9
ncol: 4
draw_dataset:
bar_kw:
error_kw:
capsize: 4
capthick: 2
elinewidth: 2
linewidth: 2
edgecolor: [0,0,0]
handle_kw:
ms: 20
mew: 2.0
manuscript:
class: target
inherits: manuscript
draw_figure:
left: 0.40
sub_width: 1.50
wspace: 0.10
right: 0.10
top: 0.35
sub_height: 1.50
bottom: 0.45
shared_legend: True
shared_legend_kw:
left: 0.40
sub_width: 1.50
sub_height: 0.40
bottom: 0.00
handle_kw:
mew: 0.5
ms: 5
legend_kw:
columnspacing: 0.5
labelspacing: 0.5
ncol: 4
draw_dataset:
bar_kw:
error_kw:
capsize: 2
capthick: 0.5
elinewidth: 0.5
linewidth: 0.5
edgecolor: [0,0,0]
handle_kw:
markeredgewidth: 0.5
markersize: 5
"""
@manage_defaults_presets()
@manage_kwargs()
def draw_dataset(self, subplot, experiment=None, x=None, label="",
handles=None, draw_bar=True, draw_plot=False, verbose=1, debug=0,
**kwargs):
"""
Draws a dataset.
Arguments:
subplot (Axes): Axes on which to draw
x (float): X coordinate of bar
label (str, optional): Dataset label
color (str, list, ndarray, float, optional): Dataset color
bar_kw (dict, optional): Additional keyword arguments passed
to subplot.plot()
handles (OrderedDict, optional): Nascent OrderedDict of
[labels]: handles on subplot
kwargs (dict): Additional keyword arguments
"""
from .myplotspec import get_colors, multi_get_copy
from .dataset import H5Dataset
# Handle missing input gracefully
handle_kw = multi_get_copy("handle_kw", kwargs, {})
if experiment is not None:
subplot.axhspan(experiment[0], experiment[1], lw=2,
color=[0.6, 0.6, 0.6])
if kwargs.get("draw_experiment_handle", True):
handles["Experiment"] = \
subplot.plot([-10, -10], [-10, -10], mfc=[0.6, 0.6, 0.6],
**handle_kw)[0]
return
if "infile" not in kwargs:
if "P unbound" in kwargs and "P unbound se" in kwargs:
y = 1.0 - kwargs.pop("P unbound")
yerr = kwargs.pop("P unbound se") * 1.96
elif "y" in kwargs and "y se" in kwargs:
y = kwargs.pop("y")
yerr = kwargs.pop("y se") * 1.96
elif "P unbound" in kwargs and not draw_bar and draw_plot:
y = 1.0 - kwargs.pop("P unbound")
else:
return
else:
dataset = H5Dataset(default_address="assign/stateprobs",
default_key="pbound", **kwargs)
y = 1.0 - dataset.datasets["pbound"]["P unbound"][0]
yerr = dataset.datasets["pbound"]["P unbound se"][0] * 1.96
# Configure plot settings
# Plot
if draw_bar:
bar_kw = multi_get_copy("bar_kw", kwargs, {})
get_colors(bar_kw, kwargs)
barplot = subplot.bar(x, y, yerr=yerr, **bar_kw)
handle_kw = multi_get_copy("handle_kw", kwargs, {})
handle_kw["mfc"] = barplot.patches[0].get_facecolor()
handle = subplot.plot([-10, -10], [-10, -10], **handle_kw)[0]
if draw_plot:
plot_kw = multi_get_copy("plot_kw", kwargs, {})
get_colors(plot_kw)
subplot.plot(x, y, **plot_kw)
if handles is not None and label is not None:
handles[label] = handle
#################################### MAIN #####################################
if __name__ == "__main__":
StateProbFigureManager().main()
| KarlTDebiec/myplotspec_sim | moldynplot/StateProbFigureManager.py | Python | bsd-3-clause | 7,284 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.vulkan;
import org.lwjgl.system.*;
import org.lwjgl.system.libffi.*;
import static org.lwjgl.system.APIUtil.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.libffi.LibFFI.*;
/**
* Application-defined debug report callback function.
*
* <h5>C Specification</h5>
*
* <p>The prototype for the {@link VkDebugReportCallbackCreateInfoEXT}{@code ::pfnCallback} function implemented by the application is:</p>
*
* <pre><code>
* typedef VkBool32 (VKAPI_PTR *PFN_vkDebugReportCallbackEXT)(
* VkDebugReportFlagsEXT flags,
* VkDebugReportObjectTypeEXT objectType,
* uint64_t object,
* size_t location,
* int32_t messageCode,
* const char* pLayerPrefix,
* const char* pMessage,
* void* pUserData);</code></pre>
*
* <h5>Description</h5>
*
* <p>The callback <b>must</b> not call {@code vkDestroyDebugReportCallbackEXT}.</p>
*
* <p>The callback returns a {@code VkBool32}, which is interpreted in a layer-specified manner. The application <b>should</b> always return {@link VK10#VK_FALSE FALSE}. The {@link VK10#VK_TRUE TRUE} value is reserved for use in layer development.</p>
*
* <p>{@code object} <b>must</b> be a Vulkan object or {@link VK10#VK_NULL_HANDLE NULL_HANDLE}. If {@code objectType} is not {@link EXTDebugReport#VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT} and {@code object} is not {@link VK10#VK_NULL_HANDLE NULL_HANDLE}, {@code object} <b>must</b> be a Vulkan object of the corresponding type associated with {@code objectType} as defined in <a target="_blank" href="https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#debug-report-object-types">{@code VkDebugReportObjectTypeEXT} and Vulkan Handle Relationship</a>.</p>
*
* <h5>See Also</h5>
*
* <p>{@link VkDebugReportCallbackCreateInfoEXT}</p>
*/
@FunctionalInterface
@NativeType("PFN_vkDebugReportCallbackEXT")
public interface VkDebugReportCallbackEXTI extends CallbackI {
FFICIF CIF = apiCreateCIF(
apiStdcall(),
ffi_type_uint32,
ffi_type_uint32, ffi_type_uint32, ffi_type_uint64, ffi_type_pointer, ffi_type_sint32, ffi_type_pointer, ffi_type_pointer, ffi_type_pointer
);
@Override
default FFICIF getCallInterface() { return CIF; }
@Override
default void callback(long ret, long args) {
int __result = invoke(
memGetInt(memGetAddress(args)),
memGetInt(memGetAddress(args + POINTER_SIZE)),
memGetLong(memGetAddress(args + 2 * POINTER_SIZE)),
memGetAddress(memGetAddress(args + 3 * POINTER_SIZE)),
memGetInt(memGetAddress(args + 4 * POINTER_SIZE)),
memGetAddress(memGetAddress(args + 5 * POINTER_SIZE)),
memGetAddress(memGetAddress(args + 6 * POINTER_SIZE)),
memGetAddress(memGetAddress(args + 7 * POINTER_SIZE))
);
apiClosureRet(ret, __result);
}
/**
* Application-defined debug report callback function.
*
* @param flags specifies the {@code VkDebugReportFlagBitsEXT} that triggered this callback.
* @param objectType a {@code VkDebugReportObjectTypeEXT} value specifying the type of object being used or created at the time the event was triggered.
* @param object the object where the issue was detected. If {@code objectType} is {@link EXTDebugReport#VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT}, {@code object} is undefined.
* @param location a component (layer, driver, loader) defined value specifying the <em>location</em> of the trigger. This is an <b>optional</b> value.
* @param messageCode a layer-defined value indicating what test triggered this callback.
* @param pLayerPrefix a null-terminated string that is an abbreviation of the name of the component making the callback. {@code pLayerPrefix} is only valid for the duration of the callback.
* @param pMessage a null-terminated string detailing the trigger conditions. {@code pMessage} is only valid for the duration of the callback.
* @param pUserData the user data given when the {@code VkDebugReportCallbackEXT} was created.
*/
@NativeType("VkBool32") int invoke(@NativeType("VkDebugReportFlagsEXT") int flags, @NativeType("VkDebugReportObjectTypeEXT") int objectType, @NativeType("uint64_t") long object, @NativeType("size_t") long location, @NativeType("int32_t") int messageCode, @NativeType("char const *") long pLayerPrefix, @NativeType("char const *") long pMessage, @NativeType("void *") long pUserData);
} | LWJGL-CI/lwjgl3 | modules/lwjgl/vulkan/src/generated/java/org/lwjgl/vulkan/VkDebugReportCallbackEXTI.java | Java | bsd-3-clause | 5,004 |
/** @file
*
* @ingroup dspFilterLib
*
* @brief Unit test for the FilterLib #TTAllpass2a class.
*
* @details Currently this test is just a stub
*
* @authors Trond Lossius, Tim Place
*
* @copyright Copyright © 2012 by Trond Lossius & Timothy Place @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTAllpass2a.h"
TTErr TTAllpass2a::test(TTValue& returnedTestInfo)
{
int errorCount = 0;
int testAssertionCount = 0;
// Wrap up the test results to pass back to whoever called this test
return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}
| jamoma/JamomaCore | DSP/extensions/FilterLib/tests/TTAllpass2a.test.cpp | C++ | bsd-3-clause | 665 |
<?php
return [
// string, required, root directory of all source files
'sourcePath' => __DIR__ . DIRECTORY_SEPARATOR . '..',
// string, required, root directory containing message translations.
'messagePath' => __DIR__,
// array, required, list of language codes that the extracted messages
// should be translated to. For example, ['zh-CN', 'de'].
'languages' => ['cz', 'da', 'de', 'el-GR', 'en', 'es', 'fa-IR', 'fr', 'hu', 'it', 'lt', 'nl', 'pl', 'pt', 'ru', 'vi', 'zh'],
// string, the name of the function for translating messages.
// Defaults to 'Yii::t'. This is used as a mark to find the messages to be
// translated. You may use a string for single function name or an array for
// multiple function names.
'translator' => 'Yii::t',
// boolean, whether to sort messages by keys when merging new messages
// with the existing ones. Defaults to false, which means the new (untranslated)
// messages will be separated from the old (translated) ones.
'sort' => false,
// boolean, whether the message file should be overwritten with the merged messages
'overwrite' => true,
// boolean, whether to remove messages that no longer appear in the source code.
// Defaults to false, which means each of these messages will be enclosed with a pair of '' marks.
'removeUnused' => false,
// array, list of patterns that specify which files/directories should NOT be processed.
// If empty or not set, all files/directories will be processed.
// A path matches a pattern if it contains the pattern string at its end. For example,
// '/a/b' will match all files and directories ending with '/a/b';
// the '*.svn' will match all files and directories whose name ends with '.svn'.
// and the '.svn' will match all files and directories named exactly '.svn'.
// Note, the '/' characters in a pattern matches both '/' and '\'.
// See helpers/FileHelper::findFiles() description for more details on pattern matching rules.
'only' => ['*.php'],
// array, list of patterns that specify which files (not directories) should be processed.
// If empty or not set, all files will be processed.
// Please refer to "except" for details about the patterns.
// If a file/directory matches both a pattern in "only" and "except", it will NOT be processed.
'except' => [
'.svn',
'.git',
'.gitignore',
'.gitkeep',
'.hgignore',
'.hgkeep',
'/messages',
],
// Generated file format. Can be either "php", "po" or "db".
'format' => 'php',
// When format is "db", you may specify the following two options
//'db' => 'db',
//'sourceMessageTable' => '{{%source_message}}',
];
| frankpaul142/aurasur | vendor/kartik-v/yii2-grid/messages/config.php | PHP | bsd-3-clause | 2,763 |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// * Neither the name of Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
namespace CallButler.Manager.Forms
{
partial class EditionChooserForm
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EditionChooserForm));
this.btnOK = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.btnChooseEdition = new global::Controls.LinkButton();
this.lbEditions = new global::Controls.ListBoxEx();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnOK
//
this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Location = new System.Drawing.Point(280, 279);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(75, 23);
this.btnOK.TabIndex = 0;
this.btnOK.Text = "&OK";
this.btnOK.UseVisualStyleBackColor = true;
//
// label1
//
this.label1.AutoSize = true;
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(243, 37);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(156, 13);
this.label1.TabIndex = 1;
this.label1.Text = "Choose a CallButler Edition";
//
// label2
//
this.label2.BackColor = System.Drawing.Color.Transparent;
this.label2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(48, 82);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(359, 48);
this.label2.TabIndex = 2;
this.label2.Text = "Please choose an Edition of CallButler to setup. You are only required to do this" +
" once, but you may change the edition later if you choose to upgrade.";
//
// label3
//
this.label3.AutoSize = true;
this.label3.BackColor = System.Drawing.Color.Transparent;
this.label3.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(48, 244);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(168, 13);
this.label3.TabIndex = 3;
this.label3.Text = "Not sure which edition to choose?";
//
// btnChooseEdition
//
this.btnChooseEdition.AntiAliasText = false;
this.btnChooseEdition.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.btnChooseEdition.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnChooseEdition.Font = new System.Drawing.Font("Tahoma", 8.25F);
this.btnChooseEdition.ForeColor = System.Drawing.Color.RoyalBlue;
this.btnChooseEdition.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnChooseEdition.Location = new System.Drawing.Point(212, 241);
this.btnChooseEdition.Name = "btnChooseEdition";
this.btnChooseEdition.Size = new System.Drawing.Size(144, 19);
this.btnChooseEdition.TabIndex = 24;
this.btnChooseEdition.Text = "Click here to learn more.";
this.btnChooseEdition.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnChooseEdition.UnderlineOnHover = true;
this.btnChooseEdition.Click += new System.EventHandler(this.btnChooseEdition_Click);
//
// lbEditions
//
this.lbEditions.AntiAliasText = false;
this.lbEditions.BackColor = System.Drawing.Color.WhiteSmoke;
this.lbEditions.BorderColor = System.Drawing.Color.Gray;
this.lbEditions.CaptionColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.lbEditions.CaptionFont = new System.Drawing.Font("Tahoma", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbEditions.DisplayMember = "Name";
this.lbEditions.DrawBorder = false;
this.lbEditions.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.lbEditions.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lbEditions.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.lbEditions.FormattingEnabled = true;
this.lbEditions.ItemMargin = 5;
this.lbEditions.Location = new System.Drawing.Point(51, 127);
this.lbEditions.Name = "lbEditions";
this.lbEditions.SelectionColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(225)))), ((int)(((byte)(244)))));
this.lbEditions.Size = new System.Drawing.Size(356, 113);
this.lbEditions.TabIndex = 25;
this.lbEditions.ValueMember = "CategoryID";
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button1.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.button1.Location = new System.Drawing.Point(361, 279);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 26;
this.button1.Text = "&Cancel";
this.button1.UseVisualStyleBackColor = true;
//
// EditionChooserForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.BackgroundImage = global::CallButler.Manager.Properties.Resources.cb_header_small;
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.ClientSize = new System.Drawing.Size(448, 314);
this.Controls.Add(this.button1);
this.Controls.Add(this.lbEditions);
this.Controls.Add(this.btnChooseEdition);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnOK);
this.Font = new System.Drawing.Font("Tahoma", 8.25F);
this.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(83)))), ((int)(((byte)(83)))), ((int)(((byte)(83)))));
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "EditionChooserForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Choose CallButler Edition";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private global::Controls.LinkButton btnChooseEdition;
private global::Controls.ListBoxEx lbEditions;
private System.Windows.Forms.Button button1;
}
} | cetin01/callbutler-in-vs2008 | CallButler Manager/Forms/EditionChooserForm.Designer.cs | C# | bsd-3-clause | 11,454 |
import { useColorScheme as maybeUseColorScheme } from 'react-native';
// TODO(brentvatne): add this warning back after releasing SDK 38.
//
// if (!maybeUseColorScheme) {
// console.warn(
// 'expo-status-bar is only supported on Expo SDK >= 38 and React Native >= 0.62. You are seeing this message because useColorScheme from react-native is not available. Some features may not work as expected.'
// );
// }
const fallbackUseColorScheme = () => 'light';
const useColorScheme = maybeUseColorScheme ?? fallbackUseColorScheme;
export default useColorScheme;
| exponent/exponent | packages/expo-status-bar/src/useColorScheme.ts | TypeScript | bsd-3-clause | 566 |
# Author: Travis Oliphant
# 1999 -- 2002
from __future__ import division, print_function, absolute_import
import warnings
import threading
from . import sigtools
from scipy._lib.six import callable
from scipy._lib._version import NumpyVersion
from scipy import linalg
from scipy.fftpack import (fft, ifft, ifftshift, fft2, ifft2, fftn,
ifftn, fftfreq)
from numpy.fft import rfftn, irfftn
from numpy import (allclose, angle, arange, argsort, array, asarray,
atleast_1d, atleast_2d, cast, dot, exp, expand_dims,
iscomplexobj, isscalar, mean, ndarray, newaxis, ones, pi,
poly, polyadd, polyder, polydiv, polymul, polysub, polyval,
prod, product, r_, ravel, real_if_close, reshape,
roots, sort, sum, take, transpose, unique, where, zeros,
zeros_like)
import numpy as np
from scipy.special import factorial
from .windows import get_window
from ._arraytools import axis_slice, axis_reverse, odd_ext, even_ext, const_ext
__all__ = ['correlate', 'fftconvolve', 'convolve', 'convolve2d', 'correlate2d',
'order_filter', 'medfilt', 'medfilt2d', 'wiener', 'lfilter',
'lfiltic', 'sosfilt', 'deconvolve', 'hilbert', 'hilbert2',
'cmplx_sort', 'unique_roots', 'invres', 'invresz', 'residue',
'residuez', 'resample', 'detrend', 'lfilter_zi', 'sosfilt_zi',
'filtfilt', 'decimate', 'vectorstrength']
_modedict = {'valid': 0, 'same': 1, 'full': 2}
_boundarydict = {'fill': 0, 'pad': 0, 'wrap': 2, 'circular': 2, 'symm': 1,
'symmetric': 1, 'reflect': 4}
_rfft_mt_safe = (NumpyVersion(np.__version__) >= '1.9.0.dev-e24486e')
_rfft_lock = threading.Lock()
def _valfrommode(mode):
try:
val = _modedict[mode]
except KeyError:
if mode not in [0, 1, 2]:
raise ValueError("Acceptable mode flags are 'valid' (0),"
" 'same' (1), or 'full' (2).")
val = mode
return val
def _bvalfromboundary(boundary):
try:
val = _boundarydict[boundary] << 2
except KeyError:
if val not in [0, 1, 2]:
raise ValueError("Acceptable boundary flags are 'fill', 'wrap'"
" (or 'circular'), \n and 'symm'"
" (or 'symmetric').")
val = boundary << 2
return val
def _check_valid_mode_shapes(shape1, shape2):
for d1, d2 in zip(shape1, shape2):
if not d1 >= d2:
raise ValueError(
"in1 should have at least as many items as in2 in "
"every dimension for 'valid' mode.")
def correlate(in1, in2, mode='full'):
"""
Cross-correlate two N-dimensional arrays.
Cross-correlate `in1` and `in2`, with the output size determined by the
`mode` argument.
Parameters
----------
in1 : array_like
First input.
in2 : array_like
Second input. Should have the same number of dimensions as `in1`;
if sizes of `in1` and `in2` are not equal then `in1` has to be the
larger array.
mode : str {'full', 'valid', 'same'}, optional
A string indicating the size of the output:
``full``
The output is the full discrete linear cross-correlation
of the inputs. (Default)
``valid``
The output consists only of those elements that do not
rely on the zero-padding.
``same``
The output is the same size as `in1`, centered
with respect to the 'full' output.
Returns
-------
correlate : array
An N-dimensional array containing a subset of the discrete linear
cross-correlation of `in1` with `in2`.
Notes
-----
The correlation z of two d-dimensional arrays x and y is defined as:
z[...,k,...] = sum[..., i_l, ...]
x[..., i_l,...] * conj(y[..., i_l + k,...])
Examples
--------
Implement a matched filter using cross-correlation, to recover a signal
that has passed through a noisy channel.
>>> from scipy import signal
>>> sig = np.repeat([0., 1., 1., 0., 1., 0., 0., 1.], 128)
>>> sig_noise = sig + np.random.randn(len(sig))
>>> corr = signal.correlate(sig_noise, np.ones(128), mode='same') / 128
>>> import matplotlib.pyplot as plt
>>> clock = np.arange(64, len(sig), 128)
>>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, sharex=True)
>>> ax_orig.plot(sig)
>>> ax_orig.plot(clock, sig[clock], 'ro')
>>> ax_orig.set_title('Original signal')
>>> ax_noise.plot(sig_noise)
>>> ax_noise.set_title('Signal with noise')
>>> ax_corr.plot(corr)
>>> ax_corr.plot(clock, corr[clock], 'ro')
>>> ax_corr.axhline(0.5, ls=':')
>>> ax_corr.set_title('Cross-correlated with rectangular pulse')
>>> ax_orig.margins(0, 0.1)
>>> fig.show()
"""
in1 = asarray(in1)
in2 = asarray(in2)
# Don't use _valfrommode, since correlate should not accept numeric modes
try:
val = _modedict[mode]
except KeyError:
raise ValueError("Acceptable mode flags are 'valid',"
" 'same', or 'full'.")
if in1.ndim == in2.ndim == 0:
return in1 * in2
elif not in1.ndim == in2.ndim:
raise ValueError("in1 and in2 should have the same dimensionality")
if mode == 'valid':
_check_valid_mode_shapes(in1.shape, in2.shape)
ps = [i - j + 1 for i, j in zip(in1.shape, in2.shape)]
out = np.empty(ps, in1.dtype)
z = sigtools._correlateND(in1, in2, out, val)
else:
# _correlateND is far slower when in2.size > in1.size, so swap them
# and then undo the effect afterward
swapped_inputs = (mode == 'full') and (in2.size > in1.size)
if swapped_inputs:
in1, in2 = in2, in1
ps = [i + j - 1 for i, j in zip(in1.shape, in2.shape)]
# zero pad input
in1zpadded = np.zeros(ps, in1.dtype)
sc = [slice(0, i) for i in in1.shape]
in1zpadded[sc] = in1.copy()
if mode == 'full':
out = np.empty(ps, in1.dtype)
elif mode == 'same':
out = np.empty(in1.shape, in1.dtype)
z = sigtools._correlateND(in1zpadded, in2, out, val)
# Reverse and conjugate to undo the effect of swapping inputs
if swapped_inputs:
slice_obj = [slice(None, None, -1)] * len(z.shape)
z = z[slice_obj].conj()
return z
def _centered(arr, newsize):
# Return the center newsize portion of the array.
newsize = asarray(newsize)
currsize = array(arr.shape)
startind = (currsize - newsize) // 2
endind = startind + newsize
myslice = [slice(startind[k], endind[k]) for k in range(len(endind))]
return arr[tuple(myslice)]
def _next_regular(target):
"""
Find the next regular number greater than or equal to target.
Regular numbers are composites of the prime factors 2, 3, and 5.
Also known as 5-smooth numbers or Hamming numbers, these are the optimal
size for inputs to FFTPACK.
Target must be a positive integer.
"""
if target <= 6:
return target
# Quickly check if it's already a power of 2
if not (target & (target-1)):
return target
match = float('inf') # Anything found will be smaller
p5 = 1
while p5 < target:
p35 = p5
while p35 < target:
# Ceiling integer division, avoiding conversion to float
# (quotient = ceil(target / p35))
quotient = -(-target // p35)
# Quickly find next power of 2 >= quotient
try:
p2 = 2**((quotient - 1).bit_length())
except AttributeError:
# Fallback for Python <2.7
p2 = 2**(len(bin(quotient - 1)) - 2)
N = p2 * p35
if N == target:
return N
elif N < match:
match = N
p35 *= 3
if p35 == target:
return p35
if p35 < match:
match = p35
p5 *= 5
if p5 == target:
return p5
if p5 < match:
match = p5
return match
def fftconvolve(in1, in2, mode="full"):
"""Convolve two N-dimensional arrays using FFT.
Convolve `in1` and `in2` using the fast Fourier transform method, with
the output size determined by the `mode` argument.
This is generally much faster than `convolve` for large arrays (n > ~500),
but can be slower when only a few output values are needed, and can only
output float arrays (int or object array inputs will be cast to float).
Parameters
----------
in1 : array_like
First input.
in2 : array_like
Second input. Should have the same number of dimensions as `in1`;
if sizes of `in1` and `in2` are not equal then `in1` has to be the
larger array.
mode : str {'full', 'valid', 'same'}, optional
A string indicating the size of the output:
``full``
The output is the full discrete linear convolution
of the inputs. (Default)
``valid``
The output consists only of those elements that do not
rely on the zero-padding.
``same``
The output is the same size as `in1`, centered
with respect to the 'full' output.
Returns
-------
out : array
An N-dimensional array containing a subset of the discrete linear
convolution of `in1` with `in2`.
Examples
--------
Autocorrelation of white noise is an impulse. (This is at least 100 times
as fast as `convolve`.)
>>> from scipy import signal
>>> sig = np.random.randn(1000)
>>> autocorr = signal.fftconvolve(sig, sig[::-1], mode='full')
>>> import matplotlib.pyplot as plt
>>> fig, (ax_orig, ax_mag) = plt.subplots(2, 1)
>>> ax_orig.plot(sig)
>>> ax_orig.set_title('White noise')
>>> ax_mag.plot(np.arange(-len(sig)+1,len(sig)), autocorr)
>>> ax_mag.set_title('Autocorrelation')
>>> fig.show()
Gaussian blur implemented using FFT convolution. Notice the dark borders
around the image, due to the zero-padding beyond its boundaries.
The `convolve2d` function allows for other types of image boundaries,
but is far slower.
>>> from scipy import misc
>>> lena = misc.lena()
>>> kernel = np.outer(signal.gaussian(70, 8), signal.gaussian(70, 8))
>>> blurred = signal.fftconvolve(lena, kernel, mode='same')
>>> fig, (ax_orig, ax_kernel, ax_blurred) = plt.subplots(1, 3)
>>> ax_orig.imshow(lena, cmap='gray')
>>> ax_orig.set_title('Original')
>>> ax_orig.set_axis_off()
>>> ax_kernel.imshow(kernel, cmap='gray')
>>> ax_kernel.set_title('Gaussian kernel')
>>> ax_kernel.set_axis_off()
>>> ax_blurred.imshow(blurred, cmap='gray')
>>> ax_blurred.set_title('Blurred')
>>> ax_blurred.set_axis_off()
>>> fig.show()
"""
in1 = asarray(in1)
in2 = asarray(in2)
if in1.ndim == in2.ndim == 0: # scalar inputs
return in1 * in2
elif not in1.ndim == in2.ndim:
raise ValueError("in1 and in2 should have the same dimensionality")
elif in1.size == 0 or in2.size == 0: # empty arrays
return array([])
s1 = array(in1.shape)
s2 = array(in2.shape)
complex_result = (np.issubdtype(in1.dtype, np.complex) or
np.issubdtype(in2.dtype, np.complex))
shape = s1 + s2 - 1
if mode == "valid":
_check_valid_mode_shapes(s1, s2)
# Speed up FFT by padding to optimal size for FFTPACK
fshape = [_next_regular(int(d)) for d in shape]
fslice = tuple([slice(0, int(sz)) for sz in shape])
# Pre-1.9 NumPy FFT routines are not threadsafe. For older NumPys, make
# sure we only call rfftn/irfftn from one thread at a time.
if not complex_result and (_rfft_mt_safe or _rfft_lock.acquire(False)):
try:
ret = irfftn(rfftn(in1, fshape) *
rfftn(in2, fshape), fshape)[fslice].copy()
finally:
if not _rfft_mt_safe:
_rfft_lock.release()
else:
# If we're here, it's either because we need a complex result, or we
# failed to acquire _rfft_lock (meaning rfftn isn't threadsafe and
# is already in use by another thread). In either case, use the
# (threadsafe but slower) SciPy complex-FFT routines instead.
ret = ifftn(fftn(in1, fshape) * fftn(in2, fshape))[fslice].copy()
if not complex_result:
ret = ret.real
if mode == "full":
return ret
elif mode == "same":
return _centered(ret, s1)
elif mode == "valid":
return _centered(ret, s1 - s2 + 1)
else:
raise ValueError("Acceptable mode flags are 'valid',"
" 'same', or 'full'.")
def convolve(in1, in2, mode='full'):
"""
Convolve two N-dimensional arrays.
Convolve `in1` and `in2`, with the output size determined by the
`mode` argument.
Parameters
----------
in1 : array_like
First input.
in2 : array_like
Second input. Should have the same number of dimensions as `in1`;
if sizes of `in1` and `in2` are not equal then `in1` has to be the
larger array.
mode : str {'full', 'valid', 'same'}, optional
A string indicating the size of the output:
``full``
The output is the full discrete linear convolution
of the inputs. (Default)
``valid``
The output consists only of those elements that do not
rely on the zero-padding.
``same``
The output is the same size as `in1`, centered
with respect to the 'full' output.
Returns
-------
convolve : array
An N-dimensional array containing a subset of the discrete linear
convolution of `in1` with `in2`.
See also
--------
numpy.polymul : performs polynomial multiplication (same operation, but
also accepts poly1d objects)
"""
volume = asarray(in1)
kernel = asarray(in2)
if volume.ndim == kernel.ndim == 0:
return volume * kernel
slice_obj = [slice(None, None, -1)] * len(kernel.shape)
if np.iscomplexobj(kernel):
return correlate(volume, kernel[slice_obj].conj(), mode)
else:
return correlate(volume, kernel[slice_obj], mode)
def order_filter(a, domain, rank):
"""
Perform an order filter on an N-dimensional array.
Perform an order filter on the array in. The domain argument acts as a
mask centered over each pixel. The non-zero elements of domain are
used to select elements surrounding each input pixel which are placed
in a list. The list is sorted, and the output for that pixel is the
element corresponding to rank in the sorted list.
Parameters
----------
a : ndarray
The N-dimensional input array.
domain : array_like
A mask array with the same number of dimensions as `in`.
Each dimension should have an odd number of elements.
rank : int
A non-negative integer which selects the element from the
sorted list (0 corresponds to the smallest element, 1 is the
next smallest element, etc.).
Returns
-------
out : ndarray
The results of the order filter in an array with the same
shape as `in`.
Examples
--------
>>> from scipy import signal
>>> x = np.arange(25).reshape(5, 5)
>>> domain = np.identity(3)
>>> x
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]])
>>> signal.order_filter(x, domain, 0)
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 1., 2., 0.],
[ 0., 5., 6., 7., 0.],
[ 0., 10., 11., 12., 0.],
[ 0., 0., 0., 0., 0.]])
>>> signal.order_filter(x, domain, 2)
array([[ 6., 7., 8., 9., 4.],
[ 11., 12., 13., 14., 9.],
[ 16., 17., 18., 19., 14.],
[ 21., 22., 23., 24., 19.],
[ 20., 21., 22., 23., 24.]])
"""
domain = asarray(domain)
size = domain.shape
for k in range(len(size)):
if (size[k] % 2) != 1:
raise ValueError("Each dimension of domain argument "
" should have an odd number of elements.")
return sigtools._order_filterND(a, domain, rank)
def medfilt(volume, kernel_size=None):
"""
Perform a median filter on an N-dimensional array.
Apply a median filter to the input array using a local window-size
given by `kernel_size`.
Parameters
----------
volume : array_like
An N-dimensional input array.
kernel_size : array_like, optional
A scalar or an N-length list giving the size of the median filter
window in each dimension. Elements of `kernel_size` should be odd.
If `kernel_size` is a scalar, then this scalar is used as the size in
each dimension. Default size is 3 for each dimension.
Returns
-------
out : ndarray
An array the same size as input containing the median filtered
result.
"""
volume = atleast_1d(volume)
if kernel_size is None:
kernel_size = [3] * len(volume.shape)
kernel_size = asarray(kernel_size)
if kernel_size.shape == ():
kernel_size = np.repeat(kernel_size.item(), volume.ndim)
for k in range(len(volume.shape)):
if (kernel_size[k] % 2) != 1:
raise ValueError("Each element of kernel_size should be odd.")
domain = ones(kernel_size)
numels = product(kernel_size, axis=0)
order = numels // 2
return sigtools._order_filterND(volume, domain, order)
def wiener(im, mysize=None, noise=None):
"""
Perform a Wiener filter on an N-dimensional array.
Apply a Wiener filter to the N-dimensional array `im`.
Parameters
----------
im : ndarray
An N-dimensional array.
mysize : int or arraylike, optional
A scalar or an N-length list giving the size of the Wiener filter
window in each dimension. Elements of mysize should be odd.
If mysize is a scalar, then this scalar is used as the size
in each dimension.
noise : float, optional
The noise-power to use. If None, then noise is estimated as the
average of the local variance of the input.
Returns
-------
out : ndarray
Wiener filtered result with the same shape as `im`.
"""
im = asarray(im)
if mysize is None:
mysize = [3] * len(im.shape)
mysize = asarray(mysize)
if mysize.shape == ():
mysize = np.repeat(mysize.item(), im.ndim)
# Estimate the local mean
lMean = correlate(im, ones(mysize), 'same') / product(mysize, axis=0)
# Estimate the local variance
lVar = (correlate(im ** 2, ones(mysize), 'same') / product(mysize, axis=0)
- lMean ** 2)
# Estimate the noise power if needed.
if noise is None:
noise = mean(ravel(lVar), axis=0)
res = (im - lMean)
res *= (1 - noise / lVar)
res += lMean
out = where(lVar < noise, lMean, res)
return out
def convolve2d(in1, in2, mode='full', boundary='fill', fillvalue=0):
"""
Convolve two 2-dimensional arrays.
Convolve `in1` and `in2` with output size determined by `mode`, and
boundary conditions determined by `boundary` and `fillvalue`.
Parameters
----------
in1, in2 : array_like
Two-dimensional input arrays to be convolved.
mode : str {'full', 'valid', 'same'}, optional
A string indicating the size of the output:
``full``
The output is the full discrete linear convolution
of the inputs. (Default)
``valid``
The output consists only of those elements that do not
rely on the zero-padding.
``same``
The output is the same size as `in1`, centered
with respect to the 'full' output.
boundary : str {'fill', 'wrap', 'symm'}, optional
A flag indicating how to handle boundaries:
``fill``
pad input arrays with fillvalue. (default)
``wrap``
circular boundary conditions.
``symm``
symmetrical boundary conditions.
fillvalue : scalar, optional
Value to fill pad input arrays with. Default is 0.
Returns
-------
out : ndarray
A 2-dimensional array containing a subset of the discrete linear
convolution of `in1` with `in2`.
Examples
--------
Compute the gradient of an image by 2D convolution with a complex Scharr
operator. (Horizontal operator is real, vertical is imaginary.) Use
symmetric boundary condition to avoid creating edges at the image
boundaries.
>>> from scipy import signal
>>> from scipy import misc
>>> lena = misc.lena()
>>> scharr = np.array([[ -3-3j, 0-10j, +3 -3j],
... [-10+0j, 0+ 0j, +10 +0j],
... [ -3+3j, 0+10j, +3 +3j]]) # Gx + j*Gy
>>> grad = signal.convolve2d(lena, scharr, boundary='symm', mode='same')
>>> import matplotlib.pyplot as plt
>>> fig, (ax_orig, ax_mag, ax_ang) = plt.subplots(1, 3)
>>> ax_orig.imshow(lena, cmap='gray')
>>> ax_orig.set_title('Original')
>>> ax_orig.set_axis_off()
>>> ax_mag.imshow(np.absolute(grad), cmap='gray')
>>> ax_mag.set_title('Gradient magnitude')
>>> ax_mag.set_axis_off()
>>> ax_ang.imshow(np.angle(grad), cmap='hsv') # hsv is cyclic, like angles
>>> ax_ang.set_title('Gradient orientation')
>>> ax_ang.set_axis_off()
>>> fig.show()
"""
in1 = asarray(in1)
in2 = asarray(in2)
if mode == 'valid':
_check_valid_mode_shapes(in1.shape, in2.shape)
val = _valfrommode(mode)
bval = _bvalfromboundary(boundary)
with warnings.catch_warnings():
warnings.simplefilter('ignore', np.ComplexWarning)
# FIXME: some cast generates a warning here
out = sigtools._convolve2d(in1, in2, 1, val, bval, fillvalue)
return out
def correlate2d(in1, in2, mode='full', boundary='fill', fillvalue=0):
"""
Cross-correlate two 2-dimensional arrays.
Cross correlate `in1` and `in2` with output size determined by `mode`, and
boundary conditions determined by `boundary` and `fillvalue`.
Parameters
----------
in1, in2 : array_like
Two-dimensional input arrays to be convolved.
mode : str {'full', 'valid', 'same'}, optional
A string indicating the size of the output:
``full``
The output is the full discrete linear cross-correlation
of the inputs. (Default)
``valid``
The output consists only of those elements that do not
rely on the zero-padding.
``same``
The output is the same size as `in1`, centered
with respect to the 'full' output.
boundary : str {'fill', 'wrap', 'symm'}, optional
A flag indicating how to handle boundaries:
``fill``
pad input arrays with fillvalue. (default)
``wrap``
circular boundary conditions.
``symm``
symmetrical boundary conditions.
fillvalue : scalar, optional
Value to fill pad input arrays with. Default is 0.
Returns
-------
correlate2d : ndarray
A 2-dimensional array containing a subset of the discrete linear
cross-correlation of `in1` with `in2`.
Examples
--------
Use 2D cross-correlation to find the location of a template in a noisy
image:
>>> from scipy import signal
>>> from scipy import misc
>>> lena = misc.lena() - misc.lena().mean()
>>> template = np.copy(lena[235:295, 310:370]) # right eye
>>> template -= template.mean()
>>> lena = lena + np.random.randn(*lena.shape) * 50 # add noise
>>> corr = signal.correlate2d(lena, template, boundary='symm', mode='same')
>>> y, x = np.unravel_index(np.argmax(corr), corr.shape) # find the match
>>> import matplotlib.pyplot as plt
>>> fig, (ax_orig, ax_template, ax_corr) = plt.subplots(1, 3)
>>> ax_orig.imshow(lena, cmap='gray')
>>> ax_orig.set_title('Original')
>>> ax_orig.set_axis_off()
>>> ax_template.imshow(template, cmap='gray')
>>> ax_template.set_title('Template')
>>> ax_template.set_axis_off()
>>> ax_corr.imshow(corr, cmap='gray')
>>> ax_corr.set_title('Cross-correlation')
>>> ax_corr.set_axis_off()
>>> ax_orig.plot(x, y, 'ro')
>>> fig.show()
"""
in1 = asarray(in1)
in2 = asarray(in2)
if mode == 'valid':
_check_valid_mode_shapes(in1.shape, in2.shape)
val = _valfrommode(mode)
bval = _bvalfromboundary(boundary)
with warnings.catch_warnings():
warnings.simplefilter('ignore', np.ComplexWarning)
# FIXME: some cast generates a warning here
out = sigtools._convolve2d(in1, in2, 0, val, bval, fillvalue)
return out
def medfilt2d(input, kernel_size=3):
"""
Median filter a 2-dimensional array.
Apply a median filter to the `input` array using a local window-size
given by `kernel_size` (must be odd).
Parameters
----------
input : array_like
A 2-dimensional input array.
kernel_size : array_like, optional
A scalar or a list of length 2, giving the size of the
median filter window in each dimension. Elements of
`kernel_size` should be odd. If `kernel_size` is a scalar,
then this scalar is used as the size in each dimension.
Default is a kernel of size (3, 3).
Returns
-------
out : ndarray
An array the same size as input containing the median filtered
result.
"""
image = asarray(input)
if kernel_size is None:
kernel_size = [3] * 2
kernel_size = asarray(kernel_size)
if kernel_size.shape == ():
kernel_size = np.repeat(kernel_size.item(), 2)
for size in kernel_size:
if (size % 2) != 1:
raise ValueError("Each element of kernel_size should be odd.")
return sigtools._medfilt2d(image, kernel_size)
def lfilter(b, a, x, axis=-1, zi=None):
"""
Filter data along one-dimension with an IIR or FIR filter.
Filter a data sequence, `x`, using a digital filter. This works for many
fundamental data types (including Object type). The filter is a direct
form II transposed implementation of the standard difference equation
(see Notes).
Parameters
----------
b : array_like
The numerator coefficient vector in a 1-D sequence.
a : array_like
The denominator coefficient vector in a 1-D sequence. If ``a[0]``
is not 1, then both `a` and `b` are normalized by ``a[0]``.
x : array_like
An N-dimensional input array.
axis : int
The axis of the input data array along which to apply the
linear filter. The filter is applied to each subarray along
this axis. Default is -1.
zi : array_like, optional
Initial conditions for the filter delays. It is a vector
(or array of vectors for an N-dimensional input) of length
``max(len(a),len(b))-1``. If `zi` is None or is not given then
initial rest is assumed. See `lfiltic` for more information.
Returns
-------
y : array
The output of the digital filter.
zf : array, optional
If `zi` is None, this is not returned, otherwise, `zf` holds the
final filter delay values.
Notes
-----
The filter function is implemented as a direct II transposed structure.
This means that the filter implements::
a[0]*y[n] = b[0]*x[n] + b[1]*x[n-1] + ... + b[nb]*x[n-nb]
- a[1]*y[n-1] - ... - a[na]*y[n-na]
using the following difference equations::
y[m] = b[0]*x[m] + z[0,m-1]
z[0,m] = b[1]*x[m] + z[1,m-1] - a[1]*y[m]
...
z[n-3,m] = b[n-2]*x[m] + z[n-2,m-1] - a[n-2]*y[m]
z[n-2,m] = b[n-1]*x[m] - a[n-1]*y[m]
where m is the output sample number and n=max(len(a),len(b)) is the
model order.
The rational transfer function describing this filter in the
z-transform domain is::
-1 -nb
b[0] + b[1]z + ... + b[nb] z
Y(z) = ---------------------------------- X(z)
-1 -na
a[0] + a[1]z + ... + a[na] z
"""
if isscalar(a):
a = [a]
if zi is None:
return sigtools._linear_filter(b, a, x, axis)
else:
return sigtools._linear_filter(b, a, x, axis, zi)
def lfiltic(b, a, y, x=None):
"""
Construct initial conditions for lfilter.
Given a linear filter (b, a) and initial conditions on the output `y`
and the input `x`, return the initial conditions on the state vector zi
which is used by `lfilter` to generate the output given the input.
Parameters
----------
b : array_like
Linear filter term.
a : array_like
Linear filter term.
y : array_like
Initial conditions.
If ``N=len(a) - 1``, then ``y = {y[-1], y[-2], ..., y[-N]}``.
If `y` is too short, it is padded with zeros.
x : array_like, optional
Initial conditions.
If ``M=len(b) - 1``, then ``x = {x[-1], x[-2], ..., x[-M]}``.
If `x` is not given, its initial conditions are assumed zero.
If `x` is too short, it is padded with zeros.
Returns
-------
zi : ndarray
The state vector ``zi``.
``zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]}``, where ``K = max(M,N)``.
See Also
--------
lfilter
"""
N = np.size(a) - 1
M = np.size(b) - 1
K = max(M, N)
y = asarray(y)
if y.dtype.kind in 'bui':
# ensure calculations are floating point
y = y.astype(np.float64)
zi = zeros(K, y.dtype)
if x is None:
x = zeros(M, y.dtype)
else:
x = asarray(x)
L = np.size(x)
if L < M:
x = r_[x, zeros(M - L)]
L = np.size(y)
if L < N:
y = r_[y, zeros(N - L)]
for m in range(M):
zi[m] = sum(b[m + 1:] * x[:M - m], axis=0)
for m in range(N):
zi[m] -= sum(a[m + 1:] * y[:N - m], axis=0)
return zi
def deconvolve(signal, divisor):
"""Deconvolves ``divisor`` out of ``signal``.
Returns the quotient and remainder such that
``signal = convolve(divisor, quotient) + remainder``
Parameters
----------
signal : array_like
Signal data, typically a recorded signal
divisor : array_like
Divisor data, typically an impulse response or filter that was
applied to the original signal
Returns
-------
quotient : ndarray
Quotient, typically the recovered original signal
remainder : ndarray
Remainder
Examples
--------
Deconvolve a signal that's been filtered:
>>> from scipy import signal
>>> original = [0, 1, 0, 0, 1, 1, 0, 0]
>>> impulse_response = [2, 1]
>>> recorded = signal.convolve(impulse_response, original)
>>> recorded
array([0, 2, 1, 0, 2, 3, 1, 0, 0])
>>> recovered, remainder = signal.deconvolve(recorded, impulse_response)
>>> recovered
array([ 0., 1., 0., 0., 1., 1., 0., 0.])
See also
--------
numpy.polydiv : performs polynomial division (same operation, but
also accepts poly1d objects)
"""
num = atleast_1d(signal)
den = atleast_1d(divisor)
N = len(num)
D = len(den)
if D > N:
quot = []
rem = num
else:
input = ones(N - D + 1, float)
input[1:] = 0
quot = lfilter(num, den, input)
rem = num - convolve(den, quot, mode='full')
return quot, rem
def hilbert(x, N=None, axis=-1):
"""
Compute the analytic signal, using the Hilbert transform.
The transformation is done along the last axis by default.
Parameters
----------
x : array_like
Signal data. Must be real.
N : int, optional
Number of Fourier components. Default: ``x.shape[axis]``
axis : int, optional
Axis along which to do the transformation. Default: -1.
Returns
-------
xa : ndarray
Analytic signal of `x`, of each 1-D array along `axis`
Notes
-----
The analytic signal ``x_a(t)`` of signal ``x(t)`` is:
.. math:: x_a = F^{-1}(F(x) 2U) = x + i y
where `F` is the Fourier transform, `U` the unit step function,
and `y` the Hilbert transform of `x`. [1]_
In other words, the negative half of the frequency spectrum is zeroed
out, turning the real-valued signal into a complex signal. The Hilbert
transformed signal can be obtained from ``np.imag(hilbert(x))``, and the
original signal from ``np.real(hilbert(x))``.
References
----------
.. [1] Wikipedia, "Analytic signal".
http://en.wikipedia.org/wiki/Analytic_signal
"""
x = asarray(x)
if iscomplexobj(x):
raise ValueError("x must be real.")
if N is None:
N = x.shape[axis]
if N <= 0:
raise ValueError("N must be positive.")
Xf = fft(x, N, axis=axis)
h = zeros(N)
if N % 2 == 0:
h[0] = h[N // 2] = 1
h[1:N // 2] = 2
else:
h[0] = 1
h[1:(N + 1) // 2] = 2
if len(x.shape) > 1:
ind = [newaxis] * x.ndim
ind[axis] = slice(None)
h = h[ind]
x = ifft(Xf * h, axis=axis)
return x
def hilbert2(x, N=None):
"""
Compute the '2-D' analytic signal of `x`
Parameters
----------
x : array_like
2-D signal data.
N : int or tuple of two ints, optional
Number of Fourier components. Default is ``x.shape``
Returns
-------
xa : ndarray
Analytic signal of `x` taken along axes (0,1).
References
----------
.. [1] Wikipedia, "Analytic signal",
http://en.wikipedia.org/wiki/Analytic_signal
"""
x = atleast_2d(x)
if len(x.shape) > 2:
raise ValueError("x must be 2-D.")
if iscomplexobj(x):
raise ValueError("x must be real.")
if N is None:
N = x.shape
elif isinstance(N, int):
if N <= 0:
raise ValueError("N must be positive.")
N = (N, N)
elif len(N) != 2 or np.any(np.asarray(N) <= 0):
raise ValueError("When given as a tuple, N must hold exactly "
"two positive integers")
Xf = fft2(x, N, axes=(0, 1))
h1 = zeros(N[0], 'd')
h2 = zeros(N[1], 'd')
for p in range(2):
h = eval("h%d" % (p + 1))
N1 = N[p]
if N1 % 2 == 0:
h[0] = h[N1 // 2] = 1
h[1:N1 // 2] = 2
else:
h[0] = 1
h[1:(N1 + 1) // 2] = 2
exec("h%d = h" % (p + 1), globals(), locals())
h = h1[:, newaxis] * h2[newaxis, :]
k = len(x.shape)
while k > 2:
h = h[:, newaxis]
k -= 1
x = ifft2(Xf * h, axes=(0, 1))
return x
def cmplx_sort(p):
"""Sort roots based on magnitude.
Parameters
----------
p : array_like
The roots to sort, as a 1-D array.
Returns
-------
p_sorted : ndarray
Sorted roots.
indx : ndarray
Array of indices needed to sort the input `p`.
"""
p = asarray(p)
if iscomplexobj(p):
indx = argsort(abs(p))
else:
indx = argsort(p)
return take(p, indx, 0), indx
def unique_roots(p, tol=1e-3, rtype='min'):
"""
Determine unique roots and their multiplicities from a list of roots.
Parameters
----------
p : array_like
The list of roots.
tol : float, optional
The tolerance for two roots to be considered equal. Default is 1e-3.
rtype : {'max', 'min, 'avg'}, optional
How to determine the returned root if multiple roots are within
`tol` of each other.
- 'max': pick the maximum of those roots.
- 'min': pick the minimum of those roots.
- 'avg': take the average of those roots.
Returns
-------
pout : ndarray
The list of unique roots, sorted from low to high.
mult : ndarray
The multiplicity of each root.
Notes
-----
This utility function is not specific to roots but can be used for any
sequence of values for which uniqueness and multiplicity has to be
determined. For a more general routine, see `numpy.unique`.
Examples
--------
>>> from scipy import signal
>>> vals = [0, 1.3, 1.31, 2.8, 1.25, 2.2, 10.3]
>>> uniq, mult = signal.unique_roots(vals, tol=2e-2, rtype='avg')
Check which roots have multiplicity larger than 1:
>>> uniq[mult > 1]
array([ 1.305])
"""
if rtype in ['max', 'maximum']:
comproot = np.max
elif rtype in ['min', 'minimum']:
comproot = np.min
elif rtype in ['avg', 'mean']:
comproot = np.mean
else:
raise ValueError("`rtype` must be one of "
"{'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}")
p = asarray(p) * 1.0
tol = abs(tol)
p, indx = cmplx_sort(p)
pout = []
mult = []
indx = -1
curp = p[0] + 5 * tol
sameroots = []
for k in range(len(p)):
tr = p[k]
if abs(tr - curp) < tol:
sameroots.append(tr)
curp = comproot(sameroots)
pout[indx] = curp
mult[indx] += 1
else:
pout.append(tr)
curp = tr
sameroots = [tr]
indx += 1
mult.append(1)
return array(pout), array(mult)
def invres(r, p, k, tol=1e-3, rtype='avg'):
"""
Compute b(s) and a(s) from partial fraction expansion.
If ``M = len(b)`` and ``N = len(a)``::
b(s) b[0] x**(M-1) + b[1] x**(M-2) + ... + b[M-1]
H(s) = ------ = ----------------------------------------------
a(s) a[0] x**(N-1) + a[1] x**(N-2) + ... + a[N-1]
r[0] r[1] r[-1]
= -------- + -------- + ... + --------- + k(s)
(s-p[0]) (s-p[1]) (s-p[-1])
If there are any repeated roots (closer than tol), then the partial
fraction expansion has terms like::
r[i] r[i+1] r[i+n-1]
-------- + ----------- + ... + -----------
(s-p[i]) (s-p[i])**2 (s-p[i])**n
Parameters
----------
r : ndarray
Residues.
p : ndarray
Poles.
k : ndarray
Coefficients of the direct polynomial term.
tol : float, optional
The tolerance for two roots to be considered equal. Default is 1e-3.
rtype : {'max', 'min, 'avg'}, optional
How to determine the returned root if multiple roots are within
`tol` of each other.
'max': pick the maximum of those roots.
'min': pick the minimum of those roots.
'avg': take the average of those roots.
See Also
--------
residue, unique_roots
"""
extra = k
p, indx = cmplx_sort(p)
r = take(r, indx, 0)
pout, mult = unique_roots(p, tol=tol, rtype=rtype)
p = []
for k in range(len(pout)):
p.extend([pout[k]] * mult[k])
a = atleast_1d(poly(p))
if len(extra) > 0:
b = polymul(extra, a)
else:
b = [0]
indx = 0
for k in range(len(pout)):
temp = []
for l in range(len(pout)):
if l != k:
temp.extend([pout[l]] * mult[l])
for m in range(mult[k]):
t2 = temp[:]
t2.extend([pout[k]] * (mult[k] - m - 1))
b = polyadd(b, r[indx] * poly(t2))
indx += 1
b = real_if_close(b)
while allclose(b[0], 0, rtol=1e-14) and (b.shape[-1] > 1):
b = b[1:]
return b, a
def residue(b, a, tol=1e-3, rtype='avg'):
"""
Compute partial-fraction expansion of b(s) / a(s).
If ``M = len(b)`` and ``N = len(a)``, then the partial-fraction
expansion H(s) is defined as::
b(s) b[0] s**(M-1) + b[1] s**(M-2) + ... + b[M-1]
H(s) = ------ = ----------------------------------------------
a(s) a[0] s**(N-1) + a[1] s**(N-2) + ... + a[N-1]
r[0] r[1] r[-1]
= -------- + -------- + ... + --------- + k(s)
(s-p[0]) (s-p[1]) (s-p[-1])
If there are any repeated roots (closer together than `tol`), then H(s)
has terms like::
r[i] r[i+1] r[i+n-1]
-------- + ----------- + ... + -----------
(s-p[i]) (s-p[i])**2 (s-p[i])**n
Returns
-------
r : ndarray
Residues.
p : ndarray
Poles.
k : ndarray
Coefficients of the direct polynomial term.
See Also
--------
invres, numpy.poly, unique_roots
"""
b, a = map(asarray, (b, a))
rscale = a[0]
k, b = polydiv(b, a)
p = roots(a)
r = p * 0.0
pout, mult = unique_roots(p, tol=tol, rtype=rtype)
p = []
for n in range(len(pout)):
p.extend([pout[n]] * mult[n])
p = asarray(p)
# Compute the residue from the general formula
indx = 0
for n in range(len(pout)):
bn = b.copy()
pn = []
for l in range(len(pout)):
if l != n:
pn.extend([pout[l]] * mult[l])
an = atleast_1d(poly(pn))
# bn(s) / an(s) is (s-po[n])**Nn * b(s) / a(s) where Nn is
# multiplicity of pole at po[n]
sig = mult[n]
for m in range(sig, 0, -1):
if sig > m:
# compute next derivative of bn(s) / an(s)
term1 = polymul(polyder(bn, 1), an)
term2 = polymul(bn, polyder(an, 1))
bn = polysub(term1, term2)
an = polymul(an, an)
r[indx + m - 1] = (polyval(bn, pout[n]) / polyval(an, pout[n])
/ factorial(sig - m))
indx += sig
return r / rscale, p, k
def residuez(b, a, tol=1e-3, rtype='avg'):
"""
Compute partial-fraction expansion of b(z) / a(z).
If ``M = len(b)`` and ``N = len(a)``::
b(z) b[0] + b[1] z**(-1) + ... + b[M-1] z**(-M+1)
H(z) = ------ = ----------------------------------------------
a(z) a[0] + a[1] z**(-1) + ... + a[N-1] z**(-N+1)
r[0] r[-1]
= --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ...
(1-p[0]z**(-1)) (1-p[-1]z**(-1))
If there are any repeated roots (closer than tol), then the partial
fraction expansion has terms like::
r[i] r[i+1] r[i+n-1]
-------------- + ------------------ + ... + ------------------
(1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n
See also
--------
invresz, unique_roots
"""
b, a = map(asarray, (b, a))
gain = a[0]
brev, arev = b[::-1], a[::-1]
krev, brev = polydiv(brev, arev)
if krev == []:
k = []
else:
k = krev[::-1]
b = brev[::-1]
p = roots(a)
r = p * 0.0
pout, mult = unique_roots(p, tol=tol, rtype=rtype)
p = []
for n in range(len(pout)):
p.extend([pout[n]] * mult[n])
p = asarray(p)
# Compute the residue from the general formula (for discrete-time)
# the polynomial is in z**(-1) and the multiplication is by terms
# like this (1-p[i] z**(-1))**mult[i]. After differentiation,
# we must divide by (-p[i])**(m-k) as well as (m-k)!
indx = 0
for n in range(len(pout)):
bn = brev.copy()
pn = []
for l in range(len(pout)):
if l != n:
pn.extend([pout[l]] * mult[l])
an = atleast_1d(poly(pn))[::-1]
# bn(z) / an(z) is (1-po[n] z**(-1))**Nn * b(z) / a(z) where Nn is
# multiplicity of pole at po[n] and b(z) and a(z) are polynomials.
sig = mult[n]
for m in range(sig, 0, -1):
if sig > m:
# compute next derivative of bn(s) / an(s)
term1 = polymul(polyder(bn, 1), an)
term2 = polymul(bn, polyder(an, 1))
bn = polysub(term1, term2)
an = polymul(an, an)
r[indx + m - 1] = (polyval(bn, 1.0 / pout[n]) /
polyval(an, 1.0 / pout[n]) /
factorial(sig - m) / (-pout[n]) ** (sig - m))
indx += sig
return r / gain, p, k
def invresz(r, p, k, tol=1e-3, rtype='avg'):
"""
Compute b(z) and a(z) from partial fraction expansion.
If ``M = len(b)`` and ``N = len(a)``::
b(z) b[0] + b[1] z**(-1) + ... + b[M-1] z**(-M+1)
H(z) = ------ = ----------------------------------------------
a(z) a[0] + a[1] z**(-1) + ... + a[N-1] z**(-N+1)
r[0] r[-1]
= --------------- + ... + ---------------- + k[0] + k[1]z**(-1)...
(1-p[0]z**(-1)) (1-p[-1]z**(-1))
If there are any repeated roots (closer than tol), then the partial
fraction expansion has terms like::
r[i] r[i+1] r[i+n-1]
-------------- + ------------------ + ... + ------------------
(1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n
See Also
--------
residuez, unique_roots, invres
"""
extra = asarray(k)
p, indx = cmplx_sort(p)
r = take(r, indx, 0)
pout, mult = unique_roots(p, tol=tol, rtype=rtype)
p = []
for k in range(len(pout)):
p.extend([pout[k]] * mult[k])
a = atleast_1d(poly(p))
if len(extra) > 0:
b = polymul(extra, a)
else:
b = [0]
indx = 0
brev = asarray(b)[::-1]
for k in range(len(pout)):
temp = []
# Construct polynomial which does not include any of this root
for l in range(len(pout)):
if l != k:
temp.extend([pout[l]] * mult[l])
for m in range(mult[k]):
t2 = temp[:]
t2.extend([pout[k]] * (mult[k] - m - 1))
brev = polyadd(brev, (r[indx] * poly(t2))[::-1])
indx += 1
b = real_if_close(brev[::-1])
return b, a
def resample(x, num, t=None, axis=0, window=None):
"""
Resample `x` to `num` samples using Fourier method along the given axis.
The resampled signal starts at the same value as `x` but is sampled
with a spacing of ``len(x) / num * (spacing of x)``. Because a
Fourier method is used, the signal is assumed to be periodic.
Parameters
----------
x : array_like
The data to be resampled.
num : int
The number of samples in the resampled signal.
t : array_like, optional
If `t` is given, it is assumed to be the sample positions
associated with the signal data in `x`.
axis : int, optional
The axis of `x` that is resampled. Default is 0.
window : array_like, callable, string, float, or tuple, optional
Specifies the window applied to the signal in the Fourier
domain. See below for details.
Returns
-------
resampled_x or (resampled_x, resampled_t)
Either the resampled array, or, if `t` was given, a tuple
containing the resampled array and the corresponding resampled
positions.
Notes
-----
The argument `window` controls a Fourier-domain window that tapers
the Fourier spectrum before zero-padding to alleviate ringing in
the resampled values for sampled signals you didn't intend to be
interpreted as band-limited.
If `window` is a function, then it is called with a vector of inputs
indicating the frequency bins (i.e. fftfreq(x.shape[axis]) ).
If `window` is an array of the same length as `x.shape[axis]` it is
assumed to be the window to be applied directly in the Fourier
domain (with dc and low-frequency first).
For any other type of `window`, the function `scipy.signal.get_window`
is called to generate the window.
The first sample of the returned vector is the same as the first
sample of the input vector. The spacing between samples is changed
from ``dx`` to ``dx * len(x) / num``.
If `t` is not None, then it represents the old sample positions,
and the new sample positions will be returned as well as the new
samples.
As noted, `resample` uses FFT transformations, which can be very
slow if the number of input samples is large and prime, see
`scipy.fftpack.fft`.
"""
x = asarray(x)
X = fft(x, axis=axis)
Nx = x.shape[axis]
if window is not None:
if callable(window):
W = window(fftfreq(Nx))
elif isinstance(window, ndarray) and window.shape == (Nx,):
W = window
else:
W = ifftshift(get_window(window, Nx))
newshape = [1] * x.ndim
newshape[axis] = len(W)
W.shape = newshape
X = X * W
sl = [slice(None)] * len(x.shape)
newshape = list(x.shape)
newshape[axis] = num
N = int(np.minimum(num, Nx))
Y = zeros(newshape, 'D')
sl[axis] = slice(0, (N + 1) // 2)
Y[sl] = X[sl]
sl[axis] = slice(-(N - 1) // 2, None)
Y[sl] = X[sl]
y = ifft(Y, axis=axis) * (float(num) / float(Nx))
if x.dtype.char not in ['F', 'D']:
y = y.real
if t is None:
return y
else:
new_t = arange(0, num) * (t[1] - t[0]) * Nx / float(num) + t[0]
return y, new_t
def vectorstrength(events, period):
'''
Determine the vector strength of the events corresponding to the given
period.
The vector strength is a measure of phase synchrony, how well the
timing of the events is synchronized to a single period of a periodic
signal.
If multiple periods are used, calculate the vector strength of each.
This is called the "resonating vector strength".
Parameters
----------
events : 1D array_like
An array of time points containing the timing of the events.
period : float or array_like
The period of the signal that the events should synchronize to.
The period is in the same units as `events`. It can also be an array
of periods, in which case the outputs are arrays of the same length.
Returns
-------
strength : float or 1D array
The strength of the synchronization. 1.0 is perfect synchronization
and 0.0 is no synchronization. If `period` is an array, this is also
an array with each element containing the vector strength at the
corresponding period.
phase : float or array
The phase that the events are most strongly synchronized to in radians.
If `period` is an array, this is also an array with each element
containing the phase for the corresponding period.
References
----------
van Hemmen, JL, Longtin, A, and Vollmayr, AN. Testing resonating vector
strength: Auditory system, electric fish, and noise.
Chaos 21, 047508 (2011);
doi: 10.1063/1.3670512
van Hemmen, JL. Vector strength after Goldberg, Brown, and von Mises:
biological and mathematical perspectives. Biol Cybern.
2013 Aug;107(4):385-96. doi: 10.1007/s00422-013-0561-7.
van Hemmen, JL and Vollmayr, AN. Resonating vector strength: what happens
when we vary the "probing" frequency while keeping the spike times
fixed. Biol Cybern. 2013 Aug;107(4):491-94.
doi: 10.1007/s00422-013-0560-8
'''
events = asarray(events)
period = asarray(period)
if events.ndim > 1:
raise ValueError('events cannot have dimensions more than 1')
if period.ndim > 1:
raise ValueError('period cannot have dimensions more than 1')
# we need to know later if period was originally a scalar
scalarperiod = not period.ndim
events = atleast_2d(events)
period = atleast_2d(period)
if (period <= 0).any():
raise ValueError('periods must be positive')
# this converts the times to vectors
vectors = exp(dot(2j*pi/period.T, events))
# the vector strength is just the magnitude of the mean of the vectors
# the vector phase is the angle of the mean of the vectors
vectormean = mean(vectors, axis=1)
strength = abs(vectormean)
phase = angle(vectormean)
# if the original period was a scalar, return scalars
if scalarperiod:
strength = strength[0]
phase = phase[0]
return strength, phase
def detrend(data, axis=-1, type='linear', bp=0):
"""
Remove linear trend along axis from data.
Parameters
----------
data : array_like
The input data.
axis : int, optional
The axis along which to detrend the data. By default this is the
last axis (-1).
type : {'linear', 'constant'}, optional
The type of detrending. If ``type == 'linear'`` (default),
the result of a linear least-squares fit to `data` is subtracted
from `data`.
If ``type == 'constant'``, only the mean of `data` is subtracted.
bp : array_like of ints, optional
A sequence of break points. If given, an individual linear fit is
performed for each part of `data` between two break points.
Break points are specified as indices into `data`.
Returns
-------
ret : ndarray
The detrended input data.
Examples
--------
>>> from scipy import signal
>>> randgen = np.random.RandomState(9)
>>> npoints = 1e3
>>> noise = randgen.randn(npoints)
>>> x = 3 + 2*np.linspace(0, 1, npoints) + noise
>>> (signal.detrend(x) - noise).max() < 0.01
True
"""
if type not in ['linear', 'l', 'constant', 'c']:
raise ValueError("Trend type must be 'linear' or 'constant'.")
data = asarray(data)
dtype = data.dtype.char
if dtype not in 'dfDF':
dtype = 'd'
if type in ['constant', 'c']:
ret = data - expand_dims(mean(data, axis), axis)
return ret
else:
dshape = data.shape
N = dshape[axis]
bp = sort(unique(r_[0, bp, N]))
if np.any(bp > N):
raise ValueError("Breakpoints must be less than length "
"of data along given axis.")
Nreg = len(bp) - 1
# Restructure data so that axis is along first dimension and
# all other dimensions are collapsed into second dimension
rnk = len(dshape)
if axis < 0:
axis = axis + rnk
newdims = r_[axis, 0:axis, axis + 1:rnk]
newdata = reshape(transpose(data, tuple(newdims)),
(N, prod(dshape, axis=0) // N))
newdata = newdata.copy() # make sure we have a copy
if newdata.dtype.char not in 'dfDF':
newdata = newdata.astype(dtype)
# Find leastsq fit and remove it for each piece
for m in range(Nreg):
Npts = bp[m + 1] - bp[m]
A = ones((Npts, 2), dtype)
A[:, 0] = cast[dtype](arange(1, Npts + 1) * 1.0 / Npts)
sl = slice(bp[m], bp[m + 1])
coef, resids, rank, s = linalg.lstsq(A, newdata[sl])
newdata[sl] = newdata[sl] - dot(A, coef)
# Put data back in original shape.
tdshape = take(dshape, newdims, 0)
ret = reshape(newdata, tuple(tdshape))
vals = list(range(1, rnk))
olddims = vals[:axis] + [0] + vals[axis:]
ret = transpose(ret, tuple(olddims))
return ret
def lfilter_zi(b, a):
"""
Compute an initial state `zi` for the lfilter function that corresponds
to the steady state of the step response.
A typical use of this function is to set the initial state so that the
output of the filter starts at the same value as the first element of
the signal to be filtered.
Parameters
----------
b, a : array_like (1-D)
The IIR filter coefficients. See `lfilter` for more
information.
Returns
-------
zi : 1-D ndarray
The initial state for the filter.
Notes
-----
A linear filter with order m has a state space representation (A, B, C, D),
for which the output y of the filter can be expressed as::
z(n+1) = A*z(n) + B*x(n)
y(n) = C*z(n) + D*x(n)
where z(n) is a vector of length m, A has shape (m, m), B has shape
(m, 1), C has shape (1, m) and D has shape (1, 1) (assuming x(n) is
a scalar). lfilter_zi solves::
zi = A*zi + B
In other words, it finds the initial condition for which the response
to an input of all ones is a constant.
Given the filter coefficients `a` and `b`, the state space matrices
for the transposed direct form II implementation of the linear filter,
which is the implementation used by scipy.signal.lfilter, are::
A = scipy.linalg.companion(a).T
B = b[1:] - a[1:]*b[0]
assuming `a[0]` is 1.0; if `a[0]` is not 1, `a` and `b` are first
divided by a[0].
Examples
--------
The following code creates a lowpass Butterworth filter. Then it
applies that filter to an array whose values are all 1.0; the
output is also all 1.0, as expected for a lowpass filter. If the
`zi` argument of `lfilter` had not been given, the output would have
shown the transient signal.
>>> from numpy import array, ones
>>> from scipy.signal import lfilter, lfilter_zi, butter
>>> b, a = butter(5, 0.25)
>>> zi = lfilter_zi(b, a)
>>> y, zo = lfilter(b, a, ones(10), zi=zi)
>>> y
array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
Another example:
>>> x = array([0.5, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0])
>>> y, zf = lfilter(b, a, x, zi=zi*x[0])
>>> y
array([ 0.5 , 0.5 , 0.5 , 0.49836039, 0.48610528,
0.44399389, 0.35505241])
Note that the `zi` argument to `lfilter` was computed using
`lfilter_zi` and scaled by `x[0]`. Then the output `y` has no
transient until the input drops from 0.5 to 0.0.
"""
# FIXME: Can this function be replaced with an appropriate
# use of lfiltic? For example, when b,a = butter(N,Wn),
# lfiltic(b, a, y=numpy.ones_like(a), x=numpy.ones_like(b)).
#
# We could use scipy.signal.normalize, but it uses warnings in
# cases where a ValueError is more appropriate, and it allows
# b to be 2D.
b = np.atleast_1d(b)
if b.ndim != 1:
raise ValueError("Numerator b must be 1-D.")
a = np.atleast_1d(a)
if a.ndim != 1:
raise ValueError("Denominator a must be 1-D.")
while len(a) > 1 and a[0] == 0.0:
a = a[1:]
if a.size < 1:
raise ValueError("There must be at least one nonzero `a` coefficient.")
if a[0] != 1.0:
# Normalize the coefficients so a[0] == 1.
b = b / a[0]
a = a / a[0]
n = max(len(a), len(b))
# Pad a or b with zeros so they are the same length.
if len(a) < n:
a = np.r_[a, np.zeros(n - len(a))]
elif len(b) < n:
b = np.r_[b, np.zeros(n - len(b))]
IminusA = np.eye(n - 1) - linalg.companion(a).T
B = b[1:] - a[1:] * b[0]
# Solve zi = A*zi + B
zi = np.linalg.solve(IminusA, B)
# For future reference: we could also use the following
# explicit formulas to solve the linear system:
#
# zi = np.zeros(n - 1)
# zi[0] = B.sum() / IminusA[:,0].sum()
# asum = 1.0
# csum = 0.0
# for k in range(1,n-1):
# asum += a[k]
# csum += b[k] - a[k]*b[0]
# zi[k] = asum*zi[0] - csum
return zi
def sosfilt_zi(sos):
"""
Compute an initial state `zi` for the sosfilt function that corresponds
to the steady state of the step response.
A typical use of this function is to set the initial state so that the
output of the filter starts at the same value as the first element of
the signal to be filtered.
Parameters
----------
sos : array_like
Array of second-order filter coefficients, must have shape
``(n_sections, 6)``. See `sosfilt` for the SOS filter format
specification.
Returns
-------
zi : ndarray
Initial conditions suitable for use with ``sosfilt``, shape
``(n_sections, 2)``.
See Also
--------
sosfilt, zpk2sos
Notes
-----
.. versionadded:: 0.16.0
Examples
--------
Filter a rectangular pulse that begins at time 0, with and without
the use of the `zi` argument of `scipy.signal.sosfilt`.
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> sos = signal.butter(9, 0.125, output='sos')
>>> zi = signal.sosfilt_zi(sos)
>>> x = (np.arange(250) < 100).astype(int)
>>> f1 = signal.sosfilt(sos, x)
>>> f2, zo = signal.sosfilt(sos, x, zi=zi)
>>> plt.plot(x, 'k--', label='x')
>>> plt.plot(f1, 'b', alpha=0.5, linewidth=2, label='filtered')
>>> plt.plot(f2, 'g', alpha=0.25, linewidth=4, label='filtered with zi')
>>> plt.legend(loc='best')
>>> plt.show()
"""
sos = np.asarray(sos)
if sos.ndim != 2 or sos.shape[1] != 6:
raise ValueError('sos must be shape (n_sections, 6)')
n_sections = sos.shape[0]
zi = np.empty((n_sections, 2))
scale = 1.0
for section in range(n_sections):
b = sos[section, :3]
a = sos[section, 3:]
zi[section] = scale * lfilter_zi(b, a)
# If H(z) = B(z)/A(z) is this section's transfer function, then
# b.sum()/a.sum() is H(1), the gain at omega=0. That's the steady
# state value of this section's step response.
scale *= b.sum() / a.sum()
return zi
def _filtfilt_gust(b, a, x, axis=-1, irlen=None):
"""Forward-backward IIR filter that uses Gustafsson's method.
Apply the IIR filter defined by `(b,a)` to `x` twice, first forward
then backward, using Gustafsson's initial conditions [1]_.
Let ``y_fb`` be the result of filtering first forward and then backward,
and let ``y_bf`` be the result of filtering first backward then forward.
Gustafsson's method is to compute initial conditions for the forward
pass and the backward pass such that ``y_fb == y_bf``.
Parameters
----------
b : scalar or 1-D ndarray
Numerator coefficients of the filter.
a : scalar or 1-D ndarray
Denominator coefficients of the filter.
x : ndarray
Data to be filtered.
axis : int, optional
Axis of `x` to be filtered. Default is -1.
irlen : int or None, optional
The length of the nonnegligible part of the impulse response.
If `irlen` is None, or if the length of the signal is less than
``2 * irlen``, then no part of the impulse response is ignored.
Returns
-------
y : ndarray
The filtered data.
x0 : ndarray
Initial condition for the forward filter.
x1 : ndarray
Initial condition for the backward filter.
Notes
-----
Typically the return values `x0` and `x1` are not needed by the
caller. The intended use of these return values is in unit tests.
References
----------
.. [1] F. Gustaffson. Determining the initial states in forward-backward
filtering. Transactions on Signal Processing, 46(4):988-992, 1996.
"""
# In the comments, "Gustafsson's paper" and [1] refer to the
# paper referenced in the docstring.
b = np.atleast_1d(b)
a = np.atleast_1d(a)
order = max(len(b), len(a)) - 1
if order == 0:
# The filter is just scalar multiplication, with no state.
scale = (b[0] / a[0])**2
y = scale * x
return y, np.array([]), np.array([])
if axis != -1 or axis != x.ndim - 1:
# Move the axis containing the data to the end.
x = np.swapaxes(x, axis, x.ndim - 1)
# n is the number of samples in the data to be filtered.
n = x.shape[-1]
if irlen is None or n <= 2*irlen:
m = n
else:
m = irlen
# Create Obs, the observability matrix (called O in the paper).
# This matrix can be interpreted as the operator that propagates
# an arbitrary initial state to the output, assuming the input is
# zero.
# In Gustafsson's paper, the forward and backward filters are not
# necessarily the same, so he has both O_f and O_b. We use the same
# filter in both directions, so we only need O. The same comment
# applies to S below.
Obs = np.zeros((m, order))
zi = np.zeros(order)
zi[0] = 1
Obs[:, 0] = lfilter(b, a, np.zeros(m), zi=zi)[0]
for k in range(1, order):
Obs[k:, k] = Obs[:-k, 0]
# Obsr is O^R (Gustafsson's notation for row-reversed O)
Obsr = Obs[::-1]
# Create S. S is the matrix that applies the filter to the reversed
# propagated initial conditions. That is,
# out = S.dot(zi)
# is the same as
# tmp, _ = lfilter(b, a, zeros(), zi=zi) # Propagate ICs.
# out = lfilter(b, a, tmp[::-1]) # Reverse and filter.
# Equations (5) & (6) of [1]
S = lfilter(b, a, Obs[::-1], axis=0)
# Sr is S^R (row-reversed S)
Sr = S[::-1]
# M is [(S^R - O), (O^R - S)]
if m == n:
M = np.hstack((Sr - Obs, Obsr - S))
else:
# Matrix described in section IV of [1].
M = np.zeros((2*m, 2*order))
M[:m, :order] = Sr - Obs
M[m:, order:] = Obsr - S
# Naive forward-backward and backward-forward filters.
# These have large transients because the filters use zero initial
# conditions.
y_f = lfilter(b, a, x)
y_fb = lfilter(b, a, y_f[..., ::-1])[..., ::-1]
y_b = lfilter(b, a, x[..., ::-1])[..., ::-1]
y_bf = lfilter(b, a, y_b)
delta_y_bf_fb = y_bf - y_fb
if m == n:
delta = delta_y_bf_fb
else:
start_m = delta_y_bf_fb[..., :m]
end_m = delta_y_bf_fb[..., -m:]
delta = np.concatenate((start_m, end_m), axis=-1)
# ic_opt holds the "optimal" initial conditions.
# The following code computes the result shown in the formula
# of the paper between equations (6) and (7).
if delta.ndim == 1:
ic_opt = linalg.lstsq(M, delta)[0]
else:
# Reshape delta so it can be used as an array of multiple
# right-hand-sides in linalg.lstsq.
delta2d = delta.reshape(-1, delta.shape[-1]).T
ic_opt0 = linalg.lstsq(M, delta2d)[0].T
ic_opt = ic_opt0.reshape(delta.shape[:-1] + (M.shape[-1],))
# Now compute the filtered signal using equation (7) of [1].
# First, form [S^R, O^R] and call it W.
if m == n:
W = np.hstack((Sr, Obsr))
else:
W = np.zeros((2*m, 2*order))
W[:m, :order] = Sr
W[m:, order:] = Obsr
# Equation (7) of [1] says
# Y_fb^opt = Y_fb^0 + W * [x_0^opt; x_{N-1}^opt]
# `wic` is (almost) the product on the right.
# W has shape (m, 2*order), and ic_opt has shape (..., 2*order),
# so we can't use W.dot(ic_opt). Instead, we dot ic_opt with W.T,
# so wic has shape (..., m).
wic = ic_opt.dot(W.T)
# `wic` is "almost" the product of W and the optimal ICs in equation
# (7)--if we're using a truncated impulse response (m < n), `wic`
# contains only the adjustments required for the ends of the signal.
# Here we form y_opt, taking this into account if necessary.
y_opt = y_fb
if m == n:
y_opt += wic
else:
y_opt[..., :m] += wic[..., :m]
y_opt[..., -m:] += wic[..., -m:]
x0 = ic_opt[..., :order]
x1 = ic_opt[..., -order:]
if axis != -1 or axis != x.ndim - 1:
# Restore the data axis to its original position.
x0 = np.swapaxes(x0, axis, x.ndim - 1)
x1 = np.swapaxes(x1, axis, x.ndim - 1)
y_opt = np.swapaxes(y_opt, axis, x.ndim - 1)
return y_opt, x0, x1
def filtfilt(b, a, x, axis=-1, padtype='odd', padlen=None, method='pad',
irlen=None):
"""
A forward-backward filter.
This function applies a linear filter twice, once forward and once
backwards. The combined filter has linear phase.
The function provides options for handling the edges of the signal.
When `method` is "pad", the function pads the data along the given axis
in one of three ways: odd, even or constant. The odd and even extensions
have the corresponding symmetry about the end point of the data. The
constant extension extends the data with the values at the end points. On
both the forward and backward passes, the initial condition of the
filter is found by using `lfilter_zi` and scaling it by the end point of
the extended data.
When `method` is "gust", Gustafsson's method [1]_ is used. Initial
conditions are chosen for the forward and backward passes so that the
forward-backward filter gives the same result as the backward-forward
filter.
Parameters
----------
b : (N,) array_like
The numerator coefficient vector of the filter.
a : (N,) array_like
The denominator coefficient vector of the filter. If ``a[0]``
is not 1, then both `a` and `b` are normalized by ``a[0]``.
x : array_like
The array of data to be filtered.
axis : int, optional
The axis of `x` to which the filter is applied.
Default is -1.
padtype : str or None, optional
Must be 'odd', 'even', 'constant', or None. This determines the
type of extension to use for the padded signal to which the filter
is applied. If `padtype` is None, no padding is used. The default
is 'odd'.
padlen : int or None, optional
The number of elements by which to extend `x` at both ends of
`axis` before applying the filter. This value must be less than
``x.shape[axis] - 1``. ``padlen=0`` implies no padding.
The default value is ``3 * max(len(a), len(b))``.
method : str, optional
Determines the method for handling the edges of the signal, either
"pad" or "gust". When `method` is "pad", the signal is padded; the
type of padding is determined by `padtype` and `padlen`, and `irlen`
is ignored. When `method` is "gust", Gustafsson's method is used,
and `padtype` and `padlen` are ignored.
irlen : int or None, optional
When `method` is "gust", `irlen` specifies the length of the
impulse response of the filter. If `irlen` is None, no part
of the impulse response is ignored. For a long signal, specifying
`irlen` can significantly improve the performance of the filter.
Returns
-------
y : ndarray
The filtered output, an array of type numpy.float64 with the same
shape as `x`.
See Also
--------
lfilter_zi, lfilter
Notes
-----
The option to use Gustaffson's method was added in scipy version 0.16.0.
References
----------
.. [1] F. Gustaffson, "Determining the initial states in forward-backward
filtering", Transactions on Signal Processing, Vol. 46, pp. 988-992,
1996.
Examples
--------
The examples will use several functions from `scipy.signal`.
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
First we create a one second signal that is the sum of two pure sine
waves, with frequencies 5 Hz and 250 Hz, sampled at 2000 Hz.
>>> t = np.linspace(0, 1.0, 2001)
>>> xlow = np.sin(2 * np.pi * 5 * t)
>>> xhigh = np.sin(2 * np.pi * 250 * t)
>>> x = xlow + xhigh
Now create a lowpass Butterworth filter with a cutoff of 0.125 times
the Nyquist rate, or 125 Hz, and apply it to ``x`` with `filtfilt`.
The result should be approximately ``xlow``, with no phase shift.
>>> b, a = signal.butter(8, 0.125)
>>> y = signal.filtfilt(b, a, x, padlen=150)
>>> np.abs(y - xlow).max()
9.1086182074789912e-06
We get a fairly clean result for this artificial example because
the odd extension is exact, and with the moderately long padding,
the filter's transients have dissipated by the time the actual data
is reached. In general, transient effects at the edges are
unavoidable.
The following example demonstrates the option ``method="gust"``.
First, create a filter.
>>> b, a = signal.ellip(4, 0.01, 120, 0.125) # Filter to be applied.
>>> np.random.seed(123456)
`sig` is a random input signal to be filtered.
>>> n = 60
>>> sig = np.random.randn(n)**3 + 3*np.random.randn(n).cumsum()
Apply `filtfilt` to `sig`, once using the Gustafsson method, and
once using padding, and plot the results for comparison.
>>> fgust = signal.filtfilt(b, a, sig, method="gust")
>>> fpad = signal.filtfilt(b, a, sig, padlen=50)
>>> plt.plot(sig, 'k-', label='input')
>>> plt.plot(fgust, 'b-', linewidth=4, label='gust')
>>> plt.plot(fpad, 'c-', linewidth=1.5, label='pad')
>>> plt.legend(loc='best')
>>> plt.show()
The `irlen` argument can be used to improve the performance
of Gustafsson's method.
Estimate the impulse response length of the filter.
>>> z, p, k = signal.tf2zpk(b, a)
>>> eps = 1e-9
>>> r = np.max(np.abs(p))
>>> approx_impulse_len = int(np.ceil(np.log(eps) / np.log(r)))
>>> approx_impulse_len
137
Apply the filter to a longer signal, with and without the `irlen`
argument. The difference between `y1` and `y2` is small. For long
signals, using `irlen` gives a significant performance improvement.
>>> x = np.random.randn(5000)
>>> y1 = signal.filtfilt(b, a, x, method='gust')
>>> y2 = signal.filtfilt(b, a, x, method='gust', irlen=approx_impulse_len)
>>> print(np.max(np.abs(y1 - y2)))
1.80056858312e-10
"""
b = np.atleast_1d(b)
a = np.atleast_1d(a)
x = np.asarray(x)
if method not in ["pad", "gust"]:
raise ValueError("method must be 'pad' or 'gust'.")
if method == "gust":
y, z1, z2 = _filtfilt_gust(b, a, x, axis=axis, irlen=irlen)
return y
# `method` is "pad"...
ntaps = max(len(a), len(b))
if padtype not in ['even', 'odd', 'constant', None]:
raise ValueError(("Unknown value '%s' given to padtype. padtype "
"must be 'even', 'odd', 'constant', or None.") %
padtype)
if padtype is None:
padlen = 0
if padlen is None:
# Original padding; preserved for backwards compatibility.
edge = ntaps * 3
else:
edge = padlen
# x's 'axis' dimension must be bigger than edge.
if x.shape[axis] <= edge:
raise ValueError("The length of the input vector x must be at least "
"padlen, which is %d." % edge)
if padtype is not None and edge > 0:
# Make an extension of length `edge` at each
# end of the input array.
if padtype == 'even':
ext = even_ext(x, edge, axis=axis)
elif padtype == 'odd':
ext = odd_ext(x, edge, axis=axis)
else:
ext = const_ext(x, edge, axis=axis)
else:
ext = x
# Get the steady state of the filter's step response.
zi = lfilter_zi(b, a)
# Reshape zi and create x0 so that zi*x0 broadcasts
# to the correct value for the 'zi' keyword argument
# to lfilter.
zi_shape = [1] * x.ndim
zi_shape[axis] = zi.size
zi = np.reshape(zi, zi_shape)
x0 = axis_slice(ext, stop=1, axis=axis)
# Forward filter.
(y, zf) = lfilter(b, a, ext, axis=axis, zi=zi * x0)
# Backward filter.
# Create y0 so zi*y0 broadcasts appropriately.
y0 = axis_slice(y, start=-1, axis=axis)
(y, zf) = lfilter(b, a, axis_reverse(y, axis=axis), axis=axis, zi=zi * y0)
# Reverse y.
y = axis_reverse(y, axis=axis)
if edge > 0:
# Slice the actual signal from the extended signal.
y = axis_slice(y, start=edge, stop=-edge, axis=axis)
return y
def sosfilt(sos, x, axis=-1, zi=None):
"""
Filter data along one dimension using cascaded second-order sections
Filter a data sequence, `x`, using a digital IIR filter defined by
`sos`. This is implemented by performing `lfilter` for each
second-order section. See `lfilter` for details.
Parameters
----------
sos : array_like
Array of second-order filter coefficients, must have shape
``(n_sections, 6)``. Each row corresponds to a second-order
section, with the first three columns providing the numerator
coefficients and the last three providing the denominator
coefficients.
x : array_like
An N-dimensional input array.
axis : int
The axis of the input data array along which to apply the
linear filter. The filter is applied to each subarray along
this axis. Default is -1.
zi : array_like, optional
Initial conditions for the cascaded filter delays. It is a (at
least 2D) vector of shape ``(n_sections, ..., 2, ...)``, where
``..., 2, ...`` denotes the shape of `x`, but with ``x.shape[axis]``
replaced by 2. If `zi` is None or is not given then initial rest
(i.e. all zeros) is assumed.
Note that these initial conditions are *not* the same as the initial
conditions given by `lfiltic` or `lfilter_zi`.
Returns
-------
y : ndarray
The output of the digital filter.
zf : ndarray, optional
If `zi` is None, this is not returned, otherwise, `zf` holds the
final filter delay values.
See Also
--------
zpk2sos, sos2zpk, sosfilt_zi
Notes
-----
The filter function is implemented as a series of second-order filters
with direct-form II transposed structure. It is designed to minimize
numerical precision errors for high-order filters.
.. versionadded:: 0.16.0
Examples
--------
Plot a 13th-order filter's impulse response using both `lfilter` and
`sosfilt`, showing the instability that results from trying to do a
13th-order filter in a single stage (the numerical error pushes some poles
outside of the unit circle):
>>> import matplotlib.pyplot as plt
>>> from scipy import signal
>>> b, a = signal.ellip(13, 0.009, 80, 0.05, output='ba')
>>> sos = signal.ellip(13, 0.009, 80, 0.05, output='sos')
>>> x = np.zeros(700)
>>> x[0] = 1.
>>> y_tf = signal.lfilter(b, a, x)
>>> y_sos = signal.sosfilt(sos, x)
>>> plt.plot(y_tf, 'r', label='TF')
>>> plt.plot(y_sos, 'k', label='SOS')
>>> plt.legend(loc='best')
>>> plt.show()
"""
x = np.asarray(x)
sos = atleast_2d(sos)
if sos.ndim != 2:
raise ValueError('sos array must be 2D')
n_sections, m = sos.shape
if m != 6:
raise ValueError('sos array must be shape (n_sections, 6)')
use_zi = zi is not None
if use_zi:
zi = np.asarray(zi)
x_zi_shape = list(x.shape)
x_zi_shape[axis] = 2
x_zi_shape = tuple([n_sections] + x_zi_shape)
if zi.shape != x_zi_shape:
raise ValueError('Invalid zi shape. With axis=%r, an input with '
'shape %r, and an sos array with %d sections, zi '
'must have shape %r.' %
(axis, x.shape, n_sections, x_zi_shape))
zf = zeros_like(zi)
for section in range(n_sections):
if use_zi:
x, zf[section] = lfilter(sos[section, :3], sos[section, 3:],
x, axis, zi=zi[section])
else:
x = lfilter(sos[section, :3], sos[section, 3:], x, axis)
out = (x, zf) if use_zi else x
return out
from scipy.signal.filter_design import cheby1
from scipy.signal.fir_filter_design import firwin
def decimate(x, q, n=None, ftype='iir', axis=-1):
"""
Downsample the signal by using a filter.
By default, an order 8 Chebyshev type I filter is used. A 30 point FIR
filter with hamming window is used if `ftype` is 'fir'.
Parameters
----------
x : ndarray
The signal to be downsampled, as an N-dimensional array.
q : int
The downsampling factor.
n : int, optional
The order of the filter (1 less than the length for 'fir').
ftype : str {'iir', 'fir'}, optional
The type of the lowpass filter.
axis : int, optional
The axis along which to decimate.
Returns
-------
y : ndarray
The down-sampled signal.
See also
--------
resample
"""
if not isinstance(q, int):
raise TypeError("q must be an integer")
if n is None:
if ftype == 'fir':
n = 30
else:
n = 8
if ftype == 'fir':
b = firwin(n + 1, 1. / q, window='hamming')
a = 1.
else:
b, a = cheby1(n, 0.05, 0.8 / q)
y = lfilter(b, a, x, axis=axis)
sl = [slice(None)] * y.ndim
sl[axis] = slice(None, None, q)
return y[sl]
| witcxc/scipy | scipy/signal/signaltools.py | Python | bsd-3-clause | 81,684 |
/*******************************************************************************
* Open Behavioral Health Information Technology Architecture (OBHITA.org)
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.10.18 at 11:05:26 AM EDT
//
package gov.samhsa.consent2share.c32.dto;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
// TODO: Auto-generated Javadoc
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="name">
* <complexType>
* <complexContent>
* <restriction base="{urn:hl7-org:v3}cd">
* <sequence>
* <element name="originalText" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element ref="{urn:hl7-org:v3}qualifier" maxOccurs="0" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="value">
* <complexType>
* <complexContent>
* <restriction base="{urn:hl7-org:v3}cd">
* <sequence>
* <element name="originalText" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element ref="{urn:hl7-org:v3}qualifier" maxOccurs="0" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"name",
"value"
})
@XmlRootElement(name = "qualifier")
public class Qualifier {
/** The name. */
@XmlElement(required = true)
protected Name name;
/** The value. */
@XmlElement(required = true)
protected Qualifier.Value value;
/**
* Gets the value of the name property.
*
* @return the name
* possible object is
* {@link Name }
*/
public Name getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link Name }
*
*/
public void setName(Name value) {
this.name = value;
}
/**
* Gets the value of the value property.
*
* @return the value
* possible object is
* {@link Qualifier.Value }
*/
public Qualifier.Value getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link Qualifier.Value }
*
*/
public void setValue(Qualifier.Value value) {
this.value = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{urn:hl7-org:v3}cd">
* <sequence>
* <element name="originalText" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element ref="{urn:hl7-org:v3}qualifier" maxOccurs="0" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
public static class Value
extends Cd
{
}
}
| OBHITA/Consent2Share | DS4P/acs-showcase/c32-parser/src/main/java/gov/samhsa/consent2share/c32/dto/Qualifier.java | Java | bsd-3-clause | 5,997 |
<div class="form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'menu-item-form',
'enableAjaxValidation' => false,
'enableClientValidation' => true,
));
echo $form->errorSummary($model);
?>
<div class="row">
<?php echo $form->labelEx($model, 'name'); ?>
<?php echo $form->textField($model, 'name', array('size' => 60, 'maxlength' => 128)); ?>
<?php echo $form->error($model, 'name'); ?>
</div><!-- row -->
<div class="row">
<?php echo CHtml::radioButton('MenuItem[type]', $model->type == 'module', array('value' => 'module', 'id' => 'radio_module')); ?>
<?php echo Yii::t('app', 'Module') . ' '; ?>
<?php echo Chtml::dropDownList('MenuItem[module]', $model->link, Awecms::getModulesWithPath(), array('onfocus' => 'js:$("#radio_module").attr("checked", "checked");'));?>
<br/>
<?php // echo CHtml::radioButton('MenuItem[type]', $model->type == 'action', array('value' => 'action')); ?>
<?php
// echo Yii::t('app', 'Action');
// print_r(Awecms::getAllActions());
?>
<!--<br/>-->
<?php
if (Yii::app()->hasModule('page')) {
echo CHtml::radioButton('MenuItem[type]', $model->type == 'content', array('value' => 'content', 'id' => 'radio_content'));
echo Yii::t('app', 'Content') . ' ';
echo CHtml::dropDownList('MenuItem[content]', $model->link, CHtml::listData(Page::model()->findAll(), 'path', 'title'), array('onfocus' => 'js:$("#radio_content").attr("checked", "checked");'));
}
?>
<br/>
<?php echo CHtml::radioButton('MenuItem[type]', $model->type == 'url', array('value' => 'url', 'id' => 'radio_url')); ?>
<?php echo Yii::t('app', 'Link') . ' '; ?>
<?php echo Chtml::textField('MenuItem[url]', $model->link, array('size' => 60, 'onfocus' => 'js:$("#radio_url").attr("checked", "checked");')); ?>
<?php echo $form->error($model, 'link'); ?>
<br/>
<p class="hint">
/item points to base_url/item, //item points to root_of_server/item, item creates link relative to dynamic user location,
URLs rendered as is.
</p>
</div><!-- row -->
<div class="row">
<?php echo $form->labelEx($model, 'description'); ?>
<?php echo $form->textArea($model, 'description', array('rows' => 6, 'cols' => 50)); ?>
<?php echo $form->error($model, 'description'); ?>
</div><!-- row -->
<div class="row">
<?php echo $form->labelEx($model, 'enabled'); ?>
<?php echo $form->checkBox($model, 'enabled'); ?>
<?php echo $form->error($model, 'enabled'); ?>
</div><!-- row -->
<div class="row">
<?php echo $form->labelEx($model, 'role'); ?>
<?php
echo CHtml::checkBoxList(get_class($model) . '[role]', explode(',', $model->role), $model->roles, array('selected' => 'all'));
?>
<?php echo $form->error($model, 'role'); ?>
</div><!-- row -->
<div class="row">
<?php echo $form->labelEx($model, 'Open in new tab?'); ?>
<?php echo CHtml::checkBox('MenuItem[target]', $model->target == '_blank', array('value' => '_blank')); ?>
<?php echo $form->error($model, 'target'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model, 'parent_id'); ?>
<?php
//show all menu items but current one
$allModels = MenuItem::model()->findAll();
foreach ($allModels as $key => $aModel) {
if ($aModel->id == $model->id)
unset($allModels[$key]);
}
echo $form->dropDownList($model, 'parent', CHtml::listData($allModels, 'id', 'name'), array('prompt' => 'None'));
?>
<?php echo $form->error($model, 'parent_id'); ?>
</div><!-- row -->
<?php
//menu selection available only for edit
if (isset($menuId))
echo $form->hiddenField($model, 'menu', array('value' => $menuId));
else {
?>
<div class="row">
<?php echo $form->labelEx($model, 'menu_id'); ?>
<?php echo $form->dropDownList($model, 'menu', CHtml::listData(Menu::model()->findAll(), 'id', 'name')); ?>
<?php echo $form->error($model, 'menu_id'); ?>
</div>
<?php
}
?>
<div class="row buttons">
<?php
echo CHtml::submitButton(Yii::t('app', 'Save'));
echo CHtml::Button(Yii::t('app', 'Cancel'), array(
'submit' => 'javascript:history.go(-1)'));
?>
</div>
<?php
$this->endWidget();
?>
</div> | mdcconcepts/opinion_desk_CAP | protected/models/menu/views/item/_form.php | PHP | bsd-3-clause | 4,676 |
<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \app\models\SignupForm */
$this->title = Yii::t('app','Signup');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="site-signup">
<h1><?= Html::encode($this->title) ?></h1>
<p><?= Yii::t("app", "Please fill out the following fields to sign up"); ?></p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>
<fieldset><legend><?= Yii::t('app', 'User')?></legend>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'password_repeat')->passwordInput() ?>
</fieldset>
<div class="form-group">
<?= Html::submitButton(Yii::t('app','Signup'), ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
| thuctoa/ungdungtoan | views/site/signup.php | PHP | bsd-3-clause | 1,196 |
///
/// \file InvMassFit.C
/// \ingroup CaloTrackCorrMacrosPlotting
/// \brief Fit invariant mass distributions
///
/// Macro using as input the 2D histograms mass vs pT of AliAnaPi0
/// For a given set of pT bins invariant mass plots are fitted and mass vs pT
/// and width vs pT and neutral meson spectra plots are obtained.
/// Also pure MC histograms checking the origin of the clusters and generated spectra
/// is used to plot efficiencies and acceptance
///
/// Based on old macros
///
/// \author Gustavo Conesa Balbastre <Gustavo.Conesa.Balbastre@cern.ch>, (LPSC-CNRS)
///
#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TString.h>
#include <TH2F.h>
#include <TH1F.h>
#include <TH3F.h>
#include <TH1D.h>
#include <TF1.h>
#include <TMath.h>
#include <TCanvas.h>
#include <TStyle.h>
#include <TPad.h>
#include <TFile.h>
#include <TLegend.h>
#include <TObject.h>
#include <TDirectoryFile.h>
#include <TGraphErrors.h>
#include <TList.h>
#include <TArrayD.h>
#include <TGaxis.h>
#include <TROOT.h>
#include "PlotUtils.C"
#endif
// Settings
Bool_t kMix = kFALSE; /// use mixed event to constrain combinatorial background
Int_t kPolN = 1; /// polinomyal type for residual background under the peak
Bool_t kSumw2 = kTRUE; /// Apply Root method Sumw2(), off for pT hard prod where already done before
Float_t kNPairCut = 20; /// Minimum number of cluster pairs in pi0 or eta window
Float_t kFirstTRDSM = -1; /// First Calo SM covered by a TRD SM, 6 in 2011 and 4 in 2012-13
TString kHistoStartName = "AnaPi0"; /// Common starting name in histograms
TString kProdName = "LHC18c3_NystromOn"; /// Input production directory name where input file is located
TString kFileName = "AnalysisResults"; /// Name of file with input histograms
TString kPlotFormat = "eps"; /// Automatic plots format
TString kCalorimeter= "EMCAL"; /// Calorimeter, EMCAL, DCAL (PHOS)
TString kParticle = "Pi0"; /// Particle searched: "Pi0", "Eta"
Bool_t kTrunMixFunc= kTRUE; /// Use a truncated function to get the mixed event scale
Float_t kChi2NDFMax = 1000; /// Maximum value of chi2/ndf to define a fit as good (set lower than 1e6)
Int_t kRebin = 1; /// Rebin invariant mass histograms default binning with this value
// Initializations
Double_t nEvt = 0;
TFile * fil = 0;
TFile * fout = 0;
TList * lis = 0;
TF1 * fitfun= 0;
TDirectoryFile * direc =0;
// Mixing
TF1 *tPolPi0 = 0;
TF1 *tPolEta = 0;
Int_t modColorIndex[]={1 , 1, 2, 2, 3, 3, 4, 4, 7, 7, 6, 6, 2, 3, 4, 7, 6, 2, 2, 3, 3, 4, 4, 6, 6};
Int_t modStyleIndex[]={24,25,25,24,25,24,25,24,25,24,25,21,21,21,21,21,22,26,22,26,22,26,22,26};
///
/// Open the file and the list and the number of analyzed events
///
//-----------------------------------------------------------------------------
Bool_t GetFileAndEvents( TString dirName , TString listName )
{
fil = new TFile(Form("%s/%s.root",kProdName.Data(),kFileName.Data()),"read");
printf("Open Input File: %s/%s.root\n",kProdName.Data(),kFileName.Data());
if ( !fil ) return kFALSE;
direc = (TDirectoryFile*) fil->Get(dirName);
if ( !direc && dirName != "" ) return kFALSE;
//printf("dir %p, list %s\n",dir,listName.Data());
if(direc)
lis = (TList*) direc ->Get(listName);
else
lis = (TList*) fil->Get(listName);
if ( !lis && listName != "") return kFALSE;
if(!lis)
nEvt = ((TH1F*) fil->Get("hNEvents"))->GetBinContent(1);
else
nEvt = ((TH1F*) lis->FindObject("hNEvents"))->GetBinContent(1);
printf("nEvt = %2.3e\n",nEvt);
//nEvt = 1;
return kTRUE;
}
///
/// Initialize the fitting function
/// The function definitions are in PlotUtils.C
///
//-----------------------------------------------------------------------------
void SetFitFun()
{
//Fitting function
//if(mix) kPolN = 0;
if(kParticle == "Pi0")
{
if ( kPolN == 0)
fitfun = new TF1("fitfun",FunctionGaussPol0,0.100,0.250,4);
else if (kPolN == 1)
fitfun = new TF1("fitfun",FunctionGaussPol1,0.100,0.250,5);
else if (kPolN == 2)
fitfun = new TF1("fitfun",FunctionGaussPol2,0.100,0.250,6);
else if (kPolN == 3)
fitfun = new TF1("fitfun",FunctionGaussPol3,0.100,0.250,7);
else
{
printf("*** <<< Set Crystal Ball!!! >>> ***\n");
fitfun = new TF1("fitfun",FunctionCrystalBall,0.100,0.250,6);
}
if(kPolN < 4)
{
fitfun->SetParLimits(0, kNPairCut/5,kNPairCut*1.e4);
fitfun->SetParLimits(1, 0.105,0.185);
fitfun->SetParLimits(2, 0.001,0.040);
}
else
{
fitfun->SetParLimits(0, kNPairCut/5,kNPairCut*1.e6);
fitfun->SetParLimits(2, 0.105,0.185);
fitfun->SetParLimits(1, 0.001,0.040);
fitfun->SetParLimits(3, 0.001,0.040);
fitfun->SetParLimits(4, 0,10);
fitfun->SetParLimits(5, 1,1.e+6);
}
} // Pi0
else // Eta
{
if ( kPolN == 0)
fitfun = new TF1("fitfun",FunctionGaussPol0,0.400,0.650,4);
else if (kPolN == 1)
fitfun = new TF1("fitfun",FunctionGaussPol1,0.400,0.650,5);
else if (kPolN == 2)
fitfun = new TF1("fitfun",FunctionGaussPol2,0.400,0.650,6);
else if (kPolN == 3)
fitfun = new TF1("fitfun",FunctionGaussPol3,0.400,0.650,7);
if(kPolN < 4)
{
fitfun->SetParLimits(0, kNPairCut/10,1.e+6);
fitfun->SetParLimits(1, 0.20,0.80);
fitfun->SetParLimits(2, 0.001,0.06);
}
}
fitfun->SetLineColor(kRed);
fitfun->SetLineWidth(2);
fitfun->SetParName(0,"A");
fitfun->SetParName(1,"m_{0}");
fitfun->SetParName(2,"#sigma");
// fitfun->SetParName(3,"a_{0}");
// fitfun->SetParName(4,"a_{1}");
if (kPolN > 1)
{
fitfun->SetParName(5,"a_{2}");
if (kPolN > 2) fitfun->SetParName(6,"a_{3}");
}
//Mix fit func
tPolPi0 = new TF1("truncatedPolPi0" , FunctionTruncatedPolPi0 , 0.02, 0.25, 2);
tPolEta = new TF1("truncatedPolEta" , FunctionTruncatedPolEta , 0.2, 1, 2);
}
//-----------------------
/// Efficiency calculation called in ProjectAndFit()
//-----------------------
void Efficiency
(Int_t nPt,
TArrayD xPt , TArrayD exPt ,
TArrayD mesonPt , TArrayD emesonPt ,
TArrayD mesonPtBC, TArrayD emesonPtBC,
TString hname)
{
gStyle->SetOptTitle(1);
gStyle->SetTitleOffset(2,"Y");
gStyle->SetOptStat(0);
gStyle->SetOptFit(000000);
TGraphErrors * gPrim = (TGraphErrors*) fout->Get("Primary");
TGraphErrors * gPrimAcc = (TGraphErrors*) fout->Get("PrimaryInAcceptance");
if ( !gPrim || !gPrimAcc ) return ;
TArrayD effPt ; effPt .Set(nPt);
TArrayD effBCPt ; effBCPt .Set(nPt);
TArrayD effPtAcc ; effPtAcc .Set(nPt);
TArrayD effBCPtAcc ; effBCPtAcc .Set(nPt);
TArrayD effPtErr ; effPtErr .Set(nPt);
TArrayD effBCPtErr ; effBCPtErr .Set(nPt);
TArrayD effPtAccErr ; effPtAccErr .Set(nPt);
TArrayD effBCPtAccErr; effBCPtAccErr.Set(nPt);
for(Int_t ibin = 0; ibin < nPt; ibin++ )
{
//printf("Bin %d \n",ibin);
//printf("- Fit Reco %2.3e, Prim %2.3e, PrimAcc %2.3e\n",
// mesonPt[ibin],gPrim->GetY()[ibin],gPrimAcc->GetY()[ibin]);
if ( gPrim->GetY()[ibin] > 0 && mesonPt[ibin] > 0 )
{
effPt [ibin] = 100 * mesonPt[ibin] / gPrim->GetY()[ibin];
effPtErr[ibin] = 100 * GetFractionError( mesonPt[ibin], gPrim->GetY ()[ibin],
emesonPt[ibin], gPrim->GetEY()[ibin]); // PlotUtils.C
//printf("\t EffxAcc %f, err %f\n",effPt[ibin],effPtErr[ibin]);
}
else { effPt[ibin] = 0; effPtErr[ibin] = 0; }
if ( gPrimAcc->GetY()[ibin] > 0 && mesonPt[ibin] > 0 )
{
effPtAcc [ibin] = 100 * mesonPt[ibin] / gPrimAcc->GetY()[ibin];
effPtAccErr[ibin] = 100 * GetFractionError( mesonPt[ibin], gPrimAcc->GetY ()[ibin],
emesonPt[ibin], gPrimAcc->GetEY()[ibin]); // PlotUtils.C
//printf("\t Eff %f, err %f\n",effPtAcc[ibin],effPtAccErr[ibin]);
}
else { effPtAcc[ibin] = 0; effPtAccErr[ibin] = 0; }
if ( kMix || hname.Contains("MCpT") )
{
//printf("- BC Reco %2.3e, Prim %2.3e, PrimAcc %2.3e\n",
// mesonPtBC[ibin],gPrim->GetY()[ibin],gPrimAcc->GetY()[ibin]);
if ( gPrim->GetY()[ibin] > 0 && mesonPtBC[ibin] > 0 )
{
effBCPt [ibin] = 100 * mesonPtBC[ibin] / gPrim->GetY()[ibin];
effBCPtErr[ibin] = 100 * GetFractionError( mesonPtBC[ibin], gPrim->GetY ()[ibin],
emesonPtBC[ibin], gPrim->GetEY()[ibin]); // PlotUtils.C
//printf("\t EffxAcc %f, err %f\n",effBCPt[ibin],effBCPtErr[ibin]);
}
else { effBCPt[ibin] = 0; effBCPtErr[ibin] = 0; }
if ( gPrimAcc->GetY()[ibin] > 0 && mesonPtBC[ibin] > 0 )
{
effBCPtAcc [ibin] = 100 * mesonPtBC[ibin] / gPrimAcc->GetY()[ibin];
effBCPtAccErr[ibin] = 100 * GetFractionError( mesonPtBC[ibin], gPrimAcc->GetY ()[ibin],
emesonPtBC[ibin], gPrimAcc->GetEY()[ibin]); // PlotUtils.C
//printf("\t EffxAcc %f, err %f\n",effBCPtAcc[ibin],effBCPtAccErr[ibin]);
}
else { effBCPtAcc[ibin] = 0; effBCPtAccErr[ibin] = 0; }
} // Bin counting
} // pt bin loop
TGraphErrors *gEff = new TGraphErrors(nPt,xPt.GetArray(),effPt.GetArray(),exPt.GetArray(),effPtErr.GetArray());
gEff->SetName(Form("EfficiencyxAcceptance_%s",hname.Data()));
gEff->GetHistogram()->SetYTitle("#epsilon_{Reco #times PID #times Acc} (%)");
gEff->GetHistogram()->SetTitleOffset(1.4,"Y");
gEff->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gEff->GetHistogram()->SetTitleOffset(1.2,"X");
gEff->GetHistogram()->SetTitle("Reconstruction efficiency #times acceptance");
gEff->SetMarkerColor(1);
gEff->SetLineColor(1);
gEff->SetMarkerStyle(20);
gEff->Write();
TGraphErrors *gEffAcc = new TGraphErrors(nPt,xPt.GetArray(),effPtAcc.GetArray(),exPt.GetArray(),effPtAccErr.GetArray());
gEffAcc->SetName(Form("Efficiency_%s",hname.Data()));
gEffAcc->GetHistogram()->SetYTitle("#epsilon_{Reco #times PID} (%)");
gEffAcc->GetHistogram()->SetTitleOffset(1.5,"Y");
gEffAcc->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gEffAcc->GetHistogram()->SetTitleOffset(1.2,"X");
gEffAcc->SetMarkerColor(1);
gEffAcc->SetLineColor(1);
gEffAcc->SetMarkerStyle(20);
gEffAcc->GetHistogram()->SetTitle("Reconstruction efficiency");
gEffAcc->Write();
TGraphErrors *gBCEff = 0;
TGraphErrors *gBCEffAcc = 0;
if(kMix)
{
gBCEff = new TGraphErrors(nPt,xPt.GetArray(),effBCPt.GetArray(),exPt.GetArray(),effBCPtErr.GetArray());
gBCEff->SetName(Form("EfficiencyxAcceptance_BC_%s",hname.Data()));
gBCEff->GetHistogram()->SetYTitle("#epsilon_{Reco #times PID #times Acc}");
gBCEff->GetHistogram()->SetTitleOffset(1.5,"Y");
gBCEff->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gBCEff->GetHistogram()->SetTitleOffset(1.2,"X");
gBCEff->SetMarkerColor(4);
gBCEff->SetLineColor(4);
gBCEff->SetMarkerStyle(24);
gBCEff->Write();
gBCEffAcc = new TGraphErrors(nPt,xPt.GetArray(),effBCPtAcc.GetArray(),exPt.GetArray(),effBCPtAccErr.GetArray());
gBCEffAcc->SetName(Form("Efficiency_BC_%s",hname.Data()));
gBCEffAcc->GetHistogram()->SetYTitle("#epsilon_{Reco #times PID}");
gBCEffAcc->GetHistogram()->SetTitleOffset(1.4,"Y");
gBCEffAcc->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gBCEffAcc->GetHistogram()->SetTitleOffset(1.2,"X");
gBCEffAcc->SetMarkerColor(4);
gBCEffAcc->SetLineColor(4);
gBCEffAcc->SetMarkerStyle(24);
gBCEffAcc->Write();
}
// Plot efficiencies
//
TCanvas *cEff = new TCanvas(Form("cEff_%s",hname.Data()),
Form("Efficiency Graphs for %s",hname.Data()),2*600,600);
cEff->Divide(2, 1);
cEff->cd(1);
gPad->SetGridx();
gPad->SetGridy();
//gPad->SetLogy();
//gEff->SetMaximum(1);
//gEff->SetMinimum(1e-8);
gEff->Draw("AP");
if(kMix)
{
gBCEff ->Draw("P");
TLegend * legend = new TLegend(0.5,0.7,0.9,0.9);
legend->AddEntry(gEff ,"From fit","P");
legend->AddEntry(gBCEff,"From bin counting","P");
legend->Draw();
}
cEff->cd(2);
gPad->SetGridx();
gPad->SetGridy();
//gPad->SetLogy();
//gEffAcc->SetMaximum(1);
//gEffAcc->SetMinimum(1e-8);
gEffAcc->Draw("AP");
if(kMix)
{
gBCEffAcc->Draw("P");
TLegend * legend = new TLegend(0.5,0.7,0.9,0.9);
legend->AddEntry(gEffAcc ,"From fit","P");
legend->AddEntry(gBCEffAcc,"From bin counting","P");
legend->Draw();
}
cEff->Print(Form("IMfigures/%s_%s_Efficiency_%s_%s.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),hname.Data(),
/*kFileName.Data(),*/ kPlotFormat.Data()));
}
//-------------------------------------
/// Do energy projections, fits and plotting
/// of invariant mass distributions.
//-------------------------------------
void ProjectAndFit
(
const Int_t nPt, TString comment, TString leg, TString hname,
TArrayD xPtLimits, TArrayD xPt, TArrayD exPt,
TH2F * hRe, TH2F * hMi
)
{
if ( !hRe )
{
printf("ProjectAndFit() - Null inv mass 2D histo for %s, skip!\n",hname.Data());
return;
}
gStyle->SetOptTitle(1);
gStyle->SetTitleOffset(2,"Y");
gStyle->SetOptStat(0);
gStyle->SetOptFit(000000);
Double_t mmin = 0;
Double_t mmax = 1;
TString particleN = "";
if(kParticle=="Pi0")
{
mmin = 0.04;
mmax = 0.44;
particleN = " #pi^{0}";
}
else // eta
{
mmin = 0.25;
mmax = 0.95;
particleN = " #eta";
}
TLegend * pLegendIM[nPt];
TH1D* hIM [nPt];
TH1D* hMix [nPt];
TH1D* hMixCorrected [nPt];
TH1D* hRatio [nPt];
TH1D* hSignal [nPt];
for(Int_t ipt = 0; ipt< nPt; ipt++)
{
hIM [ipt] = 0 ;
hMix [ipt] = 0 ;
hMixCorrected[ipt] = 0 ;
hRatio [ipt] = 0 ;
hSignal [ipt] = 0 ;
}
TArrayD mesonPt ; mesonPt .Set(nPt);
TArrayD mesonPtBC ; mesonPtBC .Set(nPt);
TArrayD mesonMass ; mesonMass .Set(nPt);
TArrayD mesonWidth; mesonWidth.Set(nPt);
TArrayD emesonPt ; emesonPt .Set(nPt);
TArrayD emesonPtBC ; emesonPtBC .Set(nPt);
TArrayD emesonMass ; emesonMass .Set(nPt);
TArrayD emesonWidth; emesonWidth.Set(nPt);
Int_t rebin2 = 2*kRebin;
Int_t col = TMath::Ceil(TMath::Sqrt(nPt));
//hRe->Scale(1./nEvt);
// Mix correction factor
TF1 *line3[nPt];// = new TF1("line3", "[0]+[1]*x+[2]*x*x+[3]*x*x*x", 0.0, 1);
TF1 * fitFunction = 0;
Bool_t ok = kFALSE;
TCanvas * cIMModi = new TCanvas(Form("c%s", hname.Data()), Form("%s", leg.Data()), 1200, 1200) ;
cIMModi->Divide(col, col);
for(Int_t i = 0; i < nPt; i++)
{
cIMModi->cd(i+1) ;
//gPad->SetLogy();
Double_t ptMin = xPtLimits[i];
Double_t ptMax = xPtLimits[i+1];
//printf("Bin %d (%2.1f, %2.1f)\n",i, ptMin,ptMax);
hIM[i] = hRe->ProjectionY(Form("IM_%s_PtBin%d",hname.Data(),i),
hRe->GetXaxis()->FindBin(ptMin),
hRe->GetXaxis()->FindBin(ptMax));
hIM[i]->SetTitle(Form("%2.1f < #it{p}_{T, #gamma#gamma} < %2.1f GeV/#it{c}",ptMin,ptMax));
if(i < nPt-3)
hIM[i]->Rebin(kRebin);
else
hIM[i]->Rebin(rebin2);
if ( kSumw2 )
hIM[i]->Sumw2();
hIM[i]->SetXTitle("M_{#gamma,#gamma} (GeV/#it{c}^{2})");
//printf("mmin %f, mmax %f\n",mmin,mmax);
hIM[i]->SetAxisRange(mmin,mmax,"X");
hIM[i]->SetLineWidth(2);
hIM[i]->SetLineColor(4);
Double_t mStep = hIM[i]->GetBinWidth(1);
hSignal[i] = (TH1D*) hIM[i]->Clone();
//--------------------------------------------------
// Mix: Project, scale and subract to real pairs
//--------------------------------------------------
if ( kMix && hMi )
{
hMix[i] = (TH1D*) hMi->ProjectionY(Form("MiMass_PtBin%d_%s",i,hname.Data()),
hMi->GetXaxis()->FindBin(ptMin),
hMi->GetXaxis()->FindBin(ptMax));
hMix[i]->SetLineColor(1);
hMix[i]->SetTitle(Form("%2.2f < #it{p}_{T, #gamma#gamma} < %2.2f GeV/#it{c}",ptMin,ptMax));
if(i < nPt-3)
hMix[i]->Rebin(kRebin);
else
hMix[i]->Rebin(rebin2);
// Double_t sptmin = 0.2;
// Double_t sptmax = 0.45;
// Double_t scalereal = hIM->Integral(hIM->FindBin(sptmin),
// hIM->FindBin(sptmax));
// Double_t scalemix = hMix->Integral(hMix->FindBin(sptmin),
// hMix->FindBin(sptmax));
// if(scalemix > 0)
// hMix->Scale(scalereal/scalemix);
// else{
// //printf("could not scale: re %f mi %f\n",scalereal,scalemix);
// continue;
// }
// hMix[i]->SetLineWidth(1);
if ( kSumw2 )
hMix[i]->Sumw2();
// --- Ratio ---
hRatio[i] = (TH1D*)hIM[i]->Clone(Form("RatioRealMix_PtBin%d_%s",i,hname.Data()));
hRatio[i]->SetAxisRange(mmin,mmax,"X");
hRatio[i]->Divide(hMix[i]);
Double_t p0 =0;
Double_t p1 =0;
Double_t p2 =0;
Double_t p3 =0;
// --- Subtract from signal ---
hSignal[i] ->SetName(Form("Signal_PtBin%d_%s",i,hname.Data()));
if ( hMix[i]->GetEntries() > kNPairCut*3 )
{
hSignal[i] ->SetLineColor(kViolet);
if ( kTrunMixFunc )
{
if ( kParticle == "Pi0" )
{
hRatio[i]->Fit("truncatedPolPi0", "NQRL","",0.11,0.4);
p0= tPolPi0->GetParameter(0);
p1= tPolPi0->GetParameter(1);
//p2= tPolPi0->GetParameter(2);
//p3= tPolPi0->GetParameter(3);
} // pi0
else // eta
{
hRatio[i]->SetAxisRange(mmin,mmax);
hRatio[i]->Fit("truncatedPolEta", "NQRL","",0.35,0.95);
p0 = tPolEta->GetParameter(0);
p1 = tPolEta->GetParameter(1);
//p2 = tPolEta->GetParameter(2);
//p3 = tPolEta->GetParameter(3);
}
//line3[i] = new TF1("line3", "[0]+[1]*x+[2]*x*x+[3]*x*x*x", mmin, mmax);
line3[i] = new TF1("line3", "[0]+[1]*x", mmin, mmax);
line3[i]->SetParameters(p0,p1,p2,p3);
//printf("Correct\n");
hMixCorrected[i] = (TH1D*) hMix[i]->Clone(Form("MixCorrected_PtBin%d_%s",i,hname.Data()));
for(Int_t j = 0; j< hMix[i]->GetNbinsX(); j++)
{
Double_t x = hMix[i]->GetBinCenter(j);
Double_t correction = line3[i]->Eval(x);
Double_t corrected = hMix[i]->GetBinContent(j)*correction;
Double_t ecorrected = hMix[i]->GetBinError(j) *correction;
//printf("bin %d, center %f, mix %f, corrected %f\n",i,x,hMix[i]->GetBinContent(j),corrected);
hMixCorrected[i]->SetBinContent(j, corrected);
hMixCorrected[i]->SetBinError (j,ecorrected);
}
// Subtract
hSignal[i] ->Add(hMixCorrected[i],-1);
}
else
{
Float_t scale = hRatio[i]->GetBinContent(hRatio[i]->FindBin(0.7));
hMix[i]->Scale(scale);
// Subtract
hSignal[i] ->Add(hMix[i],-1);
}
} // enough mixed entries
} // mixed event histogtam exists
//----------------------------
// ---- Fit subtracted signal
//----------------------------
Double_t nMax = 0;
if(kParticle=="Pi0")
{
nMax= hSignal[i]->Integral(hIM[i]->FindBin(0.1),
hIM[i]->FindBin(0.2));
}
else
{
nMax = hSignal[i]->Integral(hIM[i]->FindBin(0.5),
hIM[i]->FindBin(0.7));
}
if(nMax > kNPairCut)
{
fitfun->SetParLimits(0,nMax/100,nMax*100);
if(kParticle=="Pi0")
{
if(kPolN < 4 )fitfun->SetParameters(nMax/5,0.135,20,0);
else fitfun->SetParameters(nMax/5,20,0.135,20,20,nMax/5);
if(i < nPt-4)
hSignal[i]->Fit("fitfun","QR","",0.11,0.3);
else
hSignal[i]->Fit("fitfun","QR","",0.11,0.3);
}// pi0
else // eta
{
if ( kPolN < 4 ) fitfun->SetParameters(nMax/5,0.54,40,0);
else fitfun->SetParameters(nMax/5,40,0.54,40,40,nMax/5);
//if(i<4)
hSignal[i]->Fit("fitfun","QR","",0.4,0.7);
//else if(i < 15)
// hSignal[i]->Fit("fitfun","QRL","",0.3,0.8);
//else
//hSignal[i]->Fit("fitfun","QRL","",0.3,0.8);
}
}
else
printf("Skip bin %d: n max %2.3e < cut %2.3e\n",i, nMax, kNPairCut);
//----------------------------
// ---- Put fit results in arrays
//----------------------------
// Init results arrays
mesonPt .SetAt(-1,i);
emesonPt .SetAt(-1,i);
mesonPtBC .SetAt(-1,i);
emesonPtBC .SetAt(-1,i);
mesonMass .SetAt(-1,i);
emesonMass .SetAt(-1,i);
mesonWidth.SetAt(-1,i);
emesonWidth.SetAt(-1,i);
fitFunction = (TF1*) hSignal[i]->GetFunction("fitfun");
Float_t chi2ndf = 1e6;
if ( fitFunction )
{
// printf("ipt %d: Chi/NDF %f, Chi %f, NDF %d\n",i,
// fitFunction->GetChisquare()/fitFunction->GetNDF(),
// fitFunction->GetChisquare(),
// fitFunction->GetNDF());
Float_t chi2 = fitFunction->GetChisquare();
Int_t ndf = fitFunction->GetNDF();
if( ndf > 0 ) chi2ndf = chi2 / ndf;
if ( chi2ndf < kChi2NDFMax )
{
Double_t A = fitFunction->GetParameter(0);
Double_t mean = fitFunction->GetParameter(1);
Double_t sigm = fitFunction->GetParameter(2);
// Double_t a0 = fitFunction->GetParameter(3);
// Double_t a1 = fitFunction->GetParameter(4);
// Double_t a2 = 0;
// if (kPolN == 2)
// a2 = fitFunction->GetParameter(5);
Double_t eA = fitFunction->GetParError(0);
Double_t emean = fitFunction->GetParError(1);
Double_t esigm = fitFunction->GetParError(2);
// Double_t ea0 = fitFunction->GetParError(3);
// Double_t ea1 = fitFunction->GetParError(4);
// Double_t ea2 = 0;
// if (kPolN == 2)
// ea2 = fitFunction->GetParError(5);
pLegendIM[i] = new TLegend(0.48,0.65,0.95,0.93);
pLegendIM[i]->SetTextSize(0.035);
pLegendIM[i]->SetFillColor(10);
pLegendIM[i]->SetBorderSize(1);
pLegendIM[i]->SetHeader(Form(" %s - %s",particleN.Data(), leg.Data()));
pLegendIM[i]->AddEntry("",Form("A = %2.1e#pm%2.1e ",A,eA),"");
pLegendIM[i]->AddEntry("",Form("#mu = %3.1f #pm %3.1f GeV/#it{c}^{2}",mean*1000,emean*1000),"");
pLegendIM[i]->AddEntry("",Form("#sigma = %3.1f #pm %3.1f GeV/#it{c}^{2}",sigm*1000,esigm*1000),"");
//pLegendIM[i]->AddEntry("",Form("p_{0} = %2.1f #pm %2.1f ",a0,ea0),"");
//pLegendIM[i]->AddEntry("",Form("p_{1} = %2.1f #pm %2.1f ",a1,ea1),"");
//if(kPolN==2)pLegendIM[i]->AddEntry("",Form("p_{2} = %2.1f#pm %2.1f ",a2,ea2),"");
Double_t counts = A*sigm / mStep * TMath::Sqrt(TMath::TwoPi());
Double_t eCounts =
TMath::Power(eA/A,2) +
TMath::Power(esigm/sigm,2);
eCounts = TMath::Sqrt(eCounts) * counts;
//eCounts = TMath::Min(eCounts, TMath::Sqrt(counts));
counts/=(nEvt*(exPt.At(i)*2));
eCounts/=(nEvt*(exPt.At(i)*2));
mesonPt.SetAt( counts,i);
emesonPt.SetAt(eCounts,i);
//printf("A %e Aerr %e; mu %f muErr %f; sig %f sigErr %f",
// A,eA,mean,emean,sigm,esigm);
//cout << "N(pi0) fit = " << counts << "+-"<< eCounts << " mstep " << mStep<<endl;
mesonMass .SetAt( mean*1000.,i);
emesonMass .SetAt(emean*1000.,i);
mesonWidth.SetAt( sigm*1000.,i);
emesonWidth.SetAt(esigm*1000.,i);
} //Good fit
else
{
printf("Bin %d, Bad fit, Chi2 %f ndf %d, ratio %f!\n",
i,chi2,ndf,chi2ndf);
}
}
else printf("Bin %d, NO fit available!\n",i);
// Set the integration window, depending on mass mean and width
// 2 sigma
Double_t mass = mesonMass [i]/1000.;
Double_t width = mesonWidth[i]/1000.;
Double_t mMinBin = mass - 2 * width;
Double_t mMaxBin = mass + 2 * width;
if(mass <= 0 || width <= 0)
{
if(kParticle=="Pi0")
{
mMinBin = 0.115; mMaxBin = 0.3 ;
}
else // eta
{
mMinBin = 0.4; mMaxBin = 0.9 ;
}
}
//
// Bin counting instead of fit
//
//printf("Signal %p, Mix %p, hname %s\n",hSignal[i], hMix[i], hname.Data());
if ( hSignal[i] && ( hMix[i] || hname.Contains("MCpT") ) )
{
Double_t countsBin = 0.;//hSignal[i]->Integral(hSignal[i]->FindBin(mMinBin), hSignal[i]->FindBin(mMaxBin)) ;
Double_t eCountsBin = 0.;//TMath::Sqrt(countsBin);
// PlotUtils.C
GetRangeIntegralAndError(hSignal[i], hSignal[i]->FindBin(mMinBin), hSignal[i]->FindBin(mMaxBin), countsBin, eCountsBin );
countsBin/=(nEvt*(exPt.At(i)*2));
eCountsBin/=(nEvt*(exPt.At(i)*2));
mesonPtBC.SetAt( countsBin,i);
emesonPtBC.SetAt(eCountsBin,i);
//printf("pt bin %d: [%2.1f,%2.1f] - Mass window [%2.2f, %2.2f] - N(pi0) BC = %2.3e +- %2.4e\n",
// i, xPtLimits[i], xPtLimits[i+1], mMinBin, mMaxBin, countsBin, eCountsBin);
}
if ( nMax > kNPairCut && chi2ndf < kChi2NDFMax )
{
if( kMix && hMix[i] )
{
// if ( !kMix ) hIM[i]->SetMinimum( 0.1);
// else hIM[i]->SetMinimum(-0.1);
hIM[i]->SetMaximum(hIM[i]->GetMaximum()*1.2);
hIM[i]->SetMinimum(hSignal[i]->GetMinimum()*0.2);
hIM[i]->Draw("HE");
pLegendIM[i]->AddEntry(hIM[i],"Raw pairs" ,"L");
if ( hMix[i]->GetEntries() > kNPairCut*3 )
{
if ( kTrunMixFunc )
{
hMixCorrected[i]->Draw("same");
pLegendIM[i]->AddEntry(hMixCorrected[i],"Mixed pairs" ,"L");
}
else
{
hMix[i]->Draw("same");
pLegendIM[i]->AddEntry(hMix[i],"Mixed pairs" ,"L");
}
}
ok = kTRUE;
hSignal[i] -> Draw("same");
pLegendIM[i]->AddEntry(hSignal[i],"Signal pairs","L");
}
else
{
ok = kTRUE;
hSignal[i]->SetMaximum(hSignal[i]->GetMaximum()*1.2);
hSignal[i]->SetMinimum(hSignal[i]->GetMinimum()*0.8);
pLegendIM[i]->AddEntry(hSignal[i],"Raw pairs","L");
hSignal[i] -> Draw("HE");
}
// Plot mass from pairs originated from pi0/eta
if ( hname.Contains("All") )
{
TH1F* hMesonPairOrigin = (TH1F*) fout->Get(Form("IM_MCpTReco_PtBin%d",i));
if ( hMesonPairOrigin )
{
hMesonPairOrigin->SetLineColor(8);
hMesonPairOrigin->Draw("same");
pLegendIM[i]->AddEntry(hMesonPairOrigin,Form("%s origin",particleN.Data()),"L");
}
} // MC origin
// if ( fitFunction )
// pLegendIM[i]->AddEntry(fitFunction,"Fit","L");
pLegendIM[i]->Draw();
}
else
{
// Plot just raw pairs
hIM[i]->Draw("HE");
}
} //pT bins
if ( ok )
cIMModi->Print(Form("IMfigures/%s_%s_Mgg_%s_%s.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),/*kFileName.Data(),*/
hname.Data(),kPlotFormat.Data()));
//xxxx Real / Mixxxxx
if(kMix)
{
//printf("Do real/mix\n");
Bool_t okR = kFALSE;
TCanvas * cRat = new TCanvas(Form("Ratio_%s\n",hname.Data()), Form("Ratio %s\n", leg.Data()), 1200, 1200) ;
cRat->Divide(col, col);
for(Int_t i = 0; i < nPt; i++)
{
cRat->cd(i+1) ;
//gPad->SetGridy();
//gPad->SetLog();
if(!hRatio[i])
{
//printf("No ratio in pt bin %d continue\n",i);
continue;
}
Double_t nMax =0;
if(kParticle=="Pi0")
nMax = hRatio[i]->Integral(hRatio[i]->FindBin(0.005),
hRatio[i]->FindBin(0.20));
else
nMax = hRatio[i]->Integral(hRatio[i]->FindBin(0.4),
hRatio[i]->FindBin(0.6));
if ( nMax <= 0 ) continue;
//printf("Ratio nMax = %e \n",nMax);
hRatio[i]->SetMaximum(nMax/4);
hRatio[i]->SetMinimum(1e-6);
hRatio[i]->SetAxisRange(mmin,mmax,"X");
okR = kTRUE;
hRatio[i]->SetYTitle("Real pairs / Mixed pairs");
hRatio[i]->SetTitleOffset(1.5,"Y");
hRatio[i]->Draw();
//if(line3[i]) line3[i]->Draw("same");
}
if ( okR )
cRat->Print(Form("IMfigures/%s_%s_MggRatio_%s_%s.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),/*kFileName.Data(),*/
hname.Data(),kPlotFormat.Data()));
} // Mix
if( !ok ) return ;
//------------------------------
// Fit parameters
//------------------------------
// Put fit results in TGraphErrors
TGraphErrors* gPt = new TGraphErrors(nPt,xPt.GetArray(),mesonPt.GetArray(),exPt.GetArray(),emesonPt.GetArray());
gPt->SetName(Form("gPt_%s",hname.Data()));
gPt->GetHistogram()->SetTitle(Form("#it{p}_{T} of reconstructed %s, %s ",particleN.Data(), comment.Data()));
gPt->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c}) ");
gPt->GetHistogram()->SetYTitle(Form("dN_{%s}/d#it{p}_{T} (GeV/#it{c})^{-1} / N_{events} ",particleN.Data()));
//gPt->GetHistogram()->SetAxisRange(0.,30);
gPt->GetHistogram()->SetTitleOffset(1.5,"Y");
gPt->SetMarkerStyle(20);
//gPt->SetMarkerSize(1);
gPt->SetMarkerColor(1);
// gPt->GetHistogram()->SetMaximum(1e8);
// gPt->GetHistogram()->SetMinimum(1e-8);
TGraphErrors* gPtBC = new TGraphErrors(nPt,xPt.GetArray(),mesonPtBC.GetArray(),exPt.GetArray(),emesonPtBC.GetArray());
gPtBC->SetName(Form("gPtBC_%s",hname.Data()));
gPtBC->GetHistogram()->SetTitle(Form("#it{p}_{T} of reconstructed %s, %s ",particleN.Data(), comment.Data()));
gPtBC->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c}) ");
gPtBC->GetHistogram()->SetYTitle(Form("d#it{N}_{%s}/d#it{p}_{T} (GeV/#it{c})^{-1} / #it{N}_{events} ",particleN.Data()));
//gPtBC->GetHistogram()->SetAxisRange(0.,30);
gPtBC->GetHistogram()->SetTitleOffset(1.5,"Y");
gPtBC->SetMarkerStyle(24);
//gPtBC->SetMarkerSize(1);
gPtBC->SetMarkerColor(4);
// gPtBC->GetHistogram()->SetMaximum(1e8);
// gPtBC->GetHistogram()->SetMinimum(1e-8);
TGraphErrors* gMass = new TGraphErrors(nPt,xPt.GetArray(),mesonMass.GetArray(),exPt.GetArray(),emesonMass.GetArray());
gMass->SetName(Form("gMass_%s",hname.Data()));
gMass->GetHistogram()->SetTitle(Form("mass vs #it{p}_{T} of reconstructed %s, %s ",particleN.Data(), comment.Data()));
gMass->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c}) ");
gMass->GetHistogram()->SetYTitle(Form("mass_{%s} (MeV/#it{c}^{2}) ",particleN.Data()));
//gMass->GetHistogram()->SetAxisRange(0.,30);
gMass->GetHistogram()->SetTitleOffset(1.5,"Y");
gMass->SetMarkerStyle(20);
//gMass->SetMarkerSize(1);
gMass->SetMarkerColor(1);
TGraphErrors* gWidth= new TGraphErrors(nPt,xPt.GetArray(),mesonWidth.GetArray(),exPt.GetArray(),emesonWidth.GetArray());
gWidth->SetName(Form("gWidth_%s",hname.Data()));
gWidth->GetHistogram()->SetTitle(Form("Width vs #it{p}_{T} of reconstructed %s, %s ",particleN.Data(), comment.Data()));
gWidth->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c}) ");
gWidth->GetHistogram()->SetYTitle(Form("#sigma_{%s} (MeV/#it{c}^{2}) ",particleN.Data()));
//gWidth->GetHistogram()->SetAxisRange(0.,30);
gWidth->GetHistogram()->SetTitleOffset(1.5,"Y");
gWidth->SetMarkerStyle(20);
//gWidth->SetMarkerSize(1);
gWidth->SetMarkerColor(1);
// Plot the fitted results
TCanvas *cFitGraph = new TCanvas(Form("cFitGraph_%s",hname.Data()),
Form("Fit Graphs for %s",hname.Data()),600,600);
cFitGraph->Divide(2, 2);
// Mass
cFitGraph->cd(1);
gPad->SetGridx();
gPad->SetGridy();
if ( kParticle=="Pi0" )
{
gMass->SetMaximum(160);
gMass->SetMinimum(100);
}
else
{
gMass->SetMaximum(660);
gMass->SetMinimum(420);
}
gMass->Draw("AP");
cFitGraph->cd(2);
gPad->SetGridx();
gPad->SetGridy();
if(kParticle=="Pi0")
{
gWidth->SetMaximum(16);
gWidth->SetMinimum(6);
}
else
{
gWidth->SetMaximum(60);
gWidth->SetMinimum(0);
}
gWidth->Draw("AP");
cFitGraph->cd(3);
gPad->SetGridx();
gPad->SetGridy();
gPad->SetLogy();
gPt->Draw("AP");
Double_t maximum = gPt->GetHistogram()->GetMaximum();
Double_t minimum = gPt->GetHistogram()->GetMinimum();
//printf("A-maximum %e, minimum %e\n",maximum,minimum);
// Double_t maximum = gPrim->GetHistogram()->GetMaximum();
// Double_t minimum = gPrim->GetHistogram()->GetMinimum();
//
// if ( gPrimAcc->GetMaximum() > maximum ) maximum = gPrimAcc->GetMaximum() ;
// if ( gPrimAcc->GetMinimum() > minimum ) minimum = gPrimAcc->GetMinimum() ;
//
// gPrim->SetMaximum(maximum*10);
// gPrim->SetMinimum(minimum/10);
if(kMix)
{
gPtBC ->Draw("P");
if(maximum < gPtBC->GetHistogram()->GetMaximum()) maximum = gPtBC->GetHistogram()->GetMaximum();
if(minimum > gPtBC->GetHistogram()->GetMinimum()) minimum = gPtBC->GetHistogram()->GetMaximum();
//printf("B-maximum %e, minimum %e\n",maximum,minimum);
if(minimum < 0 ) minimum = 2.e-9 ;
gPtBC->SetMaximum(maximum*2.);
gPtBC->SetMinimum(minimum/2.);
TLegend * legend = new TLegend(0.5,0.7,0.9,0.9);
legend->AddEntry(gPt ,"From fit","P");
legend->AddEntry(gPtBC,"From bin counting","P");
legend->Draw();
}
gPt->SetMaximum(maximum*2.);
gPt->SetMinimum(minimum/2.);
cFitGraph->Print(Form("IMfigures/%s_%s_MassWidthPtSpectra_%s_%s.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),hname.Data(),
/*kFileName.Data(),*/ kPlotFormat.Data()));
//-----------------------
// Write results to file
//-----------------------
hRe->Write();
if ( hMi ) hMi->Write();
for(Int_t ipt = 0; ipt < nPt; ipt++)
{
if ( hIM[ipt] ) hIM[ipt]->Write();
if ( kMix )
{
if (hMix [ipt] ) hMix [ipt]->Write();
if (hMixCorrected[ipt] ) hMixCorrected[ipt]->Write();
if (hRatio [ipt] ) hRatio [ipt]->Write();
if (hSignal [ipt] ) hSignal [ipt]->Write();
}
}
gPt ->Write();
gMass ->Write();
gWidth->Write();
if ( kMix ) gPtBC->Write();
// Do some final efficiency calculations if MC
Efficiency(nPt, xPt, exPt, mesonPt, emesonPt, mesonPtBC, emesonPtBC, hname);
}
///
/// Plot combinations of graphs with fit results
/// SM/Sector/Side/SM group by SM/Sector/Side/SM group comparisons
///
//-----------------------------------------------------------------------------
void PlotGraphs(TString opt, Int_t first, Int_t last)
{
gStyle->SetOptTitle(1);
gStyle->SetTitleOffset(2,"Y");
gStyle->SetOptStat(0);
gStyle->SetOptFit(000000);
const Int_t nCombi = last-first+1;
Int_t nCombiActive = 0;
Float_t xmin = 0.7;
Float_t ymin = 0.3;
Float_t xmax = 0.9;
Float_t ymax = 0.9;
if(opt.Contains("Group"))
{
xmin = 0.3;
ymin = 0.7;
}
if(opt.Contains("Sector"))
{
xmin = 0.65;
ymin = 0.5;
}
TLegend * legend = new TLegend(xmin,ymin,xmax,ymax);
legend->SetTextSize(0.05);
TString particleN = " #pi^{0}";
if(kParticle=="Eta") particleN = " #eta";
// recover the graphs from output file
//printf("%s\n",opt.Data());
// Recover SUM
TString opt2 = opt;
if(opt.Contains("SMGroup")) opt2 = "SM";
TGraphErrors* gSumPt = (TGraphErrors*) fout->Get(Form("gPt_Same%s" ,opt2.Data()));
TGraphErrors* gSumPtBC = (TGraphErrors*) fout->Get(Form("gPtBC_Same%s" ,opt2.Data()));
TGraphErrors* gSumMass = (TGraphErrors*) fout->Get(Form("gMass_Same%s" ,opt2.Data()));
TGraphErrors* gSumWidth = (TGraphErrors*) fout->Get(Form("gWidth_Same%s",opt2.Data()));
//printf("\t Sum %p %p %p %p\n",gSumPt,gSumPtBC,gSumMass,gSumWidth);
if ( !gSumMass ) return ;
gSumPt ->SetMarkerStyle(20);
gSumPt ->SetMarkerColor(1);
gSumPt ->SetLineColor (1);
gSumMass->SetMarkerStyle(20);
gSumMass->SetMarkerColor(1);
gSumMass->SetLineColor (1);
gSumWidth->SetMarkerStyle(20);
gSumWidth->SetMarkerColor(1);
gSumWidth->SetLineColor (1);
if ( kMix )
{
gSumPtBC ->SetMarkerStyle(20);
gSumPtBC ->SetMarkerColor(1);
gSumPtBC ->SetLineColor (1);
}
legend->AddEntry(gSumPt,"Sum","P");
// Normalize to total number of SMs/Sectors/Sides
if ( opt != "SMGroup" )
{
for (Int_t ibin = 0; ibin < gSumPt->GetN(); ibin++)
{
gSumPt->GetY ()[ibin] /= nCombi;
gSumPt->GetEY()[ibin] /= nCombi;
if ( kMix )
{
gSumPtBC->GetY ()[ibin] /= nCombi;
gSumPtBC->GetEY()[ibin] /= nCombi;
}
}
}
TGraphErrors* gSumTRDnotPt = 0;
TGraphErrors* gSumTRDnotPtBC = 0;
TGraphErrors* gSumTRDnotMass = 0;
TGraphErrors* gSumTRDnotWidth = 0;
TGraphErrors* gSumTRDyesPt = 0;
TGraphErrors* gSumTRDyesPtBC = 0;
TGraphErrors* gSumTRDyesMass = 0;
TGraphErrors* gSumTRDyesWidth = 0;
//
//// TRD covered
//
if ( kFirstTRDSM > 0 && opt == "SM" ) // it could be extended to sector/side
{
gSumTRDnotPt = (TGraphErrors*) fout->Get(Form("gPt_Same%sTRDNot" ,opt2.Data()));
gSumTRDnotPtBC = (TGraphErrors*) fout->Get(Form("gPtBC_Same%sTRDNot" ,opt2.Data()));
gSumTRDnotMass = (TGraphErrors*) fout->Get(Form("gMass_Same%sTRDNot" ,opt2.Data()));
gSumTRDnotWidth = (TGraphErrors*) fout->Get(Form("gWidth_Same%sTRDNot",opt2.Data()));
printf("\t Sum Not TRD %p %p %p %p\n",gSumTRDnotPt,gSumTRDnotPtBC,gSumTRDnotMass,gSumTRDnotWidth);
gSumTRDnotPt ->SetMarkerStyle(20);
gSumTRDnotPt ->SetMarkerColor(kGray);
gSumTRDnotPt ->SetLineColor (kGray);
gSumTRDnotMass->SetMarkerStyle(20);
gSumTRDnotMass->SetMarkerColor(kGray);
gSumTRDnotMass->SetLineColor (kGray);
gSumTRDnotWidth->SetMarkerStyle(20);
gSumTRDnotWidth->SetMarkerColor(kGray);
gSumTRDnotWidth->SetLineColor (kGray);
if ( kMix )
{
gSumTRDnotPtBC ->SetMarkerStyle(20);
gSumTRDnotPtBC ->SetMarkerColor(kGray);
gSumTRDnotPtBC ->SetLineColor (kGray);
}
legend->AddEntry(gSumTRDnotPt,"w/o TRD","P");
for (Int_t ibin = 0; ibin < gSumPt->GetN(); ibin++)
{
gSumTRDnotPt->GetY ()[ibin] /= kFirstTRDSM;
gSumTRDnotPt->GetEY()[ibin] /= kFirstTRDSM;
if ( kMix )
{
gSumTRDnotPtBC->GetY ()[ibin] /= kFirstTRDSM;
gSumTRDnotPtBC->GetEY()[ibin] /= kFirstTRDSM;
}
}
gSumTRDyesPt = (TGraphErrors*) fout->Get(Form("gPt_Same%sTRDYes" ,opt2.Data()));
gSumTRDyesPtBC = (TGraphErrors*) fout->Get(Form("gPtBC_Same%sTRDYes" ,opt2.Data()));
gSumTRDyesMass = (TGraphErrors*) fout->Get(Form("gMass_Same%sTRDYes" ,opt2.Data()));
gSumTRDyesWidth = (TGraphErrors*) fout->Get(Form("gWidth_Same%sTRDYes",opt2.Data()));
printf("\t Sum Yes TRD %p %p %p %p\n",gSumTRDyesPt,gSumTRDyesPtBC,gSumTRDyesMass,gSumTRDyesWidth);
gSumTRDyesPt ->SetMarkerStyle(20);
gSumTRDyesPt ->SetMarkerColor(kCyan);
gSumTRDyesPt ->SetLineColor (kCyan);
gSumTRDyesMass->SetMarkerStyle(20);
gSumTRDyesMass->SetMarkerColor(kCyan);
gSumTRDyesMass->SetLineColor (kCyan);
gSumTRDyesWidth->SetMarkerStyle(20);
gSumTRDyesWidth->SetMarkerColor(kCyan);
gSumTRDyesWidth->SetLineColor (kCyan);
if ( kMix )
{
gSumTRDyesPtBC ->SetMarkerStyle(20);
gSumTRDyesPtBC ->SetMarkerColor(kCyan);
gSumTRDyesPtBC ->SetLineColor (kCyan);
}
legend->AddEntry(gSumTRDyesPt,"w/ TRD","P");
Int_t nCovered = 10-kFirstTRDSM;
for (Int_t ibin = 0; ibin < gSumPt->GetN(); ibin++)
{
gSumTRDyesPt->GetY ()[ibin] /= nCovered;
gSumTRDyesPt->GetEY()[ibin] /= nCovered;
if ( kMix )
{
gSumTRDyesPtBC->GetY ()[ibin] /= nCovered;
gSumTRDyesPtBC->GetEY()[ibin] /= nCovered;
}
}
} // TRD
//
// Get different combinations
//
TGraphErrors* gPt [nCombi];
TGraphErrors* gPtBC [nCombi];
TGraphErrors* gMass [nCombi];
TGraphErrors* gWidth[nCombi];
for(Int_t icomb = 0; icomb < nCombi; icomb ++)
{
gPt [icomb] = (TGraphErrors*) fout->Get(Form("gPt_%s%d" ,opt.Data(),icomb+first));
gPtBC [icomb] = (TGraphErrors*) fout->Get(Form("gPtBC_%s%d" ,opt.Data(),icomb+first));
gMass [icomb] = (TGraphErrors*) fout->Get(Form("gMass_%s%d" ,opt.Data(),icomb+first));
gWidth[icomb] = (TGraphErrors*) fout->Get(Form("gWidth_%s%d",opt.Data(),icomb+first));
//printf("\t %d %p %p %p %p\n",icomb,gPt[icomb],gPtBC[icomb],gMass[icomb],gWidth[icomb]);
if ( !gPt[icomb] ) continue ;
nCombiActive++;
gPt [icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gPt [icomb]->SetMarkerColor(modColorIndex[icomb]);
gPt [icomb]->SetLineColor (modColorIndex[icomb]);
gMass[icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gMass[icomb]->SetMarkerColor(modColorIndex[icomb]);
gMass[icomb]->SetLineColor (modColorIndex[icomb]);
gWidth[icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gWidth[icomb]->SetMarkerColor(modColorIndex[icomb]);
gWidth[icomb]->SetLineColor (modColorIndex[icomb]);
gPt [icomb]->GetHistogram()->SetTitle(Form("#it{p}_{T} of %s from fit, %s " ,particleN.Data(), opt.Data()));
gWidth[icomb]->GetHistogram()->SetTitle(Form("%s mass #sigma vs #it{p}_{T}, %s ",particleN.Data(), opt.Data()));
gMass [icomb]->GetHistogram()->SetTitle(Form("%s mass #mu vs #it{p}_{T}, %s " ,particleN.Data(), opt.Data()));
if ( kMix )
{
gPtBC [icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gPtBC [icomb]->SetMarkerColor(modColorIndex[icomb]);
gPtBC [icomb]->SetLineColor (modColorIndex[icomb]);
gPtBC [icomb]->GetHistogram()->SetTitle(Form("#it{p}_{T} of %s bin counted, %s ",particleN.Data(), opt.Data()));
}
if ( !opt.Contains("Group") )
legend->AddEntry(gPt[icomb],Form("%s %d",opt.Data(),icomb),"P");
else
{
if(icomb == 0) legend->AddEntry(gPt[icomb],"SM0+4+5+6+7+8+9","P");
if(icomb == 1) legend->AddEntry(gPt[icomb],"SM1+2","P");
if(icomb == 2) legend->AddEntry(gPt[icomb],"SM3+7","P");
}
}
if ( !gMass[0] ) return ;
//
// PLOT
//
TCanvas *cFitGraph = new TCanvas(Form("cFitGraph_%sCombinations",opt.Data()),
Form("Fit Graphs for %s combinations",opt.Data()),1000,1000);
cFitGraph->Divide(2, 2);
// Mass
cFitGraph->cd(1);
gPad->SetGridx();
gPad->SetGridy();
if ( kParticle == "Pi0" )
{
gMass[0]->SetMaximum(141);
gMass[0]->SetMinimum(116);
}
else
{
gMass[0]->SetMaximum(600);
gMass[0]->SetMinimum(450);
}
gMass[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gMass[icomb] ) gMass[icomb]->Draw("P");
}
gSumMass->Draw("P");
if ( kFirstTRDSM > 0 && opt == "SM" )
{
gSumTRDnotMass->Draw("P");
gSumTRDyesMass->Draw("P");
}
legend->Draw();
cFitGraph->cd(2);
gPad->SetGridx();
gPad->SetGridy();
if ( kParticle == "Pi0" )
{
gWidth[0]->SetMaximum(17);
gWidth[0]->SetMinimum(7);
if(opt=="Side") gWidth[0]->SetMinimum(2);
}
else
{
gWidth[0]->SetMaximum(50);
gWidth[0]->SetMinimum(10);
}
gWidth[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gWidth[icomb] ) gWidth[icomb]->Draw("P");
}
gSumWidth->Draw("P");
if ( kFirstTRDSM > 0 && opt == "SM" )
{
gSumTRDnotWidth->Draw("P");
gSumTRDyesWidth->Draw("P");
}
legend->Draw();
cFitGraph->cd(3);
gPad->SetGridx();
gPad->SetGridy();
gPad->SetLogy();
gPt[0]->SetMaximum(1);
gPt[0]->SetMinimum(1e-8);
gPt[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gPt[icomb] ) gPt[icomb]->Draw("P");
}
gSumPt->Draw("P");
if ( kFirstTRDSM > 0 && opt == "SM" )
{
gSumTRDnotPt->Draw("P");
gSumTRDyesPt->Draw("P");
}
legend->Draw();
if ( kMix )
{
cFitGraph->cd(4);
gPad->SetGridx();
gPad->SetGridy();
gPad->SetLogy();
gPtBC[0]->SetMaximum(1);
gPtBC[0]->SetMinimum(1e-8);
gPtBC[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gPtBC[icomb] ) gPtBC[icomb]->Draw("P");
}
gSumPtBC->Draw("P");
if ( kFirstTRDSM > 0 && opt == "SM" )
{
gSumTRDnotPtBC->Draw("P");
gSumTRDyesPtBC->Draw("P");
}
legend->Draw();
}
cFitGraph->Print(Form("IMfigures/%s_%s_MassWidthPtSpectra_%s_%sCombinations.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),opt.Data(),
/*kFileName.Data(),*/kPlotFormat.Data()));
//
// Calculate the ratio to the sum
//
TGraphErrors* gRatPt [nCombi];
TGraphErrors* gRatPtBC [nCombi];
TGraphErrors* gRatMass [nCombi];
TGraphErrors* gRatWidth[nCombi];
TLegend * legendR = new TLegend(xmin,ymin,xmax,ymax);
legendR->SetTextSize(0.05);
for(Int_t icomb = 0; icomb < nCombi; icomb ++)
{
//printf("icomb %d\n",icomb);
//printf("\t pt %p %p\n",gPt[icomb],gSumPt);
gRatPt [icomb] = DivideGraphs(gPt [icomb],gSumPt ); // PlotUtils.C
//printf("\t ptBC %p %p\n",gPtBC[icomb],gSumPtBC);
gRatPtBC [icomb] = DivideGraphs(gPtBC [icomb],gSumPtBC ); // PlotUtils.C
//printf("\t pt %p %p\n",gMass[icomb],gSumMass);
gRatMass [icomb] = DivideGraphs(gMass [icomb],gSumMass ); // PlotUtils.C
//printf("\t pt %p %p\n",gWidth[icomb],gSumWidth);
gRatWidth[icomb] = DivideGraphs(gWidth[icomb],gSumWidth); // PlotUtils.C
if(!gRatMass[icomb]) continue;
gRatPt [icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatPt [icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatPt [icomb]->SetLineColor (modColorIndex[icomb]);
gRatMass[icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatMass[icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatMass[icomb]->SetLineColor (modColorIndex[icomb]);
gRatWidth[icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatWidth[icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatWidth[icomb]->SetLineColor (modColorIndex[icomb]);
gRatPt [icomb]->GetHistogram()->SetTitle(Form("#it{p}_{T} of %s from fit, %s " ,particleN.Data(), opt.Data()));
gRatWidth[icomb]->GetHistogram()->SetTitle(Form("%s mass #sigma vs #it{p}_{T}, %s ",particleN.Data(), opt.Data()));
gRatMass [icomb]->GetHistogram()->SetTitle(Form("%s mass #mu vs #it{p}_{T}, %s " ,particleN.Data(), opt.Data()));
gRatPt [icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatWidth[icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatMass [icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatPt [icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatWidth[icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatMass [icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatPt [icomb]->GetHistogram()->SetTitleOffset(1.4,"Y");
gRatWidth[icomb]->GetHistogram()->SetTitleOffset(1.4,"Y");
gRatMass [icomb]->GetHistogram()->SetTitleOffset(1.4,"Y");
if ( kMix )
{
gRatPtBC [icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatPtBC [icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatPtBC [icomb]->SetLineColor (modColorIndex[icomb]);
gRatPtBC [icomb]->GetHistogram()->SetTitle(Form("#it{p}_{T} of %s bin counted, %s ",particleN.Data(), opt.Data()));
gRatPtBC [icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatPtBC [icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatPtBC [icomb]->GetHistogram()->SetTitleOffset(1.5,"Y");
}
if ( !opt.Contains("Group") )
legendR->AddEntry(gPt[icomb],Form("%s %d",opt.Data(),icomb),"P");
else
{
if(icomb == 0) legendR->AddEntry(gPt[icomb],"SM0+4+5+6+7+8+9","P");
if(icomb == 1) legendR->AddEntry(gPt[icomb],"SM1+2","P");
if(icomb == 2) legendR->AddEntry(gPt[icomb],"SM3+7","P");
}
} // combi loop
//
// PLOT
//
TCanvas *cFitGraphRatio = new TCanvas(Form("cFitGraphSumRatio_%sCombinations",opt.Data()),
Form("Fit Graphs ratio to sum for %s combinations",opt.Data()),1000,1000);
cFitGraphRatio->Divide(2, 2);
// Mass
cFitGraphRatio->cd(1);
gPad->SetGridx();
gPad->SetGridy();
gRatMass[0]->SetMaximum(1.03);
gRatMass[0]->SetMinimum(0.97);
gRatMass[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatMass[icomb] ) gRatMass[icomb]->Draw("P");
}
legendR->Draw();
cFitGraphRatio->cd(2);
gPad->SetGridx();
gPad->SetGridy();
gRatWidth[0]->SetMaximum(1.5);
gRatWidth[0]->SetMinimum(0.7);
gRatWidth[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatWidth[icomb] ) gRatWidth[icomb]->Draw("P");
}
legendR->Draw();
cFitGraphRatio->cd(3);
gPad->SetGridx();
gPad->SetGridy();
// gPad->SetLogy();
gRatPt[0]->SetMaximum(2);
gRatPt[0]->SetMinimum(0);
gRatPt[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatPt[icomb] ) gRatPt[icomb]->Draw("P");
}
legendR->Draw();
if ( kMix )
{
cFitGraphRatio->cd(4);
gPad->SetGridx();
gPad->SetGridy();
// gPad->SetLogy();
gRatPtBC[0]->SetMaximum(2);
gRatPtBC[0]->SetMinimum(0);
gRatPtBC[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatPtBC[icomb] ) gRatPtBC[icomb]->Draw("P");
}
legendR->Draw();
}
cFitGraphRatio->Print(Form("IMfigures/%s_%s_MassWidthPtSpectra_%s_%sCombinations_RatioToSum.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),opt.Data(),
/*kFileName.Data(),*/kPlotFormat.Data()));
// Ratio to corresponding TRD case
if ( kFirstTRDSM > 0 && opt == "SM" ) // it could be extended for Sector/Side
{
//
// Calculate the ratio to the sum
//
TGraphErrors* gRatTRDPt [nCombi];
TGraphErrors* gRatTRDPtBC [nCombi];
TGraphErrors* gRatTRDMass [nCombi];
TGraphErrors* gRatTRDWidth[nCombi];
TLegend * legendR = new TLegend(xmin,ymin,xmax,ymax);
legendR->SetTextSize(0.05);
for(Int_t icomb = 0; icomb < nCombi; icomb ++)
{
//printf("icomb %d\n",icomb);
//printf("\t pt %p %p\n",gPt[icomb],gSumPt);
if(icomb < kFirstTRDSM)
{
gRatTRDPt [icomb] = DivideGraphs(gPt [icomb],gSumTRDnotPt ); // PlotUtils.C
gRatTRDPtBC [icomb] = DivideGraphs(gPtBC [icomb],gSumTRDnotPtBC ); // PlotUtils.C
gRatTRDMass [icomb] = DivideGraphs(gMass [icomb],gSumTRDnotMass ); // PlotUtils.C
gRatTRDWidth[icomb] = DivideGraphs(gWidth[icomb],gSumTRDnotWidth); // PlotUtils.C
}
else
{
gRatTRDPt [icomb] = DivideGraphs(gPt [icomb],gSumTRDyesPt ); // PlotUtils.C
gRatTRDPtBC [icomb] = DivideGraphs(gPtBC [icomb],gSumTRDyesPtBC ); // PlotUtils.C
gRatTRDMass [icomb] = DivideGraphs(gMass [icomb],gSumTRDyesMass ); // PlotUtils.C
gRatTRDWidth[icomb] = DivideGraphs(gWidth[icomb],gSumTRDyesWidth); // PlotUtils.C
}
if(!gRatTRDMass[icomb]) continue;
gRatTRDPt [icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatTRDPt [icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatTRDPt [icomb]->SetLineColor (modColorIndex[icomb]);
gRatTRDMass[icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatTRDMass[icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatTRDMass[icomb]->SetLineColor (modColorIndex[icomb]);
gRatTRDWidth[icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatTRDWidth[icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatTRDWidth[icomb]->SetLineColor (modColorIndex[icomb]);
gRatTRDPt [icomb]->GetHistogram()->SetTitle(Form("#it{p}_{T} of %s from fit, %s " ,particleN.Data(), opt.Data()));
gRatTRDWidth[icomb]->GetHistogram()->SetTitle(Form("%s mass #sigma vs #it{p}_{T}, %s ",particleN.Data(), opt.Data()));
gRatTRDMass [icomb]->GetHistogram()->SetTitle(Form("%s mass #mu vs #it{p}_{T}, %s " ,particleN.Data(), opt.Data()));
gRatTRDPt [icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatTRDWidth[icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatTRDMass [icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatTRDPt [icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatTRDWidth[icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatTRDMass [icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatTRDPt [icomb]->GetHistogram()->SetTitleOffset(1.4,"Y");
gRatTRDWidth[icomb]->GetHistogram()->SetTitleOffset(1.4,"Y");
gRatTRDMass [icomb]->GetHistogram()->SetTitleOffset(1.4,"Y");
if ( kMix )
{
gRatTRDPtBC [icomb]->SetMarkerStyle(modStyleIndex[icomb]);
gRatTRDPtBC [icomb]->SetMarkerColor(modColorIndex[icomb]);
gRatTRDPtBC [icomb]->SetLineColor (modColorIndex[icomb]);
gRatTRDPtBC [icomb]->GetHistogram()->SetTitle(Form("#it{p}_{T} of %s bin counted, %s ",particleN.Data(), opt.Data()));
gRatTRDPtBC [icomb]->GetHistogram()->SetYTitle("Ratio to sum");
gRatTRDPtBC [icomb]->GetHistogram()->SetXTitle("#it{p}_{T} (GeV/#it{c})");
gRatTRDPtBC [icomb]->GetHistogram()->SetTitleOffset(1.5,"Y");
}
if ( !opt.Contains("Group") )
legendR->AddEntry(gPt[icomb],Form("%s %d",opt.Data(),icomb),"P");
else
{
if(icomb == 0) legendR->AddEntry(gPt[icomb],"SM0+4+5+6+7+8+9","P");
if(icomb == 1) legendR->AddEntry(gPt[icomb],"SM1+2","P");
if(icomb == 2) legendR->AddEntry(gPt[icomb],"SM3+7","P");
}
} // combi loop
//
// PLOT
//
TCanvas *cFitGraphRatioTRD = new TCanvas(Form("cFitGraphSumRatioTRD_%sCombinations",opt.Data()),
Form("Fit Graphs ratio to sum for %s combinations for TRD cases",opt.Data()),1000,1000);
cFitGraphRatioTRD->Divide(2, 2);
// Mass
cFitGraphRatioTRD->cd(1);
gPad->SetGridx();
gPad->SetGridy();
gRatTRDMass[0]->SetMaximum(1.03);
gRatTRDMass[0]->SetMinimum(0.97);
gRatTRDMass[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatTRDMass[icomb] ) gRatTRDMass[icomb]->Draw("P");
}
legendR->Draw();
cFitGraphRatioTRD->cd(2);
gPad->SetGridx();
gPad->SetGridy();
gRatTRDWidth[0]->SetMaximum(1.5);
gRatTRDWidth[0]->SetMinimum(0.7);
gRatTRDWidth[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatTRDWidth[icomb] ) gRatTRDWidth[icomb]->Draw("P");
}
legendR->Draw();
cFitGraphRatioTRD->cd(3);
gPad->SetGridx();
gPad->SetGridy();
// gPad->SetLogy();
gRatTRDPt[0]->SetMaximum(2);
gRatTRDPt[0]->SetMinimum(0);
gRatTRDPt[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatTRDPt[icomb] ) gRatTRDPt[icomb]->Draw("P");
}
legendR->Draw();
if ( kMix )
{
cFitGraphRatioTRD->cd(4);
gPad->SetGridx();
gPad->SetGridy();
// gPad->SetLogy();
gRatTRDPtBC[0]->SetMaximum(2);
gRatTRDPtBC[0]->SetMinimum(0);
gRatTRDPtBC[0]->Draw("AP");
for(Int_t icomb = 1; icomb < nCombi; icomb ++)
{
if ( gRatTRDPtBC[icomb] ) gRatTRDPtBC[icomb]->Draw("P");
}
legendR->Draw();
}
cFitGraphRatioTRD->Print(Form("IMfigures/%s_%s_MassWidthPtSpectra_%s_%sCombinations_RatioToSumTRD.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),opt.Data(),
/*kFileName.Data(),*/kPlotFormat.Data()));
TLegend * legendSums = new TLegend(xmin,ymin,xmax,ymax);
//
// PLOT
//
TCanvas *cFitGraphSums = new TCanvas(Form("cFitGraph_%sSums",opt.Data()),
Form("Fit Graphs for %s Sums",opt.Data()),1000,1000);
cFitGraphSums->Divide(2, 2);
// Mass
cFitGraphSums->cd(1);
gPad->SetGridx();
gPad->SetGridy();
if ( kParticle == "Pi0" )
{
gSumMass->SetMaximum(135);
gSumMass->SetMinimum(125);
}
else
{
gSumMass->SetMaximum(560);
gSumMass->SetMinimum(520);
}
gSumMass->Draw("AP");
gSumTRDnotMass->Draw("P");
gSumTRDyesMass->Draw("P");
legendSums->AddEntry(gSumMass,"Sum","P");
legendSums->AddEntry(gSumTRDnotMass,"w/o TRD","P");
legendSums->AddEntry(gSumTRDyesMass,"w/ TRD","P");
legendSums->Draw();
cFitGraphSums->cd(2);
gPad->SetGridx();
gPad->SetGridy();
if ( kParticle == "Pi0" )
{
gSumWidth->SetMaximum(17);
gSumWidth->SetMinimum(7);
if(opt=="Side") gSumWidth->SetMinimum(2);
}
else
{
gSumWidth->SetMaximum(50);
gSumWidth->SetMinimum(10);
}
gSumWidth->Draw("AP");
gSumTRDnotWidth->Draw("P");
gSumTRDyesWidth->Draw("P");
legendSums->Draw();
cFitGraphSums->cd(3);
gPad->SetGridx();
gPad->SetGridy();
gPad->SetLogy();
gSumPt->SetMaximum(1);
gSumPt->SetMinimum(1e-8);
gSumPt->Draw("AP");
gSumTRDnotPt->Draw("P");
gSumTRDyesPt->Draw("P");
legendSums->Draw();
if ( kMix )
{
cFitGraphSums->cd(4);
gPad->SetGridx();
gPad->SetGridy();
gPad->SetLogy();
gSumPtBC->SetMaximum(1);
gSumPtBC->SetMinimum(1e-8);
gSumPtBC->Draw("AP");
gSumTRDnotPtBC->Draw("P");
gSumTRDyesPtBC->Draw("P");
legend->Draw();
}
cFitGraphSums->Print(Form("IMfigures/%s_%s_MassWidthPtSpectra_%s_%sSums.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),opt.Data(),
/*kFileName.Data(),*/kPlotFormat.Data()));
}
}
///
/// Get primary generated spectra and detector acceptance
/// Plot them
///
//-----------------------------------------------------------------------------
void PrimarySpectra(Int_t nPt, TArrayD xPtLimits, TArrayD xPt, TArrayD exPt)
{
gStyle->SetOptTitle(1);
gStyle->SetTitleOffset(2,"Y");
gStyle->SetOptStat(0);
gStyle->SetOptFit(000000);
TArrayD primMesonPt ; primMesonPt .Set(nPt);
TArrayD eprimMesonPt ; eprimMesonPt .Set(nPt);
TArrayD primMesonPtAcc; primMesonPtAcc.Set(nPt);
TArrayD eprimMesonPtAcc; eprimMesonPtAcc.Set(nPt);
TArrayD primMesonAcc ; primMesonAcc.Set(nPt);
TArrayD eprimMesonAcc ; eprimMesonAcc.Set(nPt);
TH2D* h2PrimMesonPtY = (TH2D*) fil->Get( Form("%s_hPrim%sRapidity" ,kHistoStartName.Data(), kParticle.Data() ) );
TH2D* h2PrimMesonPtYAcc = (TH2D*) fil->Get( Form("%s_hPrim%sAccRapidity",kHistoStartName.Data(), kParticle.Data() ) );
if ( !h2PrimMesonPtY ) return ;
if(kSumw2)
{
h2PrimMesonPtY ->Sumw2();
h2PrimMesonPtYAcc->Sumw2();
}
// if ( nEvt < 1 )
// {
// h2PrimMesonPtY ->Scale(1e10);
// h2PrimMesonPtYAcc->Scale(1e10);
// }
// else
{
h2PrimMesonPtY ->Scale(1./nEvt);
h2PrimMesonPtYAcc->Scale(1./nEvt);
}
h2PrimMesonPtY ->Write();
h2PrimMesonPtYAcc->Write();
TH1D* hY = h2PrimMesonPtY->ProjectionY("Rapidity",-1,-1);
Int_t binYmin = hY->FindBin(-0.65);
Int_t binYmax = hY->FindBin(+0.65);
//printf("Y bin min %d, max %d\n",binYmin,binYmax);
TH1D* hPrimMesonPt = (TH1D*) h2PrimMesonPtY->ProjectionX("PrimaryPt" ,binYmin ,binYmax );
hPrimMesonPt->Write();
TH1D* hYAcc = h2PrimMesonPtYAcc->ProjectionY("RapidityAcc",-1,-1);
binYmin = hYAcc->FindBin(-0.65);
binYmax = hYAcc->FindBin(+0.65);
//printf("Y bin min %d, max %d\n",binYmin,binYmax);
TH1D* hPrimMesonPtAcc = (TH1D*) h2PrimMesonPtYAcc->ProjectionX("PrimaryPtAccepted" ,binYmin ,binYmax );
hPrimMesonPtAcc->Write();
// PlotUtils.C
ScaleBinBySize(hPrimMesonPt);
ScaleBinBySize(hPrimMesonPtAcc);
Double_t integralA = 0;
Double_t integralAErr = 0;
Double_t integralB = 0;
Double_t integralBErr = 0;
Double_t ptMin = -1;
Double_t ptMax = -1;
Int_t binMin= -1;
Int_t binMax= -1;
for(Int_t ibin = 0; ibin < nPt; ibin++ )
{
ptMin = xPtLimits[ibin];
ptMax = xPtLimits[ibin+1];
binMin = hPrimMesonPt->FindBin(ptMin);
binMax = hPrimMesonPt->FindBin(ptMax)-1;
// PlotUtils.C
GetRangeIntegralAndError(hPrimMesonPt , binMin, binMax, integralA, integralAErr );
GetRangeIntegralAndError(hPrimMesonPtAcc, binMin, binMax, integralB, integralBErr );
primMesonPt [ibin] = integralA;
eprimMesonPt [ibin] = integralAErr;
primMesonPtAcc[ibin] = integralB;
eprimMesonPtAcc[ibin] = integralBErr;
if ( integralA > 0 && integralB > 0 )
{
primMesonAcc[ibin] = integralB / integralA ;
eprimMesonAcc[ibin] = GetFractionError(integralB,integralA,integralBErr,integralAErr); // PlotUtils.C
}
else
{
primMesonAcc[ibin] = 0;
eprimMesonAcc[ibin] = 0;
}
// printf("Bin %d, [%1.1f,%1.1f] bin size %1.1f, content num %2.2e, content den %2.2e: frac %2.3f+%2.3f\n",
// ibin,xPtLimits[ibin],xPtLimits[ibin+1],2*exPt[ibin],primMesonPtAcc[ibin],primMesonPt[ibin],primMesonAcc[ibin],eprimMesonAcc[ibin] );
primMesonPt [ibin]/=((exPt[ibin]*4)); // It should be 2 not 4???
primMesonPtAcc[ibin]/=((exPt[ibin]*4));
// // Scale biased production
// if(kFileName.Contains("pp_7TeV_Pi0"))
// {
// primMeson[ibin]*=1.e6;
// primMeson[ibin]*=360./100.;
//
// //eprimMeson[ibin]*=1.e6*1.e6;
// eprimMeson[ibin]*=360./100.;
//
// mesonPtBC [0][ibin] /= (0.62 +xPt[ibin]*0.0017 );
// emesonPtBC[0][ibin] /= (0.62 +xPt[ibin]*0.0017 );
//
// primMeson [ibin] /= (0.56 +xPt[ibin]*0.0096 );
// eprimMeson[ibin] /= (0.56 +xPt[ibin]*0.0096 );
// }
} // pT bin loop
TGraphErrors * gPrim = new TGraphErrors(nPt,xPt.GetArray(),primMesonPt.GetArray(),exPt.GetArray(),eprimMesonPt.GetArray());
gPrim->SetName("Primary");
gPrim->GetHistogram()->SetYTitle("d #it{N}/d #it{p}_{T}");
gPrim->GetHistogram()->SetTitleOffset(1.4,"Y");
gPrim->GetHistogram()->SetXTitle("#it{p}_{T,gen} (GeV/#it{c})");
gPrim->GetHistogram()->SetTitleOffset(1.2,"X");
gPrim->GetHistogram()->SetTitle("#it{p}_{T} spectra for |#it{Y}| < 0.65");
gPrim->Write();
TGraphErrors * gPrimAcc = new TGraphErrors(nPt,xPt.GetArray(),primMesonPtAcc.GetArray(),exPt.GetArray(),eprimMesonPtAcc.GetArray());
gPrimAcc->SetName("PrimaryInAcceptance");
gPrimAcc->GetHistogram()->SetYTitle("d#it{N}/d #it{p}_{T}");
gPrimAcc->GetHistogram()->SetTitle(Form("|#it{Y}| < 0.65 in %s",kCalorimeter.Data()));
gPrimAcc->Write();
// Acceptance
TH1D* hAcc = (TH1D*) hPrimMesonPtAcc->Clone("hAcceptance");
hAcc->Divide(hPrimMesonPt);
TGraphErrors * gAcc = new TGraphErrors(nPt,xPt.GetArray(),primMesonAcc.GetArray(),exPt.GetArray(),eprimMesonAcc.GetArray());
gAcc->SetName("Acceptance");
gAcc->GetHistogram()->SetYTitle("Acceptance");
gAcc->GetHistogram()->SetTitleOffset(1.4,"Y");
gAcc->GetHistogram()->SetXTitle("#it{p}_{T,gen} (GeV/#it{c})");
gAcc->GetHistogram()->SetTitleOffset(1.2,"X");
gAcc->GetHistogram()->SetTitle(Form("Acceptance for |#it{Y}| < 0.65 in %s",kCalorimeter.Data()));
gAcc->Write();
// Plot spectra and acceptance
//
TCanvas *cAcc = new TCanvas(Form("cAcceptance"),
Form("Primary generated p_{T} spectra and acceptance"),2*600,600);
cAcc->Divide(2, 1);
cAcc->cd(1);
//gPad->SetGridx();
//gPad->SetGridy();
gPad->SetLogy();
Double_t maximum = gPrim->GetHistogram()->GetMaximum();
Double_t minimum = gPrim->GetHistogram()->GetMinimum();
if ( gPrimAcc->GetMaximum() > maximum ) maximum = gPrimAcc->GetMaximum() ;
if ( gPrimAcc->GetMinimum() > minimum ) minimum = gPrimAcc->GetMinimum() ;
gPrim->SetMaximum(maximum*10);
gPrim->SetMinimum(minimum/10);
gPrim ->Draw("AP");
gPrimAcc->Draw("P");
gPrim ->SetMarkerColor(1);
gPrimAcc->SetMarkerColor(4);
gPrim ->SetLineColor(1);
gPrimAcc->SetLineColor(4);
gPrim ->SetMarkerStyle(24);
gPrimAcc->SetMarkerStyle(24);
hPrimMesonPt ->Draw("same");
hPrimMesonPtAcc->Draw("same");
hPrimMesonPt ->Draw("Hsame");
hPrimMesonPtAcc->Draw("Hsame");
hPrimMesonPt ->SetLineColor(1);
hPrimMesonPtAcc->SetLineColor(4);
TLegend * legendS = new TLegend(0.4,0.7,0.9,0.9);
legendS->AddEntry(gPrim,"|Y| < 0.65","P");
legendS->AddEntry(gPrimAcc,Form("Both in %s",kCalorimeter.Data()),"P");
legendS->AddEntry(hPrimMesonPt,"Histo |Y| < 0.65","L");
legendS->AddEntry(hPrimMesonPtAcc,Form("Histo Both in %s",kCalorimeter.Data()),"L");
legendS->Draw();
cAcc->cd(2);
gPad->SetGridx();
gPad->SetGridy();
//gPad->SetLogy();
//gAcc->SetMaximum(1);
gAcc->SetMaximum(gAcc->GetHistogram()->GetMaximum()*1.3);
gAcc->SetMinimum(0);
gAcc->Draw("AP");
gAcc->SetMarkerColor(1);
gAcc->SetMarkerStyle(24);
hAcc->Draw("Hsame");
hAcc->SetLineColor(4);
TLegend * legendA = new TLegend(0.7,0.75,0.9,0.9);
legendA->AddEntry(gAcc,"Graph","P");
legendA->AddEntry(hAcc,"Histo","L");
legendA->Draw();
cAcc->Print(Form("IMfigures/%s_%s_PrimarySpectraAcceptance_%s.%s",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data(),
/*kFileName.Data(),*/ kPlotFormat.Data()));
}
///
/// Main method
///
/// \param prodname : name of directory with histogram file
/// \param filename : histogram file name
/// \param histoDir : TDirectoryFile folder name
/// \param histoList : TList folder name
/// \param histoStart : begining of histograms name
/// \param calorimeter: "EMCAL","DCAL"
/// \param particle : "Pi0","Eta", define fitting and plotting ranges for particle
/// \param nPairMin : minimum number of entries un the pi0 or eta peak integral to do the fits and plotting. Careful in MC scaled productions.
/// \param sumw2 : bool, apply the histograms Sumw2 method to get proper errors when not done before
/// \param rebin : int, rebin default Inv Mass histograms binning with this value
/// \param firstTRD : int, First EMCal SM covered by a TRD SM, in 2011 and 4 in 2012-13
/// \param mixed : bool, use mixed event to constrain combinatorial background
/// \param truncmix : bool, 1: use truncated function to constrain backgroun; 0: use factor from fixed bin
/// \param pol : int, polinomyal type for residual background under the peak
/// \param drawAll : bool, activate plot per pair in any SM
/// \param drawMCAll : bool, activate plot per pair in any SM and MC
/// \param drawPerSM : bool, activate plot per pair in same SM
/// \param drawPerSMGr: bool, activate plot per pair in same SM adding SM: 3 groups [3,7], [1,2], [0,4,5,6,8,9], needs drawPerSM=kTRUE
/// \param drawPerSector: bool, activate plot per pair in different continuous SM sectors
/// \param drawPerSide: bool, activate plot per pair in different continuous SM sides
/// \param plotFormat : define the type of figures: eps, pdf, etc.
///
//-----------------------------------------------------------------------------
void InvMassFit
(TString prodname = "LHC18c3_NystromOn",//"LHC17l3b_fast",
TString filename = "AnalysisResults",
TString histoDir = "Pi0IM_GammaTrackCorr_EMCAL",
TString histoList = "default",
TString histoStart = "",
TString calorimeter = "EMCAL",
TString particle = "Pi0",
Float_t nPairMin = 20,
Bool_t sumw2 = kTRUE,
Int_t rebin = 1,
Int_t firstTRD = 6,
Bool_t mixed = kTRUE,
Bool_t truncmix = kFALSE,
Int_t pol = 1,
Bool_t drawAll = kFALSE,
Bool_t drawMCAll = kFALSE,
Bool_t drawPerSM = kTRUE,
Bool_t drawPerSMGr = kFALSE,
Bool_t drawPerSector= kFALSE,
Bool_t drawPerSide = kFALSE,
TString plotFormat = "eps")
{
// Load plotting utilities
//gROOT->Macro("$ALICE_PHYSICS/PWGGA/CaloTrackCorrelations/macros/PlotUtils.C"); // Already in include
//gROOT->Macro("$MACROS/style.C");//Set different root style parameters
kSumw2 = sumw2;
kPolN = pol;
kMix = mixed;
kTrunMixFunc= truncmix;
kParticle = particle;
kProdName = prodname;
kFileName = filename;
kPlotFormat = plotFormat;
kCalorimeter= calorimeter;
kNPairCut = nPairMin;
kRebin = rebin;
kFirstTRDSM = firstTRD;
if(histoStart !="")
kHistoStartName = histoStart;
else
{
kHistoStartName = "AnaPi0_Calo0";
if(kCalorimeter=="DCAL")
kHistoStartName = "AnaPi0_Calo1";
}
if(drawPerSMGr) drawPerSM = kTRUE;
//---------------------------------------
// Get input file
//---------------------------------------
Int_t ok = GetFileAndEvents(histoDir, histoList);
// kProdName.ReplaceAll("module/","");
// kProdName.ReplaceAll("TCardChannel","");
kProdName.ReplaceAll("/","_");
// kProdName.ReplaceAll("2_","_");
// kProdName.ReplaceAll("__","_");
if( kFileName !="AnalysisResults" && !kFileName.Contains("Scale") )
kProdName+=kFileName;
printf("Settings: prodname <%s>, filename <%s>, histoDir <%s>, histoList <%s>,\n"
" \t histo start name <%s>, particle <%s>, calorimeter <%s>, \n"
" \t mix %d, kPolN %d, sumw2 %d, n pairs cut %2.2e\n",
kProdName.Data(), kFileName.Data(),histoDir.Data(),histoList.Data(), kHistoStartName.Data(),
kParticle.Data(), kCalorimeter.Data(), kMix, kPolN, kSumw2, kNPairCut);
if ( !ok )
{
printf("Could not recover file <%p> or dir <%p> or list <%p>\n",fil,direc,lis);
return ;
}
// kNPairCut/=nEvt;
//---------------------------------------
// Set-up output file with processed histograms
//---------------------------------------
// Open output file
fout = new TFile(Form("IMfigures/%s_%s_MassWidthPtHistograms_%s.root",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data() /*,kFileName.Data()*/), "recreate");
printf("Open Output File: IMfigures/%s_%s_MassWidthPtHistograms_%s.root\n",
kProdName.Data(),kCalorimeter.Data(),kParticle.Data());//,kFileName.Data());
//---------------------------------------
// Set the pt bins and total range
//---------------------------------------
const Int_t nPtEta = 13;
Double_t xPtLimitsEta[] = {2.,3.,4.,5.,6.,8.,10.,14.,18.,24.,28.,34.,40.,50.};
// const Int_t nPtPi0 = 7;
// Double_t xPtLimitsPi0[] = {1.5,2,2.5,3.,3.5,4.,5.,6.};
const Int_t nPtPi0 = 23;
Double_t xPtLimitsPi0[] = {1.6,1.8,2.,2.2,2.4,2.6,2.8,3.,3.4,3.8,4.2,4.6,5.,5.5,6.,6.5,7.,7.5,8.,9.,10.,12.,15.,17.,20.};
Int_t nPt = nPtPi0;
if(kParticle == "Eta") nPt = nPtEta;
TArrayD xPtLimits; xPtLimits.Set(nPt+1);
TArrayD xPt ; xPt .Set(nPt);
TArrayD exPt ; exPt .Set(nPt);
for(Int_t i = 0; i < nPt; i++)
{
if(kParticle == "Pi0")
{
xPtLimits.SetAt(xPtLimitsPi0[i],i);
exPt .SetAt((xPtLimitsPi0[i+1]-xPtLimitsPi0[i])/2,i);
xPt .SetAt(xPtLimitsPi0[i]+exPt[i],i);
}
else
{
xPtLimits.SetAt(xPtLimitsEta[i],i);
exPt .SetAt((xPtLimitsEta[i+1]-xPtLimitsEta[i])/2,i);
xPt .SetAt(xPtLimitsEta[i]+exPt[i],i);
}
//printf("%s pT bin %d, pT %2.2f, dpT %2.2f, limit %2.2f\n",kParticle.Data(),i,xPt[i],exPt[i],xPtLimits[i]);
}
// Extra entry
if ( kParticle == "Pi0" ) xPtLimits.SetAt(xPtLimitsPi0[nPt],nPt);
else xPtLimits.SetAt(xPtLimitsEta[nPt],nPt);
TString comment = "";
TString leg = "";
TString hname = "";
//---------------------------------------
// Fitting function and histograms initialization
//---------------------------------------
SetFitFun();
TH2F * hRe ;
TH2F * hMi ;
//=======================================
// Get histograms, project per pT bin and fit
// Do it for different kind of histograms:
// Total pairs, MC pairs, pairs per SM combinations
//=======================================
//---------------------------------------
// MC input
//---------------------------------------
if ( drawMCAll )
{
// Get the generated primary pi0 spectra, for efficiency calculation
PrimarySpectra(nPt,xPtLimits, xPt, exPt);
// Reconstructed pT of real meson pairs
//hRe = (TH2F *) fil->Get( Form("%s_hMCOrgMass_2", kHistoStartName.Data()) ); // Pi0
//hRe = (TH2F *) fil->Get( Form("%s_hMCOrgMass_3", kHistoStartName.Data()) ); // Eta
hRe = (TH2F *) fil->Get( Form("%s_hMC%sMassPtRec", kHistoStartName.Data(), kParticle.Data()) );
comment = "MC pT reconstructed";
leg = "MC pT reconstructed";
hname = "MCpTReco" ;
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hRe, 0x0 );
// Reconstructed pT of real eta pairs
hRe = (TH2F *) fil->Get( Form("%s_hMC%sMassPtTrue", kHistoStartName.Data(), kParticle.Data()) );
comment = "MC pT generated";
leg = "MC pT generated";
hname = "MCpTGener" ;
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hRe, 0x0 );
} // MC treatment
//---------------------------------------
// All SM
//---------------------------------------
if ( drawAll )
{
if ( !lis )
{
hRe = (TH2F *) fil->Get(Form("%s_hRe_cen0_pidbit0_asy0_dist1", kHistoStartName.Data()));
hMi = (TH2F *) fil->Get(Form("%s_hMi_cen0_pidbit0_asy0_dist1", kHistoStartName.Data()));
}
else
{
hRe = (TH2F *) lis->FindObject(Form("%s_hRe_cen0_pidbit0_asy0_dist1", kHistoStartName.Data()));
hMi = (TH2F *) lis->FindObject(Form("%s_hMi_cen0_pidbit0_asy0_dist1", kHistoStartName.Data()));
}
printf("histo Re %p - Mix %p All SM\n",hRe,hMi);
if( !hMi ) kMix = kFALSE;
comment = "All SM";
leg = "All SM";
hname = "AllSM";
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hRe, hMi );
}
//-------------------------------------------
// Histograms for cluster pairs in different
// combinations of SM
//-------------------------------------------
//
// Pairs in same SM
//
if ( drawPerSM )
{
Int_t imod;
Int_t firstMod = 0;
Int_t lastMod = 11;
if ( kCalorimeter=="DCAL" )
{
firstMod = 12;
lastMod = 19;
}
// Initialize SM grouping histograms
// 0 : SM 0+4+5+6+8+9
// 1 : SM 1+2
// 2 : SM 3+7
TH2F * hReSMGroups[3] ;
TH2F * hMiSMGroups[3] ;
TH2F * hReSM = 0;
TH2F * hMiSM = 0;
TH2F * hReSMTRDYes = 0;
TH2F * hMiSMTRDYes = 0;
TH2F * hReSMTRDNot = 0;
TH2F * hMiSMTRDNot = 0;
for(Int_t imodgroup = 0; imodgroup<=2; imodgroup++)
{
hReSMGroups[imodgroup] = hMiSMGroups[imodgroup] = 0x0;
}
for(imod = firstMod; imod<=lastMod; imod++)
{
if(!lis)
{
hRe = (TH2F *) fil->Get(Form("%s_hReMod_%d", kHistoStartName.Data(), imod));
hMi = (TH2F *) fil->Get(Form("%s_hMiMod_%d", kHistoStartName.Data(), imod));
}
else
{
hRe = (TH2F *) lis->FindObject(Form("%s_hReMod_%d", kHistoStartName.Data(), imod));
hMi = (TH2F *) lis->FindObject(Form("%s_hMiMod_%d", kHistoStartName.Data(), imod));
}
//printf("histo mod %d Re %p - Mix %p\n",imod, hRe,hMi);
comment = Form("both clusters in SM %d",imod);
leg = Form("SM %d",imod);
hname = Form("SM%d" ,imod);
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hRe, hMi );
// Add all SM
if( imod == firstMod )
{
hReSM = (TH2F*) hRe->Clone("h2D_Re_IM_SM");
if(kMix) hMiSM = (TH2F*) hMi->Clone("h2D_Mi_IM_SM");
}
else
{
hReSM->Add( hRe );
if(kMix) hMiSM ->Add( hMi );
}
// Add TRD covered or not SM
if( kFirstTRDSM > 0 )
{
if ( imod >= kFirstTRDSM && imod < 10 )
{
if( imod == kFirstTRDSM )
{
hReSMTRDYes = (TH2F*) hRe->Clone("h2D_Re_IM_SM_TRD_Yes");
if(kMix) hMiSMTRDYes = (TH2F*) hMi->Clone("h2D_Mi_IM_SM_TRD_Yes");
}
else
{
hReSMTRDYes->Add( hRe );
if(kMix) hMiSMTRDYes ->Add( hMi );
}
}
}
// Group SMs in with particular behaviors
if ( drawPerSMGr )
{
if ( imod == 0 )
{
hReSMGroups[0] = (TH2F*) hRe->Clone("h2D_Re_IM_SM045689");
if(kMix)
hMiSMGroups[0] = (TH2F*) hMi->Clone("h2D_Mi_IM_SM045689");
}
else if ( imod == 1 )
{
hReSMGroups[1] = (TH2F*) hRe->Clone("h2D_Re_IM_SM12");
if(kMix) hMiSMGroups[1] = (TH2F*) hMi->Clone("h2D_Mi_IM_SM12");
}
else if ( imod == 3 )
{
hReSMGroups[2] = (TH2F*) hRe->Clone("h2D_Re_IM_SM37");
if(kMix) hMiSMGroups[2] = (TH2F*) hMi->Clone("h2D_Mi_IM_SM37");
}
else if ( imod == 2 )
{
hReSMGroups[1]->Add(hRe);
if(kMix) hMiSMGroups[1]->Add(hMi);
}
else if ( imod == 7 )
{
hReSMGroups[2]->Add(hRe);
if(kMix) hMiSMGroups[2]->Add(hMi);
}
else if ( imod < 10 )
{
hReSMGroups[0]->Add(hRe);
if(kMix) hMiSMGroups[0]->Add(hMi);
}
} // do SM groups addition
} // SM loop
// Sum of pairs in same SM
comment = "both clusters in same SM";
leg = "Same SM";
hname = "SameSM";
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hReSM, hMiSM );
if ( kFirstTRDSM > 0 )
{
// Sum of pairs in same SM with TRD
comment = "both clusters in same SM, TRD covered";
leg = "Same SM, TRD Yes";
hname = "SameSMTRDYes";
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hReSMTRDYes, hMiSMTRDYes );
// Sum of pairs in same SM without TRD
hReSMTRDNot = (TH2F*) hReSM->Clone("h2D_Re_IM_SM_TRD_Not");
hReSMTRDNot->Add(hReSMTRDYes,-1);
if(kMix)
{
hMiSMTRDNot = (TH2F*) hMiSM->Clone("h2D_Mi_IM_SM_TRD_Not");
hMiSMTRDNot->Add(hMiSMTRDYes,-1);
}
comment = "both clusters in same SM, NOT TRD covered";
leg = "Same SM, TRD No";
hname = "SameSMTRDNot";
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hReSMTRDNot, hMiSMTRDNot );
}
// Fit parameters final plotting
PlotGraphs("SM" ,firstMod ,lastMod );
// Group SMs in with particular behaviors
if( drawPerSMGr )
{
for(Int_t imodgroup = 0; imodgroup<=2; imodgroup++)
{
//printf("histo modgroup %d Re %p - Mix %p\n",
// imod, hReSMGroups[imodgroup], hMiSMGroups[imodgroup]);
comment = Form("both clusters in same SM, group %d",imodgroup);
leg = Form("SMGroup %d",imodgroup);
hname = Form("SMGroup%d" ,imodgroup);
if ( imodgroup != 0 )
{
hReSMGroups[imodgroup]->Scale(1./2.);
if ( kMix ) hMiSMGroups[imodgroup]->Scale(1./2.);
}
else
{
hReSMGroups[imodgroup]->Scale(1./6.);
if ( kMix ) hMiSMGroups[imodgroup]->Scale(1./6.);
}
ProjectAndFit(nPt, comment, leg, hname, xPtLimits, xPt, exPt,
hReSMGroups[imodgroup], hMiSMGroups[imodgroup] );
}
// Fit parameters final plotting
PlotGraphs("SMGroup",0 ,2 );
} // Per SM groups
} // Per SM
//
// Pairs in same sector
//
if(drawPerSector)
{
Int_t firstSector = 0;
Int_t lastSector = 5;
if ( kCalorimeter=="DCAL" )
{
firstSector = 6;
lastSector = 9;
}
TH2F * hReSector = 0;
TH2F * hMiSector = 0;
Int_t isector;
for(isector = firstSector; isector<=lastSector; isector++)
{
if(!lis)
{
hRe = (TH2F *) fil->Get(Form("%s_hReSameSectorEMCALMod_%d", kHistoStartName.Data(), isector));
hMi = (TH2F *) fil->Get(Form("%s_hMiSameSectorEMCALMod_%d", kHistoStartName.Data(), isector));
}
else
{
hRe = (TH2F *) lis->FindObject(Form("%s_hReSameSectorEMCALMod_%d", kHistoStartName.Data(), isector));
hMi = (TH2F *) lis->FindObject(Form("%s_hMiSameSectorEMCALMod_%d", kHistoStartName.Data(), isector));
}
// Add all Sectors
if( isector == firstSector )
{
hReSector = (TH2F*) hRe->Clone("h2D_Re_IM_Sector");
if(kMix) hMiSector = (TH2F*) hMi->Clone("h2D_Mi_IM_Sector");
}
else
{
hReSector->Add( hRe );
if(kMix) hMiSector ->Add( hMi );
}
//printf("histo sector %d Re %p - Mix %p\n",isector, hRe,hMi);
comment = Form("both clusters in Sector %d",isector);
leg = Form("Sector %d",isector);
hname = Form("Sector%d" ,isector);
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hRe, hMi );
}
// Sum of pairs in same Sector
comment = "both clusters in same Sector";
leg = "Same Sector";
hname = "SameSector";
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hReSector, hMiSector );
// Fit parameters final plotting
PlotGraphs("Sector" ,firstSector,lastSector);
} // Per sector
// Pairs in same side
//
if(drawPerSide)
{
Int_t firstSide = 0;
Int_t lastSide = 9;
if ( kCalorimeter=="DCAL" )
{
firstSide = 10;
lastSide = 15;
}
TH2F * hReSide = 0;
TH2F * hMiSide = 0;
Int_t iside;
for(iside = firstSide; iside <= lastSide; iside++)
{
if(!lis)
{
hRe = (TH2F *) fil->Get(Form("%s_hReSameSideEMCALMod_%d", kHistoStartName.Data(), iside));
hMi = (TH2F *) fil->Get(Form("%s_hMiSameSideEMCALMod_%d", kHistoStartName.Data(), iside));
}
else
{
hRe = (TH2F *) lis->FindObject(Form("%s_hReSameSideEMCALMod_%d", kHistoStartName.Data(), iside));
hMi = (TH2F *) lis->FindObject(Form("%s_hMiSameSideEMCALMod_%d", kHistoStartName.Data(), iside));
}
// Add all Sides
if( iside == firstSide )
{
hReSide = (TH2F*) hRe->Clone("h2D_Re_IM_Side");
if(kMix) hMiSide = (TH2F*) hMi->Clone("h2D_Mi_IM_Side");
}
else
{
hReSide->Add( hRe );
if(kMix) hMiSide ->Add( hMi );
}
//printf("histo side %d Re %p - Mix %p\n",iside, hRe,hMi);
comment = Form("both clusters in Side %d",iside);
leg = Form("Side %d",iside);
hname = Form("Side%d" ,iside);
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hRe, hMi );
}
// Sum of pairs in same Side
comment = "both clusters in same Side";
leg = "Same Side";
hname = "SameSide";
ProjectAndFit(nPt,comment,leg,hname,xPtLimits, xPt, exPt, hReSide, hMiSide );
// Fit parameters final plotting
PlotGraphs("Side" ,firstSide ,lastSide );
} // per Side
fout->Close();
}
| dstocco/AliPhysics | PWGGA/CaloTrackCorrelations/macros/plotting/invmass/InvMassFit.C | C++ | bsd-3-clause | 85,625 |
<?php
use vova07\themes\admin\widgets\Box;
use modules\directory\Module;
$this->title = Module::t('shop', 'BACKEND_STORE_UPDATE_TITLE');
$this->params['subtitle'] = Module::t('shop', 'BACKEND_STORE_UPDATE_SUBTITLE');
$this->params['breadcrumbs'] = [
[
'label' => $this->title,
'url' => ['index'],
],
$this->params['subtitle']
];
$boxButtons[] = '{create}';
$boxButtons[] = '{delete}';
$boxButtons[] = '{cancel}';
$buttons['cancel'] = [
'url' => ['shop/index'],
'icon' => 'fa-reply',
'options' => [
'class' => 'btn-default',
'title' => Yii::t('vova07/themes/admin/widgets/box', 'Cancel')
]
];
$boxButtons = !empty($boxButtons) ? implode(' ', $boxButtons) : null; ?>
<div class="row">
<div class="col-sm-12">
<?php $box = Box::begin(
[
'title' => $this->params['subtitle'],
'renderBody' => false,
'options' => [
'class' => 'box-success'
],
'bodyOptions' => [
'class' => 'table-responsive'
],
'buttonsTemplate' => $boxButtons,
'buttons' => $buttons,
]
);
echo $this->render(
'_form',
[
'model' => $model,
'formModel' => $formModel,
'box' => $box
]
);
Box::end(); ?>
</div>
</div> | d-bo/unitaly-dev | modules/directory/views/backend/store/update.php | PHP | bsd-3-clause | 1,520 |
var archiver = require('archiver'),
async = require('async'),
escape = require('handlebars').Utils.escapeExpression,
fs = require('fs'),
glob = require('glob'),
path = require('path'),
yui = require('yui');
var config = require('../config'),
hbs = require('./hbs');
exports.archive = archiveLayout;
exports.clone = cloneLayouts;
exports.find = findLayout;
exports.load = loadLayouts;
// -----------------------------------------------------------------------------
var DIR_PATH = path.join(config.dirs.views, 'layouts', 'examples'),
LICENSE = fs.readFileSync(path.join(process.cwd(), 'LICENSE.md')),
README = fs.readFileSync(path.join(DIR_PATH, 'README.md')),
cache = null,
pending = null;
function archiveLayout(layout) {
if (!layout) { return null; }
var archive = archiver('zip');
archive.append(LICENSE, {name: 'LICENSE.md'});
archive.append(README, {name: 'README.md'});
archive.append(layout.html, {name: 'index.html'});
// Layout resources.
['css', 'js', 'imgs'].forEach(function (type) {
layout[type].forEach(function (file) {
archive.append(file.data, {name: file.filename});
});
});
return archive.finalize();
}
function cloneLayouts(layouts, options) {
layouts = clone(layouts);
options || (options = {});
layouts.forEach(function (layout) {
// Convert imgs back into Buffers.
layout.imgs.forEach(function (img) {
img.data = new Buffer(img.data);
});
if (options.escape) {
layout.description = escape(layout.description);
layout.html = escape(layout.html);
['css', 'js'].forEach(function (type) {
layout[type].forEach(function (file) {
file.data = escape(file.data);
});
});
}
});
return layouts;
}
function findLayout(layouts, name) {
var layout = null;
layouts.some(function (l) {
if (l.name === name) {
layout = l;
return true;
}
});
return layout;
}
/*
This provides metadata about the layout examples. If the `cache` option is set,
then the hard work is only performed once. A copy of the layouts metadata is
returned to the caller via the `callback`, therefore they are free to mute the
data and it won't affect any other caller.
*/
function loadLayouts(options, callback) {
// Options are optional.
if (typeof options === 'function') {
callback = options;
options = null;
}
options || (options = {});
// Check cache.
if (options.cache && cache) {
// Return clone of the cache.
callback(null, cloneLayouts(cache, options));
return;
}
// Put caller on the queue if the hard work of compiling the layouts
// metadata is currently in progress for another caller.
if (pending) {
pending.push(callback);
return;
}
pending = [callback];
// Run the show!
// 1) Glob the layout examples dir to get a list of filenames.
//
// 2) Create the metadata for the layout examples:
// a) Render each layout and capture its output *and* metadata set from
// within the template itself.
//
// b) Create a metadata object to represent the layout based on the
// data siphoned from the context object in which it was rendered.
//
// 3) Read the CSS, JS, and images associated with the layout example from
// the filesystem and capture it as part of the metadata.
//
// 4) Cache the result and call all queued calls with their own copy of the
// layout examples metadata.
async.waterfall([
glob.bind(null, '*' + hbs.extname, {cwd: DIR_PATH}),
createLayouts,
loadResources
], function (err, layouts) {
if (!err) { cache = layouts; }
while (pending.length) {
pending.shift().call(null, err, cloneLayouts(layouts, options));
}
pending = null;
});
}
// -- Utilities ----------------------------------------------------------------
function clone(obj) {
// Poor-man's clone.
return JSON.parse(JSON.stringify(obj));
}
function createLayouts(filenames, callback) {
// Default context values that mascarade as being the "app" and make the
// layout examples render in a particular way.
var contextProto = {
forDownload: true,
site : 'Pure',
section: 'Layout Examples',
pure: {
version: config.pure.version
},
yui_version: yui.YUI.version,
min: '-min',
layout : 'blank',
relativePath: '/',
helpers: {
pathTo: function () { return ''; }
}
};
function createLayout(filename, context, html, callback) {
var css = [];
// Include all `localCSS` files, including old IE versions.
(context.localCSS || []).forEach(function (entry) {
css.push(entry.path);
if (entry.oldIE) {
css.push(entry.oldIE);
}
});
callback(null, {
name : path.basename(filename, path.extname(filename)),
label : context.title,
description: context.subTitle,
tags : context.tags,
html: html,
css : css,
js : context.localJS || [],
imgs: context.localImgs || []
});
}
function renderTemplate(filename, callback) {
// Create a new context object that inherits from the defaults so when
// the template is rendered the own properties will be enumerable
// allowing us to sniff out the data added by the Handlebars helpers.
var context = Object.create(contextProto);
async.waterfall([
hbs.renderView.bind(hbs, path.join(DIR_PATH, filename), context),
createLayout.bind(null, filename, context)
], callback);
}
async.map(filenames, renderTemplate, callback);
}
function loadResources(layouts, callback) {
function processFile(type, filename, callback) {
fs.readFile(path.join(config.dirs.pub, filename), {
// Set the encoding for non-binary files.
encoding: type === 'imgs' ? null : 'utf8'
}, function (err, data) {
callback(err, {
name : path.basename(filename),
filename: filename,
data : data
});
});
}
function loadFiles(layout, type, callback) {
async.map(layout[type], processFile.bind(null, type), function (err, files) {
// Replace the list of filenames used by this layout with a
// collection of metadata for each file which includes its:
// name, filename, and contents.
layout[type] = files;
callback(err, files);
});
}
async.each(layouts, function (layout, callback) {
async.parallel([
loadFiles.bind(null, layout, 'css'),
loadFiles.bind(null, layout, 'js'),
loadFiles.bind(null, layout, 'imgs')
], callback);
}, function (err) {
callback(err, layouts);
});
}
| igorstefurak/pushcourse | lib/layouts.js | JavaScript | bsd-3-clause | 7,374 |
/*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "platform/graphics/Image.h"
#include "platform/graphics/GraphicsLayer.h"
#include "wtf/PassOwnPtr.h"
#include <gtest/gtest.h>
namespace blink {
namespace {
class MockGraphicsLayerClient : public GraphicsLayerClient {
public:
void paintContents(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect&) override { }
String debugName(const GraphicsLayer*) override { return String(); }
};
class TestImage : public Image {
public:
static PassRefPtr<TestImage> create(const IntSize& size, bool isOpaque)
{
return adoptRef(new TestImage(size, isOpaque));
}
TestImage(const IntSize& size, bool isOpaque)
: Image(0)
, m_size(size)
{
m_bitmap.allocN32Pixels(size.width(), size.height(), isOpaque);
m_bitmap.eraseColor(SK_ColorTRANSPARENT);
}
bool isBitmapImage() const override
{
return true;
}
bool currentFrameKnownToBeOpaque() override
{
return m_bitmap.isOpaque();
}
IntSize size() const override
{
return m_size;
}
bool bitmapForCurrentFrame(SkBitmap* bitmap) override
{
if (m_size.isZero())
return false;
*bitmap = m_bitmap;
return true;
}
// Stub implementations of pure virtual Image functions.
void destroyDecodedData(bool) override
{
}
void draw(SkCanvas*, const SkPaint&, const FloatRect&, const FloatRect&, RespectImageOrientationEnum, ImageClampingMode) override
{
}
private:
IntSize m_size;
SkBitmap m_bitmap;
};
class GraphicsLayerForTesting : public GraphicsLayer {
public:
explicit GraphicsLayerForTesting(GraphicsLayerClient* client)
: GraphicsLayer(client) { }
WebLayer* contentsLayer() const { return GraphicsLayer::contentsLayer(); }
};
} // anonymous namespace
TEST(ImageLayerChromiumTest, imageLayerContentReset)
{
MockGraphicsLayerClient client;
OwnPtr<GraphicsLayerForTesting> graphicsLayer = adoptPtr(new GraphicsLayerForTesting(&client));
ASSERT_TRUE(graphicsLayer.get());
ASSERT_FALSE(graphicsLayer->hasContentsLayer());
ASSERT_FALSE(graphicsLayer->contentsLayer());
RefPtr<Image> image = TestImage::create(IntSize(100, 100), false);
ASSERT_TRUE(image.get());
graphicsLayer->setContentsToImage(image.get());
ASSERT_TRUE(graphicsLayer->hasContentsLayer());
ASSERT_TRUE(graphicsLayer->contentsLayer());
graphicsLayer->setContentsToImage(0);
ASSERT_FALSE(graphicsLayer->hasContentsLayer());
ASSERT_FALSE(graphicsLayer->contentsLayer());
}
TEST(ImageLayerChromiumTest, opaqueImages)
{
MockGraphicsLayerClient client;
OwnPtr<GraphicsLayerForTesting> graphicsLayer = adoptPtr(new GraphicsLayerForTesting(&client));
ASSERT_TRUE(graphicsLayer.get());
RefPtr<Image> opaqueImage = TestImage::create(IntSize(100, 100), true /* opaque */);
ASSERT_TRUE(opaqueImage.get());
RefPtr<Image> nonOpaqueImage = TestImage::create(IntSize(100, 100), false /* opaque */);
ASSERT_TRUE(nonOpaqueImage.get());
ASSERT_FALSE(graphicsLayer->contentsLayer());
graphicsLayer->setContentsToImage(opaqueImage.get());
ASSERT_TRUE(graphicsLayer->contentsLayer()->opaque());
graphicsLayer->setContentsToImage(nonOpaqueImage.get());
ASSERT_FALSE(graphicsLayer->contentsLayer()->opaque());
}
} // namespace blink
| crosswalk-project/blink-crosswalk | Source/platform/graphics/ImageLayerChromiumTest.cpp | C++ | bsd-3-clause | 4,769 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/singleton_tabs.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_url_handler.h"
#include "content/public/browser/web_contents.h"
namespace chrome {
namespace {
// Returns true if two URLs are equal after taking |replacements| into account.
bool CompareURLsWithReplacements(
const GURL& url,
const GURL& other,
const url_canon::Replacements<char>& replacements) {
if (url == other)
return true;
GURL url_replaced = url.ReplaceComponents(replacements);
GURL other_replaced = other.ReplaceComponents(replacements);
return url_replaced == other_replaced;
}
} // namespace
void ShowSingletonTab(Browser* browser, const GURL& url) {
NavigateParams params(GetSingletonTabNavigateParams(browser, url));
Navigate(¶ms);
}
void ShowSingletonTabRespectRef(Browser* browser, const GURL& url) {
NavigateParams params(GetSingletonTabNavigateParams(browser, url));
params.ref_behavior = NavigateParams::RESPECT_REF;
Navigate(¶ms);
}
void ShowSingletonTabOverwritingNTP(Browser* browser,
const NavigateParams& params) {
NavigateParams local_params(params);
content::WebContents* contents =
browser->tab_strip_model()->GetActiveWebContents();
if (contents) {
const GURL& contents_url = contents->GetURL();
if ((contents_url == GURL(kChromeUINewTabURL) ||
contents_url == GURL(kAboutBlankURL)) &&
GetIndexOfSingletonTab(&local_params) < 0) {
local_params.disposition = CURRENT_TAB;
}
}
Navigate(&local_params);
}
NavigateParams GetSingletonTabNavigateParams(Browser* browser,
const GURL& url) {
NavigateParams params(browser, url, content::PAGE_TRANSITION_AUTO_BOOKMARK);
params.disposition = SINGLETON_TAB;
params.window_action = NavigateParams::SHOW_WINDOW;
params.user_gesture = true;
return params;
}
// Returns the index of an existing singleton tab in |params->browser| matching
// the URL specified in |params|.
int GetIndexOfSingletonTab(NavigateParams* params) {
if (params->disposition != SINGLETON_TAB)
return -1;
// In case the URL was rewritten by the BrowserURLHandler we need to ensure
// that we do not open another URL that will get redirected to the rewritten
// URL.
GURL rewritten_url(params->url);
bool reverse_on_redirect = false;
content::BrowserURLHandler::GetInstance()->RewriteURLIfNecessary(
&rewritten_url,
params->browser->profile(),
&reverse_on_redirect);
// If there are several matches: prefer the active tab by starting there.
int start_index =
std::max(0, params->browser->tab_strip_model()->active_index());
int tab_count = params->browser->tab_strip_model()->count();
for (int i = 0; i < tab_count; ++i) {
int tab_index = (start_index + i) % tab_count;
content::WebContents* tab =
params->browser->tab_strip_model()->GetWebContentsAt(tab_index);
url_canon::Replacements<char> replacements;
if (params->ref_behavior == NavigateParams::IGNORE_REF)
replacements.ClearRef();
if (params->path_behavior == NavigateParams::IGNORE_AND_NAVIGATE ||
params->path_behavior == NavigateParams::IGNORE_AND_STAY_PUT) {
replacements.ClearPath();
replacements.ClearQuery();
}
GURL tab_url = tab->GetURL();
GURL rewritten_tab_url = tab_url;
content::BrowserURLHandler::GetInstance()->RewriteURLIfNecessary(
&rewritten_tab_url,
params->browser->profile(),
&reverse_on_redirect);
if (CompareURLsWithReplacements(tab_url, params->url, replacements) ||
CompareURLsWithReplacements(rewritten_tab_url,
rewritten_url,
replacements)) {
params->target_contents = tab;
return tab_index;
}
}
return -1;
}
} // namespace chrome
| zcbenz/cefode-chromium | chrome/browser/ui/singleton_tabs.cc | C++ | bsd-3-clause | 4,284 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.