answer stringlengths 15 1.25M |
|---|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NHibernate;
using DataAccessLayer.Entiteti;
namespace SBPDemo
{
public partial class <API key> : Form
{
// Designer currently being displayed
private int m_designerKey = -1;
public <API key>(int designerKey)
{
InitializeComponent();
// Received session holds the shown designer
m_designerKey = designerKey;
// Clear the listbox
listBoxShows.Items.Clear();
}
private void <API key>(object sender, EventArgs e)
{
if (m_designerKey == -1)
{
MessageBox.Show("Error receiving data on designer");
this.Close();
}
// Load designer data into UI controls
<API key>();
}
private void <API key>()
{
ISession session = DataAccessLayer.DataLayer.GetSession();
MODNI_KREATOR designer = session.Get<MODNI_KREATOR>(m_designerKey);
// Personal Number
labelPn.Text = designer.MATICNI_BROJ.ToString();
// First Name
labelFirstName.Text = designer.IME;
// Last Name
labelLastName.Text = designer.PREZIME;
Text = labelFirstName.Text + " " + labelLastName.Text;
// Birth Date
if (designer.DATUM_RODJENJA == DateTime.MinValue)
labelBirthDate.Text = "Unknown";
else
labelBirthDate.Text = designer.DATUM_RODJENJA.ToShortDateString();
// Gender
char gender = designer.POL;
if (gender == 'F') labelGender.Text = "Female";
if (gender == 'M') labelGender.Text = "Male";
// Country
labelCountry.Text = designer.ZEMLJA_POREKLA;
// Fashion House
labelFashionHouse.Text = designer.MODNA_KUCA;
// Fashion Shows
IList<MODNA_REVIJA> shows = designer.modneRevije;
if (shows.Count > 0)
{
listBoxShows.DataSource = shows;
listBoxShows.DisplayMember = "NAZIV";
}
session.Close();
}
private void buttonClose_Click(object sender, EventArgs e)
{
Close();
}
private void <API key>(object sender, MouseEventArgs e)
{
int index = listBoxShows.IndexFromPoint(e.Location);
if (index != System.Windows.Forms.ListBox.NoMatches)
{
MODNA_REVIJA mr = listBoxShows.Items[index] as MODNA_REVIJA;
ShowsDetailsForm mrDetailsForm = new ShowsDetailsForm(mr.REDNI_BROJ);
mrDetailsForm.Show();
}
}
}
} |
<?php
namespace RecordManager\Base\Enrichment;
class <API key> extends OnkiLightEnrichment
{
/**
* Enrich the record and return any additions in solrArray
*
* @param string $sourceId Source ID
* @param object $record Metadata Record
* @param array $solrArray Metadata to be sent to Solr
*
* @return void
*/
public function enrich($sourceId, $record, &$solrArray)
{
if (!($record instanceof \RecordManager\Base\Record\Ead)) {
return;
}
foreach ($record->getTopicIDs() as $id) {
$this->enrichField(
$sourceId,
$record,
$solrArray,
$id,
'topic_add_txt_mv',
'topic_alt_txt_mv',
'topic'
);
}
}
} |
/* Enable to make ^Z dump the inode table for debug */
#undef CONFIG_IDUMP
/* Enable to make ^A drop back into the monitor */
#undef CONFIG_MONITOR
/* Profil syscall support (not yet complete) */
#undef CONFIG_PROFIL
/* Multiple processes in memory at once */
#define CONFIG_MULTI
/* Single tasking */
#undef CONFIG_SINGLETASK
/* Fixed banking */
#define CONFIG_BANK_FIXED
/* 7 64K banks, 1 is kernel */
#define MAX_MAPS 6
#define MAP_SIZE 0xF000U
/* Banks as reported to user space */
#define CONFIG_BANKS 1
#define TICKSPERSEC 10 /* Ticks per second */
#define PROGBASE 0x0000 /* also data base */
#define PROGLOAD 0x0100 /* also data base */
#define PROGTOP 0xED00 /* Top of program, base of U_DATA copy */
#define PROC_SIZE 60 /* Memory needed per process */
#define BOOT_TTY (512 + 1)/* Set this to default device for stdio, stderr */
/* In this case, the default is the first TTY device */
/* We need a tidier way to do this from the loader */
#define CMDLINE NULL /* Location of root dev name */
/* Device parameters */
#define NUM_DEV_TTY 3
#define TTYDEV BOOT_TTY /* Device used by kernel for messages, panics */
#define NBUFS 8 /* Number of block buffers */
#define NMOUNTS 4 /* Number of mounts at a time */
#define platform_discard()
#define platform_copyright() |
/* -*- Mode: c++; -*- */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "mime.h"
#include "convert.h"
#include "io.h"
#include <string>
#include <vector>
#include <map>
#include <exception>
#include <iostream>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <errno.h>
using namespace ::std;
const Binc::MimePart *Binc::MimePart::getPart(const string &findpart,
string genpart, FetchType fetchType) const
{
if (findpart == genpart)
return this;
if (isMultipart()) {
if (members.size() != 0) {
vector<MimePart>::const_iterator i = members.begin();
int part = 1;
while (i != members.end()) {
BincStream ss;
ss << genpart;
if (genpart != "")
ss << ".";
ss << part;
const MimePart *m;
if ((m = (*i).getPart(findpart, ss.str())) != 0) {
if (fetchType == FetchHeader && m->isMessageRFC822())
m = &m->members[0];
return m;
}
++i;
++part;
}
}
} else if (isMessageRFC822()) {
if (members.size() == 1) {
const MimePart *m = members[0].getPart(findpart, genpart);
return m;
} else {
return 0;
}
} else {
// Singlepart
if (genpart != "")
genpart += ".";
genpart += "1";
if (findpart == genpart)
return this;
}
return 0;
} |
/**
@file storage/perfschema/<API key>.cc
Table SOCKET_INSTANCES (implementation).
*/
#include "my_global.h"
#include "my_pthread.h"
#include "pfs_instr.h"
#include "pfs_column_types.h"
#include "pfs_column_values.h"
#include "<API key>.h"
#include "pfs_global.h"
THR_LOCK <API key>::m_table_lock;
<API key>
<API key>::m_share=
{
{ C_STRING_WITH_LEN("socket_instances") },
&pfs_readonly_acl,
&<API key>::create,
NULL, /* write_row */
NULL, /* delete_all_rows */
NULL, /* get_row_count */
1000, /* records */
sizeof(PFS_simple_index),
&m_table_lock,
{ C_STRING_WITH_LEN("CREATE TABLE socket_instances("
"EVENT_NAME VARCHAR(128) not null,"
"<API key> BIGINT unsigned not null,"
"THREAD_ID BIGINT unsigned,"
"SOCKET_ID INTEGER not null,"
"IP VARCHAR(64) not null,"
"PORT INTEGER not null,"
"STATE ENUM('IDLE','ACTIVE') not null)") }
};
PFS_engine_table* <API key>::create(void)
{
return new <API key>();
}
<API key>::<API key>()
: PFS_engine_table(&m_share, &m_pos),
m_row_exists(false), m_pos(0), m_next_pos(0)
{}
void <API key>::reset_position(void)
{
m_pos.m_index= 0;
m_next_pos.m_index= 0;
}
int <API key>::rnd_next(void)
{
PFS_socket *pfs;
for (m_pos.set_at(&m_next_pos);
m_pos.m_index < socket_max;
m_pos.next())
{
pfs= &socket_array[m_pos.m_index];
if (pfs->m_lock.is_populated())
{
make_row(pfs);
m_next_pos.set_after(&m_pos);
return 0;
}
}
return HA_ERR_END_OF_FILE;
}
int <API key>::rnd_pos(const void *pos)
{
PFS_socket *pfs;
set_position(pos);
DBUG_ASSERT(m_pos.m_index < socket_max);
pfs= &socket_array[m_pos.m_index];
if (! pfs->m_lock.is_populated())
return <API key>;
make_row(pfs);
return 0;
}
void <API key>::make_row(PFS_socket *pfs)
{
pfs_lock lock;
PFS_socket_class *safe_class;
m_row_exists= false;
/* Protect this reader against a socket delete */
pfs->m_lock.<API key>(&lock);
safe_class= <API key>(pfs->m_class);
if (unlikely(safe_class == NULL))
return;
/** Extract ip address and port from raw address */
m_row.m_ip_length= <API key>(m_row.m_ip, sizeof(m_row.m_ip),
&m_row.m_port,
&pfs->m_sock_addr, pfs->m_addr_len);
m_row.m_event_name= safe_class->m_name;
m_row.m_event_name_length= safe_class->m_name_length;
m_row.m_identity= pfs->m_identity;
m_row.m_fd= pfs->m_fd;
m_row.m_state= (pfs->m_idle ? <API key>
: <API key>);
PFS_thread *safe_thread= sanitize_thread(pfs->m_thread_owner);
if (safe_thread != NULL)
{
m_row.m_thread_id= safe_thread-><API key>;
m_row.m_thread_id_set= true;
}
else
m_row.m_thread_id_set= false;
if (pfs->m_lock.end_optimistic_lock(&lock))
m_row_exists= true;
}
int <API key>::read_row_values(TABLE *table,
unsigned char *buf,
Field **fields,
bool read_all)
{
Field *f;
if (unlikely(!m_row_exists))
return <API key>;
/* Set the null bits */
DBUG_ASSERT(table->s->null_bytes == 1);
buf[0]= 0;
for (; (f= *fields) ; fields++)
{
if (read_all || bitmap_is_set(table->read_set, f->field_index))
{
switch(f->field_index)
{
case 0: /* EVENT_NAME */
<API key>(f, m_row.m_event_name, m_row.m_event_name_length);
break;
case 1: /* <API key> */
set_field_ulonglong(f, (intptr)m_row.m_identity);
break;
case 2: /* THREAD_ID */
if (m_row.m_thread_id_set)
set_field_ulonglong(f, m_row.m_thread_id);
else
f->set_null();
break;
case 3: /* SOCKET_ID */
set_field_ulong(f, m_row.m_fd);
break;
case 4:
<API key>(f, m_row.m_ip, m_row.m_ip_length);
break;
case 5: /* PORT */
set_field_ulong(f, m_row.m_port);
break;
case 6: /* STATE */
set_field_enum(f, m_row.m_state);
break;
default:
DBUG_ASSERT(false);
}
}
}
return 0;
} |
#include <iomanip>
using std::ostream;
using std::istream;
using std::setw;
#include "PhoneNumber.h"
//overloads stream input operator do this
//cout<<somePhoneNumber;
ostream &operator<<(ostream &output, const PhoneNumber &number){
output<<"("<<number.areaCode<<")"<<number.exchange<<"-"<<number.line;
return output;
}
//overload extraction operator
//cin>>somePhoneNumber;
istream &operator>>(istream &input, PhoneNumber &number){
input.ignore();//skip space
input>>setw(3)>>number.areaCode;
input.ignore(2);// skip )
input>>setw(3)>>number.exchange;
input.ignore();//skip -
input>>setw(4)>>number.line;
return input;
} |
package com.kartoflane.superluminal2.ui;
import java.util.HashMap;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.MenuAdapter;
import org.eclipse.swt.events.MenuEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import com.kartoflane.superluminal2.Superluminal;
import com.kartoflane.superluminal2.components.Hotkey;
import com.kartoflane.superluminal2.components.enums.Hotkeys;
import com.kartoflane.superluminal2.components.enums.OS;
import com.kartoflane.superluminal2.components.interfaces.Alias;
import com.kartoflane.superluminal2.components.interfaces.Indexable;
import com.kartoflane.superluminal2.core.Cache;
import com.kartoflane.superluminal2.core.Manager;
import com.kartoflane.superluminal2.events.SLDeleteEvent;
import com.kartoflane.superluminal2.events.SLDisposeEvent;
import com.kartoflane.superluminal2.events.SLEvent;
import com.kartoflane.superluminal2.events.SLListener;
import com.kartoflane.superluminal2.events.SLRestoreEvent;
import com.kartoflane.superluminal2.mvc.controllers.AbstractController;
import com.kartoflane.superluminal2.mvc.controllers.CursorController;
import com.kartoflane.superluminal2.mvc.controllers.DoorController;
import com.kartoflane.superluminal2.mvc.controllers.GibController;
import com.kartoflane.superluminal2.mvc.controllers.MountController;
import com.kartoflane.superluminal2.mvc.controllers.ObjectController;
import com.kartoflane.superluminal2.mvc.controllers.RoomController;
import com.kartoflane.superluminal2.tools.ManipulationTool;
import com.kartoflane.superluminal2.tools.Tool.Tools;
import com.kartoflane.superluminal2.undo.UndoableOrderEdit;
import com.kartoflane.superluminal2.utils.UIUtils;
import com.kartoflane.superluminal2.utils.Utils;
public class OverviewWindow implements SLListener
{
private static final OverviewWindow instance = new OverviewWindow();
private ShipContainer ship;
private ObjectController <API key> = null;
private HashMap<AbstractController, TreeItem> controllerMap = new HashMap<AbstractController, TreeItem>();
private Color disabledColor = null;
private TreeItem dragItem = null;
private ObjectController dragData = null;
private Shell shell;
private TreeItem trtmRooms;
private TreeItem trtmDoors;
private TreeItem trtmMounts;
private TreeItem trtmGibs;
private Tree tree;
private Menu overviewMenu;
private ToolBar toolBar;
private ToolItem tltmAlias;
private ToolItem tltmRemove;
private ToolItem tltmToggleVis;
private TreeColumn trclmnName;
private TreeColumn trclmnAlias;
private DragSource dragSource;
private DropTarget dropTarget;
private OverviewWindow()
{
}
/**
* @wbp.parser.entryPoint
*/
public void init( Shell parent )
{
Image helpImage = Cache.checkOutImage( this, "cpath:/assets/help.png" );
shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.MIN | SWT.RESIZE );
shell.setText( String.format( "%s - Ship Overview", Superluminal.APP_NAME ) );
shell.setLayout( new GridLayout( 2, false ) );
toolBar = new ToolBar( shell, SWT.FLAT | SWT.RIGHT );
toolBar.setLayoutData( new GridData( SWT.FILL, SWT.TOP, true, false, 1, 1 ) );
Label lblHelp = new Label( shell, SWT.NONE );
lblHelp.setLayoutData( new GridData( SWT.RIGHT, SWT.CENTER, false, false, 1, 1 ) );
lblHelp.setImage( helpImage );
String msg = "Alias is a short name to help you distinguish between objects.";
UIUtils.addTooltip( lblHelp, Utils.wrapOSNot( msg, Superluminal.WRAP_WIDTH, Superluminal.WRAP_TOLERANCE, OS.MACOSX() ) );
tltmAlias = new ToolItem( toolBar, SWT.NONE );
tltmAlias.setToolTipText( "Set Alias" );
tltmAlias.setImage( Cache.checkOutImage( this, "cpath:/assets/alias.png" ) );
tltmRemove = new ToolItem( toolBar, SWT.NONE );
tltmRemove.setToolTipText( "Remove Alias" );
tltmRemove.setImage( Cache.checkOutImage( this, "cpath:/assets/noalias.png" ) );
tltmToggleVis = new ToolItem( toolBar, SWT.NONE );
tltmToggleVis.setToolTipText( "Show/Hide" );
tltmToggleVis.setImage( Cache.checkOutImage( this, "cpath:/assets/cloak.png" ) );
tree = new Tree( shell, SWT.BORDER | SWT.FULL_SELECTION );
tree.setLinesVisible( true );
tree.setHeaderVisible( true );
tree.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true, 2, 1 ) );
RGB rgb = tree.getBackground().getRGB();
rgb.red = (int)( 0.85 * rgb.red );
rgb.green = (int)( 0.85 * rgb.green );
rgb.blue = (int)( 0.85 * rgb.blue );
disabledColor = Cache.checkOutColor( this, rgb );
trclmnName = new TreeColumn( tree, SWT.NONE );
trclmnName.setWidth( 175 );
trclmnName.setText( "Name" );
trclmnAlias = new TreeColumn( tree, SWT.RIGHT );
trclmnAlias.setWidth( 100 );
trclmnAlias.setText( "Alias" );
trtmRooms = new TreeItem( tree, SWT.NONE );
trtmRooms.setText( "Rooms" );
trtmDoors = new TreeItem( tree, SWT.NONE );
trtmDoors.setText( "Doors" );
trtmMounts = new TreeItem( tree, SWT.NONE );
trtmMounts.setText( "Mounts" );
trtmGibs = new TreeItem( tree, SWT.NONE );
trtmGibs.setText( "Gibs" );
// Need to specify a transfer type, even if it's not used, because
// otherwise it's not even possible to initiate drag and drop...
Transfer[] sourceTypes = new Transfer[] { TextTransfer.getInstance() };
dragSource = new DragSource( tree, DND.DROP_MOVE );
dragSource.setTransfer( sourceTypes );
Transfer[] dropTypes = new Transfer[] { TextTransfer.getInstance(), FileTransfer.getInstance() };
dropTarget = new DropTarget( tree, DND.DROP_MOVE | DND.DROP_DEFAULT );
dropTarget.setTransfer( dropTypes );
// Overview popup menu
overviewMenu = new Menu( tree );
tree.setMenu( overviewMenu );
final MenuItem mntmSetAlias = new MenuItem( overviewMenu, SWT.NONE );
mntmSetAlias.setText( "Set Alias" );
final MenuItem mntmRemoveAlias = new MenuItem( overviewMenu, SWT.NONE );
mntmRemoveAlias.setText( "Remove Alias" );
dragSource.addDragListener(
new DragSourceListener() {
@Override
public void dragStart( DragSourceEvent e )
{
TreeItem[] selection = tree.getSelection();
if ( selection.length > 0 && selection[0].getData() instanceof Indexable ) {
e.doit = true;
dragItem = selection[0];
dragData = (ObjectController)dragItem.getData();
}
else {
e.doit = false;
}
}
@Override
public void dragSetData( DragSourceEvent e )
{
e.data = "whatever"; // This needs not be an empty string, otherwise the drag mechanism freaks out...
}
@Override
public void dragFinished( DragSourceEvent e )
{
dragItem = null;
dragData = null;
}
}
);
dropTarget.addDropListener(
new DropTargetAdapter() {
@Override
public void dragOver( DropTargetEvent e )
{
e.detail = DND.DROP_MOVE;
e.feedback = DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL;
if ( dragItem != null ) {
Point p = tree.toControl( e.x, e.y );
TreeItem item = tree.getItem( p );
if ( item == null ) {
e.detail = DND.DROP_NONE;
e.feedback = DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL;
}
else {
TreeItem parent = item.getParentItem();
if ( canDrop( parent, dragData ) ) {
e.detail = DND.DROP_MOVE;
Rectangle bounds = item.getBounds();
if ( p.y < bounds.y + bounds.height / 2 ) {
e.feedback = DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL | DND.<API key>;
}
else {
e.feedback = DND.FEEDBACK_EXPAND | DND.FEEDBACK_SCROLL | DND.<API key>;
}
}
else {
e.detail = DND.DROP_NONE;
e.feedback |= DND.FEEDBACK_NONE;
}
}
}
}
@Override
public void drop( DropTargetEvent e )
{
if ( dragData != null ) {
if ( ( e.detail & DND.DROP_MOVE ) == DND.DROP_MOVE ) {
Point p = tree.toControl( e.x, e.y );
TreeItem item = tree.getItem( p );
if ( item != null ) {
Rectangle bounds = item.getBounds();
TreeItem parent = item.getParentItem();
if ( parent != null ) {
ShipContainer container = Manager.getCurrentShip();
TreeItem[] items = parent.getItems();
int from = indexOf( items, dragItem );
int to = indexOf( items, item );
if ( dragItem != item ) {
if ( p.y > bounds.y + bounds.height / 2 ) {
to += from > to ? 1 : 0;
}
else {
to += from > to ? 0 : -1;
}
}
Indexable[] array = new Indexable[items.length];
for ( int i = 0; i < items.length; i++ ) {
array[i] = (Indexable)items[i].getData();
}
UndoableOrderEdit edit = new UndoableOrderEdit( array.clone() );
edit.setOld( from );
edit.setCurrent( to );
container.postEdit( edit );
Utils.reorder( array, from, to );
container.sort();
update();
}
}
}
}
}
}
);
shell.addListener(
SWT.Close, new Listener() {
@Override
public void handleEvent( Event event )
{
dispose();
event.doit = false;
}
}
);
ControlAdapter resizer = new ControlAdapter() {
@Override
public void controlResized( ControlEvent e )
{
final int BORDER_OFFSET = tree.getBorderWidth();
if ( trclmnName.getWidth() > tree.getClientArea().width - BORDER_OFFSET )
trclmnName.setWidth( tree.getClientArea().width - BORDER_OFFSET );
trclmnAlias.setWidth( tree.getClientArea().width - trclmnName.getWidth() - BORDER_OFFSET );
}
};
tree.addControlListener( resizer );
trclmnName.addControlListener( resizer );
tree.addListener(
SWT.MouseMove, new Listener() {
@Override
public void handleEvent( Event e )
{
if ( Manager.getSelectedToolId() == Tools.POINTER ) {
TreeItem item = tree.getItem( new Point( e.x, e.y ) );
ObjectController controller = null;
if ( item != null && item.getData() != null )
controller = (ObjectController)item.getData();
highlightController( controller );
}
}
}
);
tree.addListener(
SWT.MouseExit, new Listener() {
@Override
public void handleEvent( Event e )
{
highlightController( null );
}
}
);
tree.<API key>(
new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e )
{
ObjectController controller = null;
if ( tree.getSelectionCount() != 0 ) {
TreeItem item = tree.getSelection()[0];
controller = (ObjectController)item.getData();
}
if ( Manager.getSelectedToolId() == Tools.POINTER ) {
ManipulationTool tool = (ManipulationTool)Manager.getSelectedTool();
if ( tool.isStateManipulate() && ( controller == null || controller.isVisible() ) ) {
Manager.setSelected( controller );
}
else {
AbstractController selected = Manager.getSelected();
if ( tool.isStateDoorLinkLeft() || tool.<API key>() )
tool.linkDoor( selected, controller );
else if ( tool.isStateMountGibLink() )
tool.linkGib( selected, controller );
if ( selected != null && selected != controller )
CursorController.getInstance().setVisible( false );
}
}
tltmAlias.setEnabled( controller != null );
tltmRemove.setEnabled( controller != null && controller.getAlias() != null && !controller.getAlias().equals( "" ) );
tltmToggleVis.setEnabled( controller != null );
}
}
);
tree.addMouseListener(
new MouseAdapter() {
@Override
public void mouseDoubleClick( MouseEvent e )
{
if ( e.button == 1 && tree.getSelectionCount() != 0 ) {
TreeItem selectedItem = tree.getSelection()[0];
if ( selectedItem.getItemCount() != 0 && selectedItem.getBounds().contains( e.x, e.y ) )
selectedItem.setExpanded( !selectedItem.getExpanded() );
}
}
}
);
tree.addTraverseListener(
new TraverseListener() {
@Override
public void keyTraversed( TraverseEvent e )
{
if ( e.detail == SWT.TRAVERSE_RETURN && tree.getSelectionCount() != 0 ) {
TreeItem sel = tree.getSelection()[0];
if ( sel.getItemCount() != 0 )
sel.setExpanded( !sel.getExpanded() );
}
}
}
);
overviewMenu.addMenuListener(
new MenuAdapter() {
@Override
public void menuShown( MenuEvent e )
{
if ( tree.getSelectionCount() == 0 || tree.getSelection()[0].getData() == null ) {
overviewMenu.setVisible( false );
}
}
}
);
SelectionAdapter setAliasListener = new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e )
{
Alias alias = (Alias)tree.getSelection()[0].getData();
AliasDialog dialog = new AliasDialog( shell );
dialog.setAlias( alias );
dialog.open();
}
};
mntmSetAlias.<API key>( setAliasListener );
tltmAlias.<API key>( setAliasListener );
SelectionAdapter removeAliasListener = new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e )
{
Alias alias = (Alias)tree.getSelection()[0].getData();
alias.setAlias( null );
update( tree.getSelection()[0] );
}
};
mntmRemoveAlias.<API key>( removeAliasListener );
tltmRemove.<API key>( removeAliasListener );
tltmToggleVis.<API key>(
new SelectionAdapter() {
@Override
public void widgetSelected( SelectionEvent e )
{
if ( tree.getSelectionCount() != 0 ) {
AbstractController ac = (AbstractController)tree.getSelection()[0].getData();
if ( ac != null ) {
ac.setVisible( !ac.isVisible() );
tree.getSelection()[0].setBackground( ac.isVisible() ? null : disabledColor );
}
}
}
}
);
registerHotkeys();
shell.setSize( 300, 600 );
Point size = shell.getSize();
Point pSize = parent.getSize();
Point pLoc = parent.getLocation();
shell.setLocation( pLoc.x + pSize.x - size.x, pLoc.y + 50 );
}
public void open()
{
shell.open();
update();
shell.setMinimized( false );
}
public void update()
{
if ( isDisposed() )
return;
ship = Manager.getCurrentShip();
AbstractController prevSelection = Manager.getSelected();
if ( !controllerMap.containsKey( prevSelection ) )
prevSelection = null;
if ( Manager.getSelectedToolId() != Tools.POINTER && tree.getSelectionCount() == 1 && tree.getSelection()[0] != null )
prevSelection = (AbstractController)tree.getSelection()[0].getData();
for ( TreeItem it : trtmRooms.getItems() )
it.dispose();
for ( TreeItem it : trtmDoors.getItems() )
it.dispose();
for ( TreeItem it : trtmMounts.getItems() )
it.dispose();
for ( TreeItem it : trtmGibs.getItems() )
it.dispose();
controllerMap.clear();
if ( ship != null ) {
for ( RoomController r : ship.getRoomControllers() )
createItem( r, -1 );
trtmRooms.setText( String.format( "Rooms (%s)", trtmRooms.getItemCount() ) );
for ( DoorController d : ship.getDoorControllers() )
createItem( d, -1 );
trtmDoors.setText( String.format( "Doors (%s)", trtmDoors.getItemCount() ) );
for ( MountController m : ship.getMountControllers() )
createItem( m, -1 );
trtmMounts.setText( String.format( "Mounts (%s)", trtmMounts.getItemCount() ) );
for ( int i = 1; i <= ship.getGibControllers().length; i++ ) {
GibController g = ship.<API key>( i );
if ( g != null )
createItem( g, -1 );
}
trtmGibs.setText( String.format( "Gibs (%s)", trtmGibs.getItemCount() ) );
}
TreeItem item = controllerMap.get( prevSelection );
if ( item == null ) {
tree.select( trtmRooms );
}
else {
tree.select( item );
Rectangle b = item.getBounds();
if ( !tree.getClientArea().contains( b.x, b.y ) )
tree.setTopItem( item );
}
String alias = null;
if ( controllerMap.containsKey( prevSelection ) )
alias = ( (Alias)prevSelection ).getAlias();
tltmAlias.setEnabled( prevSelection != null );
tltmRemove.setEnabled( alias != null && !alias.equals( "" ) );
tltmToggleVis.setEnabled( prevSelection != null );
}
public void update( ObjectController controller )
{
if ( controller == null )
throw new <API key>( "Argument must not be null." );
TreeItem item = controllerMap.get( controller );
if ( item == null && !controller.isDeleted() ) {
item = createItem( controller, -1 );
}
else if ( item != null ) {
update( item );
}
}
private void update( TreeItem item )
{
if ( item.getData() instanceof ObjectController == false )
return;
ObjectController oc = (ObjectController)item.getData();
if ( oc.isDeleted() ) {
item.dispose();
controllerMap.remove( oc );
}
else {
if ( oc instanceof RoomController ) {
RoomController controller = (RoomController)oc;
item.setText( 0, controller.getGameObject().toStringNoAlias() );
}
else if ( oc instanceof DoorController ) {
DoorController controller = (DoorController)oc;
item.setText( 0, "Door " + ( controller.isHorizontal() ? "H" : "V" ) );
}
else if ( oc instanceof MountController ) {
MountController controller = (MountController)oc;
item.setText( 0, "Mount " + controller.getId() );
}
else if ( oc instanceof GibController ) {
GibController controller = (GibController)oc;
item.setText( 0, "Gib " + controller.getId() );
}
String alias = oc.getAlias();
item.setText( 1, alias == null ? "" : alias );
item.setBackground( oc.isVisible() ? null : disabledColor );
if ( oc.isSelected() ) {
tree.select( item );
Rectangle b = item.getBounds();
if ( !tree.getClientArea().contains( b.x, b.y ) )
tree.setTopItem( item );
}
}
tltmAlias.setEnabled( oc != null );
tltmRemove.setEnabled( oc != null && oc.getAlias() != null && !oc.getAlias().equals( "" ) );
tltmToggleVis.setEnabled( oc != null );
}
/**
* Updates the overview window if it exists, or does nothing if it does not.
*/
public static void staticUpdate()
{
if ( instance != null && !instance.isDisposed() ) {
instance.update();
}
}
/**
* Updates the overview window if it exists, or does nothing if it does not.
*/
public static void staticUpdate( ObjectController controller )
{
if ( instance != null && !instance.isDisposed() ) {
instance.update( controller );
}
}
public static OverviewWindow getInstance()
{
return instance;
}
public void setEnabled( boolean b )
{
tree.setEnabled( b );
if ( <API key> != null && <API key>.isHighlighted() )
<API key>.setHighlighted( false );
}
public boolean isEnabled()
{
return !isDisposed() && tree.isEnabled();
}
public boolean isActive()
{
return !isDisposed() && tree.isFocusControl();
}
public boolean isDisposed()
{
return shell == null || shell.isDisposed();
}
private boolean canDrop( TreeItem newParent, ObjectController data )
{
return ( newParent == trtmRooms && data instanceof RoomController ) ||
( newParent == trtmMounts && data instanceof MountController ) ||
( newParent == trtmGibs && data instanceof GibController );
}
private int indexOf( TreeItem[] items, TreeItem item )
{
if ( items == null )
throw new <API key>( "Array must not be null." );
if ( item == null )
throw new <API key>( "Item must not be null." );
int result = -1;
for ( int i = 0; i < items.length && result == -1; i++ ) {
if ( items[i] == item )
result = i;
}
return result;
}
private TreeItem createItem( AbstractController controller, int index )
{
TreeItem parent = identifyParent( controller );
if ( parent == null )
return null;
TreeItem item = null;
if ( index < 0 || parent.getItemCount() >= index ) {
item = new TreeItem( parent, SWT.NONE );
}
else {
item = new TreeItem( parent, SWT.NONE, index );
}
item.setData( controller );
update( item );
controllerMap.put( controller, item );
return item;
}
private TreeItem identifyParent( AbstractController controller )
{
if ( controller instanceof RoomController )
return trtmRooms;
else if ( controller instanceof DoorController )
return trtmDoors;
else if ( controller instanceof MountController )
return trtmMounts;
else if ( controller instanceof GibController )
return trtmGibs;
else
return null;
}
public void dispose()
{
Cache.checkInColor( this, disabledColor.getRGB() );
disabledColor = null;
Cache.checkInImage( this, "cpath:/assets/help.png" );
Cache.checkInImage( this, "cpath:/assets/alias.png" );
Cache.checkInImage( this, "cpath:/assets/noalias.png" );
Cache.checkInImage( this, "cpath:/assets/cloak.png" );
Manager.unhookHotkeys( shell );
shell.dispose();
controllerMap.clear();
}
@Override
public void handleEvent( SLEvent e )
{
if ( e.data instanceof ObjectController ) {
ObjectController data = (ObjectController)e.data;
if ( e instanceof SLDeleteEvent ) {
update( data );
}
else if ( e instanceof SLRestoreEvent ) {
update();
}
else if ( e instanceof SLDisposeEvent ) {
data.removeListener( this );
}
}
}
private void highlightController( ObjectController controller )
{
if ( <API key> != null && <API key> != controller && <API key>.isHighlighted() )
<API key>.setHighlighted( false );
if ( controller != null && !controller.isHighlighted() )
controller.setHighlighted( true );
<API key> = controller;
}
private void registerHotkeys()
{
Hotkey h = Manager.getHotkey( Hotkeys.UNDO );
Manager.hookHotkey( shell, h );
h = Manager.getHotkey( Hotkeys.REDO );
Manager.hookHotkey( shell, h );
}
} |
/*
* @test
* @bug 8076318
* @summary split verifier needs to add <API key>
* @library /testlibrary
*/
import jdk.test.lib.*;
// Test that the verifier outputs the classes it loads if -XX:+<API key> is specified"
public class TraceClassRes {
public static void main(String[] args) throws Exception {
ProcessBuilder pb = ProcessTools.<API key>(
"-XX:+<API key>", "-verify", "-Xshare:off", "-version");
OutputAnalyzer output = new OutputAnalyzer(pb.start());
output.shouldContain("[classresolve] java.lang.ClassLoader java.lang.Throwable ClassLoader.java (verification)");
output.shouldHaveExitValue(0);
}
} |
cat <<\TEMPLATEQUOTE
XDvi.grey: true
XDvi.reverseVideo: true
XDvi.expert: true
XTerm*background: black
XTerm*foreground: white
XTerm.VT100.geometry: 80x25
XTerm.VT100.scrollBar: False
XTerm.VT100.font: -*-fixed-medium-r-*-*-12-*-*-*-*-*-*-*
XTerm.VT100.colorBDMode: false
XTerm*VT100*translations: #override \
Shift <Btn4Down>: scroll-back(1,line) \n\
Ctrl <Btn4Down>: scroll-back(1,halfpage) \n\
Alt <Btn4Down>: scroll-back(10,page) \n\
<Btn4Down>: scroll-back(5,line) \n\
Shift <Btn5Down>: scroll-forw(1,line) \n\
Ctrl <Btn5Down>: scroll-forw(1,halfpage) \n\
Alt <Btn5Down>: scroll-forw(10,page) \n\
<Btn5Down>: scroll-forw(5,line)
!# In the scrollbar we map buttons 5 & 4 to 1 and 2 otherwise, core dump
!# This will move proportionnaly to cursor position but we dont know how to
!# program the same exact behavior as in the text widget.
XTerm.vt100.Scrollbar.translations: #override\n\
<Btn5Down>: StartScroll(Forward)\n\
<Btn4Down>: StartScroll(Backward)\n\
!Netscape*globalTranslations: #override \
! Shift <Btn4Down>: LineUp() \n\
! Ctrl <Btn4Down>: PageUp() \n\
! Alt <Btn4Down>: PageUp(3) \n\
! <Btn4Down>: LineUp(5) \n\
! Shift <Btn5Down>: LineDown() \n\
! Ctrl <Btn5Down>: PageDown() \n\
! Alt <Btn5Down>: PageDown(3) \n\
! <Btn5Down>: LineDown(5)
!## NETSCAPE
Netscape*drawingArea.translations: #replace \
<Btn1Down>: ArmLink() \n\
<Btn2Down>: ArmLink() \n\
~Shift<Btn1Up>: ActivateLink() \n\
~Shift<Btn2Up>: ActivateLink(new-window) \
DisarmLink() \n\
Shift<Btn1Up>: ActivateLink(save-only) \
DisarmLink() \n\
Shift<Btn2Up>: ActivateLink(save-only) \
DisarmLink() \n\
<Btn1Motion>: DisarmLinkIfMoved() \n\
<Btn2Motion>: DisarmLinkIfMoved() \n\
<Btn3Motion>: DisarmLinkIfMoved() \n\
<Motion>: DescribeLink() \n\
<Btn3Down>: xfeDoPopup() \n\
<Btn3Up>: ActivatePopup() \n\
Ctrl<Btn4Down>: PageUp()\n\
Ctrl<Btn5Down>: PageDown()\n\
Shift<Btn4Down>: LineUp()\n\
Shift<Btn5Down>: LineDown()\n\
None<Btn4Down>: LineUp()LineUp()LineUp()LineUp()LineUp()LineUp()\n\
None<Btn5Down>: LineDown()LineDown()LineDown()LineDown()LineDown()LineDown()\n\
Alt<Btn4Down>: xfeDoCommand(forward)\n\
Alt<Btn5Down>: xfeDoCommand(back)\n
Netscape*<API key>: #override\n\
Shift<Btn4Down>: LineUp()\n\
Shift<Btn5Down>: LineDown()\n\
None<Btn4Down>:LineUp()LineUp()LineUp()LineUp()LineUp()LineUp()\n\
None<Btn5Down>:LineDown()LineDown()LineDown()LineDown()LineDown()LineDown()\n\
Alt<Btn4Down>: xfeDoCommand(forward)\n\
Alt<Btn5Down>: xfeDoCommand(back)\n
Netscape*composeFolder.shadowThickness: 1
Netscape*newComposeFolder*attachItemImage.highlightThickness: 1
Netscape*XmPushButton*shadowThickness: 1
Netscape*XmPushButtonGadget*shadowThickness: 1
Netscape*XmCascadeButton.shadowThickness: 1
Netscape*<API key>.shadowThickness: 1
Netscape*drawingArea*XmList.highlightThickness: 1
Netscape*alignmentRowColumn*<API key>.shadowThickness: 1
Netscape*XmDialogShell*highlightThickness: 1
Netscape*toolBar*XmSeparator.shadowThickness: 0
Netscape*Composition*XmTextField.highlightThickness: 1
Netscape*Composition*XmText.highlightThickness: 1
rxvt.background: black
rxvt.foreground: white
rxvt.geometry: 80x25
rxvt.font: -*-fixed-medium-r-*-*-12-*-*-*-*-*-*-*
rxvt.scrollBar: False
rxvt.mapAlert: true
cxterm*VT100.Translations: #override \
<KeyPress> F1: set-HZ-parameter(input-conv=toggle) \n\
<KeyPress> F2: switch-HZ-mode(IC) \n\
<KeyPress> F3: popup-panel(config) \n\
~Shift <KeyPress> F4: switch-HZ-mode(TONEPY) \n\
Shift <KeyPress> F4: switch-HZ-mode(PY) \n\
~Shift <KeyPress> F5: switch-HZ-mode(WuBi) \n\
Shift <KeyPress> F5: switch-HZ-mode(CangJie) \n\
~Meta <KeyPress> Escape: insert() set-HZ-parameter(input-conv=off)
XGsub*background: lemonChiffon4
XGsub*header.background: lemonChiffon2
XGsub*header.foreground: black
XGsub*header.font: 6x13
XGsub*message.background: white
XGsub*message.foreground: black
XGsub*message.font: 6x13
XGsub*geometry: +200+300
XGsub*message*vertDistance: 0
XGsub*puff*defaultDistance: 2
XFontSel*fieldBox*field2.menu*font: -<API key>-*-*-*-c-50-iso8859-1
XFontSel*fieldBox*field1.menu*font: -<API key>-*-*-*-c-50-iso8859-1
*fieldBox*field1.menu.Options.ShowUnselectable: False
Zwgc*reverseStack: false
Zwgc*minTimeToLive: 1000
Zwgc*resetSaver: off
!Zwgc*style.message.personal*geometry: -0+0
!Zwgc*style.login*geometry: +0+0
!Zwgc*style.mail*geometry: -0-0
Zwgc*transient: true
zwgc*style*substyle.default.fontfamily: charter
Zwgc.foreground: SlateGray1
Zwgc.background: Black
XMailbox.geometry: +0+20
xmailbox*volume: 50
xmailbox*update: 1
xmailbox*onceOnly: true
xmailbox*mailNumOfXpmFile: 1
xmailbox*mailAnimOnce: true
xmailbox*mailSndFile: /net/smonger/drop/audio/youvegotmail.au
xmailbox*mailSndComm: /usr/local/bin/rplay %s
xmailbox*mailAnimUpdate: 1000
xmailbox*mailapp: echo 'LINES=25; COLUMNS=80; export LINES; export COLUMNS; rxvt -n pine -e pine' | /bin/sh -s
!xmailbox*nomailXpmFile: /net/smonger/drop/pixmaps/ToasterEmpty.xpm
!xmailbox*mailXpmFile: /net/smonger/drop/pixmaps/ToasterFull.xpm
!xmailbox*nomailXpmFile: /net/smonger/drop/pixmaps/DisketteBoxEmpty.xpm
!xmailbox*mailXpmFile: /net/smonger/drop/pixmaps/DisketteBoxFull.xpm
*fontfamily.charter.small.roman: *-charter-medium-r-*-80-*-p-*
*fontfamily.charter.small.bold: *-charter-bold-r-*-80-*-p-*
*fontfamily.charter.small.italic: *-charter-medium-i-*-80-*-p-*
*fontfamily.charter.small.bolditalic: *-charter-bold-i-*-80-*-p-*
*fontfamily.charter.medium.roman: *-charter-medium-r-*-120-*-p-*
*fontfamily.charter.medium.bold: *-charter-bold-r-*-120-*-p-*
*fontfamily.charter.medium.italic: *-charter-medium-i-*-120-*-p-*
*fontfamily.charter.medium.bolditalic: *-charter-bold-i-*-120-*-p-*
*fontfamily.charter.large.roman: *-charter-medium-r-*-240-*-p-*
*fontfamily.charter.large.bold: *-charter-bold-r-*-240-*-p-*
*fontfamily.charter.large.italic: *-charter-medium-i-*-240-*-p-*
*fontfamily.charter.large.bolditalic: *-charter-bold-i-*-240-*-p-*
*fontfamily.times.small.roman: *<API key>-*-80-*-p-*
*fontfamily.times.small.bold: *adobe-times-bold-r-*-80-*-p-*
*fontfamily.times.small.italic: *<API key>-*-80-*-p-*
*fontfamily.times.small.bolditalic: *adobe-times-bold-i-*-80-*-p-*
*fontfamily.times.medium.roman: *<API key>-*-120-*-p-*
*fontfamily.times.medium.bold: *adobe-times-bold-r-*-120-*-p-*
*fontfamily.times.medium.italic: *<API key>-*-120-*-p-*
*fontfamily.times.medium.bolditalic: *adobe-times-bold-i-*-120-*-p-*
*fontfamily.times.large.roman: *<API key>-*-240-*-p-*
*fontfamily.times.large.bold: *adobe-times-bold-r-*-240-*-p-*
*fontfamily.times.large.italic: *<API key>-*-240-*-p-*
*fontfamily.times.large.bolditalic: *adobe-times-bold-i-*-240-*-p-*
*ttyModes: intr ^C erase ^? susp ^Z kill ^U
*VT100.Translations: #override <Key>Delete: string(0x1b) string("[3~")\n\
<Key>Home: string(0x1b) string("[1~")\n\
<Key>End: string(0x1b) string("[4~")\n\
Ctrl<Key>Prior: string(0x1b) string("[40~")\n\
Ctrl<Key>Next: string(0x1b) string("[41~")\n\
<Key>KP_Decimal: string(0x1b) string("[3~")\n
XDaliClock.seconds: false
XDaliClock*cycle: true
XDaliClock.shape: true
XDaliClock*memory: low
XDaliClock*font: -*-lucida-*-r-*-*-*-190-*-*-*-*-*-*
XDaliClock*mode: 24
XDaliClock.geometry: 90x25-0+0
xscreensaver.timeout: 3
xscreensaver.lock: true
xscreensaver.lockTimeout: 2
xscreensaver.splash: false
xscreensaver.cycle: 10
xscreensaver.nice: 19
xscreensaver.fade: false
xscreensaver.unfade: false
xscreensaver.installColormap: false
!xscreensaver.visualID: PseudoColor
xearth.pos: fixed 34.08 -118.08
xearth.gamma: 1.47
xearth.label: true
xearth.labelpos: -0+0
xearth.night: 5
xearth.wait: 300
xearth.fork: true
xearth.nice: 19
xearth.ncolors: 16
XLock.mode: blank
XLock.font: -b&<API key>-*-*-*-*-*-iso8859-1
XLock.background: White
XLock.foreground: Black
XLock.username: Name:
XLock.password: Password:
XLock.info: Enter password to unlock; select icon to lock.
XLock.validate: Validating login...
XLock.invalid: Invalid login.
XLock.geometry:
XLock.nice: 10
XLock.timeout: 30
XLock.lockdelay: 0
XLock.mono: off
XLock.enablesaver: off
XLock.allowaccess: off
XLock.grabmouse: on
XLock.echokeys: off
XLock.usefirst: on
XLock.verbose: off
XLock.timeelapsed: off
XLock.install: on
XLock.use3d: off
XLock.delta3d: 1.5
XLock.right3d: rgb:ffff/0/0
XLock.left3d: rgb:0/ffff/0
XLock.program: fortune -s
XLock.messagesfile:
XLock.messagefile:
XLock.message:
XLock.mfont: -*-times-*-*-*-*-18-*-*-*-*-*-*-*
XLock.ant.delay: 1000
XLock.ant.batchcount: 1
XLock.ant.cycles: 32767
XLock.ant.saturation: 1
XLock.bat.delay: 100000
XLock.bat.batchcount: 6
XLock.bat.cycles: 20
XLock.bat.saturation: 1
XLock.blot.delay: 100000
XLock.blot.batchcount: 6
XLock.blot.cycles: 30
XLock.blot.saturation: 0.4
XLock.bouboule.delay: 1000
XLock.bouboule.batchcount: 100
XLock.bouboule.cycles: 15
XLock.bouboule.saturation: 1
XLock.bounce.delay: 10000
XLock.bounce.batchcount: 10
XLock.bounce.cycles: 20
XLock.bounce.saturation: 1
XLock.braid.delay: 1000
XLock.braid.batchcount: 15
XLock.braid.cycles: 30
XLock.braid.saturation: 1
XLock.bug.delay: 75000
XLock.bug.batchcount: 10
XLock.bug.cycles: 32767
XLock.bug.saturation: 1
XLock.clock.delay: 100000
XLock.clock.batchcount: 30
XLock.clock.cycles: 200
XLock.clock.saturation: 1
XLock.demon.delay: 750000
XLock.demon.batchcount: 16
XLock.demon.cycles: 1000
XLock.demon.saturation: 1
XLock.flame.delay: 750000
XLock.flame.batchcount: 20
XLock.flame.cycles: 10000
XLock.flame.saturation: 1
XLock.forest.delay: 100000
XLock.forest.batchcount: 100
XLock.forest.cycles: 200
XLock.forest.saturation: 1
XLock.galaxy.delay: 100
XLock.galaxy.batchcount: 3
XLock.galaxy.cycles: 20
XLock.galaxy.saturation: 1
XLock.geometry.delay: 2000
XLock.geometry.batchcount: 8
XLock.geometry.cycles: 20
XLock.geometry.saturation: 1
XLock.grav.delay: 10000
XLock.grav.batchcount: 10
XLock.grav.cycles: 20
XLock.grav.saturation: 1
XLock.helix.delay: 10000
XLock.helix.batchcount: 1
XLock.helix.cycles: 100
XLock.helix.saturation: 1
XLock.hop.delay: 10000
XLock.hop.batchcount: 1000
XLock.hop.cycles: 2500
XLock.hop.saturation: 1
XLock.hyper.delay: 10000
XLock.hyper.batchcount: 1
XLock.hyper.cycles: 300
XLock.hyper.saturation: 1
XLock.image.delay: 2000000
XLock.image.batchcount: 1
XLock.image.cycles: 20
XLock.image.saturation: 1
XLock.kaleid.delay: 2000
XLock.kaleid.batchcount: 4
XLock.kaleid.cycles: 700
XLock.kaleid.saturation: 1
XLock.laser.delay: 5000
XLock.laser.batchcount: 10
XLock.laser.cycles: 200
XLock.laser.saturation: 1
XLock.life.delay: 750000
XLock.life.batchcount: 40
XLock.life.cycles: 140
XLock.life.saturation: 1
XLock.life1d.delay: 2500000
XLock.life1d.batchcount: 10
XLock.life1d.cycles: 10
XLock.life1d.saturation: 1
XLock.life3d.delay: 1000000
XLock.life3d.batchcount: 35
XLock.life3d.cycles: 85
XLock.life3d.saturation: 1
XLock.marquee.delay: 100000
XLock.marquee.batchcount: 10
XLock.marquee.cycles: 20
XLock.marquee.saturation: 1
XLock.maze.delay: 10000
XLock.maze.batchcount: 40
XLock.maze.cycles: 300
XLock.maze.saturation: 1
XLock.mountain.delay: 10000
XLock.mountain.batchcount: 30
XLock.mountain.cycles: 100
XLock.mountain.saturation: 1
XLock.nose.delay: 100000
XLock.nose.batchcount: 10
XLock.nose.cycles: 20
XLock.nose.saturation: 1
XLock.petal.delay: 10000
XLock.petal.batchcount: 500
XLock.petal.cycles: 100
XLock.petal.saturation: 1
XLock.pyro.delay: 15000
XLock.pyro.batchcount: 40
XLock.pyro.cycles: 20
XLock.pyro.saturation: 1
XLock.qix.delay: 30000
XLock.qix.batchcount: 100
XLock.qix.cycles: 64
XLock.qix.saturation: 1
XLock.rock.delay: 20000
XLock.rock.batchcount: 100
XLock.rock.cycles: 20
XLock.rock.saturation: 0.2
XLock.rotor.delay: 10000
XLock.rotor.batchcount: 4
XLock.rotor.cycles: 20
XLock.rotor.saturation: 0.4
XLock.shape.delay: 10000
XLock.shape.batchcount: 100
XLock.shape.cycles: 256
XLock.shape.saturation: 1
XLock.slip.delay: 50000
XLock.slip.batchcount: 35
XLock.slip.cycles: 50
XLock.slip.saturation: 1
XLock.sphere.delay: 10000
XLock.sphere.batchcount: 1
XLock.sphere.cycles: 20
XLock.sphere.saturation: 1
XLock.spiral.delay: 5000
XLock.spiral.batchcount: 6
XLock.spiral.cycles: 350
XLock.spiral.saturation: 1
XLock.spline.delay: 30000
XLock.spline.batchcount: 100
XLock.spline.cycles: 20
XLock.spline.saturation: 0.4
XLock.swarm.delay: 10000
XLock.swarm.batchcount: 100
XLock.swarm.cycles: 20
XLock.swarm.saturation: 1
XLock.swirl.delay: 5000
XLock.swirl.batchcount: 5
XLock.swirl.cycles: 20
XLock.swirl.saturation: 1
XLock.triangle.delay: 100000
XLock.triangle.batchcount: 100
XLock.triangle.cycles: 30
XLock.triangle.saturation: 1
XLock.wator.delay: 750000
XLock.wator.batchcount: 4
XLock.wator.cycles: 32767
XLock.wator.saturation: 1
XLock.world.delay: 100000
XLock.world.batchcount: 8
XLock.world.cycles: 20
XLock.world.saturation: 0.3
XLock.worm.delay: 10000
XLock.worm.batchcount: 20
XLock.worm.cycles: 20
XLock.worm.saturation: 1
XLock.blank.delay: 3000000
XLock.blank.batchcount: 1
XLock.blank.cycles: 20
XLock.blank.saturation: 1
XLock.random.delay: 1
XLock.random.batchcount: 0
XLock.random.cycles: 0
XLock.random.saturation: 0
TEMPLATEQUOTE |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<!-- template designed by Marco Von Ballmoos -->
<title>Docs for page banner.php</title>
<link rel="stylesheet" href="../../media/stylesheet.css" />
<script src="../../media/lib/classTree.js"></script>
<script language="javascript" type="text/javascript">
var imgPlus = new Image();
var imgMinus = new Image();
imgPlus.src = "../../media/images/plus.png";
imgMinus.src = "../../media/images/minus.png";
function showNode(Node){
switch(navigator.family){
case 'nn4':
// Nav 4.x code fork...
var oTable = document.layers["span" + Node];
var oImg = document.layers["img" + Node];
break;
case 'ie4':
// IE 4/5 code fork...
var oTable = document.all["span" + Node];
var oImg = document.all["img" + Node];
break;
case 'gecko':
// Standards Compliant code fork...
var oTable = document.getElementById("span" + Node);
var oImg = document.getElementById("img" + Node);
break;
}
oImg.src = imgMinus.src;
oTable.style.display = "block";
}
function hideNode(Node){
switch(navigator.family){
case 'nn4':
// Nav 4.x code fork...
var oTable = document.layers["span" + Node];
var oImg = document.layers["img" + Node];
break;
case 'ie4':
// IE 4/5 code fork...
var oTable = document.all["span" + Node];
var oImg = document.all["img" + Node];
break;
case 'gecko':
// Standards Compliant code fork...
var oTable = document.getElementById("span" + Node);
var oImg = document.getElementById("img" + Node);
break;
}
oImg.src = imgPlus.src;
oTable.style.display = "none";
}
function nodeIsVisible(Node){
switch(navigator.family){
case 'nn4':
// Nav 4.x code fork...
var oTable = document.layers["span" + Node];
break;
case 'ie4':
// IE 4/5 code fork...
var oTable = document.all["span" + Node];
break;
case 'gecko':
// Standards Compliant code fork...
var oTable = document.getElementById("span" + Node);
break;
}
return (oTable && oTable.style.display == "block");
}
function <API key>(Node){
if (nodeIsVisible(Node)){
hideNode(Node);
}else{
showNode(Node);
}
}
</script>
</head>
<body>
<div class="page-body">
<h2 class="file-name"><img src="../../media/images/Page_logo.png" alt="File" style="vertical-align: middle">/administrator/components/com_banners/models/banner.php</h2>
<a name="sec-description"></a>
<div class="info-box">
<div class="info-box-title">Description</div>
<div class="nav-bar">
<span class="disabled">Description</span> |
<a href="#sec-classes">Classes</a>
</div>
<div class="info-box-body">
<ul class="tags">
<li><span class="field">copyright:</span> Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.</li>
<li><span class="field">filesource:</span> <a href="../../filesource/fsource_Joomla<API key>.php.html">Source Code for this file</a></li>
<li><span class="field">license:</span> GNU</li>
</ul>
</div>
</div>
<a name="sec-classes"></a>
<div class="info-box">
<div class="info-box-title">Classes</div>
<div class="nav-bar">
<a href="#sec-description">Description</a> |
<span class="disabled">Classes</span>
</div>
<div class="info-box-body">
<table cellpadding="2" cellspacing="0" class="class-table">
<tr>
<th class="class-table-header">Class</th>
<th class="class-table-header">Description</th>
</tr>
<tr>
<td style="padding-right: 2em; vertical-align: top; white-space: nowrap">
<img src="../../media/images/Class.png"
alt=" class"
title=" class"/>
<a href="../../<API key>/com_banners/BannersModelBanner.html">BannersModelBanner</a>
</td>
<td>
Banner model.
</td>
</tr>
</table>
</div>
</div>
<p class="notes" id="credit">
Documentation generated on Tue, 19 Nov 2013 14:54:12 +0100 by <a href="http:
</p>
</div></body>
</html> |
<HTML>
<HEAD>
<TITLE>Engineering Computing Systems</TITLE>
</HEAD>
<SCRIPT LANGUAGE="Javascript">
<!
function winOpen(open)
{ win = window.open(open, '_blank','width=600,height=400,resizable=1,scrollbars=1');}
</SCRIPT>
<BODY BGCOLOR= "#FFFFFF" TEXT="#000000" LINK="#6666CC" VLINK="#9966CC" ALINK="#FF0000">
<H1 ALIGN = "center">Engineering Computing Systems</H1>
<P ALIGN = "center"><IMG SRC = "sjsu-coe.jpg" WIDTH="137" HEIGHT="115">
<TABLE WIDTH="65%" BORDER="2" BORDERCOLORLIGHT="#CCCCFF" ALIGN="CENTER" BORDERCOLORDARK="#999999" HEIGHT="120">
<TR>
<TD>
<CENTER>
<FONT SIZE="3"><B><FONT SIZE="+3">T</FONT>he mission of ECS is to provide
information technology systems, services, computing facilities, and network
infrastructure to support the College of Engineering in achieving its
academic and administrative missions and goals.</B></FONT>
</CENTER>
</TD>
</TR>
</TABLE>
<CENTER>
<BR>
<FONT SIZE="2"><I>We are located in the College of Engineering Building room
239.</I></FONT> <BR>
<BR>
<HR width="25%">
</CENTER>
<P><BR>
</P>
<TABLE width="40%" border="0" cellpadding="10" hspace="30" align="left">
<TR>
<TD>
<P><STRONG><FONT size="4">ECS Support</FONT></STRONG> <B><BR>
<A href = "http://dolphin.engr.sjsu.edu/cgi-bin/JobTrackRequest/requestFrame.pl"><FONT size="3">Service
Request Form</FONT></A></B></P>
<P> <STRONG><FONT size="4">Information</FONT></STRONG><FONT size="3"><BR>
</FONT> <FONT size="3"><B><A href="strategicplan.html">Information Technology
Strategic Plan</A><BR>
</B></FONT><A href="http://dolphin.engr.sjsu.edu/cgi-bin/public/info.cgi"><B>COE
Information System</B></A>
<A HREF="javascript:winOpen('win2k.html')"><B><BR>
Memo on Windows 2000</B></A> <BR>
<STRONG><A href="students/students.html">Distinguished Students</A></STRONG></P>
<P align="left"> <STRONG><FONT size="4">Software</FONT></STRONG><BR>
<A href="software.html"><B><STRONG>Software</STRONG></B><STRONG> Downloads
& Links</STRONG></A></P>
<P align="left"><STRONG><FONT size="4">Technical Contacts</FONT></STRONG><BR>
<A href="ecstech.html"><STRONG>ECS</STRONG></A> <STRONG> <A href="CoeContacts.html"><BR>
COE</A> </STRONG> <STRONG><A href="supportserv.html"><BR>
Support Services</A><BR>
</STRONG> <STRONG> <A HREF="javascript:winOpen('pagers.html')">Pager Numbers</A>
</STRONG> <BR>
</P>
<P align="left"><FONT size="4"><STRONG>Technical Training<BR>
</STRONG></FONT><STRONG><A href="training.html">Microsoft</A></STRONG></P>
</TD>
</TR>
</TABLE>
<P>
<BR CLEAR="all">
<BR><BR>
<HR width="50%" size="4" align="center">
<HR width="15%" size="4" align="center">
<P> </P><TABLE WIDTH="17%" BORDER="2" CELLPADDING="2" CELLSPACING="1" BORDERCOLORLIGHT="#CCCCCC" BORDERCOLORDARK="#999999" vspace="10">
<TR>
<TD><A HREF="http:
</TR>
<TR>
<TD><A HREF="http:
</TR>
</TABLE>
</HTML> |
PWD := $(shell pwd)
# Set these from the environment to override
KERNEL_VERSION ?= 4.8.12
BUILD_PATH ?= $(PWD)/../../../qemu-build
DISTFILES_PATH ?= $(PWD)/distfiles
DEBUG_KERNEL ?= no
NR_CPUS ?= 2
DOWNLOAD := wget -O
# DOWNLOAD := curl -f -o
MIRROR := https://download.wireguard.io/qemu-test/distfiles/
CHOST := x86_64-pc-linux-gnu |
<?php
namespace Magento\Store\Test\TestCase;
use Magento\Backend\Test\Page\Adminhtml\NewWebsiteIndex;
use Magento\Backend\Test\Page\Adminhtml\StoreIndex;
use Magento\Store\Test\Fixture\Website;
use Magento\Mtf\TestCase\Injectable;
/**
* Create Website (Store Management)
*
* Test Flow:
* 1. Open Backend
* 2. Go to Stores-> All Stores
* 3. Click "Create Website" button
* 4. Fill data according to dataset
* 5. Click "Save Web Site" button
* 6. Perform all assertions
*
* @group Store_Management
* @ZephyrId MAGETWO-27665
*/
class <API key> extends Injectable
{
/* tags */
const MVP = 'yes';
const SEVERITY = 'S1';
/* end tags */
/**
* Page StoreIndex
*
* @var StoreIndex
*/
protected $storeIndex;
/**
* NewWebsiteIndex page
*
* @var NewWebsiteIndex
*/
protected $newWebsiteIndex;
/**
* Injection data
*
* @param StoreIndex $storeIndex
* @param NewWebsiteIndex $newWebsiteIndex
* @return void
*/
public function __inject(
StoreIndex $storeIndex,
NewWebsiteIndex $newWebsiteIndex
) {
$this->storeIndex = $storeIndex;
$this->newWebsiteIndex = $newWebsiteIndex;
}
/**
* Create Website
*
* @param Website $website
* @return void
*/
public function test(Website $website)
{
//Steps
$this->storeIndex->open();
$this->storeIndex->getGridPageActions()->addNew();
$this->newWebsiteIndex->getEditWebsiteForm()->fill($website);
$this->newWebsiteIndex->getFormPageActions()->save();
}
} |
using System;
using QuantSys.Analytics.Timeseries.Indicators.Abstraction;
using QuantSys.Analytics.Timeseries.Indicators.Averages;
using QuantSys.MarketData;
namespace QuantSys.Analytics.Timeseries.Indicators.Misc
{
public class ForceIndex: AbstractIndicator
{
private EMA EMA;
private Tick prevTick;
public ForceIndex(int n) : base(n)
{
EMA = new EMA(n);
}
public override double HandleNextTick(Tick t)
{
double value = Double.NaN;
if (prevTick != null)
{
value = EMA.HandleNextTick(t.Volume*(t.BidClose - prevTick.BidClose));
}
prevTick = t;
indicatorData.Enqueue(value);
return value;
}
public override string ToString()
{
return "Force Index" + Period;
}
}
} |
package org.opennms.plugins.elasticsearch.rest;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
import org.junit.Test;
import org.opennms.netmgt.dao.api.DistPollerDao;
import org.opennms.netmgt.events.api.EventConstants;
import org.opennms.features.jest.client.SearchResultUtils;
import org.opennms.netmgt.model.OnmsSeverity;
import org.opennms.netmgt.xml.event.Event;
import org.opennms.netmgt.xml.event.Parm;
import org.opennms.netmgt.xml.event.Value;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
public class AlarmEventToIndexIT extends <API key> {
public static final int INDEX_WAIT_SECONDS=10; // time to wait for index to catch up
// See NMS-9831 for more information
@Test
public void verifyOidMapping() throws <API key>, IOException {
int eventId = 13;
final Event event = <API key>(eventId);
getEventToIndex().forwardEvents(Arrays.asList(event));
TimeUnit.SECONDS.sleep(INDEX_WAIT_SECONDS);
final String query = buildSearchQuery(eventId);
final Search search = new Search.Builder(query)
.addIndex("opennms-events-raw-*")
.build();
final SearchResult result = jestClient.execute(search);
assertEquals(200, result.getResponseCode());
assertEquals(1L, SearchResultUtils.getTotal(result));
}
// See NMS-9831 for more information
@Test
public void verifyOidGrouping() throws <API key>, IOException {
int eventId = 15;
final Event event = <API key>(eventId);
getEventToIndex().<API key>(true);
getEventToIndex().forwardEvents(Arrays.asList(event));
TimeUnit.SECONDS.sleep(INDEX_WAIT_SECONDS);
final String query = buildSearchQuery(eventId);
final Search search = new Search.Builder(query)
.addIndex("opennms-events-raw-*")
.build();
final SearchResult result = jestClient.execute(search);
assertEquals(200, result.getResponseCode());
assertEquals(1L, SearchResultUtils.getTotal(result));
// Verify oids
final JsonArray oids = result.getJsonObject()
.get("hits").getAsJsonObject()
.get("hits").getAsJsonArray()
.get(0).getAsJsonObject()
.get("_source").getAsJsonObject()
.get("p_oids").getAsJsonArray();
assertNotNull(oids);
assertEquals(99, oids.size());
}
// See HZN-1272
@Test
public void <API key>() throws <API key>, IOException {
final int eventId = 17;
final Event event = createDummyEvent(eventId);
final JsonObject addressObject = new JsonObject();
addressObject.addProperty("street", "950 Windy Rd, Ste 300");
addressObject.addProperty("city", "Apex");
addressObject.addProperty("state", "NC");
final JsonObject jsonObject = new JsonObject();
jsonObject.add("address", addressObject);
jsonObject.addProperty("name", "The OpenNMS Group");
// Create Event Parameter, which carries a json representation
final Value value = new Value();
value.setType("json");
value.setEncoding("text");
value.setContent(jsonObject.toString());
final Parm p = new Parm();
p.setValue(value);
p.setParmName("name");
event.addParm(p);
// Forward event...
getEventToIndex().forwardEvents(Arrays.asList(event));
TimeUnit.SECONDS.sleep(INDEX_WAIT_SECONDS);
// ... and verify that the json was actually persisted as json and not as string
final String query = buildSearchQuery(eventId);
final Search search = new Search.Builder(query)
.addIndex("opennms-events-raw-*")
.build();
final SearchResult result = jestClient.execute(search);
assertEquals(200, result.getResponseCode());
assertEquals(1L, SearchResultUtils.getTotal(result));
final JsonArray jsonArray = result.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray();
assertEquals(jsonObject, jsonArray.get(0).getAsJsonObject().get("_source").getAsJsonObject().get("p_name").getAsJsonObject());
}
private static Event createDummyEvent(int eventId) {
final Event event = new Event();
event.setUei(EventConstants.NODE_DOWN_EVENT_UEI);
event.setCreationTime(new Date());
event.setDistPoller(DistPollerDao.<API key>);
event.setDescr("Dummy Event");
event.setSeverity(OnmsSeverity.WARNING.getLabel());
event.setDbid(eventId);
return event;
}
private static Event <API key>(int eventId) {
final Event event = createDummyEvent(eventId);
IntStream.range(1, 100).forEach(i -> {
Parm parm = new Parm();
parm.setParmName("." + i + ".0.0.0.0.0.0.0.0.0"); // 10 * 100 -> 1000 fields at least
parm.setValue(new Value("dummy value"));
event.addParm(parm);
});
return event;
}
private static String buildSearchQuery(int eventId) {
return "{\n"
+"\n \"query\": {"
+ "\n \"match\": {"
+ "\n \"id\": \"" + eventId + "\""
+ "\n }"
+ "\n }"
+ "\n }";
}
} |
* setInterval
* setTimeout
* clearIntervalclearTimeout
*
* tweenmTween
* getComputedStyle
*
1.

2.

3.

1. setInterval 1s
2.
1. Date()
2. getSeconds() getMinutes() getHours()
3. json
4. transform rotate transition
5. setInterval,
6. |
#ifndef RegExp_h
#define RegExp_h
#include "ExecutableAllocator.h"
#include "MatchResult.h"
#include "RegExpKey.h"
#include "Structure.h"
#include "yarr/Yarr.h"
#include <wtf/Forward.h>
#include <wtf/RefCounted.h>
#include <wtf/text/WTFString.h>
#if ENABLE(YARR_JIT)
#include "yarr/YarrJIT.h"
#endif
namespace JSC {
struct <API key>;
class VM;
JS_EXPORT_PRIVATE RegExpFlags regExpFlags(const String&);
class RegExp final : public JSCell {
public:
typedef JSCell Base;
static const unsigned StructureFlags = Base::StructureFlags | StructureIsImmortal;
JS_EXPORT_PRIVATE static RegExp* create(VM&, const String& pattern, RegExpFlags);
static const bool needsDestruction = true;
static void destroy(JSCell*);
static size_t estimatedSize(JSCell*);
bool global() const { return m_flags & FlagGlobal; }
bool ignoreCase() const { return m_flags & FlagIgnoreCase; }
bool multiline() const { return m_flags & FlagMultiline; }
bool unicode() const { return m_flags & FlagUnicode; }
const String& pattern() const { return m_patternString; }
bool isValid() const { return !m_constructionError && m_flags != InvalidFlags; }
const char* errorMessage() const { return m_constructionError; }
JS_EXPORT_PRIVATE int match(VM&, const String&, unsigned startOffset, Vector<int, 32>& ovector);
JS_EXPORT_PRIVATE MatchResult match(VM&, const String&, unsigned startOffset);
unsigned numSubpatterns() const { return m_numSubpatterns; }
bool hasCode()
{
return m_state != NotCompiled;
}
void deleteCode();
#if ENABLE(REGEXP_TRACING)
void printTraceData();
#endif
static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
{
return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
}
DECLARE_INFO;
RegExpKey key() { return RegExpKey(m_flags, m_patternString); }
protected:
void finishCreation(VM&);
private:
friend class RegExpCache;
RegExp(VM&, const String&, RegExpFlags);
static RegExp* <API key>(VM&, const String&, RegExpFlags);
enum RegExpState {
ParseError,
JITCode,
ByteCode,
NotCompiled
};
RegExpState m_state;
void compile(VM*, Yarr::YarrCharSize);
void compileIfNecessary(VM&, Yarr::YarrCharSize);
void compileMatchOnly(VM*, Yarr::YarrCharSize);
void <API key>(VM&, Yarr::YarrCharSize);
#if ENABLE(YARR_JIT_DEBUG)
void <API key>(const String&, int startOffset, int* offsetVector, int jitResult);
#endif
String m_patternString;
RegExpFlags m_flags;
const char* m_constructionError;
unsigned m_numSubpatterns;
#if ENABLE(REGEXP_TRACING)
double <API key>;
double <API key>;
unsigned <API key>;
unsigned <API key>;
unsigned m_rtMatchCallCount;
unsigned m_rtMatchFoundCount;
#endif
#if ENABLE(YARR_JIT)
Yarr::YarrCodeBlock m_regExpJITCode;
#endif
std::unique_ptr<Yarr::BytecodePattern> m_regExpBytecode;
};
} // namespace JSC
#endif // RegExp_h |
<?
$sub_menu = "100600";
include_once("./_common.php");
check_demo();
if ($is_admin != "super")
alert(" .", $g4[path]);
$g4[title] = "";
if (!$g4[b4_upgrade]) include_once("./admin.head.php");
$sql = " select bo_table from $g4[board_table] ";
$result = sql_query($sql);
for ($i=0; $row=sql_fetch_array($result); $i++) {
$tmp_write_table = $g4[write_prefix] . $row[bo_table];
$sql1 = " ALTER TABLE $tmp_write_table ADD `wr_imagesize` INT( 11) NOT NULL DEFAULT '-1' ";
sql_query($sql1, false);
echo "<BR>" . $i . " : " . $row[bo_table] . " wr_imagesize <br>";
}
echo "<br> wr_imagesize UPGRADE .";
if (!$g4[b4_upgrade]) include_once("./admin.tail.php");
?> |
#ifndef TARGET_KERNEL
#include <math.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ft2build.h>
#include FT_FREETYPE_H
#include <freetype/ftoutln.h>
#include "splash.h"
TTF_Font *global_font;
char *boot_message = NULL;
#define DEFAULT_PTSIZE 18
#define NUM_GRAYS 256
void <API key>(u8 *target, const unsigned short *text,
TTF_Font* font, int x, int y, color fcol, u8 hotspot);
static void Flush_Glyph(c_glyph* glyph);
static void Flush_Cache(TTF_Font* font)
{
int i;
int size = sizeof(font->cache) / sizeof(font->cache[0]);
for(i = 0; i < size; ++i) {
if(font->cache[i].cached) {
Flush_Glyph(&font->cache[i]);
}
}
if(font->scratch.cached) {
Flush_Glyph(&font->scratch);
}
}
/* character conversion */
/* Macro to convert a character to a Unicode value -- assume already Unicode */
#define UNICODE(c) c
/*
static unsigned short *ASCII_to_UNICODE(unsigned short *unicode, const char *text, int len)
{
int i;
for (i=0; i < len; ++i) {
unicode[i] = ((const unsigned char *)text)[i];
}
unicode[i] = 0;
return unicode;
}
*/
#ifdef TARGET_KERNEL
int ceil(float a)
{
int h = (int)a;
if (a - h >= 0.5)
return h+1;
else
return h;
}
#endif
static unsigned short *UTF8_to_UNICODE(unsigned short *unicode, const char *utf8, int len)
{
int i, j;
unsigned short ch;
for (i=0, j=0; i < len; ++i, ++j) {
ch = ((const unsigned char *)utf8)[i];
if (ch >= 0xF0) {
ch = (unsigned short)(utf8[i]&0x07) << 18;
ch |= (unsigned short)(utf8[++i]&0x3F) << 12;
ch |= (unsigned short)(utf8[++i]&0x3F) << 6;
ch |= (unsigned short)(utf8[++i]&0x3F);
} else
if (ch >= 0xE0) {
ch = (unsigned short)(utf8[i]&0x3F) << 12;
ch |= (unsigned short)(utf8[++i]&0x3F) << 6;
ch |= (unsigned short)(utf8[++i]&0x3F);
} else
if (ch >= 0xC0) {
ch = (unsigned short)(utf8[i]&0x3F) << 6;
ch |= (unsigned short)(utf8[++i]&0x3F);
}
unicode[j] = ch;
}
unicode[j] = 0;
return unicode;
}
/* TTF stuff */
static FT_Library library;
static int TTF_initialized = 0;
int TTF_Init(void)
{
int status;
FT_Error error;
status = 0;
error = FT_Init_FreeType(&library);
if (error) {
fprintf(stderr, "Couldn't init FreeType engine %d\n", error);
status = -1;
} else {
TTF_initialized = 1;
}
return status;
}
void TTF_Quit(void)
{
if (TTF_initialized) {
FT_Done_FreeType(library);
}
TTF_initialized = 0;
}
unsigned char*<API key>(u8 *target, const char *text, TTF_Font *font, int x, int y, color col, u8 hotspot)
{
unsigned short *p, *t, *unicode_text;
int unicode_len;
/* Copy the Latin-1 text to a UNICODE text buffer */
unicode_len = strlen(text);
unicode_text = (unsigned short *)malloc((unicode_len+1)*(sizeof*unicode_text));
if (unicode_text == NULL) {
printf("Out of memory\n");
return(NULL);
}
UTF8_to_UNICODE(unicode_text, text, unicode_len);
// ASCII_to_UNICODE(unicode_text, text, unicode_len);
for (t = p = unicode_text; *p != 0; p++) {
if (*p == '\n') {
*p = 0;
if (p > t)
<API key>(target, t, font, x, y, col, hotspot);
y += font->height;
t = p+1;
}
}
if (*t != 0) {
<API key>(target, t, font, x, y, col, hotspot);
}
/* Free the text buffer and return */
free(unicode_text);
return NULL;
}
void TTF_CloseFont(TTF_Font* font)
{
Flush_Cache(font);
FT_Done_Face(font->face);
free(font);
}
void TTF_SetFontStyle(TTF_Font* font, int style)
{
font->style = style;
Flush_Cache(font);
}
TTF_Font* TTF_OpenFontIndex(const char *file, int ptsize, long index)
{
TTF_Font* font;
FT_Error error;
FT_Face face;
FT_Fixed scale;
font = (TTF_Font*) malloc(sizeof *font);
if (font == NULL) {
fprintf(stderr, "Out of memory\n");
return NULL;
}
memset(font, 0, sizeof(*font));
/* Open the font and create ancillary data */
error = FT_New_Face(library, file, 0, &font->face);
if (error)
error = FT_New_Face(library, TTF_DEFAULT, 0, &font->face);
// if (error && !strict_font)
// error=FT_New_Memory_Face(library, (const FT_Byte*)luxisri_ttf, LUXISRI_SIZE, 0, &font->face);
if (error) {
printf("Couldn't load font file: Error %x\n", error);
free(font);
return NULL;
}
if (index != 0) {
if (font->face->num_faces > index) {
FT_Done_Face(font->face);
error = FT_New_Face(library, file, index, &font->face);
if(error) {
printf("Couldn't get font face: Error %x\n", error);
free(font);
return NULL;
}
} else {
fprintf(stderr, "No such font face: Error %x\n", error);
free(font);
return NULL;
}
}
face = font->face;
/* Make sure that our font face is scalable (global metrics) */
if (! FT_IS_SCALABLE(face)) {
fprintf(stderr,"Font face is not scalable\n");
TTF_CloseFont(font);
return NULL;
}
/* Set the character size and use default DPI (72) */
error = FT_Set_Char_Size(font->face, 0, ptsize * 64, 0, 0);
if (error) {
fprintf(stderr, "Couldn't set font size\n");
TTF_CloseFont(font);
return NULL;
}
/* Get the scalable font metrics for this font */
scale = face->size->metrics.y_scale;
font->ascent = FT_CEIL(FT_MulFix(face->bbox.yMax, scale));
font->descent = FT_CEIL(FT_MulFix(face->bbox.yMin, scale));
font->height = font->ascent - font->descent + /* baseline */ 1;
font->lineskip = FT_CEIL(FT_MulFix(face->height, scale));
font->underline_offset = FT_FLOOR(FT_MulFix(face->underline_position, scale));
font->underline_height = FT_FLOOR(FT_MulFix(face->underline_thickness, scale));
if (font->underline_height < 1) {
font->underline_height = 1;
}
/* Set the default font style */
font->style = TTF_STYLE_NORMAL;
font->glyph_overhang = face->size->metrics.y_ppem / 10;
/* x offset = cos(((90.0-12)/360)*2*M_PI), or 12 degree angle */
font->glyph_italics = 0.207f;
font->glyph_italics *= font->height;
return font;
}
TTF_Font* TTF_OpenFont(const char *file, int ptsize)
{
TTF_Font *a;
a = TTF_OpenFontIndex(file, ptsize, 0);
if (a == NULL) {
fprintf(stderr, "Couldn't load %d pt font from %s\n", ptsize, file);
}
return a;
}
static void Flush_Glyph(c_glyph* glyph)
{
glyph->stored = 0;
glyph->index = 0;
if(glyph->bitmap.buffer) {
free(glyph->bitmap.buffer);
glyph->bitmap.buffer = 0;
}
if(glyph->pixmap.buffer) {
free(glyph->pixmap.buffer);
glyph->pixmap.buffer = 0;
}
glyph->cached = 0;
}
static FT_Error Load_Glyph(TTF_Font* font, unsigned short ch, c_glyph* cached, int want)
{
FT_Face face;
FT_Error error;
FT_GlyphSlot glyph;
FT_Glyph_Metrics* metrics;
FT_Outline* outline;
assert(font);
assert(font->face);
face = font->face;
/* Load the glyph */
if (! cached->index) {
cached->index = FT_Get_Char_Index(face, ch);
}
error = FT_Load_Glyph(face, cached->index, FT_LOAD_DEFAULT);
if(error) {
return error;
}
/* Get our glyph shortcuts */
glyph = face->glyph;
metrics = &glyph->metrics;
outline = &glyph->outline;
/* Get the glyph metrics if desired */
if ((want & CACHED_METRICS) && !(cached->stored & CACHED_METRICS)) {
/* Get the bounding box */
cached->minx = FT_FLOOR(metrics->horiBearingX);
cached->maxx = cached->minx + FT_CEIL(metrics->width);
cached->maxy = FT_FLOOR(metrics->horiBearingY);
cached->miny = cached->maxy - FT_CEIL(metrics->height);
cached->yoffset = font->ascent - cached->maxy;
cached->advance = FT_CEIL(metrics->horiAdvance);
/* Adjust for bold and italic text */
if(font->style & TTF_STYLE_BOLD) {
cached->maxx += font->glyph_overhang;
}
if(font->style & TTF_STYLE_ITALIC) {
cached->maxx += (int)ceil(font->glyph_italics);
}
cached->stored |= CACHED_METRICS;
}
if (((want & CACHED_BITMAP) && !(cached->stored & CACHED_BITMAP)) ||
((want & CACHED_PIXMAP) && !(cached->stored & CACHED_PIXMAP))) {
int mono = (want & CACHED_BITMAP);
int i;
FT_Bitmap* src;
FT_Bitmap* dst;
/* Handle the italic style */
if(font->style & TTF_STYLE_ITALIC) {
FT_Matrix shear;
shear.xx = 1 << 16;
shear.xy = (int) (font->glyph_italics * (1 << 16))/ font->height;
shear.yx = 0;
shear.yy = 1 << 16;
<API key>(outline, &shear);
}
/* Render the glyph */
if (mono) {
error = FT_Render_Glyph(glyph, ft_render_mode_mono);
} else {
error = FT_Render_Glyph(glyph, <API key>);
}
if(error) {
return error;
}
/* Copy over information to cache */
src = &glyph->bitmap;
if (mono) {
dst = &cached->bitmap;
} else {
dst = &cached->pixmap;
}
memcpy(dst, src, sizeof(*dst));
if (mono) {
dst->pitch *= 8;
}
/* Adjust for bold and italic text */
if(font->style & TTF_STYLE_BOLD) {
int bump = font->glyph_overhang;
dst->pitch += bump;
dst->width += bump;
}
if(font->style & TTF_STYLE_ITALIC) {
int bump = (int)ceil(font->glyph_italics);
dst->pitch += bump;
dst->width += bump;
}
if (dst->rows != 0) {
dst->buffer = malloc(dst->pitch * dst->rows);
if(!dst->buffer) {
return <API key>;
}
memset(dst->buffer, 0, dst->pitch * dst->rows);
for(i = 0; i < src->rows; i++) {
int soffset = i * src->pitch;
int doffset = i * dst->pitch;
if (mono) {
unsigned char *srcp = src->buffer + soffset;
unsigned char *dstp = dst->buffer + doffset;
int j;
for (j = 0; j < src->width; j += 8) {
unsigned char ch = *srcp++;
*dstp++ = (ch&0x80) >> 7;
ch <<= 1;
*dstp++ = (ch&0x80) >> 7;
ch <<= 1;
*dstp++ = (ch&0x80) >> 7;
ch <<= 1;
*dstp++ = (ch&0x80) >> 7;
ch <<= 1;
*dstp++ = (ch&0x80) >> 7;
ch <<= 1;
*dstp++ = (ch&0x80) >> 7;
ch <<= 1;
*dstp++ = (ch&0x80) >> 7;
ch <<= 1;
*dstp++ = (ch&0x80) >> 7;
}
} else {
memcpy(dst->buffer+doffset,
src->buffer+soffset,src->pitch);
}
}
}
/* Handle the bold style */
if (font->style & TTF_STYLE_BOLD) {
int row;
int col;
int offset;
int pixel;
unsigned char* pixmap;
/* The pixmap is a little hard, we have to add and clamp */
for(row = dst->rows - 1; row >= 0; --row) {
pixmap = (unsigned char*) dst->buffer + row * dst->pitch;
for(offset=1; offset <= font->glyph_overhang; ++offset) {
for(col = dst->width - 1; col > 0; --col) {
pixel = (pixmap[col] + pixmap[col-1]);
if(pixel > NUM_GRAYS - 1) {
pixel = NUM_GRAYS - 1;
}
pixmap[col] = (unsigned char) pixel;
}
}
}
}
/* Mark that we rendered this format */
if (mono) {
cached->stored |= CACHED_BITMAP;
} else {
cached->stored |= CACHED_PIXMAP;
}
}
/* We're done, mark this glyph cached */
cached->cached = ch;
return 0;
}
static FT_Error Find_Glyph(TTF_Font* font, unsigned short ch, int want)
{
int retval = 0;
if(ch < 256) {
font->current = &font->cache[ch];
} else {
if (font->scratch.cached != ch) {
Flush_Glyph(&font->scratch);
}
font->current = &font->scratch;
}
if ((font->current->stored & want) != want) {
retval = Load_Glyph(font, ch, font->current, want);
}
return retval;
}
int TTF_SizeUNICODE(TTF_Font *font, const unsigned short *text, int *w, int *h)
{
int status;
const unsigned short *ch;
int x, z;
int minx, maxx;
int miny, maxy;
c_glyph *glyph;
FT_Error error;
/* Initialize everything to 0 */
if (! TTF_initialized) {
return -1;
}
status = 0;
minx = maxx = 0;
miny = maxy = 0;
/* Load each character and sum it's bounding box */
x= 0;
for (ch=text; *ch; ++ch) {
error = Find_Glyph(font, *ch, CACHED_METRICS);
if (error) {
return -1;
}
glyph = font->current;
z = x + glyph->minx;
if (minx > z) {
minx = z;
}
if (font->style & TTF_STYLE_BOLD) {
x += font->glyph_overhang;
}
if (glyph->advance > glyph->maxx) {
z = x + glyph->advance;
} else {
z = x + glyph->maxx;
}
if (maxx < z) {
maxx = z;
}
x += glyph->advance;
if (glyph->miny < miny) {
miny = glyph->miny;
}
if (glyph->maxy > maxy) {
maxy = glyph->maxy;
}
}
/* Fill the bounds rectangle */
if (w) {
*w = (maxx - minx);
}
if (h)
*h = font->height;
return status;
}
void <API key>(u8 *target, const unsigned short *text,
TTF_Font* font, int x, int y, color fcol, u8 hotspot)
{
int xstart, width, height, i, j, row_underline;
unsigned int val;
const unsigned short* ch;
unsigned char* src;
unsigned char* dst;
int row, col;
c_glyph *glyph;
FT_Error error;
/* Get the dimensions of the text surface */
if ((TTF_SizeUNICODE(font, text, &width, NULL) < 0) || !width) {
fprintf(stderr,"Text has zero width\n");
return;
}
height = font->height;
i = hotspot & F_HS_HORIZ_MASK;
if (i == F_HS_HMIDDLE)
x -= width/2;
else if (i == F_HS_RIGHT)
x -= width;
i = hotspot & F_HS_VERT_MASK;
if (i == F_HS_VMIDDLE)
y -= height/2;
else if (i == F_HS_BOTTOM)
y -= height;
/*
* The underline stuff below is a little hackish. The characters
* that are being rendered do not form a continuous rectangle, and
* we want for the underline to be continuous and span below the
* whole text. To achieve that, while rendering each character,
* we have to not only paint the part of the underline that is
* directly below it, but also the part that 'links' it to the next
* character. Thus all the (font->style & TTF_STYLE_UNDERLINE) ? .. : ..
* code.
*/
row_underline = font->ascent - font->underline_offset - 1;
if (row_underline >= height) {
row_underline = (height-1) - font->underline_height;
}
/* Load and render each character */
xstart = 0;
for(ch = text; *ch; ++ch) {
FT_Bitmap* current;
error = Find_Glyph(font, *ch, CACHED_METRICS|CACHED_PIXMAP);
if (error)
return;
glyph = font->current;
current = &glyph->pixmap;
for(row = 0; row < ((font->style & TTF_STYLE_UNDERLINE) ? height-glyph->yoffset : current->rows); ++row) {
int add;
u8 *memlimit = target + fb_var.xres * fb_var.yres * bytespp;
/* Sanity checks.. */
i = y + row + glyph->yoffset;
j = xstart + glyph->minx + x;
if (i < 0 || i >= fb_var.yres || j >= fb_var.xres)
continue;
if (j < 0)
goto next_glyph;
if (font->style & TTF_STYLE_UNDERLINE && glyph->minx > 0) {
j -= glyph->minx;
}
dst = (unsigned char *)target + (i * fb_var.xres + j)*bytespp;
src = current->buffer + row*current->pitch;
add = x & 1;
add ^= (add ^ (row+y)) & 1 ? 1 : 3;
for (col= ((font->style & TTF_STYLE_UNDERLINE && glyph->minx > 0) ? -glyph->minx : 0);
col < ((font->style & TTF_STYLE_UNDERLINE && *(ch+1)) ?
current->width + glyph->advance : current->width); col++) {
if (col + j >= fb_var.xres-1)
continue;
if (dst+bytespp-1 > memlimit)
break;
if (row < current->rows && col < current->width && col >= 0)
val=*src++;
else
val=0;
/* Handle underline */
if (font->style & TTF_STYLE_UNDERLINE && row+glyph->yoffset >= row_underline &&
row+glyph->yoffset < row_underline + font->underline_height) {
val = NUM_GRAYS-1;
}
put_pixel(fcol.a*val/255, fcol.r, fcol.g, fcol.b, dst, dst, add);
dst += bytespp;
add ^= 3;
}
}
next_glyph: xstart += glyph->advance;
if (font->style & TTF_STYLE_BOLD) {
xstart += font->glyph_overhang;
}
}
return;
}
int TTF_PrimeCache(char *text, TTF_Font *font, int style) {
char *p;
if (!text || !font)
return -1;
TTF_SetFontStyle(font, style);
Flush_Cache(font);
for (p = text; *p; ++p) {
Find_Glyph(font, *p, CACHED_METRICS|CACHED_PIXMAP);
}
return 0;
}
int TTF_Render(u8 *target, char *text, TTF_Font *font, int style, int x, int y, color col, u8 hotspot)
{
if (!target || !text || !font)
return -1;
TTF_SetFontStyle(font, style);
<API key>(target, text, font, x, y, col, hotspot);
return 0;
}
int load_fonts(void)
{
item *i;
if (!global_font)
global_font = TTF_OpenFont(cf.text_font, cf.text_size);
for (i = fonts.head; i != NULL; i = i->next) {
font_e *fe = (font_e*) i->p;
if (!fe->font) {
fe->font = TTF_OpenFont(fe->file, fe->size);
}
}
return 0;
}
int free_fonts(void)
{
item *i, *j;
if (global_font) {
TTF_CloseFont(global_font);
global_font = NULL;
}
for (i = fonts.head; i != NULL;) {
font_e *fe = (font_e*) i->p;
j = i->next;
if (fe->font)
TTF_CloseFont(fe->font);
if (fe->file)
free(fe->file);
free(fe);
free(i);
i = j;
}
fonts.head = NULL;
return 0;
} |
using Brunet;
using Brunet.Util;
using System;
namespace NetworkPackets {
/**
<summary>Unsupported, this class is too big to support now!</summary>
*/
public class IgmpPacket: NetworkPacket {
/**
<summary>Unsupported, this class is too big to support now!</summary>
*/
public enum Types { Join = 0x16, Leave = 0x17};
public readonly byte Type;
public readonly MemBlock GroupAddress;
public IgmpPacket(MemBlock packet) {
_icpacket = _packet = packet;
Type = packet[0];
GroupAddress = packet.Slice(4, 4);
_icpayload = _payload = packet.Slice(8);
}
public IgmpPacket(byte Type, MemBlock GroupAddress) {
// byte[] header = new byte[8];
}
}
} |
<?php
defined('JPATH_BASE') or die;
$d = $displayData;
if ($d->optsPerRow < 1)
{
$d->optsPerRow = 1;
}
if ($d->optsPerRow > 12)
{
$d->optsPerRow = 12;
}
$label = isset($d->option) ? $d->option->text : '';
$value = isset($d->option) ? $d->option->value : '';
$colSize = floor(floatval(12) / $d->optsPerRow);
$colClass = (int) $colSize === 12 ? '' : 'class="span' . $colSize . '"';
?>
<div <?php echo $colClass;?> data-role="suboption">
<label class="radio">
<input type="radio" value="<?php echo $value;?>" <?php echo $d->checked;?> data-role="fabrikinput" name="<?php echo $d->name; ?>" class="fabrikinput" />
<span><?php echo $label;?></span>
</label>
</div> |
#ifndef _WSTHREADPOOL_H_
#define _WSTHREADPOOL_H_
#include "queue.h"
#include "fred.h"
#include "random.h"
#include "functionclosure.h"
extern "C"
{
// Forward declaration (see below).
void *wsthreadpool_worker (void *tp);
// The function type invoked by a call to create a thread.
typedef void *(*<API key>) (void *);
}
namespace markov
{
class wsthreadpool_base
{
public:
virtual void worker (int index) = 0;
};
/**
*
* A pool of threads that wait for work and run it.
* Uses work-stealing.
*
* @author Emery Berger
*/
template < int NTHREADS > class wsthreadpool:public wsthreadpool_base
{
public:
enum
{ <API key> = 1 };
wsthreadpool (void)
{
// Fire up all the threads in the pool.
for (int i = 0; i < NTHREADS; i++)
{
running[i] = true;
threads[i].create (wsthreadpool_worker,
new std::pair < wsthreadpool *, int >(this, i));
}
}
// Place a task on the work queue to be picked up by a worker.
inline void queue_task (void *(*fn) (void *), void *data)
{
// Put the work on the local queue, using the thread id
// as the key. It might be better (& cheaper) to pass in
// the id explicitly.
task_queue[markov::fred::id () % NTHREADS].fifo_push
(new functionClosure (fn, data));
}
// The actual worker.
void worker (int myIndex)
{
// Look for work to do, first checking the local queue,
// and then going out and randomly checking other work queues.
markov::random rng;
functionClosure *t;
while (running[myIndex])
{
if (tryLocal (myIndex, t))
{
runIt (myIndex, t);
}
else
{
if (trySteal (rng.next () % NTHREADS, t))
{
runIt (myIndex, t);
}
}
}
}
// Kill one worker thread.
void killOne (void)
{
static int index = 0;
running[index] = false;
index++;
}
// Wait for all worker threads to terminate.
void wait (void)
{
for (int i = 0; i < NTHREADS; i++)
{
threads[i].join ();
}
}
private:
void runIt (int myIndex, functionClosure * t)
{
if (t == (functionClosure *) <API key>)
{
running[myIndex] = false;
}
else
{
t->run ();
delete t;
}
}
bool tryLocal (int index, functionClosure * &t)
{
bool gotWork = task_queue[index].fifo_trypop (t);
return gotWork;
}
bool trySteal (int index, functionClosure * &t)
{
bool gotWork = task_queue[index].lifo_trypop (t);
return gotWork;
}
// Run state of each thread.
volatile bool running[NTHREADS];
// Queue of work to do.
markov::queue < functionClosure * >task_queue[NTHREADS];
// The worker threads.
markov::fred threads[NTHREADS];
};
};
// A helper function, to be invoked by a call to pthread_create
// (which requires functions to have C linkage).
extern "C" void *
wsthreadpool_worker (void *tp)
{
std::pair < markov::wsthreadpool_base *, int >*p =
(std::pair < markov::wsthreadpool_base *, int >*) tp;
p->first->worker (p->second);
delete p;
return NULL;
}
#endif // _THREADPOOL_H_ |
<?php
/**
* @file views-view.tpl.php
* Main view template
*
* Variables available:
* - $classes_array: An array of classes determined in
* <API key>(). Default classes are:
* .view
* .view-[css_name]
* .view-id-[view_name]
* .view-display-id-[display_name]
* .view-dom-id-[dom_id]
* - $classes: A string version of $classes_array for use in the class attribute
* - $css_name: A css-safe version of the view name.
* - $css_class: The user-specified classes names, if any
* - $header: The view header
* - $footer: The view footer
* - $rows: The results of the view query, if any
* - $empty: The empty text to display if the view is empty
* - $pager: The pager next/prev links to display, if any
* - $exposed: Exposed widget form/info to display
* - $feed_icon: Feed icon to display, if any
* - $more: A link to view more, if any
*
* @ingroup views_templates
*/
?>
<div class="<?php print $classes; ?>">
<?php print render($title_prefix); ?>
<?php if ($title): ?>
<?php print $title; ?>
<?php endif; ?>
<?php print render($title_suffix); ?>
<?php if ($header): ?>
<div class="view-header">
<?php print $header; ?>
</div>
<?php endif; ?>
<?php if ($exposed): ?>
<div class="view-filters">
<?php print $exposed; ?>
</div>
<?php endif; ?>
<?php if ($attachment_before): ?>
<div class="attachment attachment-before">
<?php print $attachment_before; ?>
</div>
<?php endif; ?>
<?php if ($rows): ?>
<div class="view-content">
<?php print $rows; ?>
<div class="next-btn">></div>
<div class="last-btn"><</div>
</div>
<?php elseif ($empty): ?>
<div class="view-empty">
<?php print $empty; ?>
</div>
<?php endif; ?>
<?php if ($pager): ?>
<?php print $pager; ?>
<?php endif; ?>
<?php if ($attachment_after): ?>
<div class="attachment attachment-after">
<?php print $attachment_after; ?>
</div>
<?php endif; ?>
<?php if ($more): ?>
<?php print $more; ?>
<?php endif; ?>
<?php if ($footer): ?>
<div class="view-footer">
<?php print $footer; ?>
</div>
<?php endif; ?>
<?php if ($feed_icon): ?>
<div class="feed-icon">
<?php print $feed_icon; ?>
</div>
<?php endif; ?>
</div><?php /* class view */ ?>
<script>
jQuery(document).ready(function(){
});
</script> |
using Server.Gumps;
using Server.Network;
using System;
using System.Collections;
using System.IO;
namespace Server.Engines.Help
{
public class MessageSentGump : Gump
{
private readonly string m_Name;
private readonly string m_Text;
private readonly Mobile m_Mobile;
public MessageSentGump(Mobile mobile, string name, string text)
: base(30, 30)
{
m_Name = name;
m_Text = text;
m_Mobile = mobile;
Closable = false;
AddPage(0);
AddBackground(0, 0, 92, 75, 0xA3C);
if (mobile != null && mobile.NetState != null && mobile.NetState.IsEnhancedClient)
AddBackground(5, 7, 82, 61, 9300);
else
{
AddImageTiled(5, 7, 82, 61, 0xA40);
AddAlphaRegion(5, 7, 82, 61);
}
AddImageTiled(9, 11, 21, 53, 0xBBC);
AddButton(10, 12, 0x7D2, 0x7D2, 0, GumpButtonType.Reply, 0);
AddHtmlLocalized(34, 28, 65, 24, 3001002, 0xFFFFFF, false, false); // Message
}
public override void OnResponse(NetState state, RelayInfo info)
{
m_Mobile.SendGump(new PageResponseGump(m_Mobile, m_Name, m_Text));
//m_Mobile.SendMessage( 0x482, "{0} tells you:", m_Name );
//m_Mobile.SendMessage( 0x482, m_Text );
}
}
public class PageQueueGump : Gump
{
private readonly PageEntry[] m_List;
public PageQueueGump(Mobile m)
: base(30, 30)
{
Add(new GumpPage(0));
if (m != null && m.NetState != null && m.NetState.IsEnhancedClient)
AddBackground(1, 1, 408, 446, 9300);
else
{
Add(new GumpImageTiled(0, 0, 410, 448, 0xA40));
Add(new GumpAlphaRegion(1, 1, 408, 446));
}
Add(new GumpLabel(180, 12, 2100, "Page Queue"));
ArrayList list = PageQueue.List;
for (int i = 0; i < list.Count;)
{
PageEntry e = (PageEntry)list[i];
if (e.Sender.Deleted)
{
e.AddResponse(e.Sender, "[Logout]");
PageQueue.Remove(e);
}
else
{
++i;
}
}
m_List = (PageEntry[])list.ToArray(typeof(PageEntry));
if (m_List.Length > 0)
{
Add(new GumpPage(1));
for (int i = 0; i < m_List.Length; ++i)
{
PageEntry e = m_List[i];
if (i >= 5 && (i % 5) == 0)
{
AddButton(368, 12, 0xFA5, 0xFA7, 0, GumpButtonType.Page, (i / 5) + 1);
Add(new GumpLabel(298, 12, 2100, "Next Page"));
Add(new GumpPage((i / 5) + 1));
AddButton(12, 12, 0xFAE, 0xFB0, 0, GumpButtonType.Page, (i / 5));
Add(new GumpLabel(48, 12, 2100, "Previous Page"));
}
string typeString = PageQueue.GetPageTypeName(e.Type);
string html = String.Format("[{0}] {1} <basefont color=#{2:X6}>[<u>{3}</u>]</basefont>", typeString, e.Message, e.Handler == null ? 0xFF0000 : 0xFF, e.Handler == null ? "Unhandled" : "Handling");
Add(new GumpHtml(12, 44 + ((i % 5) * 80), 350, 70, html, true, true));
AddButton(370, 44 + ((i % 5) * 80) + 24, 0xFA5, 0xFA7, i + 1, GumpButtonType.Reply, 0);
}
}
else
{
Add(new GumpLabel(12, 44, 2100, "The page queue is empty."));
}
}
public override void OnResponse(NetState state, RelayInfo info)
{
if (info.ButtonID >= 1 && info.ButtonID <= m_List.Length)
{
if (PageQueue.List.IndexOf(m_List[info.ButtonID - 1]) >= 0)
{
PageEntryGump g = new PageEntryGump(state.Mobile, m_List[info.ButtonID - 1]);
g.SendTo(state);
}
else
{
state.Mobile.SendGump(new PageQueueGump(state.Mobile));
state.Mobile.SendMessage("That page has been removed.");
}
}
}
}
public class PredefinedResponse
{
private static ArrayList m_List;
private string m_Title;
private string m_Message;
public PredefinedResponse(string title, string message)
{
m_Title = title;
m_Message = message;
}
public static ArrayList List
{
get
{
if (m_List == null)
m_List = Load();
return m_List;
}
}
public string Title
{
get
{
return m_Title;
}
set
{
m_Title = value;
}
}
public string Message
{
get
{
return m_Message;
}
set
{
m_Message = value;
}
}
public static PredefinedResponse Add(string title, string message)
{
if (m_List == null)
m_List = Load();
PredefinedResponse resp = new PredefinedResponse(title, message);
m_List.Add(resp);
Save();
return resp;
}
public static void Save()
{
if (m_List == null)
m_List = Load();
try
{
string path = Path.Combine(Core.BaseDirectory, "Data/pageresponse.cfg");
using (StreamWriter op = new StreamWriter(path))
{
for (int i = 0; i < m_List.Count; ++i)
{
PredefinedResponse resp = (PredefinedResponse)m_List[i];
op.WriteLine("{0}\t{1}", resp.Title, resp.Message);
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public static ArrayList Load()
{
ArrayList list = new ArrayList();
string path = Path.Combine(Core.BaseDirectory, "Data/pageresponse.cfg");
if (File.Exists(path))
{
try
{
using (StreamReader ip = new StreamReader(path))
{
string line;
while ((line = ip.ReadLine()) != null)
{
try
{
line = line.Trim();
if (line.Length == 0 || line.StartsWith("
continue;
string[] split = line.Split('\t');
if (split.Length == 2)
list.Add(new PredefinedResponse(split[0], split[1]));
}
catch
{
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
return list;
}
}
public class PredefGump : Gump
{
private const int LabelColor32 = 0xFFFFFF;
private readonly Mobile m_From;
private readonly PredefinedResponse m_Response;
public PredefGump(Mobile from, PredefinedResponse response)
: base(30, 30)
{
m_From = from;
m_Response = response;
from.CloseGump(typeof(PredefGump));
bool canEdit = (from.AccessLevel >= AccessLevel.GameMaster);
AddPage(0);
if (response == null)
{
if (from != null && from.NetState != null && from.NetState.IsEnhancedClient)
AddBackground(1, 1, 408, 446, 9300);
else
{
AddImageTiled(0, 0, 410, 448, 0xA40);
AddAlphaRegion(1, 1, 408, 446);
}
AddHtml(10, 10, 390, 20, Color(Center("Predefined Responses"), LabelColor32), false, false);
ArrayList list = PredefinedResponse.List;
AddPage(1);
int i;
for (i = 0; i < list.Count; ++i)
{
if (i >= 5 && (i % 5) == 0)
{
AddButton(368, 10, 0xFA5, 0xFA7, 0, GumpButtonType.Page, (i / 5) + 1);
AddLabel(298, 10, 2100, "Next Page");
AddPage((i / 5) + 1);
AddButton(12, 10, 0xFAE, 0xFB0, 0, GumpButtonType.Page, i / 5);
AddLabel(48, 10, 2100, "Previous Page");
}
PredefinedResponse resp = (PredefinedResponse)list[i];
string html = String.Format("<u>{0}</u><br>{1}", resp.Title, resp.Message);
AddHtml(12, 44 + ((i % 5) * 80), 350, 70, html, true, true);
if (canEdit)
{
AddButton(370, 44 + ((i % 5) * 80) + 24, 0xFA5, 0xFA7, 2 + (i * 3), GumpButtonType.Reply, 0);
if (i > 0)
AddButton(377, 44 + ((i % 5) * 80) + 2, 0x15E0, 0x15E4, 3 + (i * 3), GumpButtonType.Reply, 0);
else
AddImage(377, 44 + ((i % 5) * 80) + 2, 0x25E4);
if (i < (list.Count - 1))
AddButton(377, 44 + ((i % 5) * 80) + 70 - 2 - 16, 0x15E2, 0x15E6, 4 + (i * 3), GumpButtonType.Reply, 0);
else
AddImage(377, 44 + ((i % 5) * 80) + 70 - 2 - 16, 0x25E8);
}
}
if (canEdit)
{
if (i >= 5 && (i % 5) == 0)
{
AddButton(368, 10, 0xFA5, 0xFA7, 0, GumpButtonType.Page, (i / 5) + 1);
AddLabel(298, 10, 2100, "Next Page");
AddPage((i / 5) + 1);
AddButton(12, 10, 0xFAE, 0xFB0, 0, GumpButtonType.Page, i / 5);
AddLabel(48, 10, 2100, "Previous Page");
}
AddButton(12, 44 + ((i % 5) * 80), 0xFAB, 0xFAD, 1, GumpButtonType.Reply, 0);
AddHtml(45, 44 + ((i % 5) * 80), 200, 20, Color("New Response", LabelColor32), false, false);
}
}
else if (canEdit)
{
AddImageTiled(0, 0, 410, 250, 0xA40);
if (from.NetState.IsEnhancedClient)
AddBackground(1, 1, 408, 248, 9300);
else
AddAlphaRegion(1, 1, 408, 248);
AddHtml(10, 10, 390, 20, Color(Center("Predefined Response Editor"), LabelColor32), false, false);
AddButton(10, 40, 0xFB1, 0xFB3, 1, GumpButtonType.Reply, 0);
AddHtml(45, 40, 200, 20, Color("Remove", LabelColor32), false, false);
AddButton(10, 70, 0xFA5, 0xFA7, 2, GumpButtonType.Reply, 0);
AddHtml(45, 70, 200, 20, Color("Title:", LabelColor32), false, false);
AddTextInput(10, 90, 300, 20, 0, response.Title);
AddButton(10, 120, 0xFA5, 0xFA7, 3, GumpButtonType.Reply, 0);
AddHtml(45, 120, 200, 20, Color("Message:", LabelColor32), false, false);
AddTextInput(10, 140, 390, 100, 1, response.Message);
}
}
public string Center(string text)
{
return String.Format("<CENTER>{0}</CENTER>", text);
}
public string Color(string text, int color)
{
return String.Format("<BASEFONT COLOR=#{0:X6}>{1}</BASEFONT>", color, text);
}
public void AddTextInput(int x, int y, int w, int h, int id, string def)
{
AddImageTiled(x, y, w, h, 0xA40);
AddImageTiled(x + 1, y + 1, w - 2, h - 2, 0xBBC);
AddTextEntry(x + 3, y + 1, w - 4, h - 2, 0x480, id, def);
}
public override void OnResponse(NetState sender, RelayInfo info)
{
if (m_From.AccessLevel < AccessLevel.Administrator)
return;
if (m_Response == null)
{
int index = info.ButtonID - 1;
if (index == 0)
{
PredefinedResponse resp = new PredefinedResponse("", "");
ArrayList list = PredefinedResponse.List;
list.Add(resp);
m_From.SendGump(new PredefGump(m_From, resp));
}
else
{
--index;
int type = index % 3;
index /= 3;
ArrayList list = PredefinedResponse.List;
if (index >= 0 && index < list.Count)
{
PredefinedResponse resp = (PredefinedResponse)list[index];
switch (type)
{
case 0: // edit
{
m_From.SendGump(new PredefGump(m_From, resp));
break;
}
case 1: // move up
{
if (index > 0)
{
list.RemoveAt(index);
list.Insert(index - 1, resp);
PredefinedResponse.Save();
m_From.SendGump(new PredefGump(m_From, null));
}
break;
}
case 2: // move down
{
if (index < (list.Count - 1))
{
list.RemoveAt(index);
list.Insert(index + 1, resp);
PredefinedResponse.Save();
m_From.SendGump(new PredefGump(m_From, null));
}
break;
}
}
}
}
}
else
{
ArrayList list = PredefinedResponse.List;
switch (info.ButtonID)
{
case 1:
{
list.Remove(m_Response);
PredefinedResponse.Save();
m_From.SendGump(new PredefGump(m_From, null));
break;
}
case 2:
{
TextRelay te = info.GetTextEntry(0);
if (te != null)
m_Response.Title = te.Text;
PredefinedResponse.Save();
m_From.SendGump(new PredefGump(m_From, m_Response));
break;
}
case 3:
{
TextRelay te = info.GetTextEntry(1);
if (te != null)
m_Response.Message = te.Text;
PredefinedResponse.Save();
m_From.SendGump(new PredefGump(m_From, m_Response));
break;
}
}
}
}
}
public class PageEntryGump : Gump
{
private static readonly int[] m_AccessLevelHues = new int[]
{
2100, //Player
2122, //VIP
2122, //Counselor
2117, //Decorator
2117, //Spawner
2117, //GameMaster
2129, //Seer
2415, //Admin
2415, //Developer
2415, //CoOwner
2415 //Owner
};
private readonly PageEntry m_Entry;
private readonly Mobile m_Mobile;
public PageEntryGump(Mobile m, PageEntry entry)
: base(30, 30)
{
try
{
m_Mobile = m;
m_Entry = entry;
int buttons = 0;
int bottom = 356;
AddPage(0);
if (m != null && m.NetState != null && m.NetState.IsEnhancedClient)
AddBackground(1, 1, 408, 454, 9300);
else
{
AddImageTiled(0, 0, 410, 456, 0xA40);
AddAlphaRegion(1, 1, 408, 454);
}
AddPage(1);
AddLabel(18, 18, 2100, "Sent:");
AddLabelCropped(128, 18, 264, 20, 2100, entry.Sent.ToString());
AddLabel(18, 38, 2100, "Sender:");
AddLabelCropped(128, 38, 264, 20, 2100, String.Format("{0} {1} [{2}]", entry.Sender.RawName, entry.Sender.Location, entry.Sender.Map));
AddButton(18, bottom - (buttons * 22), 0xFAB, 0xFAD, 8, GumpButtonType.Reply, 0);
AddImageTiled(52, bottom - (buttons * 22) + 1, 340, 80, 0xA40/*0xBBC*//*0x2458*/);
AddImageTiled(53, bottom - (buttons * 22) + 2, 338, 78, 0xBBC/*0x2426*/);
AddTextEntry(55, bottom - (buttons++ * 22) + 2, 336, 78, 0x480, 0, "");
AddButton(18, bottom - (buttons * 22), 0xFA5, 0xFA7, 0, GumpButtonType.Page, 2);
AddLabel(52, bottom - (buttons++ * 22), 2100, "Predefined Response");
if (entry.Sender != m)
{
AddButton(18, bottom - (buttons * 22), 0xFA5, 0xFA7, 1, GumpButtonType.Reply, 0);
AddLabel(52, bottom - (buttons++ * 22), 2100, "Go to Sender");
}
AddLabel(18, 58, 2100, "Handler:");
if (entry.Handler == null)
{
AddLabelCropped(128, 58, 264, 20, 2100, "Unhandled");
AddButton(18, bottom - (buttons * 22), 0xFB1, 0xFB3, 5, GumpButtonType.Reply, 0);
AddLabel(52, bottom - (buttons++ * 22), 2100, "Delete Page");
AddButton(18, bottom - (buttons * 22), 0xFB7, 0xFB9, 4, GumpButtonType.Reply, 0);
AddLabel(52, bottom - (buttons++ * 22), 2100, "Handle Page");
}
else
{
AddLabelCropped(128, 58, 264, 20, m_AccessLevelHues[(int)entry.Handler.AccessLevel], entry.Handler.Name);
if (entry.Handler != m)
{
AddButton(18, bottom - (buttons * 22), 0xFA5, 0xFA7, 2, GumpButtonType.Reply, 0);
AddLabel(52, bottom - (buttons++ * 22), 2100, "Go to Handler");
}
else
{
AddButton(18, bottom - (buttons * 22), 0xFA2, 0xFA4, 6, GumpButtonType.Reply, 0);
AddLabel(52, bottom - (buttons++ * 22), 2100, "Abandon Page");
AddButton(18, bottom - (buttons * 22), 0xFB7, 0xFB9, 7, GumpButtonType.Reply, 0);
AddLabel(52, bottom - (buttons++ * 22), 2100, "Page Handled");
}
}
AddLabel(18, 78, 2100, "Page Location:");
AddLabelCropped(128, 78, 264, 20, 2100, String.Format("{0} [{1}]", entry.PageLocation, entry.PageMap));
AddButton(18, bottom - (buttons * 22), 0xFA5, 0xFA7, 3, GumpButtonType.Reply, 0);
AddLabel(52, bottom - (buttons++ * 22), 2100, "Go to Page Location");
if (entry.SpeechLog != null)
{
AddButton(18, bottom - (buttons * 22), 0xFA5, 0xFA7, 10, GumpButtonType.Reply, 0);
AddLabel(52, bottom - (buttons++ * 22), 2100, "View Speech Log");
}
AddLabel(18, 98, 2100, "Page Type:");
AddLabelCropped(128, 98, 264, 20, 2100, PageQueue.GetPageTypeName(entry.Type));
AddLabel(18, 118, 2100, "Message:");
AddHtml(128, 118, 250, 100, entry.Message, true, true);
AddPage(2);
ArrayList preresp = PredefinedResponse.List;
AddButton(18, 18, 0xFAE, 0xFB0, 0, GumpButtonType.Page, 1);
AddButton(410 - 18 - 32, 18, 0xFAB, 0xFAC, 9, GumpButtonType.Reply, 0);
if (preresp.Count == 0)
{
AddLabel(52, 18, 2100, "There are no predefined responses.");
}
else
{
AddLabel(52, 18, 2100, "Back");
for (int i = 0; i < preresp.Count; ++i)
{
AddButton(18, 40 + (i * 22), 0xFA5, 0xFA7, 100 + i, GumpButtonType.Reply, 0);
AddLabel(52, 40 + (i * 22), 2100, ((PredefinedResponse)preresp[i]).Title);
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public void Resend(NetState state)
{
PageEntryGump g = new PageEntryGump(m_Mobile, m_Entry);
g.SendTo(state);
}
public override void OnResponse(NetState state, RelayInfo info)
{
if (info.ButtonID != 0 && PageQueue.List.IndexOf(m_Entry) < 0)
{
state.Mobile.SendGump(new PageQueueGump(state.Mobile));
state.Mobile.SendMessage("That page has been removed.");
return;
}
switch (info.ButtonID)
{
case 0: // close
{
if (m_Entry.Handler != state.Mobile)
{
PageQueueGump g = new PageQueueGump(state.Mobile);
g.SendTo(state);
}
break;
}
case 1: // go to sender
{
Mobile m = state.Mobile;
if (m_Entry.Sender.Deleted)
{
m.SendMessage("That character no longer exists.");
}
else if (m_Entry.Sender.Map == null || m_Entry.Sender.Map == Map.Internal)
{
m.SendMessage("That character is not in the world.");
}
else
{
m_Entry.AddResponse(state.Mobile, "[Go Sender]");
m.MoveToWorld(m_Entry.Sender.Location, m_Entry.Sender.Map);
m.SendMessage("You have been teleported to that page's sender.");
Resend(state);
}
break;
}
case 2: // go to handler
{
Mobile m = state.Mobile;
Mobile h = m_Entry.Handler;
if (h != null)
{
if (h.Deleted)
{
m.SendMessage("That character no longer exists.");
}
else if (h.Map == null || h.Map == Map.Internal)
{
m.SendMessage("That character is not in the world.");
}
else
{
m_Entry.AddResponse(state.Mobile, "[Go Handler]");
m.MoveToWorld(h.Location, h.Map);
m.SendMessage("You have been teleported to that page's handler.");
Resend(state);
}
}
else
{
m.SendMessage("Nobody is handling that page.");
Resend(state);
}
break;
}
case 3: // go to page location
{
Mobile m = state.Mobile;
if (m_Entry.PageMap == null || m_Entry.PageMap == Map.Internal)
{
m.SendMessage("That location is not in the world.");
}
else
{
m_Entry.AddResponse(state.Mobile, "[Go PageLoc]");
m.MoveToWorld(m_Entry.PageLocation, m_Entry.PageMap);
state.Mobile.SendMessage("You have been teleported to the original page location.");
Resend(state);
}
break;
}
case 4: // handle page
{
if (m_Entry.Handler == null)
{
m_Entry.AddResponse(state.Mobile, "[Handling]");
m_Entry.Handler = state.Mobile;
state.Mobile.SendMessage("You are now handling the page.");
}
else
{
state.Mobile.SendMessage("Someone is already handling that page.");
}
Resend(state);
break;
}
case 5: // delete page
{
if (m_Entry.Handler == null)
{
m_Entry.AddResponse(state.Mobile, "[Deleting]");
PageQueue.Remove(m_Entry);
state.Mobile.SendMessage("You delete the page.");
PageQueueGump g = new PageQueueGump(state.Mobile);
g.SendTo(state);
}
else
{
state.Mobile.SendMessage("Someone is handling that page, it can not be deleted.");
Resend(state);
}
break;
}
case 6: // abandon page
{
if (m_Entry.Handler == state.Mobile)
{
m_Entry.AddResponse(state.Mobile, "[Abandoning]");
state.Mobile.SendMessage("You abandon the page.");
m_Entry.Handler = null;
}
else
{
state.Mobile.SendMessage("You are not handling that page.");
}
Resend(state);
break;
}
case 7: // page handled
{
if (m_Entry.Handler == state.Mobile)
{
m_Entry.AddResponse(state.Mobile, "[Handled]");
PageQueue.Remove(m_Entry);
m_Entry.Handler = null;
state.Mobile.SendMessage("You mark the page as handled, and remove it from the queue.");
PageQueueGump g = new PageQueueGump(state.Mobile);
g.SendTo(state);
}
else
{
state.Mobile.SendMessage("You are not handling that page.");
Resend(state);
}
break;
}
case 8: // Send message
{
TextRelay text = info.GetTextEntry(0);
if (text != null)
{
m_Entry.AddResponse(state.Mobile, "[Response] " + text.Text);
if (m_Entry.Sender.NetState != null)
{
m_Entry.Sender.SendGump(new MessageSentGump(m_Entry.Sender, state.Mobile.Name, text.Text));
}
else
{
ResponseEntry.AddEntry(new ResponseEntry(m_Entry.Sender, state.Mobile, text.Text));
}
//m_Entry.Sender.SendMessage( 0x482, "{0} tells you:", state.Mobile.Name );
//m_Entry.Sender.SendMessage( 0x482, text.Text );
}
Resend(state);
break;
}
case 9: // predef overview
{
Resend(state);
state.Mobile.SendGump(new PredefGump(state.Mobile, null));
break;
}
case 10: // View Speech Log
{
Resend(state);
if (m_Entry.SpeechLog != null)
{
Gump gump = new SpeechLogGump(m_Entry.Sender, m_Entry.SpeechLog);
state.Mobile.SendGump(gump);
}
break;
}
default:
{
int index = info.ButtonID - 100;
ArrayList preresp = PredefinedResponse.List;
if (index >= 0 && index < preresp.Count)
{
m_Entry.AddResponse(state.Mobile, "[PreDef] " + ((PredefinedResponse)preresp[index]).Title);
m_Entry.Sender.SendGump(new MessageSentGump(m_Entry.Sender, state.Mobile.Name, ((PredefinedResponse)preresp[index]).Message));
}
Resend(state);
break;
}
}
}
}
} |
# encoding: utf-8
# module PyQt4.QtCore
# from /usr/lib/python3/dist-packages/PyQt4/QtCore.<API key>.so
# by generator 1.135
# no doc
# imports
import sip as __sip
from .QAnimationGroup import QAnimationGroup
class <API key>(QAnimationGroup):
""" <API key>(QObject parent=None) """
def addPause(self, p_int): # real signature unknown; restored from __doc__
""" <API key>.addPause(int) -> QPauseAnimation """
return QPauseAnimation
def currentAnimation(self): # real signature unknown; restored from __doc__
""" <API key>.currentAnimation() -> QAbstractAnimation """
return QAbstractAnimation
def <API key>(self, *args, **kwargs): # real signature unknown
""" <API key>.<API key>[QAbstractAnimation] [signal] """
pass
def duration(self): # real signature unknown; restored from __doc__
""" <API key>.duration() -> int """
return 0
def event(self, QEvent): # real signature unknown; restored from __doc__
""" <API key>.event(QEvent) -> bool """
return False
def insertPause(self, p_int, p_int_1): # real signature unknown; restored from __doc__
""" <API key>.insertPause(int, int) -> QPauseAnimation """
return QPauseAnimation
def updateCurrentTime(self, p_int): # real signature unknown; restored from __doc__
""" <API key>.updateCurrentTime(int) """
pass
def updateDirection(self, <API key>): # real signature unknown; restored from __doc__
""" <API key>.updateDirection(QAbstractAnimation.Direction) """
pass
def updateState(self, <API key>, <API key>): # real signature unknown; restored from __doc__
""" <API key>.updateState(QAbstractAnimation.State, QAbstractAnimation.State) """
pass
def __init__(self, QObject_parent=None): # real signature unknown; restored from __doc__
pass |
<?php use_helper ("Grid", "Object"); ?>
<h1>Pagos Realizados</h1>
<br>
<?php echo include_partial('buscarSms', array('buscarsms' => $buscarsms )) ?>
<br>
<?php echo include_partial('exportar', array('detallesms' => $detallesms )) ?> |
<?php
class <API key> extends MissionFunctions
{
function __construct($Fleet)
{
$this->_fleet = $Fleet;
}
function TargetEvent()
{
global $db, $pricelist, $LANG,$CONF, $UNI;
$UsedPlanet = $GLOBALS['DATABASE']->getFirstCell("SELECT COUNT(*) FROM ".PLANETS." WHERE `id` = '".$this->_fleet['fleet_end_id']."';");
$Target2 = $GLOBALS['DATABASE']->uniquequery("SELECT id_owner, metal, crystal, deuterium,(metal + crystal + deuterium) as der_total FROM ".PLANETS." WHERE `id` = '".$this->_fleet['fleet_end_id']."';");
if(!$UsedPlanet)
{
$this->setState(FLEET_RETURN);
$this->SaveFleet();
}elseif($Target2['id_owner'] != 9999)
{
$this->setState(FLEET_RETURN);
$this->SaveFleet();
}
else{
$Target = $GLOBALS['DATABASE']->uniquequery("SELECT id_owner, metal, crystal, deuterium,(metal + crystal + deuterium) as der_total FROM ".PLANETS." WHERE `id` = '".$this->_fleet['fleet_end_id']."';");
$FleetRecord = explode(";", $this->_fleet['fleet_array']);
$RecyclerCapacity = 0;
$OtherFleetCapacity = 0;
foreach ($FleetRecord as $Item => $Group)
{
if (empty($Group))
continue;
$Class = explode (",", $Group);
if ($Class[0] == 209 || $Class[0] == 219)
$RecyclerCapacity += $pricelist[$Class[0]]['capacity'] * $Class[1];
else
$OtherFleetCapacity += 0;
}
$temporary = array('metal' => $Target['metal'],'crystal' => $Target['crystal'],'deuterium' => $Target['deuterium']);
$RecycledGoods = array('metal' => 0, 'crystal' => 0, 'deuterium' => 0);
$IncomingFleetGoods = $this->_fleet['<API key>'] + $this->_fleet['<API key>'] + $this->_fleet['<API key>'];
if ($IncomingFleetGoods > $OtherFleetCapacity)
$RecyclerCapacity -= ($IncomingFleetGoods - $OtherFleetCapacity);
if ($Target['der_total'] <= $RecyclerCapacity) {
$RecycledGoods['metal'] = $Target['metal'];
$RecycledGoods['crystal'] = $Target['crystal'];
$RecycledGoods['deuterium'] = $Target['deuterium'];
$temporary['metal'] -= $Target['metal'];
$temporary['crystal'] -= $Target['crystal'];
$temporary['deuterium'] -= $Target['deuterium'];
} elseif (($Target['metal'] > $RecyclerCapacity / 2) && ($Target['crystal'] > $RecyclerCapacity / 2)&& ($Target['deuterium'] > $RecyclerCapacity / 2)) {
$RecycledGoods['metal'] = $RecyclerCapacity / 2;
$RecycledGoods['crystal'] = $RecyclerCapacity / 2;
$RecycledGoods['deuterium'] = $RecyclerCapacity / 2;
$temporary['metal'] -= $RecyclerCapacity / 2;
$temporary['crystal'] -= $RecyclerCapacity / 2;
$temporary['deuterium'] -= $RecyclerCapacity / 2;
} elseif ($Target['metal'] > $Target['crystal']) {
$RecycledGoods['crystal'] = $Target['crystal'];
$temporary['crystal'] -= $Target['crystal'];
if ($Target['metal'] > ($RecyclerCapacity - $RecycledGoods['crystal'])){
$RecycledGoods['metal'] = $RecyclerCapacity - $RecycledGoods['crystal'];
$temporary['metal'] -= $RecyclerCapacity - $RecycledGoods['crystal'];}
else{
$RecycledGoods['metal'] = $Target['metal'];
$temporary['metal'] -= $Target['metal'];
}
} else {
$RecycledGoods['metal'] = $Target['metal'];
$temporary['metal'] -= $Target['metal'];
if ($Target['crystal'] > ($RecyclerCapacity - $RecycledGoods['metal'])){
$RecycledGoods['crystal'] = $RecyclerCapacity - $RecycledGoods['metal'];
$temporary['crystal'] -= $RecyclerCapacity - $RecycledGoods['metal'];
}
else{
$RecycledGoods['crystal'] = $Target['crystal'];
$temporary['crystal'] -= $Target['crystal'];
}
}
if($Target['id_owner'] = 9999 && empty($temporary['metal']) && empty($temporary['crystal']) && empty($temporary['deuterium'])){
$GLOBALS['DATABASE']->query("DELETE from ".PLANETS." where `id` = '".$this->_fleet['fleet_end_id']."';");
}else{
$GLOBALS['DATABASE']->query("UPDATE ".PLANETS." SET `metal` = `metal` - ".$RecycledGoods['metal'].", `crystal` = `crystal` - ".$RecycledGoods['crystal'].", `deuterium` = `deuterium` - ".$RecycledGoods['deuterium']." WHERE `id` = '".$this->_fleet['fleet_end_id']."';");
}
if($RecycledGoods['metal'] < 0) {
$RecycledGoods['metal'] = 0;
}
if($RecycledGoods['crystal'] < 0) {
$RecycledGoods['crystal'] = 0;
}
if($RecycledGoods['deuterium'] < 0) {
$RecycledGoods['deuterium'] = 0;
}
$GLOBALS['DATABASE']->query("UPDATE ".FLEETS." set `<API key>` = `<API key>` + ".$RecycledGoods['metal'].", `<API key>` = `<API key>` + ".$RecycledGoods['crystal'].", `<API key>` = `<API key>` + ".$RecycledGoods['deuterium']." where `fleet_id` = ".$this->_fleet['fleet_id']." ;");
if($RecycledGoods['metal'] == $CONF['asteroid_metal'] && $RecycledGoods['crystal'] == $CONF['asteroid_crystal'] && $RecycledGoods['deuterium'] == $CONF['asteroid_deuterium']){
$GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `darkmatter` = `darkmatter` + 5000 where `id` = ".$this->_fleet['fleet_owner'].";");
}
$LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']);
$Message = sprintf($LNG['<API key>'], pretty_number($RecycledGoods['metal']), $LNG['Metal'], pretty_number($RecycledGoods['crystal']), $LNG['Crystal'],pretty_number($RecycledGoods['deuterium']), $LNG['Deuterium']);
SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_start_time'], 5, $LNG['sys_mess_tower'], $LNG['sys_recy_report'], $Message);
$this->setState(FLEET_RETURN);
$this->SaveFleet();
}
}
function EndStayEvent()
{
return;
}
function ReturnEvent()
{
global $LANG;
$LNG = $this->getLanguage(NULL, $this->_fleet['fleet_owner']);
$Message = sprintf( $LNG['sys_tran_mess_owner'], 'Asteroid' , GetStartAdressLink($this->_fleet, ''), pretty_number($this->_fleet['<API key>']), $LNG['Metal'], pretty_number($this->_fleet['<API key>']), $LNG['Crystal'], pretty_number($this->_fleet['<API key>']), $LNG['Deuterium'] );
SendSimpleMessage($this->_fleet['fleet_owner'], 0, $this->_fleet['fleet_end_time'], 5, $LNG['sys_mess_tower'], $LNG['sys_mess_fleetback'], $Message);
$this->RestoreFleet();
}
}
?> |
# profiling_late.py
'''
Module to enable profiling timepoints. This module is loaded
only if the configuration file exists, see profiling.py for more information
'''
import os
import sys
import yaml
import cProfile
from kano.logging import logger
from kano.profiling import CONF_FILE
# load the configuration file
with open(CONF_FILE, 'r') as inp_conf:
conf = yaml.load(inp_conf)
myProfile = cProfile.Profile()
app_name = sys.argv[0]
point_current = ""
def has_key(d, k):
return type(d) is dict and k in d
def declare_timepoint(name, isStart):
global myProfile
global point_current
cmd = None
pythonProfile = False
# Check if the app is contained in the profiling conf file
if has_key(conf, app_name):
# Check if the timepoint name is contained in the profiling conf file
if has_key(conf[app_name], name):
ct = conf[app_name][name]
# Check if python profiler should be started for this timepoint
if has_key(ct, 'python'):
pythonProfile = True
if isStart:
if point_current:
logger.error('Stop profiling for point "{0}" and do "{1}" instead'.format(point_current, name))
myProfile.disable()
myProfile.clear()
point_current = name
myProfile.enable()
else:
if point_current != name:
logger.error('Can\'t stop point "{0}" since a profiling session for "{1}" is being run'.format(name, point_current))
else:
myProfile.disable()
# Check if the statfile location in specified
if ct['python']['statfile']:
try:
myProfile.dump_stats(ct['python']['statfile'])
except IOError as e:
if e.errno == 2:
logger.error('Path to "{}" probably does not exist'.format(ct['python']['statfile']))
else:
logger.error('dump_stats IOError: errno:{0}: {1} '.format(e.errno, e.strerror))
else:
logger.error('No statfile entry in profiling conf file "{}"'.format(CONF_FILE))
myProfile.clear()
point_current = ""
else:
logger.info('Profiling conf file doesnt enable the Python profiler for point {} at app {}'.format(name, app_name))
# Check if we want to run some other command at this timepoint
if isStart and has_key(ct, 'start_exec'):
cmd = ct['start_exec']
os.system(cmd)
if not isStart and has_key(ct, 'end_exec'):
cmd = ct['end_exec']
os.system(cmd)
else:
logger.info('Profiling conf file doesnt include point:{} for app {}'.format(name, app_name))
else:
logger.info('Profiling conf file doesnt include app:{}'.format(app_name))
logger.debug('timepoint '+name, transition=name, isStart=isStart, cmd=cmd, pythonProfile=pythonProfile) |
#include "yas.h"
#if YAS_ACC_DRIVER == <API key>
#define YAS_RANGE_2G (0)
#define YAS_RANGE_4G (1)
#define YAS_RANGE_8G (2)
#define YAS_RANGE YAS_RANGE_2G
#if YAS_RANGE == YAS_RANGE_2G
#define YAS_RESOLUTION (1024)
#elif YAS_RANGE == YAS_RANGE_4G
#define YAS_RESOLUTION (512)
#elif YAS_RANGE == YAS_RANGE_8G
#define YAS_RESOLUTION (256)
#else
#define YAS_RESOLUTION (1024)
#endif
#define YAS_GRAVITY_EARTH (9806550)
#define YAS_BOOT_TIME (500)
#define <API key> (0)
#define YAS_WHO_AM_I (0x0d)
#define YAS_WHO_AM_I_VAL (0x2a)
#define YAS_XYZ_DATA_CFG (0x0e)
#define YAS_CTRL_REG1 (0x2a)
#define YAS_CTRL_REG2 (0x2b)
#define YAS_FS_2G (0x00)
#define YAS_FS_4G (0x01)
#define YAS_FS_8G (0x02)
#if YAS_RANGE == YAS_RANGE_2G
#define YAS_FS YAS_FS_2G
#elif YAS_RANGE == YAS_RANGE_4G
#define YAS_FS YAS_FS_4G
#elif YAS_RANGE == YAS_RANGE_8G
#define YAS_FS YAS_FS_8G
#else
#define YAS_FS YAS_FS_2G
#endif
#define YAS_ODR_1HZ (0x38)
#define YAS_ODR_6HZ (0x30)
#define YAS_ODR_12HZ (0x28)
#define YAS_ODR_50HZ (0x20)
#define YAS_ODR_100HZ (0x18)
#define YAS_ODR_200HZ (0x10)
#define YAS_ODR_400HZ (0x08)
#define YAS_ODR_800HZ (0x00)
#define YAS_OUT_X_MSB (0x01)
#define YAS_ACTIVE (0x01)
#define YAS_RESET (0x40)
struct yas_odr {
int delay;
uint8_t odr;
int turn_on;
};
struct yas_module {
int initialized;
int enable;
int delay;
int position;
int turn_on;
uint8_t odr;
struct yas_driver_callback cbk;
};
static const struct yas_odr yas_odr_tbl[] = {
{2, YAS_ODR_800HZ, 3},
{3, YAS_ODR_400HZ, 5},
{5, YAS_ODR_200HZ, 10},
{10, YAS_ODR_100HZ, 20},
{20, YAS_ODR_50HZ, 40},
{80, YAS_ODR_12HZ, 160},
{160, YAS_ODR_6HZ, 320},
{640, YAS_ODR_1HZ, 1283},
};
static const int yas_position_map[][3][3] = {
{ {-1, 0, 0}, { 0, -1, 0}, { 0, 0, 1} }, /* top/upper-left */
{ { 0, -1, 0}, { 1, 0, 0}, { 0, 0, 1} }, /* top/upper-right */
{ { 1, 0, 0}, { 0, 1, 0}, { 0, 0, 1} }, /* top/lower-right */
{ { 0, 1, 0}, {-1, 0, 0}, { 0, 0, 1} }, /* top/lower-left */
{ { 1, 0, 0}, { 0, -1, 0}, { 0, 0, -1} }, /* bottom/upper-left */
{ { 0, 1, 0}, { 1, 0, 0}, { 0, 0, -1} }, /* bottom/upper-right */
{ {-1, 0, 0}, { 0, 1, 0}, { 0, 0, -1} }, /* bottom/lower-right */
{ { 0, -1, 0}, {-1, 0, 0}, { 0, 0, -1} }, /* bottom/lower-right */
};
static struct yas_module module;
static int yas_read_reg(uint8_t adr, uint8_t *val);
static int yas_write_reg(uint8_t adr, uint8_t val);
static void yas_set_odr(int delay);
static int yas_power_up(void);
static int yas_power_down(void);
static int yas_init(void);
static int yas_term(void);
static int yas_get_delay(void);
static int yas_set_delay(int delay);
static int yas_get_enable(void);
static int yas_set_enable(int enable);
static int yas_get_position(void);
static int yas_set_position(int position);
static int yas_measure(struct yas_data *raw, int num);
static int yas_ext(int32_t cmd, void *result);
static int
yas_read_reg(uint8_t adr, uint8_t *val)
{
return module.cbk.device_read(YAS_TYPE_ACC, adr, val, 1);
}
static int
yas_write_reg(uint8_t adr, uint8_t val)
{
return module.cbk.device_write(YAS_TYPE_ACC, adr, &val, 1);
}
static void
yas_set_odr(int delay)
{
int i;
for (i = 1; i < NELEMS(yas_odr_tbl) &&
delay >= yas_odr_tbl[i].delay; i++)
;
module.odr = yas_odr_tbl[i-1].odr;
module.turn_on = (yas_odr_tbl[i-1].turn_on + 1) * 1000;
}
static int
yas_power_up(void)
{
if (yas_write_reg(YAS_CTRL_REG2, YAS_RESET) < 0)
return <API key>;
module.cbk.usleep(YAS_BOOT_TIME);
if (yas_write_reg(YAS_XYZ_DATA_CFG, YAS_FS) < 0)
return <API key>;
if (yas_write_reg(YAS_CTRL_REG1, module.odr | YAS_ACTIVE) < 0)
return <API key>;
module.cbk.usleep(module.turn_on);
return YAS_NO_ERROR;
}
static int
yas_power_down(void)
{
yas_write_reg(YAS_CTRL_REG1, 0x00);
return YAS_NO_ERROR;
}
static int
yas_init(void)
{
uint8_t id;
if (module.initialized == 1)
return <API key>;
module.cbk.usleep(YAS_BOOT_TIME);
if (module.cbk.device_open(YAS_TYPE_ACC) < 0)
return <API key>;
if (yas_read_reg(YAS_WHO_AM_I, &id) < 0) {
module.cbk.device_close(YAS_TYPE_ACC);
return <API key>;
}
if (id != YAS_WHO_AM_I_VAL) {
module.cbk.device_close(YAS_TYPE_ACC);
return YAS_ERROR_CHIP_ID;
}
module.enable = 0;
module.delay = <API key>;
module.position = <API key>;
yas_set_odr(module.delay);
yas_power_down();
module.cbk.device_close(YAS_TYPE_ACC);
module.initialized = 1;
return YAS_NO_ERROR;
}
static int
yas_term(void)
{
if (!module.initialized)
return <API key>;
yas_set_enable(0);
module.initialized = 0;
return YAS_NO_ERROR;
}
static int
yas_get_delay(void)
{
if (!module.initialized)
return <API key>;
return module.delay;
}
static int
yas_set_delay(int delay)
{
if (!module.initialized)
return <API key>;
if (delay < 0)
return YAS_ERROR_ARG;
module.delay = delay;
yas_set_odr(delay);
if (!module.enable)
return YAS_NO_ERROR;
if (yas_write_reg(YAS_CTRL_REG1, 0x00) < 0)
return <API key>;
if (yas_write_reg(YAS_CTRL_REG1, module.odr | YAS_ACTIVE) < 0)
return <API key>;
module.cbk.usleep(module.turn_on);
return YAS_NO_ERROR;
}
static int
yas_get_enable(void)
{
if (!module.initialized)
return <API key>;
return module.enable;
}
static int
yas_set_enable(int enable)
{
int rt;
if (!module.initialized)
return <API key>;
if (enable != 0)
enable = 1;
if (module.enable == enable)
return YAS_NO_ERROR;
if (enable) {
module.cbk.usleep(YAS_BOOT_TIME);
if (module.cbk.device_open(YAS_TYPE_ACC))
return <API key>;
rt = yas_power_up();
if (rt < 0) {
module.cbk.device_close(YAS_TYPE_ACC);
return rt;
}
} else {
yas_power_down();
module.cbk.device_close(YAS_TYPE_ACC);
}
module.enable = enable;
return YAS_NO_ERROR;
}
static int
yas_get_position(void)
{
if (!module.initialized)
return <API key>;
return module.position;
}
static int
yas_set_position(int position)
{
if (!module.initialized)
return <API key>;
if (position < 0 || position > 7)
return YAS_ERROR_ARG;
module.position = position;
return YAS_NO_ERROR;
}
static int
yas_measure(struct yas_data *raw, int num)
{
uint8_t buf[6];
int16_t dat[3];
int i, j;
if (!module.initialized)
return <API key>;
if (raw == NULL || num < 0)
return YAS_ERROR_ARG;
if (num == 0 || module.enable == 0)
return 0;
if (module.cbk.device_read(YAS_TYPE_ACC
, YAS_OUT_X_MSB
, buf
, 6) < 0)
return <API key>;
for (i = 0; i < 3; i++)
dat[i] = (int16_t)(((int16_t)((buf[i*2] << 8))
| buf[i*2+1]) >> 4);
for (i = 0; i < 3; i++) {
raw->xyz.v[i] = 0;
for (j = 0; j < 3; j++)
raw->xyz.v[i] += dat[j] *
yas_position_map[module.position][i][j];
raw->xyz.v[i] *= (YAS_GRAVITY_EARTH / YAS_RESOLUTION);
}
raw->type = YAS_TYPE_ACC;
if (module.cbk.current_time == NULL)
raw->timestamp = 0;
else
raw->timestamp = module.cbk.current_time();
raw->accuracy = 0;
return 1;
}
static int
yas_ext(int32_t cmd, void *result)
{
(void)cmd;
(void)result;
if (!module.initialized)
return <API key>;
return YAS_NO_ERROR;
}
int
yas_acc_driver_init(struct yas_acc_driver *f)
{
if (f == NULL
|| f->callback.device_open == NULL
|| f->callback.device_close == NULL
|| f->callback.device_write == NULL
|| f->callback.device_read == NULL
|| f->callback.usleep == NULL)
return YAS_ERROR_ARG;
f->init = yas_init;
f->term = yas_term;
f->get_delay = yas_get_delay;
f->set_delay = yas_set_delay;
f->get_enable = yas_get_enable;
f->set_enable = yas_set_enable;
f->get_position = yas_get_position;
f->set_position = yas_set_position;
f->measure = yas_measure;
f->ext = yas_ext;
module.cbk = f->callback;
yas_term();
return YAS_NO_ERROR;
}
#endif |
# PROBLEM 3
# Modify the below functions acceleration and
# ship_trajectory to plot the trajectory of a
# spacecraft with the given initial position
# and velocity. Use the Forward Euler Method
# to accomplish this.
#from udacityplots import *
import math
import numpy
import matplotlib
h = 1.0
earth_mass = 5.97e24
<API key> = 6.67e-11 # N m2 / kg2
def acceleration(spaceship_position):
distance = numpy.linalg.norm(spaceship_position)
direction = - spaceship_position / distance
acc = <API key> * earth_mass / distance ** 2 * direction
return acc
def ship_trajectory():
num_steps = 13000
x = numpy.zeros([num_steps + 1, 2])
v = numpy.zeros([num_steps + 1, 2]) # m / s
x[0, 0] = 15e6
x[0, 1] = 1e6
v[0, 0] = 2e3
v[0, 1] = 4e3
for step in range(num_steps):
x[step + 1] = x[step] + h * v[step]
v[step + 1] = v[step] + h * acceleration(x[step])
return x, v
x, v = ship_trajectory()
#@show_plot
def plot_me():
matplotlib.pyplot.plot(x[:, 0], x[:, 1])
matplotlib.pyplot.scatter(0, 0)
matplotlib.pyplot.axis('equal')
axes = matplotlib.pyplot.gca()
axes.set_xlabel('Longitudinal position in m')
axes.set_ylabel('Lateral position in m')
plot_me() |
package empleado;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.<API key>;
import javax.persistence.LockModeType;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import tarea.Tarea;
import departamento.Departamento;
public class ServicioEmpleadoImp implements ServicioEmpleado {
protected EntityManager entityManager;
public ServicioEmpleadoImp() {
<API key> <API key> = Persistence
.<API key>("todos");
this.entityManager = <API key>.createEntityManager();
}
@Override
public int crearEmpleado(Empleado empleado) {
entityManager.getTransaction().begin(); // empieza la transaccion
// id = 0 para nuevo empleado
int id = 0; // id del empleado
// comprueba que el departamento existe y esta activado
TypedQuery query_2 = entityManager.createQuery(
"SELECT d FROM Departamento d", Departamento.class); // ejecuta
// consulta
List<Departamento> departamentos = query_2.getResultList(); // obtiene
// la lista
// departamentos
Iterator<Departamento> it = departamentos.iterator();
Departamento d;
d = it.next();
boolean terminado = false;
while (it.hasNext() && !terminado) {
if (d.getNombre().equals(empleado.getDepartamento().getNombre())) {
terminado = true;
if (!d.isActivo())
id = -1;
} else {
// mira el siguiente elemento
d = it.next();
}
}
// comprueba que no hay empleados con el mismo dni
TypedQuery query = entityManager.createQuery(
"SELECT e FROM Empleado e", Empleado.class); // ejecuta la
// consulta
List<Empleado> empleados = query.getResultList(); // obtiene la lista de
// departamentos
for (Empleado e : empleados) {
if (empleado.getDni().equals(e.getDni())) {
if (e.isActivo()) {
id = -3;
} else {
// si existe pero no esta activo se da de alta ese con los
// nuevos datos
id = e.getId();
e.setActivo(true);
e.setDni(empleado.getDni());
e.setNombre_apellidos(empleado.getNombre_apellidos());
e.setSalario(empleado.getSalario());
e.setDepartamento(entityManager.find(Departamento.class,
d.getId(), LockModeType.<API key>));
entityManager.persist(e);
}
}
}
if (id >= 0) {// si el id es mayor o igual a 0 lo guarda
// si id = 0 quiere decir que se crea uina nueva, no se reactiva
if (id == 0) {
empleado.setDepartamento(entityManager.find(Departamento.class,
d.getId(), LockModeType.<API key>));
entityManager.persist(empleado); // lo guarda en la BD
entityManager.getTransaction().commit(); // realiza los cambios
id = empleado.getId();
}
// Si se va a dar de alta , en vez de crear, no hace falta coger el
else {
entityManager.getTransaction().commit(); // realiza los cambios
}
} else {
entityManager.getTransaction().rollback(); // no realiza cambios
}
return id;
}
@Override
public boolean bajaEmpleado(int id) {
entityManager.getTransaction().begin(); // empieza la transaccion
Empleado empleado = entityManager.find(Empleado.class, id,
LockModeType.OPTIMISTIC);
boolean correcto = false;
if (empleado != null) {
// solo se borran los empleados que no tengan tareas
if (empleado.getLista_tareas().isEmpty()) {
empleado.setActivo(false); // baja logica
// se elimina el empleado de ese departamento
empleado.getDepartamento().getLista_empleados()
.remove(empleado);
entityManager.persist(empleado);
correcto = true;
entityManager.getTransaction().commit(); // realiza los cambios
}
} else {
correcto = false;
entityManager.getTransaction().rollback(); // no realiza cambios
}
return correcto;
}
@Override
public Empleado buscarEmpleado(int id) {
entityManager.getTransaction().begin(); // empieza la transaccion
Empleado e = entityManager.find(Empleado.class, id,
LockModeType.OPTIMISTIC);
if (e != null) {
// si no esta activo el empleado no se muestra
if (!e.isActivo()) {
e = null;
}
}
return e;
}
@Override
public Collection<Empleado> <API key>() {
entityManager.getTransaction().begin();
List<Empleado> lista_empleados;
TypedQuery query = entityManager.createQuery(
// obtiene la lista de empleado
"SELECT e FROM Empleado e WHERE e.activo = 1", Empleado.class);
lista_empleados = query.getResultList();
entityManager.getTransaction().commit();
return lista_empleados;
}
@Override
public int asignarTarea(Tarea tarea) {
int id = 0;
entityManager.getTransaction().begin();
Empleado empleadoAasignar;
// Busca empleado en BD
int id_empleado = tarea.getLista_empleados().get(0).getId();
empleadoAasignar = entityManager.find(Empleado.class, id_empleado,
LockModeType.OPTIMISTIC);
// se comprueba que existe el empleado con ese id
// Busca Tarea en BD
Tarea tareaAasignar = entityManager.find(Tarea.class, tarea.getId(),
LockModeType.OPTIMISTIC);
// no existe o no activo
if (empleadoAasignar == null) {
id = -1;
} else if (!empleadoAasignar.isActivo()) {
id = -1;
} else {
for (Tarea t : empleadoAasignar.getLista_tareas()) {
if (empleadoAasignar != null) {
if (t.getId() == tareaAasignar.getId()) {
id = -3;
}
}
}
}
// no existe o no activo
if (tareaAasignar == null) {
id = -2;
} else if (!tareaAasignar.isActivo()) {
id = -2;
} else {
for (Empleado e : tareaAasignar.getLista_empleados()) {
if (empleadoAasignar != null) {
if (e.getId() == empleadoAasignar.getId()) {
id = -4;
}
}
}
}
// Los asigna a cada entidad
if (id >= 0) { // sino hay error
empleadoAasignar.getLista_tareas().add(tareaAasignar);
tareaAasignar.getLista_empleados().add(empleadoAasignar);
entityManager.persist(empleadoAasignar);
entityManager.persist(tareaAasignar);
entityManager.getTransaction().commit();
id = tareaAasignar.getId();
} else {
entityManager.getTransaction().rollback();
}
return id;
}
} |
"""
Module to control libvirtd service.
"""
import re
import logging
import aexpect
from avocado.utils import path
from avocado.utils import process
from avocado.utils import wait
from virttest import libvirt_version
from virttest import utils_split_daemons
from . import remote as remote_old
from . import utils_misc
from .staging import service
from .utils_gdb import GDB
try:
path.find_command("libvirtd")
LIBVIRTD = "libvirtd"
except path.CmdNotFoundError:
LIBVIRTD = None
class Libvirtd(object):
"""
Class to manage libvirtd service on host or guest.
"""
def __init__(self, service_name=None, session=None):
"""
Initialize an service object for libvirtd.
:params service_name: Service name such as virtqemud or libvirtd.
If service_name is None, all sub daemons will be operated when
modular daemon environment is enabled. Otherwise,if service_name is
a single string, only the given daemon/service will be operated.
:params session: An session to guest or remote host.
"""
self.session = session
if self.session:
self.remote_runner = remote_old.RemoteRunner(session=self.session)
runner = self.remote_runner.run
else:
runner = process.run
self.daemons = []
self.service_list = []
if LIBVIRTD is None:
logging.warning("Libvirtd service is not available in host, "
"utils_libvirtd module will not function normally")
self.service_name = "libvirtd" if not service_name else service_name
if libvirt_version.version_compare(5, 6, 0, self.session):
if utils_split_daemons.is_modular_daemon(session=self.session):
if self.service_name in ["libvirtd", "libvirtd.service"]:
self.service_list = ['virtqemud', 'virtproxyd',
'virtnetworkd', 'virtinterfaced',
'virtnodedevd', 'virtsecretd',
'virtstoraged', 'virtnwfilterd']
elif self.service_name == "libvirtd.socket":
self.service_name = "virtqemud.socket"
elif self.service_name in ["libvirtd-tcp.socket", "libvirtd-tls.socket"]:
self.service_name = re.sub("libvirtd", "virtproxyd",
self.service_name)
else:
self.service_name = re.sub("^virt.*d", "libvirtd",
self.service_name)
else:
self.service_name = "libvirtd"
if not self.service_list:
self.service_list = [self.service_name]
for serv in self.service_list:
self.daemons.append(service.Factory.create_service(serv, run=runner))
def _wait_for_start(self, timeout=60):
"""
Wait n seconds for libvirt to start. Default is 10 seconds.
"""
def _check_start():
virsh_cmd = "virsh list"
try:
if self.session:
self.session.cmd(virsh_cmd, timeout=2)
else:
process.run(virsh_cmd, timeout=2)
return True
except Exception:
return False
return utils_misc.wait_for(_check_start, timeout=timeout)
def start(self, reset_failed=True):
result = []
for daem_item in self.daemons:
if reset_failed:
daem_item.reset_failed()
if not daem_item.start():
return False
result.append(self._wait_for_start())
return all(result)
def stop(self):
result = []
for daem_item in self.daemons:
result.append(daem_item.stop())
return all(result)
def restart(self, reset_failed=True):
result = []
for daem_item in self.daemons:
if reset_failed:
daem_item.reset_failed()
if not daem_item.restart():
return False
result.append(self._wait_for_start())
return all(result)
def is_running(self):
result = []
for daem_item in self.daemons:
result.append(daem_item.status())
return all(result)
class DaemonSocket(object):
"""
Class to manage libvirt/virtproxy tcp/tls socket on host or guest.
"""
def __init__(self, daemon_name, session=None):
"""
Initialize an service object for virt daemons.
:param daemon_name: daemon name such as virtproxyd-tls.socket,
libvirtd-tcp.socket,etc,.
:param session: An session to guest or remote host.
"""
self.session = session
if self.session:
self.remote_runner = remote_old.RemoteRunner(session=self.session)
self.runner = self.remote_runner.run
else:
self.runner = process.run
self.daemon_name = daemon_name
supported_daemon = ["libvirtd-tcp.socket", "libvirtd-tls.socket",
"virtproxyd-tls.socket", "virtproxyd-tcp.socket"]
if self.daemon_name not in supported_daemon:
raise ValueError("Invalid daemon: %s" % self.daemon_name)
self.daemon_service_inst = Libvirtd("virtproxyd", session=self.session)
self.daemon_inst = Libvirtd(self.daemon_name, session=self.session)
self.daemon_socket = Libvirtd("virtproxyd.socket", session=self.session)
def stop(self):
self.daemon_socket.stop()
self.daemon_service_inst.stop()
self.daemon_inst.stop()
self.runner("systemctl daemon-reload")
self.daemon_socket.start()
def start(self):
self.daemon_socket.stop()
self.daemon_service_inst.stop()
self.runner("systemctl daemon-reload")
self.daemon_inst.start()
self.daemon_service_inst.start()
def restart(self, reset_failed=True):
self.daemon_socket.stop()
self.daemon_service_inst.stop()
self.runner("systemctl daemon-reload")
self.daemon_inst.restart()
self.daemon_service_inst.start()
self.daemon_inst._wait_for_start()
class LibvirtdSession(object):
"""
Interaction daemon session by directly call the command.
With gdb debugging feature can be optionally started.
It is recommended to use the service in the modular daemons for
initialization, because Libvirtd() class will switch to the
corresponding service according to the environment,
eg. If the value of "service_name" is "virtqemud",
it will take "virtqemud" if the modular daemon is enabled
and "libvirtd" if it's disabled.
"""
def __init__(self, gdb=False,
logging_handler=None,
logging_params=(),
logging_pattern=r'.*',
service_name=None):
"""
:param gdb: Whether call the session with gdb debugging support
:param logging_handler: Callback function to handle logging
:param logging_pattern: Regex for filtering specific log lines
:param service_name: Service name such as virtqemud or libvirtd
"""
self.gdb = None
self.tail = None
self.running = False
self.pid = None
self.service_name = service_name
self.bundle = {"stop-info": None}
# Get an executable program to debug by GDB
self.service_exec = Libvirtd(
service_name=self.service_name).service_list[0]
self.libvirtd_service = Libvirtd(service_name=self.service_exec)
self.was_running = self.libvirtd_service.is_running()
if self.was_running:
logging.debug('Stopping %s service', self.service_exec)
self.libvirtd_service.stop()
self.logging_handler = logging_handler
self.logging_params = logging_params
self.logging_pattern = logging_pattern
if gdb:
self.gdb = GDB(self.service_exec)
self.gdb.set_callback('stop', self._stop_callback, self.bundle)
self.gdb.set_callback('start', self._start_callback, self.bundle)
self.gdb.set_callback('termination', self.<API key>)
def _output_handler(self, line):
"""
Adapter output callback function.
"""
if self.logging_handler is not None:
if re.match(self.logging_pattern, line):
self.logging_handler(line, *self.logging_params)
def <API key>(self, status):
"""
Helper aexpect terminaltion handler
"""
self.running = False
self.exit_status = status
self.pid = None
def <API key>(self, gdb, status):
"""
Termination handler function triggered when libvirtd exited.
:param gdb: Instance of the gdb session
:param status: Return code of exited libvirtd session
"""
self.running = False
self.exit_status = status
self.pid = None
def _stop_callback(self, gdb, info, params):
"""
Stop handler function triggered when gdb libvirtd stopped.
:param gdb: Instance of the gdb session
:param status: Return code of exited libvirtd session
"""
self.running = False
params['stop-info'] = info
def _start_callback(self, gdb, info, params):
"""
Stop handler function triggered when gdb libvirtd started.
:param gdb: Instance of the gdb session
:param status: Return code of exited libvirtd session
"""
self.running = True
params['stop-info'] = None
def set_callback(self, callback_type, callback_func, callback_params=None):
"""
Set a customized gdb callback function.
"""
if self.gdb:
self.gdb.set_callback(
callback_type, callback_func, callback_params)
else:
logging.error("Only gdb session supports setting callback")
def start(self, arg_str='', wait_for_working=True):
"""
Start libvirtd session.
:param arg_str: Argument passing to the session
:param wait_for_working: Whether wait for libvirtd finish loading
"""
if self.gdb:
self.gdb.run(arg_str=arg_str)
self.pid = self.gdb.pid
else:
self.tail = aexpect.Tail(
"%s %s" % (self.service_exec, arg_str),
output_func=self._output_handler,
termination_func=self.<API key>,
)
self.running = True
if wait_for_working:
self.wait_for_working()
def cont(self):
"""
Continue a stopped libvirtd session.
"""
if self.gdb:
self.gdb.cont()
else:
logging.error("Only gdb session supports continue")
def kill(self):
"""
Kill the libvirtd session.
"""
if self.gdb:
self.gdb.kill()
else:
self.tail.kill()
def restart(self, arg_str='', wait_for_working=True):
"""
Restart the libvirtd session.
:param arg_str: Argument passing to the session
:param wait_for_working: Whether wait for libvirtd finish loading
"""
logging.debug("Restarting %s session", self.service_exec)
self.kill()
self.start(arg_str=arg_str, wait_for_working=wait_for_working)
def wait_for_working(self, timeout=60):
"""
Wait for libvirtd to work.
:param timeout: Max wait time
"""
logging.debug('Waiting for %s to work', self.service_exec)
return utils_misc.wait_for(
self.is_working,
timeout=timeout,
)
def back_trace(self):
"""
Get the backtrace from gdb session.
"""
if self.gdb:
return self.gdb.back_trace()
else:
logging.warning('Can not get back trace without gdb')
def insert_break(self, break_func):
"""
Insert a function breakpoint.
:param break_func: Function at which breakpoint inserted
"""
if self.gdb:
return self.gdb.insert_break(break_func)
else:
logging.warning('Can not insert breakpoint without gdb')
def is_working(self):
"""
Check if libvirtd is start by return status of 'virsh list'
"""
virsh_cmd = "virsh list"
try:
process.run(virsh_cmd, timeout=2)
return True
except process.CmdError:
return False
def wait_for_stop(self, timeout=60, step=0.1):
"""
Wait for libvirtd to stop.
:param timeout: Max wait time
:param step: Checking interval
"""
logging.debug('Waiting for %s to stop', self.service_exec)
if self.gdb:
return self.gdb.wait_for_stop(timeout=timeout)
else:
return wait.wait_for(
lambda: not self.running,
timeout=timeout,
step=step,
)
def <API key>(self, timeout=60):
"""
Wait for libvirtd gdb session to exit.
:param timeout: Max wait time
"""
logging.debug('Waiting for %s to terminate', self.service_exec)
if self.gdb:
return self.gdb.<API key>(timeout=timeout)
else:
logging.error("Only gdb session supports <API key>.")
def exit(self):
"""
Exit the libvirtd session.
"""
if self.gdb:
self.gdb.exit()
else:
if self.tail:
self.tail.close()
if self.was_running:
self.libvirtd_service.start()
def deprecation_warning():
"""
As the utils_libvirtd.libvirtd_xxx interfaces are deprecated,
this function are printing the warning to user.
"""
logging.warning("This function was deprecated, Please use "
"class utils_libvirtd.Libvirtd to manage "
"libvirtd service.")
def libvirtd_start():
libvirtd_instance = Libvirtd()
deprecation_warning()
return libvirtd_instance.start()
def libvirtd_is_running():
libvirtd_instance = Libvirtd()
deprecation_warning()
return libvirtd_instance.is_running()
def libvirtd_stop():
libvirtd_instance = Libvirtd()
deprecation_warning()
return libvirtd_instance.stop()
def libvirtd_restart():
libvirtd_instance = Libvirtd()
deprecation_warning()
return libvirtd_instance.restart()
def <API key>(action, session=None):
libvirtd_instance = Libvirtd(session=session)
deprecation_warning()
getattr(libvirtd_instance, action)()
def <API key>():
"""
By removing this file libvirt start behavior at boot
is simulated.
"""
cmd = "rm -rf /var/run/libvirt/storage/autostarted"
process.run(cmd, ignore_status=True, shell=True) |
module.exports = function( grunt ) {
var pkg = grunt.file.readJSON( 'package.json' );
console.log( pkg.title + ' - ' + pkg.version );
// Files to include/exclude in a release.
var distFiles = [
'**',
'!**/*~'
'includes*.php', |
namespace AZO_Library.ControlUtilitys.Forms
{
partial class SelectionOneRowBox
{
<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.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>();
System.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>();
System.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>();
System.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>();
System.Windows.Forms.<API key> <API key> = new System.Windows.Forms.<API key>();
this.btnAccept = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.dgdInformation = new System.Windows.Forms.DataGridView();
this.lblMessage = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dgdInformation)).BeginInit();
this.SuspendLayout();
// btnAccept
this.btnAccept.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnAccept.Location = new System.Drawing.Point(315, 226);
this.btnAccept.Name = "btnAccept";
this.btnAccept.Size = new System.Drawing.Size(75, 23);
this.btnAccept.TabIndex = 0;
this.btnAccept.TabStop = false;
this.btnAccept.Text = "Aceptar";
this.btnAccept.<API key> = true;
this.btnAccept.Click += new System.EventHandler(this.btnAccept_Click);
// btnCancel
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(397, 226);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 1;
this.btnCancel.TabStop = false;
this.btnCancel.Text = "Cancelar";
this.btnCancel.<API key> = true;
// dgdInformation
this.dgdInformation.AllowUserToAddRows = false;
this.dgdInformation.<API key> = false;
<API key>.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.dgdInformation.<API key> = <API key>;
this.dgdInformation.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
<API key>.Alignment = System.Windows.Forms.<API key>.MiddleLeft;
<API key>.BackColor = System.Drawing.SystemColors.Control;
<API key>.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
<API key>.ForeColor = System.Drawing.SystemColors.WindowText;
<API key>.SelectionBackColor = System.Drawing.SystemColors.Highlight;
<API key>.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
<API key>.WrapMode = System.Windows.Forms.<API key>.True;
this.dgdInformation.<API key> = <API key>;
this.dgdInformation.<API key> = System.Windows.Forms.<API key>.AutoSize;
<API key>.Alignment = System.Windows.Forms.<API key>.MiddleLeft;
<API key>.BackColor = System.Drawing.SystemColors.Window;
<API key>.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
<API key>.ForeColor = System.Drawing.SystemColors.ControlText;
<API key>.SelectionBackColor = System.Drawing.SystemColors.Highlight;
<API key>.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
<API key>.WrapMode = System.Windows.Forms.<API key>.False;
this.dgdInformation.DefaultCellStyle = <API key>;
this.dgdInformation.Location = new System.Drawing.Point(15, 44);
this.dgdInformation.MultiSelect = false;
this.dgdInformation.Name = "dgdInformation";
this.dgdInformation.ReadOnly = true;
<API key>.Alignment = System.Windows.Forms.<API key>.MiddleLeft;
<API key>.BackColor = System.Drawing.SystemColors.Control;
<API key>.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
<API key>.ForeColor = System.Drawing.SystemColors.WindowText;
<API key>.SelectionBackColor = System.Drawing.SystemColors.Highlight;
<API key>.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
<API key>.WrapMode = System.Windows.Forms.<API key>.True;
this.dgdInformation.<API key> = <API key>;
<API key>.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.dgdInformation.<API key> = <API key>;
this.dgdInformation.Size = new System.Drawing.Size(457, 167);
this.dgdInformation.TabIndex = 2;
// lblMessage
this.lblMessage.AutoSize = true;
this.lblMessage.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblMessage.Location = new System.Drawing.Point(12, 25);
this.lblMessage.Name = "lblMessage";
this.lblMessage.Size = new System.Drawing.Size(323, 16);
this.lblMessage.TabIndex = 3;
this.lblMessage.Text = "Selecciona la fila que contenga el resultado correcto:";
// SelectionOneRowBox
this.AcceptButton = this.btnAccept;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(484, 261);
this.Controls.Add(this.lblMessage);
this.Controls.Add(this.dgdInformation);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnAccept);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SelectionOneRowBox";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "SelectionOneRowBox";
((System.ComponentModel.ISupportInitialize)(this.dgdInformation)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnAccept;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.DataGridView dgdInformation;
private System.Windows.Forms.Label lblMessage;
}
} |
for i in *.[ch]
do
cat head.txt $i >$i.new && mv $i.new $i
done |
package com.espertech.esper.regression.view;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPStatement;
import com.espertech.esper.client.<API key>;
import com.espertech.esper.client.scopetest.EPAssertionUtil;
import com.espertech.esper.client.scopetest.<API key>;
import com.espertech.esper.support.bean.<API key>;
import com.espertech.esper.support.bean.SupportBeanString;
import com.espertech.esper.support.client.<API key>;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import junit.framework.TestCase;
public class <API key> extends TestCase
{
private static String SYMBOL_DELL = "DELL";
private static String SYMBOL_IBM = "IBM";
private EPServiceProvider epService;
private <API key> testListener;
public void setUp()
{
testListener = new <API key>();
epService = <API key>.getDefaultProvider(<API key>.getConfiguration());
epService.initialize();
}
protected void tearDown() throws Exception {
testListener = null;
}
public void testSumOneView()
{
// Every event generates a new row, this time we sum the price by symbol and output volume
String viewExpr = "select irstream symbol, volume, sum(price) as mySum " +
"from " + <API key>.class.getName() + ".win:length(3) " +
"where symbol='DELL' or symbol='IBM' or symbol='GE' " +
"group by symbol " +
"having sum(price) >= 50";
EPStatement selectTestView = epService.getEPAdministrator().createEPL(viewExpr);
selectTestView.addListener(testListener);
runAssertion(selectTestView);
}
public void testSumJoin()
{
// Every event generates a new row, this time we sum the price by symbol and output volume
String viewExpr = "select irstream symbol, volume, sum(price) as mySum " +
"from " + SupportBeanString.class.getName() + ".win:length(100) as one, " +
<API key>.class.getName() + ".win:length(3) as two " +
"where (symbol='DELL' or symbol='IBM' or symbol='GE') " +
" and one.theString = two.symbol " +
"group by symbol " +
"having sum(price) >= 50";
EPStatement selectTestView = epService.getEPAdministrator().createEPL(viewExpr);
selectTestView.addListener(testListener);
epService.getEPRuntime().sendEvent(new SupportBeanString(SYMBOL_DELL));
epService.getEPRuntime().sendEvent(new SupportBeanString(SYMBOL_IBM));
runAssertion(selectTestView);
}
private void runAssertion(EPStatement selectTestView)
{
// assert select result type
assertEquals(String.class, selectTestView.getEventType().getPropertyType("symbol"));
assertEquals(Long.class, selectTestView.getEventType().getPropertyType("volume"));
assertEquals(Double.class, selectTestView.getEventType().getPropertyType("mySum"));
String[] fields = "symbol,volume,mySum".split(",");
sendEvent(SYMBOL_DELL, 10000, 49);
assertFalse(testListener.isInvoked());
sendEvent(SYMBOL_DELL, 20000, 54);
EPAssertionUtil.assertProps(testListener.<API key>(), fields, new Object[]{SYMBOL_DELL, 20000L, 103d});
sendEvent(SYMBOL_IBM, 1000, 10);
assertFalse(testListener.isInvoked());
sendEvent(SYMBOL_IBM, 5000, 20);
EPAssertionUtil.assertProps(testListener.<API key>(), fields, new Object[]{SYMBOL_DELL, 10000L, 54d});
sendEvent(SYMBOL_IBM, 6000, 5);
assertFalse(testListener.isInvoked());
}
private void sendEvent(String symbol, long volume, double price)
{
<API key> bean = new <API key>(symbol, price, volume, null);
epService.getEPRuntime().sendEvent(bean);
}
private static final Log log = LogFactory.getLog(<API key>.class);
} |
<?php
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;
function <API key>() {
// Add our screen.
$hook = add_menu_page(
_x( 'Video', 'Admin Dashbord SWA page title', 'gampress' ),
_x( 'Video', 'Admin Dashbord SWA menu', 'gampress' ),
'gp_moderate',
'gp-video',
'gp_video_admin',
'div'
);
// Hook into early actions to load custom CSS and our init handler.
add_action( "load-$hook", 'gp_video_admin_load' );
}
add_action( gp_core_admin_hook(), '<API key>' );
function gp_video_admin_load() {
}
function gp_video_admin() {
// Decide whether to load the index or edit screen.
$doaction = ! empty( $_REQUEST['action'] ) ? $_REQUEST['action'] : '';
// Display the single activity edit screen.
if ( 'edit' == $doaction && ! empty( $_GET['aid'] ) )
<API key>();
// Otherwise, display the Activity index screen.
else
<API key>();
}
function <API key>() {
}
function <API key>() {
echo 'Simple Page';
}
function <API key>( $custom_menus = array() ) {
array_push( $custom_menus, 'gp-video' );
return $custom_menus;
}
add_filter( 'gp_admin_menu_order', '<API key>' ); |
#include "UmlNcRelation.h"
//Added by qt3to4:
#include <Q3CString>
Q3CString UmlNcRelation::sKind() {
return "non class relation";
}
void UmlNcRelation::html(Q3CString, unsigned int, unsigned int) {
}
void UmlNcRelation::memo_ref() {
} |
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/init.h>
#include <asm/oplib.h>
#include <asm/idprom.h>
struct idprom *idprom;
static struct idprom idprom_buffer;
/* Calculate the IDPROM checksum (xor of the data bytes). */
static unsigned char __init calc_idprom_cksum(struct idprom *idprom)
{
unsigned char cksum, i, *ptr = (unsigned char *)idprom;
for (i = cksum = 0; i <= 0x0E; i++)
cksum ^= *ptr++;
return cksum;
}
/* Create a local IDPROM copy and verify integrity. */
void __init idprom_init(void)
{
prom_get_idprom((char *) &idprom_buffer, sizeof(idprom_buffer));
idprom = &idprom_buffer;
if (idprom->id_format != 0x01) {
prom_printf("IDPROM: Warning, unknown format type!\n");
}
if (idprom->id_cksum != calc_idprom_cksum(idprom)) {
prom_printf("IDPROM: Warning, checksum failure (nvram=%x, calc=%x)!\n",
idprom->id_cksum, calc_idprom_cksum(idprom));
}
printk("Ethernet address: %02x:%02x:%02x:%02x:%02x:%02x\n",
idprom->id_ethaddr[0], idprom->id_ethaddr[1],
idprom->id_ethaddr[2], idprom->id_ethaddr[3],
idprom->id_ethaddr[4], idprom->id_ethaddr[5]);
} |
#if HAVE_CONFIG_H
# include "config.h"
#endif
#if TARGET_LINUX
#if STDC_HEADERS
# include <stdlib.h>
# include <stddef.h>
#else
# if HAVE_STDLIB_H
# include <stdlib.h>
# endif
#endif
#if HAVE_STRING_H
# if !STDC_HEADERS && HAVE_MEMORY_H
# include <memory.h>
# endif
# include <string.h>
#endif
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#if HAVE_STDIO_H
# include <stdio.h>
#endif
#if HAVE_FCNTL_H
# include <fcntl.h>
#endif
#if HAVE_UNISTD_H
# include <unistd.h>
#endif
#if HAVE_ERRNO_H
# include <errno.h>
#endif
#if HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#if HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
#if HAVE_NET_IF_H
# include <net/if.h>
#endif
#if HAVE_NETINET_IP_H
# include <netinet/ip.h>
#endif
#if HAVE_LINUX_IF_TUN_H
# include <linux/if_tun.h>
#endif
#include "tun/tun.h"
#include "options.h"
#include "log.h"
/* Allocate TUN device,
*/
int
tun_open_old ()
{
char tunname[14];
int i;
if (<API key>)
{
snprintf (tunname, sizeof(tunname), "/dev/%s", <API key>);
tun_fd = open (tunname, O_RDWR);
strncpy (tun_ifname, <API key>, sizeof(tun_ifname));
}
for (i = 0; i < 255; i++)
{
sprintf (tunname, "/dev/tun%d", i);
/* Open device */
if ((tun_fd = open (tunname, O_RDWR)) > 0)
{
sprintf (tun_ifname, "tun%d", i);
break;
}
}
if (!tun_ready ())
{
if (<API key>)
{
log (LOG_ERR, _("Unable to open tun device /dev/%s (using 2.2 kernel "
"method): %s(%d).\n"),
<API key>, strerror (errno),
errno);
}
else
{
log (LOG_ERR, _("Unable to open a valid tun device (using 2.2 kernel "
"method).\n"));
}
return 0;
}
fcntl(tun_fd, F_SETFL, O_NONBLOCK);
return 1;
}
#if HAVE_LINUX_IF_TUN_H
/* pre 2.4.6 compatibility */
#define OTUNSETNOCSUM (('T'<< 8) | 200)
#define OTUNSETDEBUG (('T'<< 8) | 201)
#define OTUNSETIFF (('T'<< 8) | 202)
#define OTUNSETPERSIST (('T'<< 8) | 203)
#define OTUNSETOWNER (('T'<< 8) | 204)
int
tun_open ()
{
struct ifreq ifr;
if ((tun_fd = open ("/dev/net/tun", O_RDWR)) < 0)
{
log (LOG_WARNING, _("Unable to open /dev/net/tun: %s(%d).\n"),
strerror (errno), errno);
log (LOG_WARNING, _("Assuming 2.2 kernel method.\n"));
return tun_open_old ();
}
memset (&ifr, 0, sizeof (ifr));
ifr.ifr_flags = IFF_TUN | IFF_NO_PI;
if (<API key>)
strncpy (ifr.ifr_name, <API key>, IFNAMSIZ);
if (ioctl (tun_fd, TUNSETIFF, (void *) &ifr) < 0)
{
if (errno == EBADFD)
{
/* Try old ioctl */
if (ioctl (tun_fd, OTUNSETIFF, (void *) &ifr) < 0)
{
log (LOG_ERR, _("Unable to open a valid tun device (using pre "
"2.4.6 kernel method): %s(%d).\n"),
strerror (errno), errno);
tun_close ();
return 0;
}
}
else
{
log (LOG_ERR, _("Unable to open a valid tun device (using post "
"2.4.6 kernel method): %s(%d).\n"), strerror (errno), errno);
tun_close ();
return 0;
}
}
strcpy(tun_ifname, ifr.ifr_name);
fcntl(tun_fd, F_SETFL, O_NONBLOCK);
return 1;
}
#else /* !HAVE_LINUX_IF_TUN_H */
int
tun_open ()
{
return tun_open_old ();
}
#endif /* HAVE_LINUX_IF_TUN_H */
int
tun_close ()
{
close (tun_fd);
tun_fd = -1;
return 1;
}
int
tun_ready ()
{
return (tun_fd != -1);
}
int
tun_have_packet(buffer)
buffer_t *buffer;
{
struct iphdr *ip;
ip = (struct iphdr *) buffer_start (buffer);
if (buffer->used < sizeof (struct iphdr))
return 0;
if (buffer->used < ntohs (ip->tot_len))
return 0;
return 1;
}
int
tun_get (buffer, data, data_size)
buffer_t *buffer;
char **data;
size_t *data_size;
{
struct iphdr *ip;
ip = (struct iphdr *) buffer_start (buffer);
if(!tun_have_packet(buffer))
return 0;
*data = (char *) ip;
*data_size = ntohs (ip->tot_len);
buffer_free (buffer, ntohs (ip->tot_len));
return 1;
}
int
tun_put (buffer, data, data_size)
buffer_t *buffer;
char *data;
size_t data_size;
{
char *p;
if (buffer_reserve (buffer, data_size))
{
p = buffer_end (buffer);
buffer_alloc (buffer, data_size);
memcpy (p, data, data_size);
return 1;
}
else {
log(LOG_WARNING, _("IP buffer is full, packet queued"));
return 0;
}
}
#endif /* TARGET_LINUX */ |
#include <linux/module.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/fcntl.h>
#include <linux/init.h>
#include <linux/skbuff.h>
#include <linux/interrupt.h>
#include <linux/notifier.h>
#include <net/sock.h>
#include <asm/system.h>
#include <linux/uaccess.h>
#include <asm/unaligned.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci_core.h>
#include <net/bluetooth/l2cap.h>
struct hci_conn *hci_le_connect(struct hci_dev *hdev, __u16 pkt_type,
bdaddr_t *dst, __u8 sec_level, __u8 auth_type,
struct bt_le_params *le_params)
{
struct hci_conn *le, *le_wlist_conn;
struct <API key> cp;
struct adv_entry *entry;
struct link_key *key;
BT_DBG("%p", hdev);
le = <API key>(hdev, LE_LINK, dst);
if (le) {
le_wlist_conn = <API key>(hdev, LE_LINK,
BDADDR_ANY);
if (!le_wlist_conn) {
hci_conn_hold(le);
return le;
} else {
BT_DBG("remove wlist conn");
le->out = 1;
le->link_mode |= HCI_LM_MASTER;
le->sec_level = BT_SECURITY_LOW;
le->type = LE_LINK;
<API key>(le, 0);
hci_conn_del(le_wlist_conn);
return le;
}
}
key = <API key>(hdev, dst, KEY_TYPE_LTK);
if (!key) {
entry = hci_find_adv_entry(hdev, dst);
if (entry)
le = hci_le_conn_add(hdev, dst,
entry->bdaddr_type);
else
le = hci_le_conn_add(hdev, dst, 0);
} else {
le = hci_le_conn_add(hdev, dst, key->addr_type);
}
if (!le)
return ERR_PTR(-ENOMEM);
hci_conn_hold(le);
le->state = BT_CONNECT;
le->out = 1;
le->link_mode |= HCI_LM_MASTER;
le->sec_level = BT_SECURITY_LOW;
le->type = LE_LINK;
memset(&cp, 0, sizeof(cp));
if (<API key>(le_params)) {
cp.supervision_timeout =
cpu_to_le16(le_params->supervision_timeout);
cp.scan_interval = cpu_to_le16(le_params->scan_interval);
cp.scan_window = cpu_to_le16(le_params->scan_window);
cp.conn_interval_min = cpu_to_le16(le_params->interval_min);
cp.conn_interval_max = cpu_to_le16(le_params->interval_max);
cp.conn_latency = cpu_to_le16(le_params->latency);
cp.min_ce_len = cpu_to_le16(le_params->min_ce_len);
cp.max_ce_len = cpu_to_le16(le_params->max_ce_len);
le->conn_timeout = le_params->conn_timeout;
} else {
cp.supervision_timeout = cpu_to_le16(<API key>);
cp.scan_interval = cpu_to_le16(<API key>);
cp.scan_window = cpu_to_le16(<API key>);
cp.conn_interval_min = cpu_to_le16(<API key>);
cp.conn_interval_max = cpu_to_le16(<API key>);
cp.conn_latency = cpu_to_le16(BT_LE_LATENCY_DEF);
le->conn_timeout = 5;
}
if (!bacmp(&le->dst, BDADDR_ANY)) {
cp.filter_policy = 0x01;
le->conn_timeout = 0;
} else {
bacpy(&cp.peer_addr, &le->dst);
cp.peer_addr_type = le->dst_type;
}
hci_send_cmd(hdev, <API key>, sizeof(cp), &cp);
return le;
}
EXPORT_SYMBOL(hci_le_connect);
static void <API key>(struct hci_conn *conn)
{
hci_send_cmd(conn->hdev, <API key>, 0, NULL);
}
void <API key>(struct hci_dev *hdev, bdaddr_t *dst)
{
struct hci_conn *le;
BT_DBG("%p", hdev);
le = <API key>(hdev, LE_LINK, dst);
if (le) {
BT_DBG("send hci connect cancel");
<API key>(le);
hci_conn_del(le);
}
}
EXPORT_SYMBOL(<API key>);
void <API key>(struct hci_dev *hdev, bdaddr_t *dst)
{
struct <API key> cp;
struct adv_entry *entry;
struct link_key *key;
BT_DBG("%p", hdev);
memset(&cp, 0, sizeof(cp));
bacpy(&cp.addr, dst);
key = <API key>(hdev, dst, KEY_TYPE_LTK);
if (!key) {
entry = hci_find_adv_entry(hdev, dst);
if (entry)
cp.addr_type = entry->bdaddr_type;
else
cp.addr_type = 0x00;
} else {
cp.addr_type = key->addr_type;
}
hci_send_cmd(hdev, <API key>, sizeof(cp), &cp);
}
EXPORT_SYMBOL(<API key>);
void <API key>(struct hci_dev *hdev, bdaddr_t *dst)
{
struct <API key> cp;
struct adv_entry *entry;
struct link_key *key;
BT_DBG("%p", hdev);
memset(&cp, 0, sizeof(cp));
bacpy(&cp.addr, dst);
key = <API key>(hdev, dst, KEY_TYPE_LTK);
if (!key) {
entry = hci_find_adv_entry(hdev, dst);
if (entry)
cp.addr_type = entry->bdaddr_type;
else
cp.addr_type = 0x00;
} else {
cp.addr_type = key->addr_type;
}
hci_send_cmd(hdev, <API key>, sizeof(cp), &cp);
}
EXPORT_SYMBOL(<API key>);
static inline bool <API key>(struct hci_dev *hdev)
{
if (<API key>(hdev, ACL_LINK, BT_CONNECTED))
return false;
return true;
}
void hci_acl_connect(struct hci_conn *conn)
{
struct hci_dev *hdev = conn->hdev;
struct inquiry_entry *ie;
struct hci_cp_create_conn cp;
BT_DBG("%p", conn);
conn->state = BT_CONNECT;
conn->out = 1;
conn->link_mode = HCI_LM_MASTER;
conn->attempt++;
conn->link_policy = hdev->link_policy;
memset(&cp, 0, sizeof(cp));
bacpy(&cp.bdaddr, &conn->dst);
cp.pscan_rep_mode = 0x02;
ie = <API key>(hdev, &conn->dst);
if (ie) {
if (inquiry_entry_age(ie) <= <API key>) {
cp.pscan_rep_mode = ie->data.pscan_rep_mode;
cp.pscan_mode = ie->data.pscan_mode;
cp.clock_offset = ie->data.clock_offset |
cpu_to_le16(0x8000);
}
memcpy(conn->dev_class, ie->data.dev_class, 3);
conn->ssp_mode = ie->data.ssp_mode;
}
cp.pkt_type = cpu_to_le16(conn->pkt_type);
if (lmp_rswitch_capable(hdev) && !(hdev->link_mode & HCI_LM_MASTER)
&& <API key>(hdev))
cp.role_switch = 0x01;
else
cp.role_switch = 0x00;
hci_send_cmd(hdev, HCI_OP_CREATE_CONN, sizeof(cp), &cp);
}
static void <API key>(struct hci_conn *conn)
{
struct <API key> cp;
BT_DBG("%p", conn);
if (conn->hdev->hci_ver < 2)
return;
bacpy(&cp.bdaddr, &conn->dst);
hci_send_cmd(conn->hdev, <API key>, sizeof(cp), &cp);
}
void hci_acl_disconn(struct hci_conn *conn, __u8 reason)
{
BT_DBG("%p", conn);
conn->state = BT_DISCONN;
if (conn->hdev->dev_type == HCI_BREDR) {
struct hci_cp_disconnect cp;
cp.handle = cpu_to_le16(conn->handle);
cp.reason = reason;
hci_send_cmd(conn->hdev, HCI_OP_DISCONNECT, sizeof(cp), &cp);
} else {
struct <API key> cp;
cp.phy_handle = (u8) conn->handle;
cp.reason = reason;
hci_send_cmd(conn->hdev, <API key>,
sizeof(cp), &cp);
}
}
void hci_add_sco(struct hci_conn *conn, __u16 handle)
{
struct hci_dev *hdev = conn->hdev;
struct hci_cp_add_sco cp;
BT_DBG("%p", conn);
conn->state = BT_CONNECT;
conn->out = 1;
conn->attempt++;
cp.handle = cpu_to_le16(handle);
cp.pkt_type = cpu_to_le16(conn->pkt_type);
hci_send_cmd(hdev, HCI_OP_ADD_SCO, sizeof(cp), &cp);
}
void hci_setup_sync(struct hci_conn *conn, __u16 handle)
{
struct hci_dev *hdev = conn->hdev;
struct <API key> cp;
BT_DBG("%p", conn);
conn->state = BT_CONNECT;
conn->out = 1;
conn->attempt++;
cp.handle = cpu_to_le16(handle);
cp.tx_bandwidth = cpu_to_le32(0x00001f40);
cp.rx_bandwidth = cpu_to_le32(0x00001f40);
if (conn->hdev->is_wbs) {
uint16_t voice_setting = hdev->voice_setting | ACF_TRANS;
cp.max_latency = cpu_to_le16(0x000D);
cp.pkt_type = cpu_to_le16(ESCO_WBS);
cp.voice_setting = cpu_to_le16(voice_setting);
cp.retrans_effort = RE_LINK_QUALITY;
} else {
cp.max_latency = cpu_to_le16(0x000A);
cp.pkt_type = cpu_to_le16(conn->pkt_type);
cp.voice_setting = cpu_to_le16(hdev->voice_setting);
cp.retrans_effort = RE_POWER_CONSUMP;
}
hci_send_cmd(hdev, <API key>, sizeof(cp), &cp);
}
void hci_le_conn_update(struct hci_conn *conn, u16 min, u16 max,
u16 latency, u16 to_multiplier)
{
struct <API key> cp;
struct hci_dev *hdev = conn->hdev;
memset(&cp, 0, sizeof(cp));
cp.handle = cpu_to_le16(conn->handle);
cp.conn_interval_min = cpu_to_le16(min);
cp.conn_interval_max = cpu_to_le16(max);
cp.conn_latency = cpu_to_le16(latency);
cp.supervision_timeout = cpu_to_le16(to_multiplier);
cp.min_ce_len = cpu_to_le16(0x0001);
cp.max_ce_len = cpu_to_le16(0x0001);
hci_send_cmd(hdev, <API key>, sizeof(cp), &cp);
}
EXPORT_SYMBOL(hci_le_conn_update);
void hci_read_rssi(struct hci_conn *conn)
{
struct hci_cp_read_rssi cp;
struct hci_dev *hdev = conn->hdev;
memset(&cp, 0, sizeof(cp));
cp.handle = cpu_to_le16(conn->handle);
hci_send_cmd(hdev, HCI_OP_READ_RSSI, sizeof(cp), &cp);
}
EXPORT_SYMBOL(hci_read_rssi);
void hci_le_start_enc(struct hci_conn *conn, __le16 ediv, __u8 rand[8],
__u8 ltk[16])
{
struct hci_dev *hdev = conn->hdev;
struct hci_cp_le_start_enc cp;
BT_DBG("%p", conn);
memset(&cp, 0, sizeof(cp));
cp.handle = cpu_to_le16(conn->handle);
memcpy(cp.ltk, ltk, sizeof(cp.ltk));
cp.ediv = ediv;
memcpy(cp.rand, rand, sizeof(cp.rand));
hci_send_cmd(hdev, HCI_OP_LE_START_ENC, sizeof(cp), &cp);
}
EXPORT_SYMBOL(hci_le_start_enc);
void hci_le_ltk_reply(struct hci_conn *conn, u8 ltk[16])
{
struct hci_dev *hdev = conn->hdev;
struct hci_cp_le_ltk_reply cp;
BT_DBG("%p", conn);
memset(&cp, 0, sizeof(cp));
cp.handle = cpu_to_le16(conn->handle);
memcpy(cp.ltk, ltk, sizeof(*ltk));
hci_send_cmd(hdev, HCI_OP_LE_LTK_REPLY, sizeof(cp), &cp);
}
EXPORT_SYMBOL(hci_le_ltk_reply);
void <API key>(struct hci_conn *conn)
{
struct hci_dev *hdev = conn->hdev;
struct <API key> cp;
BT_DBG("%p", conn);
memset(&cp, 0, sizeof(cp));
cp.handle = cpu_to_le16(conn->handle);
hci_send_cmd(hdev, <API key>, sizeof(cp), &cp);
}
void hci_sco_setup(struct hci_conn *conn, __u8 status)
{
struct hci_conn *sco = conn->link;
BT_DBG("%p", conn);
if (!sco)
return;
if (!status) {
if (lmp_esco_capable(conn->hdev))
hci_setup_sync(sco, conn->handle);
else
hci_add_sco(sco, conn->handle);
} else {
<API key>(sco, status);
hci_conn_del(sco);
}
}
static void hci_conn_timeout(unsigned long arg)
{
struct hci_conn *conn = (void *) arg;
struct hci_dev *hdev = conn->hdev;
__u8 reason;
BT_DBG("conn %p state %d", conn, conn->state);
hci_dev_lock(hdev);
switch (conn->state) {
case BT_CONNECT:
case BT_CONNECT2:
if (conn->out) {
if (conn->type == ACL_LINK)
<API key>(conn);
else if (conn->type == LE_LINK)
<API key>(conn);
}
break;
case BT_CONFIG:
case BT_CONNECTED:
if (!atomic_read(&conn->refcnt)) {
reason = <API key>(conn);
hci_acl_disconn(conn, reason);
}
break;
default:
if (!atomic_read(&conn->refcnt))
conn->state = BT_CLOSED;
break;
}
hci_dev_unlock(hdev);
}
static void hci_conn_idle(unsigned long arg)
{
struct hci_conn *conn = (void *) arg;
BT_DBG("conn %p mode %d", conn, conn->mode);
<API key>(conn);
}
static void <API key>(struct work_struct *work)
{
struct delayed_work *delayed =
container_of(work, struct delayed_work, work);
struct hci_conn *conn =
container_of(delayed, struct hci_conn, rssi_update_work);
BT_DBG("conn %p mode %d", conn, conn->mode);
hci_read_rssi(conn);
}
static void <API key>(unsigned long userdata)
{
struct hci_conn *conn = (struct hci_conn *)userdata;
BT_INFO("conn %p Grace Prd Exp ", conn);
hci_encrypt_cfm(conn, 0, 0);
if (test_bit(<API key>, &conn->pend)) {
struct <API key> cp;
BT_INFO("<API key> is set");
cp.handle = cpu_to_le16(conn->handle);
cp.encrypt = 1;
hci_send_cmd(conn->hdev, <API key>,
sizeof(cp), &cp);
}
}
struct hci_conn *hci_conn_add(struct hci_dev *hdev, int type,
__u16 pkt_type, bdaddr_t *dst)
{
struct hci_conn *conn;
BT_DBG("%s dst %s", hdev->name, batostr(dst));
conn = kzalloc(sizeof(struct hci_conn), GFP_ATOMIC);
if (!conn)
return NULL;
bacpy(&conn->dst, dst);
conn->hdev = hdev;
conn->type = type;
conn->mode = HCI_CM_ACTIVE;
conn->state = BT_OPEN;
conn->auth_type = <API key>;
conn->io_capability = hdev->io_capability;
conn->remote_auth = 0xff;
conn->power_save = 1;
conn->disc_timeout = HCI_DISCONN_TIMEOUT;
conn->conn_valid = true;
spin_lock_init(&conn->lock);
wake_lock_init(&conn->idle_lock, WAKE_LOCK_SUSPEND, "bt_idle");
switch (type) {
case ACL_LINK:
conn->pkt_type = hdev->pkt_type & ACL_PTYPE_MASK;
conn->link_policy = hdev->link_policy;
break;
case SCO_LINK:
if (!pkt_type)
pkt_type = SCO_ESCO_MASK;
case ESCO_LINK:
if (!pkt_type)
pkt_type = ALL_ESCO_MASK;
if (lmp_esco_capable(hdev)) {
conn->pkt_type = (pkt_type ^ EDR_ESCO_MASK) &
hdev->esco_type;
} else {
conn->pkt_type = (pkt_type << 5) & hdev->pkt_type &
SCO_PTYPE_MASK;
}
break;
}
skb_queue_head_init(&conn->data_q);
setup_timer(&conn->disc_timer, hci_conn_timeout, (unsigned long)conn);
setup_timer(&conn->idle_timer, hci_conn_idle, (unsigned long)conn);
INIT_DELAYED_WORK(&conn->rssi_update_work, <API key>);
setup_timer(&conn->encrypt_pause_timer, <API key>,
(unsigned long)conn);
atomic_set(&conn->refcnt, 0);
hci_dev_hold(hdev);
tasklet_disable(&hdev->tx_task);
hci_conn_hash_add(hdev, conn);
if (hdev->notify)
hdev->notify(hdev, HCI_NOTIFY_CONN_ADD);
atomic_set(&conn->devref, 0);
hci_conn_init_sysfs(conn);
tasklet_enable(&hdev->tx_task);
return conn;
}
struct hci_conn *hci_le_conn_add(struct hci_dev *hdev, bdaddr_t *dst,
__u8 addr_type)
{
struct hci_conn *conn = hci_conn_add(hdev, LE_LINK, 0, dst);
if (!conn)
return NULL;
conn->dst_type = addr_type;
return conn;
}
int hci_conn_del(struct hci_conn *conn)
{
struct hci_dev *hdev = conn->hdev;
BT_DBG("%s conn %p handle %d", hdev->name, conn, conn->handle);
spin_lock_bh(&conn->lock);
conn->conn_valid = false;
spin_unlock_bh(&conn->lock);
del_timer(&conn->idle_timer);
wake_lock_destroy(&conn->idle_lock);
del_timer(&conn->disc_timer);
del_timer(&conn->smp_timer);
<API key>(&conn->rssi_update_work);
del_timer(&conn->encrypt_pause_timer);
if (conn->type == ACL_LINK) {
struct hci_conn *sco = conn->link;
if (sco)
sco->link = NULL;
hdev->acl_cnt += conn->sent;
} else if (conn->type == LE_LINK) {
if (hdev->le_pkts)
hdev->le_cnt += conn->sent;
else
hdev->acl_cnt += conn->sent;
} else {
struct hci_conn *acl = conn->link;
if (acl) {
acl->link = NULL;
hci_conn_put(acl);
}
}
tasklet_disable(&hdev->tx_task);
hci_conn_hash_del(hdev, conn);
if (hdev->notify)
hdev->notify(hdev, HCI_NOTIFY_CONN_DEL);
tasklet_schedule(&hdev->tx_task);
tasklet_enable(&hdev->tx_task);
skb_queue_purge(&conn->data_q);
hci_conn_put_device(conn);
hci_dev_put(hdev);
return 0;
}
struct hci_chan *hci_chan_add(struct hci_dev *hdev)
{
struct hci_chan *chan;
BT_DBG("%s", hdev->name);
chan = kzalloc(sizeof(struct hci_chan), GFP_ATOMIC);
if (!chan)
return NULL;
atomic_set(&chan->refcnt, 0);
hci_dev_hold(hdev);
chan->hdev = hdev;
list_add(&chan->list, &hdev->chan_list.list);
return chan;
}
EXPORT_SYMBOL(hci_chan_add);
int hci_chan_del(struct hci_chan *chan)
{
BT_DBG("%s chan %p", chan->hdev->name, chan);
list_del(&chan->list);
hci_conn_put(chan->conn);
hci_dev_put(chan->hdev);
kfree(chan);
return 0;
}
int hci_chan_put(struct hci_chan *chan)
{
struct <API key> cp;
struct hci_conn *hcon;
u16 ll_handle;
BT_DBG("chan %p refcnt %d", chan, atomic_read(&chan->refcnt));
if (!atomic_dec_and_test(&chan->refcnt))
return 0;
hcon = chan->conn;
ll_handle = chan->ll_handle;
hci_chan_del(chan);
BT_DBG("chan->conn->state %d", hcon->state);
if (hcon->state == BT_CONNECTED) {
cp.log_handle = cpu_to_le16(ll_handle);
hci_send_cmd(hcon->hdev, <API key>,
sizeof(cp), &cp);
}
return 1;
}
EXPORT_SYMBOL(hci_chan_put);
struct hci_dev *hci_get_route(bdaddr_t *dst, bdaddr_t *src)
{
int use_src = bacmp(src, BDADDR_ANY);
struct hci_dev *hdev = NULL;
struct list_head *p;
BT_DBG("%s -> %s", batostr(src), batostr(dst));
read_lock_bh(&hci_dev_list_lock);
list_for_each(p, &hci_dev_list) {
struct hci_dev *d = list_entry(p, struct hci_dev, list);
if (d->dev_type != HCI_BREDR)
continue;
if (!test_bit(HCI_UP, &d->flags) || test_bit(HCI_RAW, &d->flags))
continue;
if (use_src) {
if (!bacmp(&d->bdaddr, src)) {
hdev = d; break;
}
} else {
if (bacmp(&d->bdaddr, dst)) {
hdev = d; break;
}
}
}
if (hdev)
hdev = hci_dev_hold(hdev);
read_unlock_bh(&hci_dev_list_lock);
return hdev;
}
EXPORT_SYMBOL(hci_get_route);
struct hci_dev *hci_dev_get_type(u8 amp_type)
{
struct hci_dev *hdev = NULL;
struct hci_dev *d;
BT_DBG("amp_type %d", amp_type);
read_lock_bh(&hci_dev_list_lock);
list_for_each_entry(d, &hci_dev_list, list) {
if ((d->amp_type == amp_type) && test_bit(HCI_UP, &d->flags)) {
hdev = d;
break;
}
}
if (hdev)
hdev = hci_dev_hold(hdev);
read_unlock_bh(&hci_dev_list_lock);
return hdev;
}
EXPORT_SYMBOL(hci_dev_get_type);
struct hci_dev *hci_dev_get_amp(bdaddr_t *dst)
{
struct hci_dev *d;
struct hci_dev *hdev = NULL;
BT_DBG("%s dst %s", hdev->name, batostr(dst));
read_lock_bh(&hci_dev_list_lock);
list_for_each_entry(d, &hci_dev_list, list) {
struct hci_conn *conn;
if (d->dev_type == HCI_BREDR)
continue;
conn = <API key>(d, ACL_LINK, dst);
if (conn) {
hdev = d;
break;
}
}
if (hdev)
hdev = hci_dev_hold(hdev);
read_unlock_bh(&hci_dev_list_lock);
return hdev;
}
EXPORT_SYMBOL(hci_dev_get_amp);
struct hci_conn *hci_connect(struct hci_dev *hdev, int type,
__u16 pkt_type, bdaddr_t *dst,
__u8 sec_level, __u8 auth_type)
{
struct hci_conn *acl;
struct hci_conn *sco;
BT_DBG("%s dst %s", hdev->name, batostr(dst));
if (type == LE_LINK)
return hci_le_connect(hdev, pkt_type, dst, sec_level,
auth_type, NULL);
acl = <API key>(hdev, ACL_LINK, dst);
if (!acl) {
acl = hci_conn_add(hdev, ACL_LINK, 0, dst);
if (!acl)
return NULL;
}
hci_conn_hold(acl);
if (acl->state == BT_OPEN || acl->state == BT_CLOSED) {
acl->sec_level = BT_SECURITY_LOW;
acl->pending_sec_level = sec_level;
acl->auth_type = auth_type;
hci_acl_connect(acl);
}
if (type == ACL_LINK)
return acl;
sco = <API key>(hdev, type, dst);
if (!sco && type == ESCO_LINK) {
sco = <API key>(hdev, SCO_LINK, dst);
} else if (!sco && type == SCO_LINK) {
sco = <API key>(hdev, ESCO_LINK, dst);
}
if (!sco) {
sco = hci_conn_add(hdev, type, pkt_type, dst);
if (!sco) {
hci_conn_put(acl);
return NULL;
}
}
acl->link = sco;
sco->link = acl;
hci_conn_hold(sco);
if (acl->state == BT_CONNECTED &&
(sco->state == BT_OPEN || sco->state == BT_CLOSED)) {
acl->power_save = 1;
<API key>(acl, 1);
if (test_bit(<API key>, &acl->pend)) {
set_bit(<API key>, &acl->pend);
return sco;
}
hci_sco_setup(acl, 0x00);
}
return sco;
}
EXPORT_SYMBOL(hci_connect);
void hci_disconnect(struct hci_conn *conn, __u8 reason)
{
BT_DBG("conn %p", conn);
<API key>(conn, reason, 0);
}
EXPORT_SYMBOL(hci_disconnect);
void hci_disconnect_amp(struct hci_conn *conn, __u8 reason)
{
struct hci_dev *hdev = NULL;
BT_DBG("conn %p", conn);
read_lock_bh(&hci_dev_list_lock);
list_for_each_entry(hdev, &hci_dev_list, list) {
struct hci_conn *c;
if (hdev == conn->hdev)
continue;
if (hdev->amp_type == HCI_BREDR)
continue;
c = <API key>(hdev, ACL_LINK, &conn->dst);
if (c)
hci_disconnect(c, reason);
}
read_unlock_bh(&hci_dev_list_lock);
}
int <API key>(struct hci_conn *conn)
{
BT_DBG("conn %p", conn);
if (conn->ssp_mode > 0 && conn->hdev->ssp_mode > 0 &&
!(conn->link_mode & HCI_LM_ENCRYPT))
return 0;
return 1;
}
EXPORT_SYMBOL(<API key>);
static int hci_conn_auth(struct hci_conn *conn, __u8 sec_level, __u8 auth_type)
{
BT_DBG("conn %p", conn);
if (conn->pending_sec_level > sec_level)
sec_level = conn->pending_sec_level;
if (sec_level > conn->sec_level)
conn->pending_sec_level = sec_level;
else if (conn->link_mode & HCI_LM_AUTH)
return 1;
auth_type |= (conn->auth_type & 0x01);
conn->auth_type = auth_type;
conn->auth_initiator = 1;
if (!test_and_set_bit(HCI_CONN_AUTH_PEND, &conn->pend)) {
struct <API key> cp;
set_bit(<API key>, &conn->pend);
cp.handle = cpu_to_le16(conn->handle);
hci_send_cmd(conn->hdev, <API key>,
sizeof(cp), &cp);
}
return 0;
}
int hci_conn_security(struct hci_conn *conn, __u8 sec_level, __u8 auth_type)
{
BT_DBG("conn %p %d %d", conn, sec_level, auth_type);
if (sec_level == BT_SECURITY_SDP)
return 1;
if (sec_level == BT_SECURITY_LOW &&
(!conn->ssp_mode || !conn->hdev->ssp_mode))
return 1;
if (conn->type == LE_LINK) {
if (conn->pending_sec_level > sec_level)
sec_level = conn->pending_sec_level;
if (sec_level > conn->sec_level)
conn->pending_sec_level = sec_level;
<API key>(conn, 0);
return 0;
} else if (conn->link_mode & HCI_LM_ENCRYPT) {
return hci_conn_auth(conn, sec_level, auth_type);
} else if (test_bit(<API key>, &conn->pend)) {
return 0;
}
if (hci_conn_auth(conn, sec_level, auth_type)) {
struct <API key> cp;
if (timer_pending(&conn->encrypt_pause_timer)) {
BT_INFO("encrypt_pause_timer is pending");
return 0;
}
cp.handle = cpu_to_le16(conn->handle);
cp.encrypt = 1;
hci_send_cmd(conn->hdev, <API key>,
sizeof(cp), &cp);
}
return 0;
}
EXPORT_SYMBOL(hci_conn_security);
int <API key>(struct hci_conn *conn)
{
BT_DBG("conn %p", conn);
if (!test_and_set_bit(HCI_CONN_AUTH_PEND, &conn->pend)) {
struct <API key> cp;
cp.handle = cpu_to_le16(conn->handle);
hci_send_cmd(conn->hdev, <API key>,
sizeof(cp), &cp);
}
return 0;
}
EXPORT_SYMBOL(<API key>);
int <API key>(struct hci_conn *conn, __u8 role)
{
BT_DBG("conn %p", conn);
if (!role && conn->link_mode & HCI_LM_MASTER)
return 1;
if (!test_and_set_bit(<API key>, &conn->pend)) {
struct hci_cp_switch_role cp;
bacpy(&cp.bdaddr, &conn->dst);
cp.role = role;
hci_send_cmd(conn->hdev, HCI_OP_SWITCH_ROLE, sizeof(cp), &cp);
}
return 0;
}
EXPORT_SYMBOL(<API key>);
void <API key>(struct hci_conn *conn, __u8 force_active)
{
struct hci_dev *hdev = conn->hdev;
BT_DBG("conn %p mode %d", conn, conn->mode);
if (test_bit(HCI_RAW, &hdev->flags))
return;
if (conn->type == LE_LINK)
return;
if (conn->mode != HCI_CM_SNIFF)
goto timer;
if (!conn->power_save && !force_active)
goto timer;
if (!test_and_set_bit(<API key>, &conn->pend)) {
struct <API key> cp;
cp.handle = cpu_to_le16(conn->handle);
hci_send_cmd(hdev, <API key>, sizeof(cp), &cp);
}
timer:
if (hdev->idle_timeout > 0) {
spin_lock_bh(&conn->lock);
if (conn->conn_valid) {
mod_timer(&conn->idle_timer,
jiffies + msecs_to_jiffies(hdev->idle_timeout));
wake_lock(&conn->idle_lock);
}
spin_unlock_bh(&conn->lock);
}
}
static inline void <API key>(struct hci_conn *conn)
{
BT_DBG("conn %p", conn);
cancel_delayed_work(&conn->rssi_update_work);
}
static inline void <API key>(struct hci_conn *conn,
u16 interval)
{
struct hci_dev *hdev = conn->hdev;
BT_DBG("conn %p, pending %d", conn,
<API key>(&conn->rssi_update_work));
if (!<API key>(&conn->rssi_update_work)) {
queue_delayed_work(hdev->workqueue, &conn->rssi_update_work,
msecs_to_jiffies(interval));
}
}
void <API key>(struct hci_conn *conn,
s8 rssi_threshold, u16 interval, u8 <API key>)
{
if (conn) {
conn->rssi_threshold = rssi_threshold;
conn-><API key> = interval;
conn-><API key> = <API key>;
<API key>(conn, interval);
}
}
void <API key>(struct hci_conn *conn)
{
if (conn) {
BT_DBG("Deleting the rssi_update_timer");
<API key>(conn);
}
}
void <API key>(struct hci_conn *conn)
{
struct hci_dev *hdev = conn->hdev;
BT_DBG("conn %p mode %d", conn, conn->mode);
if (test_bit(HCI_RAW, &hdev->flags))
return;
if (conn->type == LE_LINK)
return;
if (!lmp_sniff_capable(hdev) || !lmp_sniff_capable(conn))
return;
if (conn->mode != HCI_CM_ACTIVE ||
!(conn->link_policy & HCI_LP_SNIFF) ||
(hci_find_link_key(hdev, &conn->dst) == NULL))
return;
if (<API key>(hdev) && <API key>(conn)) {
struct <API key> cp;
cp.handle = cpu_to_le16(conn->handle);
cp.max_latency = cpu_to_le16(0);
cp.min_remote_timeout = cpu_to_le16(0);
cp.min_local_timeout = cpu_to_le16(0);
hci_send_cmd(hdev, <API key>, sizeof(cp), &cp);
}
if (!test_and_set_bit(<API key>, &conn->pend)) {
struct hci_cp_sniff_mode cp;
cp.handle = cpu_to_le16(conn->handle);
cp.max_interval = cpu_to_le16(hdev->sniff_max_interval);
cp.min_interval = cpu_to_le16(hdev->sniff_min_interval);
cp.attempt = cpu_to_le16(4);
cp.timeout = cpu_to_le16(1);
hci_send_cmd(hdev, HCI_OP_SNIFF_MODE, sizeof(cp), &cp);
}
}
struct hci_chan *hci_chan_create(struct hci_chan *chan,
struct hci_ext_fs *tx_fs, struct hci_ext_fs *rx_fs)
{
struct <API key> cp;
chan->state = BT_CONNECT;
chan->tx_fs = *tx_fs;
chan->rx_fs = *rx_fs;
cp.phy_handle = chan->conn->handle;
cp.tx_fs.id = chan->tx_fs.id;
cp.tx_fs.type = chan->tx_fs.type;
cp.tx_fs.max_sdu = cpu_to_le16(chan->tx_fs.max_sdu);
cp.tx_fs.sdu_arr_time = cpu_to_le32(chan->tx_fs.sdu_arr_time);
cp.tx_fs.acc_latency = cpu_to_le32(chan->tx_fs.acc_latency);
cp.tx_fs.flush_to = cpu_to_le32(chan->tx_fs.flush_to);
cp.rx_fs.id = chan->rx_fs.id;
cp.rx_fs.type = chan->rx_fs.type;
cp.rx_fs.max_sdu = cpu_to_le16(chan->rx_fs.max_sdu);
cp.rx_fs.sdu_arr_time = cpu_to_le32(chan->rx_fs.sdu_arr_time);
cp.rx_fs.acc_latency = cpu_to_le32(chan->rx_fs.acc_latency);
cp.rx_fs.flush_to = cpu_to_le32(chan->rx_fs.flush_to);
hci_conn_hold(chan->conn);
if (chan->conn->out)
hci_send_cmd(chan->conn->hdev, <API key>,
sizeof(cp), &cp);
else
hci_send_cmd(chan->conn->hdev, <API key>,
sizeof(cp), &cp);
return chan;
}
EXPORT_SYMBOL(hci_chan_create);
void hci_chan_modify(struct hci_chan *chan,
struct hci_ext_fs *tx_fs, struct hci_ext_fs *rx_fs)
{
struct <API key> cp;
chan->tx_fs = *tx_fs;
chan->rx_fs = *rx_fs;
cp.log_handle = cpu_to_le16(chan->ll_handle);
cp.tx_fs.id = tx_fs->id;
cp.tx_fs.type = tx_fs->type;
cp.tx_fs.max_sdu = cpu_to_le16(tx_fs->max_sdu);
cp.tx_fs.sdu_arr_time = cpu_to_le32(tx_fs->sdu_arr_time);
cp.tx_fs.acc_latency = cpu_to_le32(tx_fs->acc_latency);
cp.tx_fs.flush_to = cpu_to_le32(tx_fs->flush_to);
cp.rx_fs.id = rx_fs->id;
cp.rx_fs.type = rx_fs->type;
cp.rx_fs.max_sdu = cpu_to_le16(rx_fs->max_sdu);
cp.rx_fs.sdu_arr_time = cpu_to_le32(rx_fs->sdu_arr_time);
cp.rx_fs.acc_latency = cpu_to_le32(rx_fs->acc_latency);
cp.rx_fs.flush_to = cpu_to_le32(rx_fs->flush_to);
hci_conn_hold(chan->conn);
hci_send_cmd(chan->conn->hdev, <API key>, sizeof(cp),
&cp);
}
EXPORT_SYMBOL(hci_chan_modify);
void hci_conn_hash_flush(struct hci_dev *hdev, u8 is_process)
{
struct hci_conn_hash *h = &hdev->conn_hash;
struct list_head *p;
BT_DBG("hdev %s", hdev->name);
p = h->list.next;
while (p != &h->list) {
struct hci_conn *c;
c = list_entry(p, struct hci_conn, list);
p = p->next;
c->state = BT_CLOSED;
<API key>(c, 0x16, is_process);
hci_conn_del(c);
}
}
void <API key>(struct hci_dev *hdev)
{
struct hci_conn *conn;
BT_DBG("hdev %s", hdev->name);
hci_dev_lock(hdev);
conn = <API key>(hdev, ACL_LINK, BT_CONNECT2);
if (conn)
hci_acl_connect(conn);
hci_dev_unlock(hdev);
}
void <API key>(struct hci_conn *conn)
{
atomic_inc(&conn->devref);
}
EXPORT_SYMBOL(<API key>);
void hci_conn_put_device(struct hci_conn *conn)
{
if (atomic_dec_and_test(&conn->devref))
hci_conn_del_sysfs(conn);
}
EXPORT_SYMBOL(hci_conn_put_device);
int hci_get_conn_list(void __user *arg)
{
struct hci_conn_list_req req, *cl;
struct hci_conn_info *ci;
struct hci_dev *hdev;
struct list_head *p;
int n = 0, size, err;
if (copy_from_user(&req, arg, sizeof(req)))
return -EFAULT;
if (!req.conn_num || req.conn_num > (PAGE_SIZE * 2) / sizeof(*ci))
return -EINVAL;
size = sizeof(req) + req.conn_num * sizeof(*ci);
cl = kmalloc(size, GFP_KERNEL);
if (!cl)
return -ENOMEM;
hdev = hci_dev_get(req.dev_id);
if (!hdev) {
kfree(cl);
return -ENODEV;
}
ci = cl->conn_info;
hci_dev_lock_bh(hdev);
list_for_each(p, &hdev->conn_hash.list) {
register struct hci_conn *c;
c = list_entry(p, struct hci_conn, list);
bacpy(&(ci + n)->bdaddr, &c->dst);
(ci + n)->handle = c->handle;
(ci + n)->type = c->type;
(ci + n)->out = c->out;
(ci + n)->state = c->state;
(ci + n)->link_mode = c->link_mode;
if (c->type == SCO_LINK) {
(ci + n)->mtu = hdev->sco_mtu;
(ci + n)->cnt = hdev->sco_cnt;
(ci + n)->pkts = hdev->sco_pkts;
} else {
(ci + n)->mtu = hdev->acl_mtu;
(ci + n)->cnt = hdev->acl_cnt;
(ci + n)->pkts = hdev->acl_pkts;
}
if (++n >= req.conn_num)
break;
}
hci_dev_unlock_bh(hdev);
cl->dev_id = hdev->id;
cl->conn_num = n;
size = sizeof(req) + n * sizeof(*ci);
hci_dev_put(hdev);
err = copy_to_user(arg, cl, size);
kfree(cl);
return err ? -EFAULT : 0;
}
int hci_get_conn_info(struct hci_dev *hdev, void __user *arg)
{
struct hci_conn_info_req req;
struct hci_conn_info ci;
struct hci_conn *conn;
char __user *ptr = arg + sizeof(req);
if (copy_from_user(&req, arg, sizeof(req)))
return -EFAULT;
hci_dev_lock_bh(hdev);
conn = <API key>(hdev, req.type, &req.bdaddr);
if (conn) {
bacpy(&ci.bdaddr, &conn->dst);
ci.handle = conn->handle;
ci.type = conn->type;
ci.out = conn->out;
ci.state = conn->state;
ci.link_mode = conn->link_mode;
if (req.type == SCO_LINK) {
ci.mtu = hdev->sco_mtu;
ci.cnt = hdev->sco_cnt;
ci.pkts = hdev->sco_pkts;
} else {
ci.mtu = hdev->acl_mtu;
ci.cnt = hdev->acl_cnt;
ci.pkts = hdev->acl_pkts;
}
ci.pending_sec_level = conn->pending_sec_level;
ci.ssp_mode = conn->ssp_mode;
}
hci_dev_unlock_bh(hdev);
if (!conn)
return -ENOENT;
return copy_to_user(ptr, &ci, sizeof(ci)) ? -EFAULT : 0;
}
int hci_get_auth_info(struct hci_dev *hdev, void __user *arg)
{
struct hci_auth_info_req req;
struct hci_conn *conn;
if (copy_from_user(&req, arg, sizeof(req)))
return -EFAULT;
hci_dev_lock_bh(hdev);
conn = <API key>(hdev, ACL_LINK, &req.bdaddr);
if (conn)
req.type = conn->auth_type;
hci_dev_unlock_bh(hdev);
if (!conn)
return -ENOENT;
return copy_to_user(arg, &req, sizeof(req)) ? -EFAULT : 0;
}
int hci_set_auth_info(struct hci_dev *hdev, void __user *arg)
{
struct hci_auth_info_req req;
struct hci_conn *conn;
if (copy_from_user(&req, arg, sizeof(req)))
return -EFAULT;
hci_dev_lock_bh(hdev);
conn = <API key>(hdev, ACL_LINK, &req.bdaddr);
if (conn) {
conn->auth_type = req.type;
switch (conn->auth_type) {
case HCI_AT_NO_BONDING:
conn->pending_sec_level = BT_SECURITY_LOW;
break;
case <API key>:
case <API key>:
conn->pending_sec_level = BT_SECURITY_MEDIUM;
break;
case <API key>:
case <API key>:
conn->pending_sec_level = BT_SECURITY_HIGH;
break;
default:
break;
}
}
hci_dev_unlock_bh(hdev);
if (!conn)
return -ENOENT;
return copy_to_user(arg, &req, sizeof(req)) ? -EFAULT : 0;
} |
QMAKE_TARGET = MasterClientAppl
LUPDATE = $(QNX_HOST)/usr/bin/lupdate
LRELEASE = $(QNX_HOST)/usr/bin/lrelease
update: $(QMAKE_TARGET).pro FORCE
$(LUPDATE) $(QMAKE_TARGET).pro
release: $(QMAKE_TARGET).pro $(QMAKE_TARGET).ts
$(LRELEASE) $(QMAKE_TARGET).pro
FORCE: |
<?php
//echo "<br>".$_SERVER['REQUEST_URI'];
include('includes/session.inc');
$title = _('Journal Entry');
include('includes/header.inc');
include('includes/SQL_CommonFunctions.inc');
function filecheck($path)
{
$fn=explode("/",$path);
$mn=count($fn);
return $fn[$mn-1];
}
$sr=filecheck($_SERVER['HTTP_REFERER']);
$sel=filecheck($_SERVER['PHP_SELF']);
if($sr==$sel)
{
}
else
{
unset($_SESSION['date']);
unset($_SESSION['officername']);
unset($_SESSION['office']);
unset($_SESSION['own_authority']);
$tr="truncate table condem_item_group";
$trq=DB_query($tr,$db);
}
echo '<script type="text/javascript" src="calender/calendar.js"></script>
<link rel="stylesheet" type="text/css" href="calender/calender.css" media="all">';
if (isset($_POST['submit']) ){
$InputError = 0;
$disdate=$_POST['element_1_2']."-".$_POST['element_1_1']."-".$_POST['element_1_3'];
$purdate=$_POST['element_2_2']."-".$_POST['element_2_1']."-".$_POST['element_2_3'];
if(!isset($_SESSION['date']) || $_SESSION['date']=='')
{
$_SESSION['date']=strtotime($disdate);
}
if($_SESSION['officername']=='')
{
$_SESSION['officername']=$_POST['officername'];
}
if($_SESSION['office']=='')
{
$_SESSION['office']=$_POST['office'];
}
if($_SESSION['own_authority']=='')
{
$_SESSION['own_authority']=$_POST['own_authority'];
}
if(($_POST['element_1_2']=='' || $_POST['element_1_1']=='' || $_POST['element_1_3']=='') && $_SESSION['date']=='')
{
$InputError = 1;
prnMsg(_('Enter Date'),'error');
}
if($_POST['officername']=='')
{
$InputError = 1;
prnMsg(_('Enter Officer Name'),'error');
}
if (($_POST['officername']!='') && (!eregi('^[0-9a-zA-Z ]+$' , $_POST['officername'])))
{
$InputError = 1;
prnMsg(_('Enter valid Officer Name A-Z or 0-9 is Allowed'),'error');
}
if($_POST['office']=='')
{
$InputError = 1;
prnMsg(_('Select Office'),'error');
}
if($_POST['own_authority']=='')
{
$InputError = 1;
prnMsg(_('Enter Owning authority'),'error');
}
if (($_POST['own_authority']!='') && (!eregi('^[0-9a-zA-Z ]+$' , $_POST['own_authority'])))
{
$InputError = 1;
prnMsg(_('Enter valid Owning Authority, A-Z or 0-9 is Allowed'),'error');
}
if($_POST['sr_no']=='')
{
$InputError = 1;
prnMsg(_('Enter S. No.'),'error');
}
if (($_POST['sr_no']!='') && (!is_numeric($_POST['sr_no'])))
{
$InputError = 1;
prnMsg(_('Enter Numeric Value For S. No'),'error');
}
if($_POST['code']=='')
{
$InputError = 1;
prnMsg(_('Enter Item Code'),'error');
}
if($_POST['particulars']=='')
{
$InputError = 1;
prnMsg(_('Enter Particulars'),'error');
}
if (($_POST['particulars']!='') && (!eregi('^[0-9a-zA-Z ]+$' , $_POST['particulars'])))
{
$InputError = 1;
prnMsg(_('Enter valid Particulars, A-Z or 0-9 is Allowed'),'error');
}
if($_POST['quantity']=='')
{
$InputError = 1;
prnMsg(_('Enter Quantity'),'error');
}
if (($_POST['quantity']!='') && (!is_numeric($_POST['quantity'])))
{
$InputError = 1;
prnMsg(_('Enter Numeric Value For Quantity'),'error');
}
if($_POST['weight']=='')
{
$InputError = 1;
prnMsg(_('Enter Weight'),'error');
}
if (($_POST['weight']!='') && (!is_numeric($_POST['weight'])))
{
$InputError = 1;
prnMsg(_('Enter Numeric Value For Weight'),'error');
}
if( $_POST['element_2_2']=='' || $_POST['element_2_1']=='' || $_POST['element_2_3']=='' )
{
$InputError = 1;
prnMsg(_('Enter Purchase Date'),'error');
}
if($_POST['purchase_value']=='')
{
$InputError = 1;
prnMsg(_('Enter Purchase value'),'error');
}
if (($_POST['purchase_value']!='') && (!is_numeric($_POST['purchase_value'])))
{
$InputError = 1;
prnMsg(_('Enter Numeric Value For Purchase value'),'error');
}
if($_POST['present_condition']=='')
{
$InputError = 1;
prnMsg(_('Enter Present condition'),'error');
}
if (($_POST['present_condition']!='') && (!eregi('^[0-9a-zA-Z ]+$' , $_POST['present_condition'])))
{
$InputError = 1;
prnMsg(_('Enter valid Present Condition, A-Z or 0-9 is Allowed'),'error');
}
if($_POST['disposal_head']=='')
{
$InputError = 1;
prnMsg(_('Enter Head of account to which disposal proceeds to be credited'),'error');
}
if($_POST['debit_head']=='')
{
$InputError = 1;
prnMsg(_('Enter Head of account which the price of the article was debited at the time of purchase'),'error');
}
if($_POST['why_store']=='')
{
$InputError = 1;
prnMsg(_('Enter Why such store indented'),'error');
}
if (($_POST['why_store']!='') && (!eregi('^[0-9a-zA-Z ]+$' , $_POST['why_store'])))
{
$InputError = 1;
prnMsg(_('Enter valid Why Store Reason, A-Z or 0-9 is Allowed'),'error');
}
if($_POST['remark_page']=='')
{
$InputError = 1;
prnMsg(_('Enter Remarks ledger page no '),'error');
}
if (($_POST['remark_page']!='') && (!eregi('^[0-9a-zA-Z ]+$' , $_POST['remark_page'])))
{
$InputError = 1;
prnMsg(_('Enter valid Remarks ledger page no, A-Z or 0-9 is Allowed'),'error');
}
if($_POST['written_value']=='')
{
$InputError = 1;
prnMsg(_('Enter Written down value '),'error');
}
if (($_POST['written_value']!='') && (!is_numeric($_POST['written_value'])))
{
$InputError = 1;
prnMsg(_('Enter Numeric Value Written down value'),'error');
}
if($_POST['reserve_price']=='')
{
$InputError = 1;
prnMsg(_('Enter Reserve price fixed by the committee '),'error');
}
if (($_POST['reserve_price']!='') && (!is_numeric($_POST['reserve_price'])))
{
$InputError = 1;
prnMsg(_('Enter Numeric Value for Reserve Price'),'error');
}
if (($_POST['remarks']!='') && (!eregi('^[0-9a-zA-Z ]+$' , $_POST['remarks'])))
{
$InputError = 1;
prnMsg(_('Enter valid Remarks, A-Z or 0-9 is Allowed'),'error');
}
if($InputError!=1)
{
$it="select * from item_master where code='".$_POST['code']."'";
$itq=DB_query($it,$db);
$itn=DB_num_rows($itq);
$itr=DB_fetch_array($itq);
$qu=$itr['openingval'];
if($qu>=$_POST['quantity'])
{
$tqu=$qu-$_POST['quantity'];
$itu="update item_master set openingval='".$tqu."' where code='".$_POST['code']."'";
$ituq=DB_query($itu,$db);
$s="insert into condem_item_group set
sr_no='".$_POST['sr_no']."',
code='".$_POST['code']."',
particulars='".$_POST['particulars']."',
quantity='".$_POST['quantity']."',
weight='".$_POST['weight']."',
purchase_date='".strtotime($purdate)."',
purchase_value='".$_POST['purchase_value']."',
present_condition='".$_POST['present_condition']."',
disposal_head='".$_POST['disposal_head']."',
debit_head='".$_POST['debit_head']."',
why_store='".$_POST['why_store']."',
remark_page='".$_POST['remark_page']."',
written_value='".$_POST['written_value']."',
reserve_price='".$_POST['reserve_price']."',
remarks='".$_POST['remarks']."'";
$q=DB_query($s,$db);
if($q)
{
unset($_POST);
echo "<div class='success'>Condem Item has been added successfully</div>";
}
}
else
{
prnMsg(_('This Quantity Is Not Available In Stock'),'error');
}
}
}
if(isset($_POST['save']))
{
$con="select * from condem_item_group";
$conq=DB_query($con,$db);
while($conr=DB_fetch_array($conq))
{
$s1="insert into condem_item set date='".$_SESSION['date']."',
officername='".$_SESSION['officername']."',
office='".$_SESSION['office']."',
own_authority='".$_SESSION['own_authority']."',
sr_no='".$conr['sr_no']."',
code='".$conr['code']."',
particulars='".$conr['particulars']."',
quantity='".$conr['quantity']."',
weight='".$conr['weight']."',
purchase_date='".$conr['purchase_date']."',
purchase_value='".$conr['purchase_value']."',
present_condition='".$conr['present_condition']."',
disposal_head='".$conr['disposal_head']."',
debit_head='".$conr['debit_head']."',
why_store='".$conr['why_store']."',
remark_page='".$conr['remark_page']."',
written_value='".$conr['written_value']."',
reserve_price='".$conr['reserve_price']."',
remarks='".$conr['remarks']."'";
$q1=DB_query($s1,$db);
}
$tr="truncate table condem_item_group";
$trq=DB_query($tr,$db);
unset($_SESSION['date']);
unset($_SESSION['officername']);
unset($_SESSION['office']);
unset($_SESSION['own_authority']);
//neshat khan
//unset($_SESSION['officername']);
//unset($_SESSION['office']);
//unset($_SESSION['own_authority']);
}
?>
<link href="images/style.css" rel="stylesheet" type="text/css" />
<div class="breadcrumb">Home » <a href="<?php echo $_SERVER['PHP_SELF'];?>">Condemnation</a></div>
<form action="<?php $_SERVER['PHP_SELF']?>" method="post" name="form">
<input type="hidden" name="FormID" value="<?php echo $_SESSION['FormID'] ?>" />
<table cellpadding="2" cellspacing="1" border="0">
<tr class="oddrow"><td colspan="2" align="center"><h2>Condemnation</h2></td></tr>
<tr class="evenrow">
<td colspan="2"> <div class="left">Date: <span style="color:#FF0000">*</span></div>
<div class="right"><div id="li_1" style="width:353px;" >
<span>
<input id="element_1_2" name="element_1_2" class="element text" style="width:40px;" align="middle" size="2" maxlength="2" type="text" value="<?php echo $_POST['element_1_2'];?>" readonly="readonly">
<label for="element_1_2">DD</label>
</span>
<span>
<input id="element_1_1" name="element_1_1" class="element text" style="width:40px;" align="absmiddle" size="2" maxlength="2" type="text" value="<?php echo $_POST['element_1_1'];?>" readonly="readonly"> /
<label for="element_1_1">MM</label>
</span>
<span>
<input id="element_1_3" name="element_1_3" class="element text" style="width:67px;" align="middle" size="4" maxlength="4" type="text" value="<?php echo $_POST['element_1_2'];?>" readonly="readonly">/
<label for="element_1_3">YYYY</label>
</span>
<span id="calendar_1">
<img id="cal_img_1" class="datepicker" src="calendar.gif" alt="Pick a date."> </span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_1_3",
baseField : "element_1",
displayArea : "calendar_1",
button : "cal_img_1",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</div></div></td>
</tr>
<tr class="oddrow">
<td colspan="2"> <div class="left">Name of officer to be contacted: <span style="color:#FF0000">*</span></div>
<div class="right"><input type="text" name="officername" size="45" maxlength="45" value="<?php echo $_POST['officername'];?>"onkeypress="return alphanumeric(event)" ></div></td>
</tr>
<tr class="evenrow">
<td colspan="2"> <div class="left">Location of stores: <span style="color:#FF0000">*</span></div>
<div class="right"><select name="office"><option Value="">---Select Office-</option>
<?php
$sql = "SELECT loccode, locationname FROM locations";
$resultStkLocs = DB_query($sql,$db);
while ($myrow=DB_fetch_array($resultStkLocs)){
if($_POST['office']==$myrow['loccode'])
{
echo'<option Value="'.$myrow['loccode'].'" selected>'.$myrow['locationname'].'</option>';
}
else
{
echo'<option Value="'.$myrow['loccode'].'">'.$myrow['locationname'].'</option>';
}
}
?>
</select>
</div></td>
</tr>
<tr class="oddrow">
<td colspan="2"> <div class="left">Owning authority: <span style="color:#FF0000">*</span></div>
<div class="right"><input type="text" name="own_authority" size="45" maxlength="45" value="<?php echo $_POST['own_authority'];?>" onkeypress="return alphanumeric(event)" ></div></td>
</tr>
<tr class="evenrow"> <td colspan="2"> <div class="left">S. No.: <span style="color:#FF0000">*</span></div> <div class="right"><input type="text" name="sr_no" size="45" maxlength="10" value="<?php echo $_POST['sr_no']?>" onkeypress = "return fononlyn(event)" /></div></td></tr>
<tr class="oddrow"><td colspan="2"> <div class="left">Item Code: <span style="color:#FF0000">*</span></div><div class="right"><select name="code"><option value="">--Select Item--</option>
<?php
$ic="select code,name from item_master";
$icq=DB_query($ic,$db);
while($icr=Db_fetch_array($icq))
{ if($_POST['code']==$icr['code'])
{
echo '<option value="'.$icr['code'].'" selected>'.ucwords($icr['code']).'-'.ucwords($icr['name']).'</option>';
}
else
{
echo '<option value="'.$icr['code'].'">'.ucwords($icr['code']).'-'.ucwords($icr['name']).'</option>';
}
}
?>
</select></div></td></tr>
<tr class="evenrow"><td colspan="2"> <div class="left">Particulars of store items: <span style="color:#FF0000">*</span></div><div class="right"><input type="text" name="particulars" size="45" maxlength="45" value="<?php echo $_POST['particulars']?>"onkeypress="return alphanumeric(event)" /></div></td></tr>
<tr class="oddrow"><td colspan="2"> <div class="left">Quantity: <span style="color:#FF0000">*</span></div><div class="right"><input type="text" name="quantity" size="45" maxlength="10" value="<?php echo $_POST['quantity']?>" onkeypress = "return fononlyn(event)" /></div></td></tr>
<tr class="evenrow"><td colspan="2"> <div class="left">Weight: <span style="color:#FF0000">*</span></div> <div class="right"><input type="text" name="weight" size="45" maxlength="11" value="<?php echo $_POST['weight']?>" onkeypress = "return fononlyn(event)" /></div></tr>
<tr class="oddrow"><td colspan="2"> <div class="left">Date of Purchase: <span style="color:#FF0000">*</span></div><div class="right"><div id="li_2" style="width:353px;">
<span>
<input id="element_2_2" name="element_2_2" class="element text" style="width:40px;" align="middle" size="2" maxlength="2" type="text" value="<?php echo $_POST['element_2_2'];?>" readonly="readonly">
<label for="element_2_2">DD</label>
</span>
<span>
<input id="element_2_1" name="element_2_1" class="element text" style="width:40px;" align="middle" size="2" maxlength="2" type="text" value="<?php echo $_POST['element_2_1'];?>" readonly="readonly"> /
<label for="element_2_1">MM</label>
</span>
<span>
<input id="element_2_3" name="element_2_3" class="element text" style="width:67px;" align="middle" size="4" maxlength="4" type="text" value="<?php echo $_POST['element_2_3'];?>" readonly="readonly">/
<label for="element_2_3">YYYY</label>
</span>
<span id="calendar_2">
<img id="cal_img_2" class="datepicker" src="calendar.gif" alt="Pick a date."> </span>
<script type="text/javascript">
Calendar.setup({
inputField : "element_2_3",
baseField : "element_2",
displayArea : "calendar_2",
button : "cal_img_2",
ifFormat : "%B %e, %Y",
onSelect : selectDate
});
</script>
</div></div></td></tr>
<tr class="evenrow"> <td colspan="2"> <div class="left">Purchase Value: <span style="color:#FF0000">*</span></div> <div class="right"><input type="text" name="purchase_value" size="45" maxlength="11" value="<?php echo $_POST['purchase_value']?>" onkeypress = "return fononlyn(event)" /></div></td></tr>
<tr class="oddrow"><td colspan="2"> <div class="left">Present Condition: <span style="color:#FF0000">*</span></div> <div class="right"><input type="text" name="present_condition" size="45" maxlength="45" value="<?php echo $_POST['present_condition']?>" onkeypress="return alphanumeric(event)" /></div></td></tr>
<tr class="evenrow"><td colspan="2"> <div class="left">Head of account to which disposal proceeds to be credited: <span style="color:#FF0000">*</span></div>
<div class="right"><select name="disposal_head" ><option value="">--Select--</option>
<?php
$ac="select * from chartmaster ORDER BY accountname ASC";
$acq=DB_query($ac,$db);
while($acr=DB_fetch_array($acq))
{
if($_POST['disposal_head']==$acr['accountcode']) {?>
<option value="<?php echo ucwords($acr['accountcode']);?>" selected="selected"><?php echo ucwords ($acr['accountname']);?></option>
<?php
}
else {
?>
<option value="<?php echo ucwords( $acr['accountcode']);?>" ><?php echo ucwords ($acr['accountname']);?></option>
<?php
} }?>
</select></div></td></tr>
<tr class="oddrow"> <td colspan="2"> <div class="left">Head of account which the price of the article was debited at the time of purchase: <span style="color:#FF0000">*</span></div>
<div class="right"><select name="debit_head" ><option value="">--Select--</option>
<?php
$acd="select * from chartmaster ORDER BY accountname ASC";
$acdq=DB_query($acd,$db);
while($acrd=DB_fetch_array($acdq))
{
if($_POST['debit_head']==$acrd['accountcode']) {?>
<option value="<?php echo ucwords($acrd['accountcode']);?>" selected="selected"><?php echo ucwords($acrd['accountname']);?></option>
<?php
}
else {
?>
<option value="<?php echo ucwords ($acrd['accountcode']);?>"><?php echo ucwords($acrd['accountname']);?></option>
<?php
} }?>
</select></div></td></tr>
<tr class="evenrow"><td colspan="2"> <div class="left">Why such store indented: <span style="color:#FF0000">*</span></div> <div class="right"><input type="text" name="why_store" size="45" value="<?php echo $_POST['why_store']?>" maxlength="200" onkeypress="return alphanumeric(event)" /></div></td></tr>
<tr class="oddrow"><td colspan="2"> <div class="left">Remarks ledger page no: <span style="color:#FF0000">*</span></div><div class="right"><input type="text" name="remark_page" size="45" maxlength="10" value="<?php echo $_POST['remark_page']?>" onkeypress="return alphanumeric(event)" /></div></td></tr>
<tr class="evenrow"><td colspan="2"> <div class="left">Written down value: <span style="color:#FF0000">*</span></div> <div class="right"><input type="text" name="written_value" size="45" maxlength="11" value="<?php echo $_POST['written_value']?>" onkeypress = "return fononlyn(event)" /></div></td></tr>
<tr class="oddrow"><td colspan="2"> <div class="left">Reserve price fixed by the committee: <span style="color:#FF0000">*</span></div> <div class="right"><input type="text" name="reserve_price" size="45" maxlength="11" value="<?php echo $_POST['reserve_price']?>" onkeypress = "return fononlyn(event)" /></div></td></tr>
<tr class="evenrow"><td colspan="2"> <div class="left">Remarks: </div> <div class="right"><input type="text" name="remarks" size="45" maxlength="200" value="<?php echo $_POST['remarks']?>" onkeypress="return alphanumeric(event)" /></div></td></tr>
<tr class="oddrow"><td colspan="2" align="center"><input type="submit" name="submit" value="Submit" /> <input type="reset" name="reset" value="Reset" /></td>
</tr>
</table></form>
<?php
$sg="select * from condem_item_group";
$sgq=DB_query($sg,$db);
$sgn=Db_num_rows($sgq);
if($sgn)
{
$data="<form action='' method='post' name='form'>
<input type='hidden' name='FormID' value='". $_SESSION['FormID'] ."' />
<br/><table><tr><th>S. No.</th><th>Item Code</th><th>Quantity</th><th>Purchase Value</th><th>Present condition</th></tr>";
while($sgr=DB_fetch_array($sgq))
{
$data.="<tr class='even'><td>".$sgr['sr_no']."</td><td>".$sgr['code']."</td><td>".$sgr['quantity']."</td><td>".$sgr['purchase_value']."</td><td>".$sgr['present_condition']."</td></tr>";
}
$data.="<tr class='odd'><td colspan='6' align='center'><input type='submit' name='save' value='Save' /></td></tr></table></form>";
echo $data;
}
?>
<?php include('includes/footer.inc'); ?> |
// Rioplay - Replacement Rio Receiver player software
// This program is free software; you can redistribute it and/or
// version 2 as published by the Free Software Foundation.
// This program is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include "DisplayThread.hh"
#include "Stopwatch.h"
#include "Log.hh"
#include "MemAlloc.hh"
DisplayThread::DisplayThread(void) {
/* Initialize class variables */
TopScreenPtr = NULL;
BottomScreenPtr = NULL;
BacklightState = <API key>;
/* Open display device */
DisplayFD = open("/dev/display", O_RDWR);
if(DisplayFD < 0) {
Log::GetInstance()->Post(LOG_ERROR, __FILE__, __LINE__,
"Display: Could not open display");
return;
}
char *DisplayBuf = (char *) mmap(0, 4096, PROT_READ | PROT_WRITE,
MAP_SHARED, DisplayFD, 0);
Display.setBuffer(DisplayBuf);
/* Clear the display */
Display.setClipArea(0, 0, VFDLib::vfd_width, VFDLib::vfd_height);
Display.clear(VFDSHADE_BLACK);
Push();
/* Power on the display */
OnOff(1);
/* Show the splashscreen */
BottomScreenPtr = &Logo;
Logo.Update(Display);
Push();
}
DisplayThread::~DisplayThread(void) {
}
void *DisplayThread::ThreadMain(void *arg) {
while(1) {
/* Lock and wait for signal that display needs updating */
pthread_mutex_lock(&ClassMutex);
pthread_cond_wait(&ClassCondition, &ClassMutex);
if(TopScreenPtr != NULL) {
/* If the top screen ptr is not null, then there is a top
screen to display (top as in higher priority screen
than the bottom [for instance a menu screen should
"cover up" the audio player status screen]) */
if(TopChanged == true) {
Display.setClipArea(0, 0, VFDLib::vfd_width, VFDLib::vfd_height);
Display.clear(VFDSHADE_BLACK);
TopChanged = false;
}
TopScreenPtr->Update(Display);
}
else if(BottomScreenPtr != NULL) {
/* No top screen, but there is a bottom screen so show that */
if(BottomChanged == true) {
Display.setClipArea(0, 0, VFDLib::vfd_width, VFDLib::vfd_height);
Display.clear(VFDSHADE_BLACK);
BottomChanged = false;
}
BottomScreenPtr->Update(Display);
}
Push();
/* Unlock display */
<API key>(&ClassMutex);
}
}
void DisplayThread::SetTopScreen(Screen *ScreenPtr) {
pthread_mutex_lock(&ClassMutex);
TopScreenPtr = ScreenPtr;
TopChanged = true;
<API key>(&ClassMutex);
}
void DisplayThread::SetBottomScreen(Screen *ScreenPtr) {
pthread_mutex_lock(&ClassMutex);
BottomScreenPtr = ScreenPtr;
BottomChanged = true;
<API key>(&ClassMutex);
}
void DisplayThread::RemoveTopScreen(Screen *ScreenPtr) {
pthread_mutex_lock(&ClassMutex);
if(ScreenPtr == TopScreenPtr) {
TopScreenPtr = NULL;
}
if(BottomScreenPtr != NULL) {
/* Call update to redraw the bottom screen */
Display.setClipArea(0, 0, VFDLib::vfd_width, VFDLib::vfd_height);
Display.clear(VFDSHADE_BLACK);
BottomScreenPtr->Update(Display);
Push();
}
<API key>(&ClassMutex);
}
void DisplayThread::RemoveBottomScreen(Screen *ScreenPtr) {
pthread_mutex_lock(&ClassMutex);
if(ScreenPtr == BottomScreenPtr) {
BottomScreenPtr = NULL;
}
<API key>(&ClassMutex);
}
void DisplayThread::Update(Screen *ScreenPtr) {
pthread_mutex_lock(&ClassMutex);
if(ScreenPtr == TopScreenPtr) {
/* Requested update of top screen display */
pthread_cond_signal(&ClassCondition);
}
else if((TopScreenPtr == NULL) && (ScreenPtr == BottomScreenPtr)) {
/* Requested update of bottom screen, and no top screen is present */
pthread_cond_signal(&ClassCondition);
}
else {
/* Reqested update of screen that is not currently visible,
so we'll ignore it */
}
<API key>(&ClassMutex);
}
void DisplayThread::ShowHourglass(void) {
/* This function will display an hourglass over the screen until the
next time the screen is updated */
unsigned int Xoffset = 0, Yoffset = 0;
unsigned int watchHeight = StopwatchHeight;
unsigned char *watch = StopwatchData;
if (VFDLib::vfd_height < 64) /* Shorter display, use shorter clock */
{
watchHeight = <API key>;
watch = StopwatchDataEmpeg;
}
Xoffset = (VFDLib::vfd_width - StopwatchWidth) / 2;
Yoffset = (VFDLib::vfd_height - watchHeight) / 2;
/* This is an attempt to make sure that any pending display update
is handled before the stopwatch is drawn. Should probably
redo this better later on */
sched_yield();
pthread_mutex_lock(&ClassMutex);
Display.setClipArea(Xoffset, Yoffset, Xoffset + StopwatchWidth,
Yoffset + watchHeight);
Display.<API key>(Xoffset, Yoffset,
Xoffset + StopwatchWidth, Yoffset + watchHeight,
VFDSHADE_BLACK);
Display.drawBitmap(watch, Xoffset, Yoffset, 0, 0, StopwatchWidth,
watchHeight, -1, 0);
Push();
TopChanged = true;
BottomChanged = true;
<API key>(&ClassMutex);
} |
/*
* List of cgroup subsystems.
*
* DO NOT ADD ANY SUBSYSTEM WITHOUT EXPLICIT ACKS FROM CGROUP MAINTAINERS.
*/
#if IS_ENABLED(CONFIG_CPUSETS)
SUBSYS(cpuset)
#endif
#if IS_ENABLED(CONFIG_CGROUP_SCHED)
SUBSYS(cpu)
#endif
#if IS_ENABLED(<API key>)
SUBSYS(cpuacct)
#endif
#if IS_ENABLED(CONFIG_BLK_CGROUP)
SUBSYS(blkio)
#endif
#if IS_ENABLED(CONFIG_MEMCG)
SUBSYS(memory)
#endif
#if IS_ENABLED(<API key>)
SUBSYS(devices)
#endif
#if IS_ENABLED(<API key>)
SUBSYS(freezer)
#endif
#if IS_ENABLED(<API key>)
SUBSYS(net_cls)
#endif
#if IS_ENABLED(CONFIG_CGROUP_PERF)
SUBSYS(perf_event)
#endif
#if IS_ENABLED(<API key>)
SUBSYS(net_prio)
#endif
#if IS_ENABLED(<API key>)
SUBSYS(hugetlb)
#endif
/*
* The following subsystems are not supported on the default hierarchy.
*/
#if IS_ENABLED(CONFIG_CGROUP_DEBUG)
SUBSYS(debug)
#endif
/*
* DO NOT ADD ANY SUBSYSTEM WITHOUT EXPLICIT ACKS FROM CGROUP MAINTAINERS.
*/ |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http:
<head>
<title>Qt 4.3: Qtopia Core Character Input</title>
<link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http:
<td width="1"> </td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a> · <a href="classes.html"><font color="#004faf">All Classes</font></a> · <a href="mainclasses.html"><font color="#004faf">Main Classes</font></a> · <a href="groups.html"><font color="#004faf">Grouped Classes</font></a> · <a href="modules.html"><font color="#004faf">Modules</font></a> · <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top" width="230"><a href="http:
</h1>
<p>When running a <a href="qtopiacore.html">Qtopia Core</a> application, it either runs as a server or connects to an existing server. The keyboard driver is loaded by the server application when it starts running, using Qt's <a href="plugins-howto.html">plugin system</a>.</p>
<p>Internally in the client/server protocol, all system generated events, including key events, are passed to the server application which then propagates the event to the appropiate client. Note that key events do not always come from a keyboard device, they can can also be generated by the server process using input widgets.</p>
<p><table align="center" cellpadding="2" cellspacing="1" border="0">
<thead><tr valign="top" class="qt-style"><th>Input Widgets</th></tr></thead>
<tr valign="top" class="odd"><td>The server process may call the static <a href="qwsserver.html#sendKeyEvent">QWSServer::sendKeyEvent</a>() function at any time. Typically, this is done by popping up a widget that enables the user specify characters with the pointer device.<p>Note that the key input widget should not take focus since the server would then just send the key events back to the input widget. One way to make sure that the input widget never takes focus is to set the <a href="qt.html#WindowType-enum">Qt::Tool</a> widget flag in the <a href="qwidget.html">QWidget</a> constructor.</p>
<p>The <a href="http:
</td></tr>
</table></p>
<ul><li><a href="#<API key>">Available Keyboard Drivers</a></li>
<li><a href="#<API key>">Specifying a Keyboard Driver</a></li>
</ul>
<a name="<API key>"></a>
<h2>Available Keyboard Drivers</h2>
<p><a href="qtopiacore.html">Qtopia Core</a> provides ready-made drivers for the SL5000, Yopy, Vr41XX, console (TTY) and USB protocols. Run the <tt>configure</tt> script to list the available drivers:</p>
<pre> ./configure -help</pre>
<p>Note that the console keyboard driver also handles console switching (<b>Ctrl+Alt+F1</b>, ..., <b>Ctrl+Alt+F10</b>) and termination (<b>Ctrl+Alt+Backspace</b>).</p>
<p>In the default Qt configuration, only the "TTY" driver is enabled. The various drivers can be enabled and disabled using the <tt>configure</tt> script. For example:</p>
<pre> configure -qt-kbd-s15000</pre>
<p>Custom keyboard drivers can be implemented by subclassing the <a href="qwskeyboardhandler.html">QWSKeyboardHandler</a> class and creating a keyboard driver plugin (derived from the <a href="qkbddriverplugin.html">QKbdDriverPlugin</a> class). <a href="qtopiacore.html">Qtopia Core</a>'s implementation of the <a href="qkbddriverfactory.html">QKbdDriverFactory</a> class will automatically detect the plugin, loading the driver into the server application at runtime.</p>
<a name="<API key>"></a>
<h2>Specifying a Keyboard Driver</h2>
<p>To specify which driver to use, set the <a href="qtopiacore-envvars.html#qws-keyboard">QWS_KEYBOARD</a> environment variable. For example (if the current shell is bash, ksh, zsh or sh):</p>
<pre> export QWS_KEYBOARD=<driver>[:<driver specific options>]</pre>
<p>The <tt><driver></tt> argument are <tt>SL5000</tt>, <tt>Yopy</tt>, <tt>VR41xx</tt>, <tt>TTY</tt>, <tt>USB</tt> and <a href="qkbddriverplugin.html#keys">keys</a> identifying custom drivers, and the driver specific options are typically a device, e.g., <tt>/dev/tty0</tt>.</p>
<p>Multiple keyboard drivers can be specified in one go:</p>
<pre> export QWS_KEYBOARD="<driver>[:<driver specific options>]
<driver>[:<driver specific options>]
<driver>[:<driver specific options>]"</pre>
<p>Input will be read from all specified drivers.</p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%">Copyright © 2008 <a href="trolltech.html">Trolltech</a></td>
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt 4.3.6</div></td>
</tr></table></div></address></body>
</html> |
#ifndef __LINUX_LIBATA_H__
#define __LINUX_LIBATA_H__
#include <linux/delay.h>
#include <linux/jiffies.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/scatterlist.h>
#include <linux/io.h>
#include <linux/ata.h>
#include <linux/workqueue.h>
#include <scsi/scsi_host.h>
#include <linux/acpi.h>
#include <linux/cdrom.h>
#include <linux/sched.h>
#ifdef CONFIG_ATA_LEDS
#include <linux/leds.h>
#endif
/*
* Define if arch has non-standard setup. This is a _PCI_ standard
* not a legacy or ISA standard.
*/
#ifdef <API key>
#include <asm/libata-portmap.h>
#else
#include <asm-generic/libata-portmap.h>
#endif
/*
* compile-time options: to be removed as soon as all the drivers are
* converted to the new debugging mechanism
*/
#undef ATA_DEBUG /* debugging output */
#undef ATA_VERBOSE_DEBUG /* yet more debugging output */
#undef ATA_IRQ_TRAP /* define to ack screaming irqs */
#undef ATA_NDEBUG /* define to disable quick runtime checks */
/* note: prints function name for you */
#ifdef ATA_DEBUG
#define DPRINTK(fmt, args...) printk(KERN_ERR "%s: " fmt, __func__, ## args)
#ifdef ATA_VERBOSE_DEBUG
#define VPRINTK(fmt, args...) printk(KERN_ERR "%s: " fmt, __func__, ## args)
#else
#define VPRINTK(fmt, args...)
#endif /* ATA_VERBOSE_DEBUG */
#else
#define DPRINTK(fmt, args...)
#define VPRINTK(fmt, args...)
#endif /* ATA_DEBUG */
#define BPRINTK(fmt, args...) if (ap->flags & ATA_FLAG_DEBUGMSG) printk(KERN_ERR "%s: " fmt, __func__, ## args)
#define <API key>(dev, version) \
({ \
static bool __print_once; \
\
if (!__print_once) { \
__print_once = true; \
ata_print_version(dev, version); \
} \
})
/* NEW: debug levels */
#define HAVE_LIBATA_MSG 1
enum {
ATA_MSG_DRV = 0x0001,
ATA_MSG_INFO = 0x0002,
ATA_MSG_PROBE = 0x0004,
ATA_MSG_WARN = 0x0008,
ATA_MSG_MALLOC = 0x0010,
ATA_MSG_CTL = 0x0020,
ATA_MSG_INTR = 0x0040,
ATA_MSG_ERR = 0x0080,
};
#define ata_msg_drv(p) ((p)->msg_enable & ATA_MSG_DRV)
#define ata_msg_info(p) ((p)->msg_enable & ATA_MSG_INFO)
#define ata_msg_probe(p) ((p)->msg_enable & ATA_MSG_PROBE)
#define ata_msg_warn(p) ((p)->msg_enable & ATA_MSG_WARN)
#define ata_msg_malloc(p) ((p)->msg_enable & ATA_MSG_MALLOC)
#define ata_msg_ctl(p) ((p)->msg_enable & ATA_MSG_CTL)
#define ata_msg_intr(p) ((p)->msg_enable & ATA_MSG_INTR)
#define ata_msg_err(p) ((p)->msg_enable & ATA_MSG_ERR)
static inline u32 ata_msg_init(int dval, int <API key>)
{
if (dval < 0 || dval >= (sizeof(u32) * 8))
return <API key>; /* should be 0x1 - only driver info msgs */
if (!dval)
return 0;
return (1 << dval) - 1;
}
/* defines only for the constants which don't work well as enums */
#define ATA_TAG_POISON 0xfafbfcfdU
enum {
/* various global constants */
LIBATA_MAX_PRD = ATA_MAX_PRD / 2,
LIBATA_DUMB_MAX_PRD = ATA_MAX_PRD / 4, /* Worst case */
ATA_DEF_QUEUE = 1,
/* tag ATA_MAX_QUEUE - 1 is reserved for internal commands */
ATA_MAX_QUEUE = 32,
ATA_TAG_INTERNAL = ATA_MAX_QUEUE - 1,
ATA_SHORT_PAUSE = 16,
ATAPI_MAX_DRAIN = 16 << 10,
ATA_ALL_DEVICES = (1 << ATA_MAX_DEVICES) - 1,
ATA_SHT_EMULATED = 1,
ATA_SHT_CMD_PER_LUN = 1,
ATA_SHT_THIS_ID = -1,
<API key> = 1,
/* struct ata_taskfile flags */
ATA_TFLAG_LBA48 = (1 << 0), /* enable 48-bit LBA and "HOB" */
ATA_TFLAG_ISADDR = (1 << 1), /* enable r/w to nsect/lba regs */
ATA_TFLAG_DEVICE = (1 << 2), /* enable r/w to device reg */
ATA_TFLAG_WRITE = (1 << 3), /* data dir: host->dev==1 (write) */
ATA_TFLAG_LBA = (1 << 4), /* enable LBA */
ATA_TFLAG_FUA = (1 << 5), /* enable FUA */
ATA_TFLAG_POLLING = (1 << 6), /* set nIEN to 1 and use polling */
/* protocol flags */
ATA_PROT_FLAG_PIO = (1 << 0), /* is PIO */
ATA_PROT_FLAG_DMA = (1 << 1), /* is DMA */
ATA_PROT_FLAG_DATA = ATA_PROT_FLAG_PIO | ATA_PROT_FLAG_DMA,
ATA_PROT_FLAG_NCQ = (1 << 2), /* is NCQ */
ATA_PROT_FLAG_ATAPI = (1 << 3), /* is ATAPI */
/* struct ata_device stuff */
ATA_DFLAG_LBA = (1 << 0), /* device supports LBA */
ATA_DFLAG_LBA48 = (1 << 1), /* device supports LBA48 */
ATA_DFLAG_CDB_INTR = (1 << 2), /* device asserts INTRQ when ready for CDB */
ATA_DFLAG_NCQ = (1 << 3), /* device supports NCQ */
ATA_DFLAG_FLUSH_EXT = (1 << 4), /* do FLUSH_EXT instead of FLUSH */
<API key> = (1 << 5), /* ACPI resume action pending */
<API key> = (1 << 6), /* ACPI on devcfg has failed */
ATA_DFLAG_AN = (1 << 7), /* AN configured */
ATA_DFLAG_DMADIR = (1 << 10), /* device requires DMADIR */
ATA_DFLAG_CFG_MASK = (1 << 12) - 1,
ATA_DFLAG_PIO = (1 << 12), /* device limited to PIO mode */
ATA_DFLAG_NCQ_OFF = (1 << 13), /* device limited to non-NCQ mode */
ATA_DFLAG_SLEEPING = (1 << 15), /* device is sleeping */
<API key> = (1 << 16), /* data transfer not verified */
ATA_DFLAG_NO_UNLOAD = (1 << 17), /* device doesn't support unload */
<API key> = (1 << 18), /* unlock HPA */
<API key> = (1 << 19), /* device supports NCQ SEND and RECV */
ATA_DFLAG_INIT_MASK = (1 << 24) - 1,
ATA_DFLAG_DETACH = (1 << 24),
ATA_DFLAG_DETACHED = (1 << 25),
ATA_DFLAG_DA = (1 << 26), /* device supports Device Attention */
ATA_DFLAG_DEVSLP = (1 << 27), /* device supports Device Sleep */
<API key> = (1 << 28), /* ACPI for the device is disabled */
ATA_DEV_UNKNOWN = 0, /* unknown device */
ATA_DEV_ATA = 1, /* ATA device */
ATA_DEV_ATA_UNSUP = 2, /* ATA device (unsupported) */
ATA_DEV_ATAPI = 3, /* ATAPI device */
ATA_DEV_ATAPI_UNSUP = 4, /* ATAPI device (unsupported) */
ATA_DEV_PMP = 5, /* SATA port multiplier */
ATA_DEV_PMP_UNSUP = 6, /* SATA port multiplier (unsupported) */
ATA_DEV_SEMB = 7, /* SEMB */
ATA_DEV_SEMB_UNSUP = 8, /* SEMB (unsupported) */
ATA_DEV_NONE = 9, /* no device */
/* struct ata_link flags */
ATA_LFLAG_NO_HRST = (1 << 1), /* avoid hardreset */
ATA_LFLAG_NO_SRST = (1 << 2), /* avoid softreset */
<API key> = (1 << 3), /* assume ATA class */
<API key> = (1 << 4), /* assume SEMB class */
<API key> = <API key> | <API key>,
ATA_LFLAG_NO_RETRY = (1 << 5), /* don't retry this link */
ATA_LFLAG_DISABLED = (1 << 6), /* link is disabled */
<API key> = (1 << 7), /* keep activity stats */
ATA_LFLAG_NO_LPM = (1 << 8), /* disable LPM on this link */
ATA_LFLAG_RST_ONCE = (1 << 9), /* limit recovery to one reset */
/* struct ata_port flags */
ATA_FLAG_SLAVE_POSS = (1 << 0), /* host supports slave dev */
/* (doesn't imply presence) */
ATA_FLAG_SATA = (1 << 1),
ATA_FLAG_NO_ATAPI = (1 << 6), /* No ATAPI support */
ATA_FLAG_PIO_DMA = (1 << 7), /* PIO cmds via DMA */
ATA_FLAG_PIO_LBA48 = (1 << 8), /* Host DMA engine is LBA28 only */
<API key> = (1 << 9), /* use polling PIO if LLD
* doesn't handle PIO interrupts */
ATA_FLAG_NCQ = (1 << 10), /* host supports NCQ */
<API key> = (1 << 11), /* don't spindown before poweroff */
<API key> = (1 << 12), /* don't spindown before hibernation */
ATA_FLAG_DEBUGMSG = (1 << 13),
ATA_FLAG_FPDMA_AA = (1 << 14), /* driver supports Auto-Activate */
<API key> = (1 << 15), /* ignore SIMPLEX */
ATA_FLAG_NO_IORDY = (1 << 16), /* controller lacks iordy */
ATA_FLAG_ACPI_SATA = (1 << 17), /* need native SATA ACPI layout */
ATA_FLAG_AN = (1 << 18), /* controller supports AN */
ATA_FLAG_PMP = (1 << 19), /* controller supports PMP */
ATA_FLAG_FPDMA_AUX = (1 << 20), /* controller supports H2DFIS aux field */
ATA_FLAG_EM = (1 << 21), /* driver supports enclosure
* management */
<API key> = (1 << 22), /* driver supports sw activity
* led */
ATA_FLAG_NO_DIPM = (1 << 23), /* host not happy with DIPM */
/* bits 24:31 of ap->flags are reserved for LLD specific flags */
/* struct ata_port pflags */
<API key> = (1 << 0), /* EH pending */
<API key> = (1 << 1), /* EH in progress */
ATA_PFLAG_FROZEN = (1 << 2), /* port is frozen */
ATA_PFLAG_RECOVERED = (1 << 3), /* recovery action performed */
ATA_PFLAG_LOADING = (1 << 4), /* boot/loading probe */
<API key> = (1 << 6), /* SCSI hotplug scheduled */
<API key> = (1 << 7), /* being initialized, don't touch */
ATA_PFLAG_RESETTING = (1 << 8), /* reset in progress */
ATA_PFLAG_UNLOADING = (1 << 9), /* driver is being unloaded */
ATA_PFLAG_UNLOADED = (1 << 10), /* driver is unloaded */
ATA_PFLAG_SUSPENDED = (1 << 17), /* port is suspended (power) */
<API key> = (1 << 18), /* PM operation pending */
<API key> = (1 << 19), /* initial gtm data valid */
ATA_PFLAG_PIO32 = (1 << 20), /* 32bit PIO */
<API key> = (1 << 21), /* 32bit PIO can be turned on/off */
/* struct ata_queued_cmd flags */
ATA_QCFLAG_ACTIVE = (1 << 0), /* cmd not yet ack'd to scsi lyer */
ATA_QCFLAG_DMAMAP = (1 << 1), /* SG table is DMA mapped */
ATA_QCFLAG_IO = (1 << 3), /* standard IO command */
<API key> = (1 << 4), /* result TF requested */
<API key> = (1 << 5), /* clear excl_link on completion */
ATA_QCFLAG_QUIET = (1 << 6), /* don't report device error */
ATA_QCFLAG_RETRY = (1 << 7), /* retry after failure */
ATA_QCFLAG_FAILED = (1 << 16), /* cmd failed and is owned by EH */
<API key> = (1 << 17), /* sense data valid */
<API key> = (1 << 18), /* EH scheduled (obsolete) */
/* host set flags */
ATA_HOST_SIMPLEX = (1 << 0), /* Host is simplex, one DMA channel per host only */
ATA_HOST_STARTED = (1 << 1), /* Host started */
<API key> = (1 << 2), /* Ports on this host can be scanned in parallel */
ATA_HOST_IGNORE_ATA = (1 << 3), /* Ignore ATA devices on this host. */
/* bits 24:31 of host->flags are reserved for LLD specific flags */
/* various lengths of time */
ATA_TMOUT_BOOT = 30000, /* heuristic */
<API key> = 7000, /* heuristic */
<API key> = 5000,
ATA_TMOUT_MAX_PARK = 30000,
/*
* GoVault needs 2s and iVDR disk HHD424020F7SV00 800ms. 2s
* is too much without parallel probing. Use 2s if parallel
* probing is available, 800ms otherwise.
*/
<API key> = 2000,
ATA_TMOUT_FF_WAIT = 800,
/* Spec mandates to wait for ">= 2ms" before checking status
* after reset. We wait 150ms, because that was the magic
* delay used for ATAPI devices in Hale Landis's ATADRVR, for
* the period of time between when the ATA command register is
* written, and then status is checked. Because waiting for
* "a while" before checking status is fine, post SRST, we
* perform this magic delay here as well.
*
* Old drivers/ide uses the 2mS rule and then waits for ready.
*/
<API key> = 150,
/* If PMP is supported, we have to do follow-up SRST. As some
* PMPs don't send D2H Reg FIS after hardreset, LLDs are
* advised to wait only for the following duration before
* doing SRST.
*/
<API key> = 5000,
/* ATA bus states */
BUS_UNKNOWN = 0,
BUS_DMA = 1,
BUS_IDLE = 2,
BUS_NOINTR = 3,
BUS_NODATA = 4,
BUS_TIMER = 5,
BUS_PIO = 6,
BUS_EDD = 7,
BUS_IDENTIFY = 8,
BUS_PACKET = 9,
/* SATA port states */
PORT_UNKNOWN = 0,
PORT_ENABLED = 1,
PORT_DISABLED = 2,
/* encoding various smaller bitmaps into a single
* unsigned long bitmap
*/
ATA_NR_PIO_MODES = 7,
ATA_NR_MWDMA_MODES = 5,
ATA_NR_UDMA_MODES = 8,
ATA_SHIFT_PIO = 0,
ATA_SHIFT_MWDMA = ATA_SHIFT_PIO + ATA_NR_PIO_MODES,
ATA_SHIFT_UDMA = ATA_SHIFT_MWDMA + ATA_NR_MWDMA_MODES,
/* size of buffer to pad xfers ending on unaligned boundaries */
ATA_DMA_PAD_SZ = 4,
/* ering size */
ATA_ERING_SIZE = 32,
/* return values for ->qc_defer */
ATA_DEFER_LINK = 1,
ATA_DEFER_PORT = 2,
/* desc_len for ata_eh_info and context */
ATA_EH_DESC_LEN = 80,
/* reset / recovery action types */
ATA_EH_REVALIDATE = (1 << 0),
ATA_EH_SOFTRESET = (1 << 1), /* meaningful only in ->prereset */
ATA_EH_HARDRESET = (1 << 2), /* meaningful only in ->prereset */
ATA_EH_RESET = ATA_EH_SOFTRESET | ATA_EH_HARDRESET,
ATA_EH_ENABLE_LINK = (1 << 3),
ATA_EH_PARK = (1 << 5), /* unload heads and stop I/O */
ATA_EH_PERDEV_MASK = ATA_EH_REVALIDATE | ATA_EH_PARK,
ATA_EH_ALL_ACTIONS = ATA_EH_REVALIDATE | ATA_EH_RESET |
ATA_EH_ENABLE_LINK,
/* ata_eh_info->flags */
ATA_EHI_HOTPLUGGED = (1 << 0), /* could have been hotplugged */
ATA_EHI_NO_AUTOPSY = (1 << 2), /* no autopsy */
ATA_EHI_QUIET = (1 << 3), /* be quiet */
ATA_EHI_NO_RECOVERY = (1 << 4), /* no recovery */
<API key> = (1 << 16), /* already soft-reset this port */
<API key> = (1 << 17), /* already soft-reset this port */
ATA_EHI_PRINTINFO = (1 << 18), /* print configuration info */
ATA_EHI_SETMODE = (1 << 19), /* configure transfer mode */
<API key> = (1 << 20), /* revalidating after setmode */
ATA_EHI_DID_RESET = <API key> | <API key>,
/* mask of flags to transfer *to* the slave link */
<API key> = ATA_EHI_NO_AUTOPSY | ATA_EHI_QUIET,
/* max tries if error condition is still set after ->error_handler */
ATA_EH_MAX_TRIES = 5,
/* sometimes resuming a link requires several retries */
<API key> = 5,
/* how hard are we gonna try to probe/recover devices */
ATA_PROBE_MAX_TRIES = 3,
ATA_EH_DEV_TRIES = 3,
ATA_EH_PMP_TRIES = 5,
<API key> = 3,
SATA_PMP_RW_TIMEOUT = 3000, /* PMP read/write timeout */
/* This should match the actual table size of
* <API key> in libata-eh.c.
*/
<API key> = 6,
/* Horkage types. May be set by libata or controller on drives
(some horkage may be drive/controller pair dependent */
<API key> = (1 << 0), /* Failed boot diag */
ATA_HORKAGE_NODMA = (1 << 1), /* DMA problems */
ATA_HORKAGE_NONCQ = (1 << 2), /* Don't use NCQ */
<API key> = (1 << 3), /* Limit max sects to 128 */
<API key> = (1 << 4), /* Broken HPA */
ATA_HORKAGE_DISABLE = (1 << 5), /* Disable it */
<API key> = (1 << 6), /* native size off by one */
ATA_HORKAGE_IVB = (1 << 8), /* cbl det validity bit bugs */
<API key> = (1 << 9), /* stuck ERR on next PACKET */
<API key> = (1 << 10), /* no bridge limits */
<API key> = (1 << 11), /* use ATAPI DMA for commands
not multiple of 16 bytes */
<API key> = (1 << 12), /* firmware update warning */
<API key> = (1 << 13), /* force 1.5 Gbps */
<API key> = (1 << 14), /* skip SETXFER, SATA only */
<API key> = (1 << 15), /* skip AA */
ATA_HORKAGE_DUMP_ID = (1 << 16), /* dump IDENTIFY data */
<API key> = (1 << 17), /* Set max sects to 65535 */
<API key> = (1 << 18), /* device requires dmadir */
<API key> = (1 << 19), /* don't use queued TRIM */
ATA_HORKAGE_NOLPM = (1 << 20), /* don't use LPM */
<API key> = (1 << 21), /* some WDs have broken LPM */
/* DMA mask for user DMA control: User visible values; DO NOT
renumber */
ATA_DMA_MASK_ATA = (1 << 0), /* DMA on ATA Disk */
ATA_DMA_MASK_ATAPI = (1 << 1), /* DMA on ATAPI */
ATA_DMA_MASK_CFA = (1 << 2), /* DMA on CF Card */
/* ATAPI command types */
ATAPI_READ = 0, /* READs */
ATAPI_WRITE = 1, /* WRITEs */
ATAPI_READ_CD = 2, /* READ CD [MSF] */
ATAPI_PASS_THRU = 3, /* SAT pass-thru */
ATAPI_MISC = 4, /* the rest */
/* Timing constants */
ATA_TIMING_SETUP = (1 << 0),
ATA_TIMING_ACT8B = (1 << 1),
ATA_TIMING_REC8B = (1 << 2),
ATA_TIMING_CYC8B = (1 << 3),
ATA_TIMING_8BIT = ATA_TIMING_ACT8B | ATA_TIMING_REC8B |
ATA_TIMING_CYC8B,
ATA_TIMING_ACTIVE = (1 << 4),
ATA_TIMING_RECOVER = (1 << 5),
<API key> = (1 << 6),
ATA_TIMING_CYCLE = (1 << 7),
ATA_TIMING_UDMA = (1 << 8),
ATA_TIMING_ALL = ATA_TIMING_SETUP | ATA_TIMING_ACT8B |
ATA_TIMING_REC8B | ATA_TIMING_CYC8B |
ATA_TIMING_ACTIVE | ATA_TIMING_RECOVER |
<API key> | ATA_TIMING_CYCLE |
ATA_TIMING_UDMA,
/* ACPI constants */
<API key> = 1 << 0,
<API key> = 1 << 1,
<API key> = 1 << 2,
<API key> = 1 << 3, /* FPDMA non-zero offset */
<API key> = 1 << 4, /* FPDMA auto activate */
<API key> = <API key> |
<API key> |
<API key>,
};
enum ata_xfer_mask {
ATA_MASK_PIO = ((1LU << ATA_NR_PIO_MODES) - 1)
<< ATA_SHIFT_PIO,
ATA_MASK_MWDMA = ((1LU << ATA_NR_MWDMA_MODES) - 1)
<< ATA_SHIFT_MWDMA,
ATA_MASK_UDMA = ((1LU << ATA_NR_UDMA_MODES) - 1)
<< ATA_SHIFT_UDMA,
};
enum hsm_task_states {
HSM_ST_IDLE, /* no command on going */
HSM_ST_FIRST, /* (waiting the device to)
write CDB or first data block */
HSM_ST, /* (waiting the device to) transfer data */
HSM_ST_LAST, /* (waiting the device to) complete command */
HSM_ST_ERR, /* error */
};
enum <API key> {
AC_ERR_DEV = (1 << 0), /* device reported error */
AC_ERR_HSM = (1 << 1), /* host state machine violation */
AC_ERR_TIMEOUT = (1 << 2), /* timeout */
AC_ERR_MEDIA = (1 << 3), /* media error */
AC_ERR_ATA_BUS = (1 << 4), /* ATA bus error */
AC_ERR_HOST_BUS = (1 << 5), /* host bus error */
AC_ERR_SYSTEM = (1 << 6), /* system error */
AC_ERR_INVALID = (1 << 7), /* invalid argument */
AC_ERR_OTHER = (1 << 8), /* unknown */
AC_ERR_NODEV_HINT = (1 << 9), /* polling device detection hint */
AC_ERR_NCQ = (1 << 10), /* marker for offending NCQ qc */
};
/*
* Link power management policy: If you alter this, you also need to
* alter libata-scsi.c (for the ascii descriptions)
*/
enum ata_lpm_policy {
ATA_LPM_UNKNOWN,
ATA_LPM_MAX_POWER,
ATA_LPM_MED_POWER,
ATA_LPM_MIN_POWER,
};
enum ata_lpm_hints {
ATA_LPM_EMPTY = (1 << 0), /* port empty/probing */
ATA_LPM_HIPM = (1 << 1), /* may use HIPM */
};
/* forward declarations */
struct scsi_device;
struct ata_port_operations;
struct ata_port;
struct ata_link;
struct ata_queued_cmd;
/* typedefs */
typedef void (*ata_qc_cb_t) (struct ata_queued_cmd *qc);
typedef int (*ata_prereset_fn_t)(struct ata_link *link, unsigned long deadline);
typedef int (*ata_reset_fn_t)(struct ata_link *link, unsigned int *classes,
unsigned long deadline);
typedef void (*ata_postreset_fn_t)(struct ata_link *link, unsigned int *classes);
extern struct device_attribute <API key>;
extern struct device_attribute <API key>;
extern struct device_attribute <API key>;
extern struct device_attribute dev_attr_em_message;
extern struct device_attribute <API key>;
enum sw_activity {
OFF,
BLINK_ON,
BLINK_OFF,
};
struct ata_taskfile {
unsigned long flags; /* ATA_TFLAG_xxx */
u8 protocol; /* ATA_PROT_xxx */
u8 ctl; /* control reg */
u8 hob_feature; /* additional data */
u8 hob_nsect; /* to support LBA48 */
u8 hob_lbal;
u8 hob_lbam;
u8 hob_lbah;
u8 feature;
u8 nsect;
u8 lbal;
u8 lbam;
u8 lbah;
u8 device;
u8 command; /* IO operation */
u32 auxiliary; /* auxiliary field */
/* from SATA 3.1 and */
/* ATA-8 ACS-3 */
};
#ifdef CONFIG_ATA_SFF
struct ata_ioports {
void __iomem *cmd_addr;
void __iomem *data_addr;
void __iomem *error_addr;
void __iomem *feature_addr;
void __iomem *nsect_addr;
void __iomem *lbal_addr;
void __iomem *lbam_addr;
void __iomem *lbah_addr;
void __iomem *device_addr;
void __iomem *status_addr;
void __iomem *command_addr;
void __iomem *altstatus_addr;
void __iomem *ctl_addr;
#ifdef CONFIG_ATA_BMDMA
void __iomem *bmdma_addr;
#endif /* CONFIG_ATA_BMDMA */
void __iomem *scr_addr;
};
#endif /* CONFIG_ATA_SFF */
struct ata_host {
spinlock_t lock;
struct device *dev;
void __iomem * const *iomap;
unsigned int n_ports;
unsigned int n_tags; /* nr of NCQ tags */
void *private_data;
struct ata_port_operations *ops;
unsigned long flags;
struct mutex eh_mutex;
struct task_struct *eh_owner;
struct ata_port *simplex_claimed; /* channel owning the DMA */
struct ata_port *ports[0];
};
struct ata_queued_cmd {
struct ata_port *ap;
struct ata_device *dev;
struct scsi_cmnd *scsicmd;
void (*scsidone)(struct scsi_cmnd *);
struct ata_taskfile tf;
u8 cdb[ATAPI_CDB_LEN];
unsigned long flags; /* ATA_QCFLAG_xxx */
unsigned int tag;
unsigned int n_elem;
unsigned int orig_n_elem;
int dma_dir;
unsigned int sect_size;
unsigned int nbytes;
unsigned int extrabytes;
unsigned int curbytes;
struct scatterlist sgent;
struct scatterlist *sg;
struct scatterlist *cursg;
unsigned int cursg_ofs;
unsigned int err_mask;
struct ata_taskfile result_tf;
ata_qc_cb_t complete_fn;
void *private_data;
void *lldd_task;
};
struct ata_port_stats {
unsigned long unhandled_irq;
unsigned long idle_irq;
unsigned long rw_reqbuf;
};
struct ata_ering_entry {
unsigned int eflags;
unsigned int err_mask;
u64 timestamp;
};
struct ata_ering {
int cursor;
struct ata_ering_entry ring[ATA_ERING_SIZE];
};
struct ata_device {
struct ata_link *link;
unsigned int devno; /* 0 or 1 */
unsigned int horkage; /* List of broken features */
unsigned long flags; /* ATA_DFLAG_xxx */
struct scsi_device *sdev; /* attached SCSI device */
void *private_data;
#ifdef CONFIG_ATA_ACPI
union acpi_object *gtf_cache;
unsigned int gtf_filter;
#endif
#ifdef CONFIG_SATA_ZPODD
void *zpodd;
#endif
struct device tdev;
/* n_sector is CLEAR_BEGIN, read comment above CLEAR_BEGIN */
u64 n_sectors; /* size of device, if ATA */
u64 n_native_sectors; /* native size, if ATA */
unsigned int class; /* ATA_DEV_xxx */
unsigned long unpark_deadline;
u8 pio_mode;
u8 dma_mode;
u8 xfer_mode;
unsigned int xfer_shift; /* ATA_SHIFT_xxx */
unsigned int multi_count; /* sectors count for
READ/WRITE MULTIPLE */
unsigned int max_sectors; /* per-device max sectors */
unsigned int cdb_len;
/* per-dev xfer mask */
unsigned long pio_mask;
unsigned long mwdma_mask;
unsigned long udma_mask;
/* for CHS addressing */
u16 cylinders; /* Number of cylinders */
u16 heads; /* Number of heads */
u16 sectors; /* Number of sectors per track */
union {
u16 id[ATA_ID_WORDS]; /* IDENTIFY xxx DEVICE data */
u32 gscr[<API key>]; /* PMP GSCR block */
};
/* DEVSLP Timing Variables from Identify Device Data Log */
u8 devslp_timing[ATA_LOG_DEVSLP_SIZE];
/* NCQ send and receive log subcommand support */
u8 ncq_send_recv_cmds[<API key>];
/* error history */
int spdn_cnt;
/* ering is CLEAR_END, read comment above CLEAR_END */
struct ata_ering ering;
};
/* Fields between <API key> and <API key> are
* cleared to zero on ata_dev_init().
*/
#define <API key> offsetof(struct ata_device, n_sectors)
#define <API key> offsetof(struct ata_device, ering)
struct ata_eh_info {
struct ata_device *dev; /* offending device */
u32 serror; /* SError from LLDD */
unsigned int err_mask; /* port-wide err_mask */
unsigned int action; /* ATA_EH_* action mask */
unsigned int dev_action[ATA_MAX_DEVICES]; /* dev EH action */
unsigned int flags; /* ATA_EHI_* flags */
unsigned int probe_mask;
char desc[ATA_EH_DESC_LEN];
int desc_len;
};
struct ata_eh_context {
struct ata_eh_info i;
int tries[ATA_MAX_DEVICES];
int cmd_timeout_idx[ATA_MAX_DEVICES]
[<API key>];
unsigned int classes[ATA_MAX_DEVICES];
unsigned int did_probe_mask;
unsigned int unloaded_mask;
unsigned int saved_ncq_enabled;
u8 saved_xfer_mode[ATA_MAX_DEVICES];
/* timestamp for the last reset attempt or success */
unsigned long last_reset;
};
struct ata_acpi_drive
{
u32 pio;
u32 dma;
} __packed;
struct ata_acpi_gtm {
struct ata_acpi_drive drive[2];
u32 flags;
} __packed;
struct ata_link {
struct ata_port *ap;
int pmp; /* port multiplier port # */
struct device tdev;
unsigned int active_tag; /* active tag on this link */
u32 sactive; /* active NCQ commands */
unsigned int flags; /* ATA_LFLAG_xxx */
u32 saved_scontrol; /* SControl on probe */
unsigned int hw_sata_spd_limit;
unsigned int sata_spd_limit;
unsigned int sata_spd; /* current SATA PHY speed */
enum ata_lpm_policy lpm_policy;
/* record runtime error info, protected by host_set lock */
struct ata_eh_info eh_info;
/* EH context */
struct ata_eh_context eh_context;
struct ata_device device[ATA_MAX_DEVICES];
};
#define <API key> offsetof(struct ata_link, active_tag)
#define ATA_LINK_CLEAR_END offsetof(struct ata_link, device[0])
struct ata_port {
struct Scsi_Host *scsi_host; /* our co-allocated scsi host */
struct ata_port_operations *ops;
spinlock_t *lock;
/* Flags owned by the EH context. Only EH should touch these once the
port is active */
unsigned long flags; /* ATA_FLAG_xxx */
/* Flags that change dynamically, protected by ap->lock */
unsigned int pflags; /* ATA_PFLAG_xxx */
unsigned int print_id; /* user visible unique port ID */
unsigned int local_port_no; /* host local port num */
unsigned int port_no; /* 0 based port no. inside the host */
#ifdef CONFIG_ATA_SFF
struct ata_ioports ioaddr; /* ATA cmd/ctl/dma register blocks */
u8 ctl; /* cache of ATA control register */
u8 last_ctl; /* Cache last written value */
struct ata_link* sff_pio_task_link; /* link currently used */
struct delayed_work sff_pio_task;
#ifdef CONFIG_ATA_BMDMA
struct ata_bmdma_prd *bmdma_prd; /* BMDMA SG list */
dma_addr_t bmdma_prd_dma; /* and its DMA mapping */
#endif /* CONFIG_ATA_BMDMA */
#endif /* CONFIG_ATA_SFF */
unsigned int pio_mask;
unsigned int mwdma_mask;
unsigned int udma_mask;
unsigned int cbl; /* cable type; ATA_CBL_xxx */
struct ata_queued_cmd qcmd[ATA_MAX_QUEUE];
unsigned long qc_allocated;
unsigned int qc_active;
int nr_active_links; /* #links with active qcs */
unsigned int last_tag; /* track next tag hw expects */
struct ata_link link; /* host default link */
struct ata_link *slave_link; /* see ata_slave_link_init() */
int nr_pmp_links; /* nr of available PMP links */
struct ata_link *pmp_link; /* array of PMP links */
struct ata_link *excl_link; /* for PMP qc exclusion */
struct ata_port_stats stats;
struct ata_host *host;
struct device *dev;
struct device tdev;
struct mutex scsi_scan_mutex;
struct delayed_work hotplug_task;
struct work_struct scsi_rescan_task;
unsigned int hsm_task_state;
u32 msg_enable;
struct list_head eh_done_q;
wait_queue_head_t eh_wait_q;
int eh_tries;
struct completion park_req_pending;
pm_message_t pm_mesg;
int *pm_result;
enum ata_lpm_policy target_lpm_policy;
struct timer_list fastdrain_timer;
unsigned long fastdrain_cnt;
int em_message_type;
void *private_data;
#ifdef CONFIG_ATA_ACPI
struct ata_acpi_gtm __acpi_init_gtm; /* use ata_acpi_init_gtm() */
#endif
#ifdef CONFIG_ATA_LEDS
struct led_trigger *ledtrig;
char ledtrig_name[8];
#endif
/* owned by EH */
u8 sector_buf[ATA_SECT_SIZE] <API key>;
};
/* The following initializer overrides a method to NULL whether one of
* its parent has the method defined or not. This is equivalent to
* ERR_PTR(-ENOENT). Unfortunately, ERR_PTR doesn't render a constant
* expression and thus can't be used as an initializer.
*/
#define ATA_OP_NULL (void *)(unsigned long)(-ENOENT)
struct ata_port_operations {
/*
* Command execution
*/
int (*qc_defer)(struct ata_queued_cmd *qc);
int (*check_atapi_dma)(struct ata_queued_cmd *qc);
void (*qc_prep)(struct ata_queued_cmd *qc);
unsigned int (*qc_issue)(struct ata_queued_cmd *qc);
bool (*qc_fill_rtf)(struct ata_queued_cmd *qc);
/*
* Configuration and exception handling
*/
int (*cable_detect)(struct ata_port *ap);
unsigned long (*mode_filter)(struct ata_device *dev, unsigned long xfer_mask);
void (*set_piomode)(struct ata_port *ap, struct ata_device *dev);
void (*set_dmamode)(struct ata_port *ap, struct ata_device *dev);
int (*set_mode)(struct ata_link *link, struct ata_device **r_failed_dev);
unsigned int (*read_id)(struct ata_device *dev, struct ata_taskfile *tf, u16 *id);
void (*dev_config)(struct ata_device *dev);
void (*freeze)(struct ata_port *ap);
void (*thaw)(struct ata_port *ap);
ata_prereset_fn_t prereset;
ata_reset_fn_t softreset;
ata_reset_fn_t hardreset;
ata_postreset_fn_t postreset;
ata_prereset_fn_t pmp_prereset;
ata_reset_fn_t pmp_softreset;
ata_reset_fn_t pmp_hardreset;
ata_postreset_fn_t pmp_postreset;
void (*error_handler)(struct ata_port *ap);
void (*lost_interrupt)(struct ata_port *ap);
void (*post_internal_cmd)(struct ata_queued_cmd *qc);
void (*sched_eh)(struct ata_port *ap);
void (*end_eh)(struct ata_port *ap);
/*
* Optional features
*/
int (*scr_read)(struct ata_link *link, unsigned int sc_reg, u32 *val);
int (*scr_write)(struct ata_link *link, unsigned int sc_reg, u32 val);
void (*pmp_attach)(struct ata_port *ap);
void (*pmp_detach)(struct ata_port *ap);
int (*set_lpm)(struct ata_link *link, enum ata_lpm_policy policy,
unsigned hints);
/*
* Start, stop, suspend and resume
*/
int (*port_suspend)(struct ata_port *ap, pm_message_t mesg);
int (*port_resume)(struct ata_port *ap);
int (*port_start)(struct ata_port *ap);
void (*port_stop)(struct ata_port *ap);
void (*host_stop)(struct ata_host *host);
#ifdef CONFIG_ATA_SFF
/*
* SFF / taskfile oriented ops
*/
void (*sff_dev_select)(struct ata_port *ap, unsigned int device);
void (*sff_set_devctl)(struct ata_port *ap, u8 ctl);
u8 (*sff_check_status)(struct ata_port *ap);
u8 (*sff_check_altstatus)(struct ata_port *ap);
void (*sff_tf_load)(struct ata_port *ap, const struct ata_taskfile *tf);
void (*sff_tf_read)(struct ata_port *ap, struct ata_taskfile *tf);
void (*sff_exec_command)(struct ata_port *ap,
const struct ata_taskfile *tf);
unsigned int (*sff_data_xfer)(struct ata_device *dev,
unsigned char *buf, unsigned int buflen, int rw);
void (*sff_irq_on)(struct ata_port *);
bool (*sff_irq_check)(struct ata_port *);
void (*sff_irq_clear)(struct ata_port *);
void (*sff_drain_fifo)(struct ata_queued_cmd *qc);
#ifdef CONFIG_ATA_BMDMA
void (*bmdma_setup)(struct ata_queued_cmd *qc);
void (*bmdma_start)(struct ata_queued_cmd *qc);
void (*bmdma_stop)(struct ata_queued_cmd *qc);
u8 (*bmdma_status)(struct ata_port *ap);
#endif /* CONFIG_ATA_BMDMA */
#endif /* CONFIG_ATA_SFF */
ssize_t (*em_show)(struct ata_port *ap, char *buf);
ssize_t (*em_store)(struct ata_port *ap, const char *message,
size_t size);
ssize_t (*sw_activity_show)(struct ata_device *dev, char *buf);
ssize_t (*sw_activity_store)(struct ata_device *dev,
enum sw_activity val);
ssize_t (*<API key>)(struct ata_port *ap, u32 state,
ssize_t size);
/*
* Obsolete
*/
void (*phy_reset)(struct ata_port *ap);
void (*eng_timeout)(struct ata_port *ap);
/*
* ->inherits must be the last field and all the preceding
* fields must be pointers.
*/
const struct ata_port_operations *inherits;
} __do_const;
struct ata_port_info {
unsigned long flags;
unsigned long link_flags;
unsigned long pio_mask;
unsigned long mwdma_mask;
unsigned long udma_mask;
struct ata_port_operations *port_ops;
void *private_data;
};
struct ata_timing {
unsigned short mode; /* ATA mode */
unsigned short setup;
unsigned short act8b; /* t2 for 8-bit I/O */
unsigned short rec8b; /* t2i for 8-bit I/O */
unsigned short cyc8b; /* t0 for 8-bit I/O */
unsigned short active; /* t2 or tD */
unsigned short recover; /* t2i or tK */
unsigned short dmack_hold;
unsigned short cycle;
unsigned short udma; /* t2CYCTYP/2 */
};
/*
* Core layer - drivers/ata/libata-core.c
*/
extern const unsigned long <API key>[];
extern const unsigned long <API key>[];
extern const unsigned long <API key>[];
extern struct ata_port_operations ata_dummy_port_ops;
extern const struct ata_port_info ata_dummy_port_info;
/*
* protocol tests
*/
static inline unsigned int ata_prot_flags(u8 prot)
{
switch (prot) {
case ATA_PROT_NODATA:
return 0;
case ATA_PROT_PIO:
return ATA_PROT_FLAG_PIO;
case ATA_PROT_DMA:
return ATA_PROT_FLAG_DMA;
case ATA_PROT_NCQ:
return ATA_PROT_FLAG_DMA | ATA_PROT_FLAG_NCQ;
case ATAPI_PROT_NODATA:
return ATA_PROT_FLAG_ATAPI;
case ATAPI_PROT_PIO:
return ATA_PROT_FLAG_ATAPI | ATA_PROT_FLAG_PIO;
case ATAPI_PROT_DMA:
return ATA_PROT_FLAG_ATAPI | ATA_PROT_FLAG_DMA;
}
return 0;
}
static inline int ata_is_atapi(u8 prot)
{
return ata_prot_flags(prot) & ATA_PROT_FLAG_ATAPI;
}
static inline int ata_is_nodata(u8 prot)
{
return !(ata_prot_flags(prot) & ATA_PROT_FLAG_DATA);
}
static inline int ata_is_pio(u8 prot)
{
return ata_prot_flags(prot) & ATA_PROT_FLAG_PIO;
}
static inline int ata_is_dma(u8 prot)
{
return ata_prot_flags(prot) & ATA_PROT_FLAG_DMA;
}
static inline int ata_is_ncq(u8 prot)
{
return ata_prot_flags(prot) & ATA_PROT_FLAG_NCQ;
}
static inline int ata_is_data(u8 prot)
{
return ata_prot_flags(prot) & ATA_PROT_FLAG_DATA;
}
static inline int is_multi_taskfile(struct ata_taskfile *tf)
{
return (tf->command == ATA_CMD_READ_MULTI) ||
(tf->command == ATA_CMD_WRITE_MULTI) ||
(tf->command == <API key>) ||
(tf->command == <API key>) ||
(tf->command == <API key>);
}
static inline const unsigned long *
sata_ehc_deb_timing(struct ata_eh_context *ehc)
{
if (ehc->i.flags & ATA_EHI_HOTPLUGGED)
return <API key>;
else
return <API key>;
}
static inline int ata_port_is_dummy(struct ata_port *ap)
{
return ap->ops == &ata_dummy_port_ops;
}
extern int sata_set_spd(struct ata_link *link);
extern int ata_std_prereset(struct ata_link *link, unsigned long deadline);
extern int <API key>(struct ata_link *link, unsigned long deadline,
int (*check_ready)(struct ata_link *link));
extern int sata_link_debounce(struct ata_link *link,
const unsigned long *params, unsigned long deadline);
extern int sata_link_resume(struct ata_link *link, const unsigned long *params,
unsigned long deadline);
extern int sata_link_scr_lpm(struct ata_link *link, enum ata_lpm_policy policy,
bool spm_wakeup);
extern int sata_link_hardreset(struct ata_link *link,
const unsigned long *timing, unsigned long deadline,
bool *online, int (*check_ready)(struct ata_link *));
extern int sata_std_hardreset(struct ata_link *link, unsigned int *class,
unsigned long deadline);
extern void ata_std_postreset(struct ata_link *link, unsigned int *classes);
extern struct ata_host *ata_host_alloc(struct device *dev, int max_ports);
extern struct ata_host *<API key>(struct device *dev,
const struct ata_port_info * const * ppi, int n_ports);
extern int ata_slave_link_init(struct ata_port *ap);
extern int ata_host_start(struct ata_host *host);
extern int ata_host_register(struct ata_host *host,
struct scsi_host_template *sht);
extern int ata_host_activate(struct ata_host *host, int irq,
irq_handler_t irq_handler, unsigned long irq_flags,
struct scsi_host_template *sht);
extern void ata_host_detach(struct ata_host *host);
extern void ata_host_init(struct ata_host *, struct device *, struct ata_port_operations *);
extern int ata_scsi_detect(struct scsi_host_template *sht);
extern int ata_scsi_ioctl(struct scsi_device *dev, int cmd, void __user *arg);
extern int ata_scsi_queuecmd(struct Scsi_Host *h, struct scsi_cmnd *cmd);
extern int ata_sas_scsi_ioctl(struct ata_port *ap, struct scsi_device *dev,
int cmd, void __user *arg);
extern void <API key>(struct ata_port *);
extern struct ata_port *ata_sas_port_alloc(struct ata_host *,
struct ata_port_info *, struct Scsi_Host *);
extern void ata_sas_async_probe(struct ata_port *ap);
extern int ata_sas_sync_probe(struct ata_port *ap);
extern int ata_sas_port_init(struct ata_port *);
extern int ata_sas_port_start(struct ata_port *ap);
extern void ata_sas_port_stop(struct ata_port *ap);
extern int <API key>(struct scsi_device *, struct ata_port *);
extern int ata_sas_queuecmd(struct scsi_cmnd *cmd, struct ata_port *ap);
extern int sata_scr_valid(struct ata_link *link);
extern int sata_scr_read(struct ata_link *link, int reg, u32 *val);
extern int sata_scr_write(struct ata_link *link, int reg, u32 val);
extern int <API key>(struct ata_link *link, int reg, u32 val);
extern bool ata_link_online(struct ata_link *link);
extern bool ata_link_offline(struct ata_link *link);
#ifdef CONFIG_PM
extern int ata_host_suspend(struct ata_host *host, pm_message_t mesg);
extern void ata_host_resume(struct ata_host *host);
extern int <API key>(struct ata_port *ap, int *async);
extern int <API key>(struct ata_port *ap, int *async);
#else
static inline int <API key>(struct ata_port *ap, int *async)
{
return 0;
}
static inline int <API key>(struct ata_port *ap, int *async)
{
return 0;
}
#endif
extern int ata_ratelimit(void);
extern void ata_msleep(struct ata_port *ap, unsigned int msecs);
extern u32 ata_wait_register(struct ata_port *ap, void __iomem *reg, u32 mask,
u32 val, unsigned long interval, unsigned long timeout);
extern int atapi_cmd_type(u8 opcode);
extern void ata_tf_to_fis(const struct ata_taskfile *tf,
u8 pmp, int is_cmd, u8 *fis);
extern void ata_tf_from_fis(const u8 *fis, struct ata_taskfile *tf);
extern unsigned long ata_pack_xfermask(unsigned long pio_mask,
unsigned long mwdma_mask, unsigned long udma_mask);
extern void ata_unpack_xfermask(unsigned long xfer_mask,
unsigned long *pio_mask, unsigned long *mwdma_mask,
unsigned long *udma_mask);
extern u8 ata_xfer_mask2mode(unsigned long xfer_mask);
extern unsigned long ata_xfer_mode2mask(u8 xfer_mode);
extern int ata_xfer_mode2shift(unsigned long xfer_mode);
extern const char *ata_mode_string(unsigned long xfer_mask);
extern unsigned long ata_id_xfermask(const u16 *id);
extern int ata_std_qc_defer(struct ata_queued_cmd *qc);
extern void ata_noop_qc_prep(struct ata_queued_cmd *qc);
extern void ata_sg_init(struct ata_queued_cmd *qc, struct scatterlist *sg,
unsigned int n_elem);
extern unsigned int ata_dev_classify(const struct ata_taskfile *tf);
extern void ata_dev_disable(struct ata_device *adev);
extern void ata_id_string(const u16 *id, unsigned char *s,
unsigned int ofs, unsigned int len);
extern void ata_id_c_string(const u16 *id, unsigned char *s,
unsigned int ofs, unsigned int len);
extern unsigned int ata_do_dev_read_id(struct ata_device *dev,
struct ata_taskfile *tf, u16 *id);
extern void ata_qc_complete(struct ata_queued_cmd *qc);
extern int <API key>(struct ata_port *ap, u32 qc_active);
extern void ata_scsi_simulate(struct ata_device *dev, struct scsi_cmnd *cmd);
extern int ata_std_bios_param(struct scsi_device *sdev,
struct block_device *bdev,
sector_t capacity, int geom[]);
extern void <API key>(struct scsi_device *sdev);
extern int <API key>(struct scsi_device *sdev);
extern void <API key>(struct scsi_device *sdev);
extern int <API key>(struct scsi_device *sdev,
int queue_depth, int reason);
extern int <API key>(struct ata_port *ap, struct scsi_device *sdev,
int queue_depth, int reason);
extern struct ata_device *ata_dev_pair(struct ata_device *adev);
extern int ata_do_set_mode(struct ata_link *link, struct ata_device **r_failed_dev);
extern void <API key>(struct Scsi_Host *host, struct ata_port *ap);
extern void <API key>(struct Scsi_Host *host, struct ata_port *ap, struct list_head *eh_q);
extern int ata_cable_40wire(struct ata_port *ap);
extern int ata_cable_80wire(struct ata_port *ap);
extern int ata_cable_sata(struct ata_port *ap);
extern int ata_cable_ignore(struct ata_port *ap);
extern int ata_cable_unknown(struct ata_port *ap);
/* Timing helpers */
extern unsigned int ata_pio_need_iordy(const struct ata_device *);
extern const struct ata_timing *<API key>(u8 xfer_mode);
extern int ata_timing_compute(struct ata_device *, unsigned short,
struct ata_timing *, int, int);
extern void ata_timing_merge(const struct ata_timing *,
const struct ata_timing *, struct ata_timing *,
unsigned int);
extern u8 <API key>(unsigned int xfer_shift, int cycle);
/* PCI */
#ifdef CONFIG_PCI
struct pci_dev;
struct pci_bits {
unsigned int reg; /* PCI config register to read */
unsigned int width; /* 1 (8 bit), 2 (16 bit), 4 (32 bit) */
unsigned long mask;
unsigned long val;
};
extern int <API key>(struct pci_dev *pdev, const struct pci_bits *bits);
extern void ata_pci_remove_one(struct pci_dev *pdev);
#ifdef CONFIG_PM
extern void <API key>(struct pci_dev *pdev, pm_message_t mesg);
extern int __must_check <API key>(struct pci_dev *pdev);
extern int <API key>(struct pci_dev *pdev, pm_message_t mesg);
extern int <API key>(struct pci_dev *pdev);
#endif /* CONFIG_PM */
#endif /* CONFIG_PCI */
struct platform_device;
extern int <API key>(struct platform_device *pdev);
/*
* ACPI - drivers/ata/libata-acpi.c
*/
#ifdef CONFIG_ATA_ACPI
static inline const struct ata_acpi_gtm *ata_acpi_init_gtm(struct ata_port *ap)
{
if (ap->pflags & <API key>)
return &ap->__acpi_init_gtm;
return NULL;
}
int ata_acpi_stm(struct ata_port *ap, const struct ata_acpi_gtm *stm);
int ata_acpi_gtm(struct ata_port *ap, struct ata_acpi_gtm *stm);
unsigned long <API key>(struct ata_device *dev,
const struct ata_acpi_gtm *gtm);
int ata_acpi_cbl_80wire(struct ata_port *ap, const struct ata_acpi_gtm *gtm);
#else
static inline const struct ata_acpi_gtm *ata_acpi_init_gtm(struct ata_port *ap)
{
return NULL;
}
static inline int ata_acpi_stm(const struct ata_port *ap,
struct ata_acpi_gtm *stm)
{
return -ENOSYS;
}
static inline int ata_acpi_gtm(const struct ata_port *ap,
struct ata_acpi_gtm *stm)
{
return -ENOSYS;
}
static inline unsigned int <API key>(struct ata_device *dev,
const struct ata_acpi_gtm *gtm)
{
return 0;
}
static inline int ata_acpi_cbl_80wire(struct ata_port *ap,
const struct ata_acpi_gtm *gtm)
{
return 0;
}
#endif
/*
* EH - drivers/ata/libata-eh.c
*/
extern void <API key>(struct ata_port *ap);
extern void ata_port_wait_eh(struct ata_port *ap);
extern int ata_link_abort(struct ata_link *link);
extern int ata_port_abort(struct ata_port *ap);
extern int ata_port_freeze(struct ata_port *ap);
extern int <API key>(struct ata_port *ap);
extern void ata_eh_freeze_port(struct ata_port *ap);
extern void ata_eh_thaw_port(struct ata_port *ap);
extern void ata_eh_qc_complete(struct ata_queued_cmd *qc);
extern void ata_eh_qc_retry(struct ata_queued_cmd *qc);
extern void <API key>(struct ata_link *link);
extern void ata_do_eh(struct ata_port *ap, ata_prereset_fn_t prereset,
ata_reset_fn_t softreset, ata_reset_fn_t hardreset,
ata_postreset_fn_t postreset);
extern void <API key>(struct ata_port *ap);
extern void ata_std_sched_eh(struct ata_port *ap);
extern void ata_std_end_eh(struct ata_port *ap);
extern int ata_link_nr_enabled(struct ata_link *link);
/*
* Base operations to inherit from and initializers for sht
*
* Operations
*
* base : Common to all libata drivers.
* sata : SATA controllers w/ native interface.
* pmp : SATA controllers w/ PMP support.
* sff : SFF ATA controllers w/o BMDMA support.
* bmdma : SFF ATA controllers w/ BMDMA support.
*
* sht initializers
*
* BASE : Common to all libata drivers. The user must set
* sg_tablesize and dma_boundary.
* PIO : SFF ATA controllers w/ only PIO support.
* BMDMA : SFF ATA controllers w/ BMDMA support. sg_tablesize and
* dma_boundary are set to BMDMA limits.
* NCQ : SATA controllers supporting NCQ. The user must set
* sg_tablesize, dma_boundary and can_queue.
*/
extern const struct ata_port_operations ata_base_port_ops;
extern const struct ata_port_operations sata_port_ops;
extern struct device_attribute *<API key>[];
#define ATA_BASE_SHT(drv_name) \
.module = THIS_MODULE, \
.name = drv_name, \
.ioctl = ata_scsi_ioctl, \
.queuecommand = ata_scsi_queuecmd, \
.can_queue = ATA_DEF_QUEUE, \
.this_id = ATA_SHT_THIS_ID, \
.cmd_per_lun = ATA_SHT_CMD_PER_LUN, \
.emulated = ATA_SHT_EMULATED, \
.use_clustering = <API key>, \
.proc_name = drv_name, \
.slave_configure = <API key>, \
.slave_destroy = <API key>, \
.bios_param = ata_std_bios_param, \
.<API key> = <API key>, \
.sdev_attrs = <API key>
#define ATA_NCQ_SHT(drv_name) \
ATA_BASE_SHT(drv_name), \
.change_queue_depth = <API key>
/*
* PMP helpers
*/
#ifdef CONFIG_SATA_PMP
static inline bool sata_pmp_supported(struct ata_port *ap)
{
return ap->flags & ATA_FLAG_PMP;
}
static inline bool sata_pmp_attached(struct ata_port *ap)
{
return ap->nr_pmp_links != 0;
}
static inline int ata_is_host_link(const struct ata_link *link)
{
return link == &link->ap->link || link == link->ap->slave_link;
}
#else /* CONFIG_SATA_PMP */
static inline bool sata_pmp_supported(struct ata_port *ap)
{
return false;
}
static inline bool sata_pmp_attached(struct ata_port *ap)
{
return false;
}
static inline int ata_is_host_link(const struct ata_link *link)
{
return 1;
}
#endif /* CONFIG_SATA_PMP */
static inline int sata_srst_pmp(struct ata_link *link)
{
if (sata_pmp_supported(link->ap) && ata_is_host_link(link))
return SATA_PMP_CTRL_PORT;
return link->pmp;
}
/*
* printk helpers
*/
__printf(3, 4)
int ata_port_printk(const struct ata_port *ap, const char *level,
const char *fmt, ...);
__printf(3, 4)
int ata_link_printk(const struct ata_link *link, const char *level,
const char *fmt, ...);
__printf(3, 4)
int ata_dev_printk(const struct ata_device *dev, const char *level,
const char *fmt, ...);
#define ata_port_err(ap, fmt, ...) \
ata_port_printk(ap, KERN_ERR, fmt, ##__VA_ARGS__)
#define ata_port_warn(ap, fmt, ...) \
ata_port_printk(ap, KERN_WARNING, fmt, ##__VA_ARGS__)
#define ata_port_notice(ap, fmt, ...) \
ata_port_printk(ap, KERN_NOTICE, fmt, ##__VA_ARGS__)
#define ata_port_info(ap, fmt, ...) \
ata_port_printk(ap, KERN_INFO, fmt, ##__VA_ARGS__)
#define ata_port_dbg(ap, fmt, ...) \
ata_port_printk(ap, KERN_DEBUG, fmt, ##__VA_ARGS__)
#define ata_link_err(link, fmt, ...) \
ata_link_printk(link, KERN_ERR, fmt, ##__VA_ARGS__)
#define ata_link_warn(link, fmt, ...) \
ata_link_printk(link, KERN_WARNING, fmt, ##__VA_ARGS__)
#define ata_link_notice(link, fmt, ...) \
ata_link_printk(link, KERN_NOTICE, fmt, ##__VA_ARGS__)
#define ata_link_info(link, fmt, ...) \
ata_link_printk(link, KERN_INFO, fmt, ##__VA_ARGS__)
#define ata_link_dbg(link, fmt, ...) \
ata_link_printk(link, KERN_DEBUG, fmt, ##__VA_ARGS__)
#define ata_dev_err(dev, fmt, ...) \
ata_dev_printk(dev, KERN_ERR, fmt, ##__VA_ARGS__)
#define ata_dev_warn(dev, fmt, ...) \
ata_dev_printk(dev, KERN_WARNING, fmt, ##__VA_ARGS__)
#define ata_dev_notice(dev, fmt, ...) \
ata_dev_printk(dev, KERN_NOTICE, fmt, ##__VA_ARGS__)
#define ata_dev_info(dev, fmt, ...) \
ata_dev_printk(dev, KERN_INFO, fmt, ##__VA_ARGS__)
#define ata_dev_dbg(dev, fmt, ...) \
ata_dev_printk(dev, KERN_DEBUG, fmt, ##__VA_ARGS__)
void ata_print_version(const struct device *dev, const char *version);
/*
* ata_eh_info helpers
*/
extern __printf(2, 3)
void __ata_ehi_push_desc(struct ata_eh_info *ehi, const char *fmt, ...);
extern __printf(2, 3)
void ata_ehi_push_desc(struct ata_eh_info *ehi, const char *fmt, ...);
extern void ata_ehi_clear_desc(struct ata_eh_info *ehi);
static inline void ata_ehi_hotplugged(struct ata_eh_info *ehi)
{
ehi->probe_mask |= (1 << ATA_MAX_DEVICES) - 1;
ehi->flags |= ATA_EHI_HOTPLUGGED;
ehi->action |= ATA_EH_RESET | ATA_EH_ENABLE_LINK;
ehi->err_mask |= AC_ERR_ATA_BUS;
}
/*
* port description helpers
*/
extern __printf(2, 3)
void ata_port_desc(struct ata_port *ap, const char *fmt, ...);
#ifdef CONFIG_PCI
extern void ata_port_pbar_desc(struct ata_port *ap, int bar, ssize_t offset,
const char *name);
#endif
static inline unsigned int ata_tag_valid(unsigned int tag)
{
return (tag < ATA_MAX_QUEUE) ? 1 : 0;
}
static inline unsigned int ata_tag_internal(unsigned int tag)
{
return tag == ATA_TAG_INTERNAL;
}
/*
* device helpers
*/
static inline unsigned int ata_class_enabled(unsigned int class)
{
return class == ATA_DEV_ATA || class == ATA_DEV_ATAPI ||
class == ATA_DEV_PMP || class == ATA_DEV_SEMB;
}
static inline unsigned int ata_class_disabled(unsigned int class)
{
return class == ATA_DEV_ATA_UNSUP || class == ATA_DEV_ATAPI_UNSUP ||
class == ATA_DEV_PMP_UNSUP || class == ATA_DEV_SEMB_UNSUP;
}
static inline unsigned int ata_class_absent(unsigned int class)
{
return !ata_class_enabled(class) && !ata_class_disabled(class);
}
static inline unsigned int ata_dev_enabled(const struct ata_device *dev)
{
return ata_class_enabled(dev->class);
}
static inline unsigned int ata_dev_disabled(const struct ata_device *dev)
{
return ata_class_disabled(dev->class);
}
static inline unsigned int ata_dev_absent(const struct ata_device *dev)
{
return ata_class_absent(dev->class);
}
/*
* link helpers
*/
static inline int <API key>(const struct ata_link *link)
{
if (ata_is_host_link(link) && link->ap->flags & ATA_FLAG_SLAVE_POSS)
return 2;
return 1;
}
static inline int ata_link_active(struct ata_link *link)
{
return ata_tag_valid(link->active_tag) || link->sactive;
}
/*
* Iterators
*
* ATA_LITER_* constants are used to select link iteration mode and
* ATA_DITER_* device iteration mode.
*
* For a custom iteration directly using ata_{link|dev}_next(), if
* @link or @dev, respectively, is NULL, the first element is
* returned. @dev and @link can be any valid device or link and the
* next element according to the iteration mode will be returned.
* After the last element, NULL is returned.
*/
enum ata_link_iter_mode {
ATA_LITER_EDGE, /* if present, PMP links only; otherwise,
* host link. no slave link */
<API key>, /* host link followed by PMP or slave links */
ATA_LITER_PMP_FIRST, /* PMP links followed by host link,
* slave link still comes after host link */
};
enum ata_dev_iter_mode {
ATA_DITER_ENABLED,
<API key>,
ATA_DITER_ALL,
<API key>,
};
extern struct ata_link *ata_link_next(struct ata_link *link,
struct ata_port *ap,
enum ata_link_iter_mode mode);
extern struct ata_device *ata_dev_next(struct ata_device *dev,
struct ata_link *link,
enum ata_dev_iter_mode mode);
/*
* Shortcut notation for iterations
*
* ata_for_each_link() iterates over each link of @ap according to
* @mode. @link points to the current link in the loop. @link is
* NULL after loop termination. ata_for_each_dev() works the same way
* except that it iterates over each device of @link.
*
* Note that the mode prefixes ATA_{L|D}ITER_ shouldn't need to be
* specified when using the following shorthand notations. Only the
* mode itself (EDGE, HOST_FIRST, ENABLED, etc...) should be
* specified. This not only increases brevity but also makes it
* impossible to use ATA_LITER_* for device iteration or vice-versa.
*/
#define ata_for_each_link(link, ap, mode) \
for ((link) = ata_link_next(NULL, (ap), ATA_LITER_##mode); (link); \
(link) = ata_link_next((link), (ap), ATA_LITER_##mode))
#define ata_for_each_dev(dev, link, mode) \
for ((dev) = ata_dev_next(NULL, (link), ATA_DITER_##mode); (dev); \
(dev) = ata_dev_next((dev), (link), ATA_DITER_##mode))
/**
* ata_ncq_enabled - Test whether NCQ is enabled
* @dev: ATA device to test for
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* 1 if NCQ is enabled for @dev, 0 otherwise.
*/
static inline int ata_ncq_enabled(struct ata_device *dev)
{
return (dev->flags & (ATA_DFLAG_PIO | ATA_DFLAG_NCQ_OFF |
ATA_DFLAG_NCQ)) == ATA_DFLAG_NCQ;
}
static inline bool <API key>(struct ata_device *dev)
{
return (dev->flags & <API key>) &&
(dev->ncq_send_recv_cmds[<API key>] &
<API key>);
}
static inline void ata_qc_set_polling(struct ata_queued_cmd *qc)
{
qc->tf.ctl |= ATA_NIEN;
}
static inline struct ata_queued_cmd *__ata_qc_from_tag(struct ata_port *ap,
unsigned int tag)
{
if (likely(ata_tag_valid(tag)))
return &ap->qcmd[tag];
return NULL;
}
static inline struct ata_queued_cmd *ata_qc_from_tag(struct ata_port *ap,
unsigned int tag)
{
struct ata_queued_cmd *qc = __ata_qc_from_tag(ap, tag);
if (unlikely(!qc) || !ap->ops->error_handler)
return qc;
if ((qc->flags & (ATA_QCFLAG_ACTIVE |
ATA_QCFLAG_FAILED)) == ATA_QCFLAG_ACTIVE)
return qc;
return NULL;
}
static inline unsigned int ata_qc_raw_nbytes(struct ata_queued_cmd *qc)
{
return qc->nbytes - min(qc->extrabytes, qc->nbytes);
}
static inline void ata_tf_init(struct ata_device *dev, struct ata_taskfile *tf)
{
memset(tf, 0, sizeof(*tf));
#ifdef CONFIG_ATA_SFF
tf->ctl = dev->link->ap->ctl;
#else
tf->ctl = ATA_DEVCTL_OBS;
#endif
if (dev->devno == 0)
tf->device = ATA_DEVICE_OBS;
else
tf->device = ATA_DEVICE_OBS | ATA_DEV1;
}
static inline void ata_qc_reinit(struct ata_queued_cmd *qc)
{
qc->dma_dir = DMA_NONE;
qc->sg = NULL;
qc->flags = 0;
qc->cursg = NULL;
qc->cursg_ofs = 0;
qc->nbytes = qc->extrabytes = qc->curbytes = 0;
qc->n_elem = 0;
qc->err_mask = 0;
qc->sect_size = ATA_SECT_SIZE;
ata_tf_init(qc->dev, &qc->tf);
/* init result_tf such that it indicates normal completion */
qc->result_tf.command = ATA_DRDY;
qc->result_tf.feature = 0;
}
static inline int ata_try_flush_cache(const struct ata_device *dev)
{
return <API key>(dev->id) ||
ata_id_has_flush(dev->id) ||
<API key>(dev->id);
}
static inline unsigned int ac_err_mask(u8 status)
{
if (status & (ATA_BUSY | ATA_DRQ))
return AC_ERR_HSM;
if (status & (ATA_ERR | ATA_DF))
return AC_ERR_DEV;
return 0;
}
static inline unsigned int __ac_err_mask(u8 status)
{
unsigned int mask = ac_err_mask(status);
if (mask == 0)
return AC_ERR_OTHER;
return mask;
}
static inline struct ata_port *ata_shost_to_port(struct Scsi_Host *host)
{
return *(struct ata_port **)&host->hostdata[0];
}
static inline int ata_check_ready(u8 status)
{
if (!(status & ATA_BUSY))
return 1;
/* 0xff indicates either no device or device not ready */
if (status == 0xff)
return -ENODEV;
return 0;
}
static inline unsigned long ata_deadline(unsigned long from_jiffies,
unsigned long timeout_msecs)
{
return from_jiffies + msecs_to_jiffies(timeout_msecs);
}
/* Don't open code these in drivers as there are traps. Firstly the range may
change in future hardware and specs, secondly 0xFF means 'no DMA' but is
> UDMA_0. Dyma ddreigiau */
static inline int ata_using_mwdma(struct ata_device *adev)
{
if (adev->dma_mode >= XFER_MW_DMA_0 && adev->dma_mode <= XFER_MW_DMA_4)
return 1;
return 0;
}
static inline int ata_using_udma(struct ata_device *adev)
{
if (adev->dma_mode >= XFER_UDMA_0 && adev->dma_mode <= XFER_UDMA_7)
return 1;
return 0;
}
static inline int ata_dma_enabled(struct ata_device *adev)
{
return (adev->dma_mode == 0xFF ? 0 : 1);
}
/**************************************************************************
* PMP - drivers/ata/libata-pmp.c
*/
#ifdef CONFIG_SATA_PMP
extern const struct ata_port_operations sata_pmp_port_ops;
extern int <API key>(struct ata_queued_cmd *qc);
extern void <API key>(struct ata_port *ap);
#else /* CONFIG_SATA_PMP */
#define sata_pmp_port_ops sata_port_ops
#define <API key> ata_std_qc_defer
#define <API key> <API key>
#endif /* CONFIG_SATA_PMP */
/**************************************************************************
* SFF - drivers/ata/libata-sff.c
*/
#ifdef CONFIG_ATA_SFF
extern const struct ata_port_operations ata_sff_port_ops;
extern const struct ata_port_operations <API key>;
/* PIO only, sg_tablesize and dma_boundary limits can be removed */
#define ATA_PIO_SHT(drv_name) \
ATA_BASE_SHT(drv_name), \
.sg_tablesize = LIBATA_MAX_PRD, \
.dma_boundary = ATA_DMA_BOUNDARY
extern void ata_sff_dev_select(struct ata_port *ap, unsigned int device);
extern u8 <API key>(struct ata_port *ap);
extern void ata_sff_pause(struct ata_port *ap);
extern void ata_sff_dma_pause(struct ata_port *ap);
extern int ata_sff_busy_sleep(struct ata_port *ap,
unsigned long timeout_pat, unsigned long timeout);
extern int ata_sff_wait_ready(struct ata_link *link, unsigned long deadline);
extern void ata_sff_tf_load(struct ata_port *ap, const struct ata_taskfile *tf);
extern void ata_sff_tf_read(struct ata_port *ap, struct ata_taskfile *tf);
extern void <API key>(struct ata_port *ap,
const struct ata_taskfile *tf);
extern unsigned int ata_sff_data_xfer(struct ata_device *dev,
unsigned char *buf, unsigned int buflen, int rw);
extern unsigned int ata_sff_data_xfer32(struct ata_device *dev,
unsigned char *buf, unsigned int buflen, int rw);
extern unsigned int <API key>(struct ata_device *dev,
unsigned char *buf, unsigned int buflen, int rw);
extern void ata_sff_irq_on(struct ata_port *ap);
extern void ata_sff_irq_clear(struct ata_port *ap);
extern int ata_sff_hsm_move(struct ata_port *ap, struct ata_queued_cmd *qc,
u8 status, int in_wq);
extern void ata_sff_queue_work(struct work_struct *work);
extern void <API key>(struct delayed_work *dwork,
unsigned long delay);
extern void <API key>(struct ata_link *link, unsigned long delay);
extern unsigned int ata_sff_qc_issue(struct ata_queued_cmd *qc);
extern bool ata_sff_qc_fill_rtf(struct ata_queued_cmd *qc);
extern unsigned int ata_sff_port_intr(struct ata_port *ap,
struct ata_queued_cmd *qc);
extern irqreturn_t ata_sff_interrupt(int irq, void *dev_instance);
extern void <API key>(struct ata_port *ap);
extern void ata_sff_freeze(struct ata_port *ap);
extern void ata_sff_thaw(struct ata_port *ap);
extern int ata_sff_prereset(struct ata_link *link, unsigned long deadline);
extern unsigned int <API key>(struct ata_device *dev, int present,
u8 *r_err);
extern int <API key>(struct ata_link *link, unsigned int devmask,
unsigned long deadline);
extern int ata_sff_softreset(struct ata_link *link, unsigned int *classes,
unsigned long deadline);
extern int sata_sff_hardreset(struct ata_link *link, unsigned int *class,
unsigned long deadline);
extern void ata_sff_postreset(struct ata_link *link, unsigned int *classes);
extern void ata_sff_drain_fifo(struct ata_queued_cmd *qc);
extern void <API key>(struct ata_port *ap);
extern void ata_sff_std_ports(struct ata_ioports *ioaddr);
#ifdef CONFIG_PCI
extern int <API key>(struct ata_host *host);
extern int <API key>(struct pci_dev *pdev,
const struct ata_port_info * const * ppi,
struct ata_host **r_host);
extern int <API key>(struct ata_host *host,
irq_handler_t irq_handler,
struct scsi_host_template *sht);
extern int <API key>(struct pci_dev *pdev,
const struct ata_port_info * const * ppi,
struct scsi_host_template *sht, void *host_priv, int hflags);
#endif /* CONFIG_PCI */
#ifdef CONFIG_ATA_BMDMA
extern const struct ata_port_operations ata_bmdma_port_ops;
#define ATA_BMDMA_SHT(drv_name) \
ATA_BASE_SHT(drv_name), \
.sg_tablesize = LIBATA_MAX_PRD, \
.dma_boundary = ATA_DMA_BOUNDARY
extern void ata_bmdma_qc_prep(struct ata_queued_cmd *qc);
extern unsigned int ata_bmdma_qc_issue(struct ata_queued_cmd *qc);
extern void <API key>(struct ata_queued_cmd *qc);
extern unsigned int ata_bmdma_port_intr(struct ata_port *ap,
struct ata_queued_cmd *qc);
extern irqreturn_t ata_bmdma_interrupt(int irq, void *dev_instance);
extern void <API key>(struct ata_port *ap);
extern void <API key>(struct ata_queued_cmd *qc);
extern void ata_bmdma_irq_clear(struct ata_port *ap);
extern void ata_bmdma_setup(struct ata_queued_cmd *qc);
extern void ata_bmdma_start(struct ata_queued_cmd *qc);
extern void ata_bmdma_stop(struct ata_queued_cmd *qc);
extern u8 ata_bmdma_status(struct ata_port *ap);
extern int <API key>(struct ata_port *ap);
extern int <API key>(struct ata_port *ap);
#ifdef CONFIG_PCI
extern int <API key>(struct pci_dev *pdev);
extern void ata_pci_bmdma_init(struct ata_host *host);
extern int <API key>(struct pci_dev *pdev,
const struct ata_port_info * const * ppi,
struct ata_host **r_host);
extern int <API key>(struct pci_dev *pdev,
const struct ata_port_info * const * ppi,
struct scsi_host_template *sht,
void *host_priv, int hflags);
#endif /* CONFIG_PCI */
#endif /* CONFIG_ATA_BMDMA */
/**
* ata_sff_busy_wait - Wait for a port status register
* @ap: Port to wait for.
* @bits: bits that must be clear
* @max: number of 10uS waits to perform
*
* Waits up to max*10 microseconds for the selected bits in the port's
* status register to be cleared.
* Returns final value of status register.
*
* LOCKING:
* Inherited from caller.
*/
static inline u8 ata_sff_busy_wait(struct ata_port *ap, unsigned int bits,
unsigned int max)
{
u8 status;
do {
udelay(10);
status = ap->ops->sff_check_status(ap);
max
} while (status != 0xff && (status & bits) && (max > 0));
return status;
}
/**
* ata_wait_idle - Wait for a port to be idle.
* @ap: Port to wait for.
*
* Waits up to 10ms for port's BUSY and DRQ signals to clear.
* Returns final value of status register.
*
* LOCKING:
* Inherited from caller.
*/
static inline u8 ata_wait_idle(struct ata_port *ap)
{
u8 status = ata_sff_busy_wait(ap, ATA_BUSY | ATA_DRQ, 1000);
#ifdef ATA_DEBUG
if (status != 0xff && (status & (ATA_BUSY | ATA_DRQ)))
ata_port_printk(ap, KERN_DEBUG, "abnormal Status 0x%X\n",
status);
#endif
return status;
}
#endif /* CONFIG_ATA_SFF */
#endif /* __LINUX_LIBATA_H__ */ |
/* ScriptData
SDName: Boss_Void_Reaver
SD%Complete: 90
SDComment: Should reset if raid are out of room.
SDCategory: Tempest Keep, The Eye
EndScriptData */
#include "precompiled.h"
#include "def_the_eye.h"
#define SAY_AGGRO -1550000
#define SAY_SLAY1 -1550001
#define SAY_SLAY2 -1550002
#define SAY_SLAY3 -1550003
#define SAY_DEATH -1550004
#define SAY_POUNDING1 -1550005
#define SAY_POUNDING2 -1550006
#define SPELL_POUNDING 34162
#define <API key> 34172
#define SPELL_KNOCK_AWAY 25778
#define SPELL_BERSERK 26662
//Unknown function. If target not found, this will be created and used as dummy target instead?
//#define CREATURE_ORB_TARGET 19577
struct MANGOS_DLL_DECL boss_void_reaverAI : public ScriptedAI
{
boss_void_reaverAI(Creature* pCreature) : ScriptedAI(pCreature)
{
m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
Reset();
}
ScriptedInstance* m_pInstance;
uint32 Pounding_Timer;
uint32 ArcaneOrb_Timer;
uint32 KnockAway_Timer;
uint32 Berserk_Timer;
void Reset()
{
Pounding_Timer = 15000;
ArcaneOrb_Timer = 3000;
KnockAway_Timer = 30000;
Berserk_Timer = 600000;
if (m_pInstance && m_creature->isAlive())
m_pInstance->SetData(TYPE_VOIDREAVER, NOT_STARTED);
}
void KilledUnit(Unit *victim)
{
switch(rand()%3)
{
case 0: DoScriptText(SAY_SLAY1, m_creature); break;
case 1: DoScriptText(SAY_SLAY2, m_creature); break;
case 2: DoScriptText(SAY_SLAY3, m_creature); break;
}
}
void JustDied(Unit *victim)
{
DoScriptText(SAY_DEATH, m_creature);
if (m_pInstance)
m_pInstance->SetData(TYPE_VOIDREAVER, DONE);
}
void Aggro(Unit* pWho)
{
DoScriptText(SAY_AGGRO, m_creature);
m_creature->SetInCombatWithZone();
if (m_pInstance)
m_pInstance->SetData(TYPE_VOIDREAVER, IN_PROGRESS);
}
void UpdateAI(const uint32 diff)
{
if (!m_creature->SelectHostilTarget() || !m_creature->getVictim())
return;
// Pounding
if (Pounding_Timer < diff)
{
DoCast(m_creature->getVictim(),SPELL_POUNDING);
switch(rand()%2)
{
case 0: DoScriptText(SAY_POUNDING1, m_creature); break;
case 1: DoScriptText(SAY_POUNDING2, m_creature); break;
}
Pounding_Timer = 15000; //cast time(3000) + cooldown time(12000)
}else Pounding_Timer -= diff;
// Arcane Orb
if (ArcaneOrb_Timer < diff)
{
Unit *target = NULL;
std::list<HostilReference *> t_list = m_creature->getThreatManager().getThreatList();
std::vector<Unit *> target_list;
for(std::list<HostilReference *>::iterator itr = t_list.begin(); itr!= t_list.end(); ++itr)
{
target = Unit::GetUnit(*m_creature, (*itr)->getUnitGuid());
// exclude pets & totems
if (target->GetTypeId() != TYPEID_PLAYER)
continue;
//18 yard radius minimum
if (target && !target->IsWithinDist(m_creature, 18.0f, false))
target_list.push_back(target);
target = NULL;
}
if (target_list.size())
target = *(target_list.begin()+rand()%target_list.size());
else
target = m_creature->getVictim();
if (target)
DoCast(target, <API key>);
ArcaneOrb_Timer = 3000;
}else ArcaneOrb_Timer -= diff;
// Single Target knock back, reduces aggro
if (KnockAway_Timer < diff)
{
DoCast(m_creature->getVictim(),SPELL_KNOCK_AWAY);
//Drop 25% aggro
if (m_creature->getThreatManager().getThreat(m_creature->getVictim()))
m_creature->getThreatManager().modifyThreatPercent(m_creature->getVictim(),-25);
KnockAway_Timer = 30000;
}else KnockAway_Timer -= diff;
//Berserk
if (Berserk_Timer < diff)
{
if (m_creature-><API key>(false))
m_creature-><API key>(false);
DoCast(m_creature,SPELL_BERSERK);
Berserk_Timer = 600000;
}else Berserk_Timer -= diff;
<API key>();
<API key>(diff);
}
};
CreatureAI* <API key>(Creature* pCreature)
{
return new boss_void_reaverAI(pCreature);
}
void <API key>()
{
Script *newscript;
newscript = new Script;
newscript->Name = "boss_void_reaver";
newscript->GetAI = &<API key>;
newscript->RegisterSelf();
} |
<?php
/* core/themes/bartik/templates/node.html.twig */
class <API key> extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 66
$context["classes"] = array(0 => "node", 1 => ("node--type-" . \Drupal\Component\Utility\Html::getClass($this->getAttribute((isset($context["node"]) ? $context["node"] : null), "bundle", array()))), 2 => (($this->getAttribute((isset($context["node"]) ? $context["node"] : null), "isPromoted", array(), "method")) ? ("node--promoted") : ("")), 3 => (($this->getAttribute((isset($context["node"]) ? $context["node"] : null), "isSticky", array(), "method")) ? ("node--sticky") : ("")), 4 => (((!$this->getAttribute((isset($context["node"]) ? $context["node"] : null), "isPublished", array(), "method"))) ? ("node--unpublished") : ("")), 5 => (((isset($context["view_mode"]) ? $context["view_mode"] : null)) ? (("node--view-mode-" . \Drupal\Component\Utility\Html::getClass((isset($context["view_mode"]) ? $context["view_mode"] : null)))) : ("")), 6 => "clearfix");
// line 76
echo "<article";
echo <API key>($this->env, $this->getAttribute((isset($context["attributes"]) ? $context["attributes"] : null), "addClass", array(0 => (isset($context["classes"]) ? $context["classes"] : null)), "method"), "html", null, true);
echo ">
<header>
";
// line 78
echo <API key>($this->env, (isset($context["title_prefix"]) ? $context["title_prefix"] : null), "html", null, true);
echo "
";
// line 79
if ((!(isset($context["page"]) ? $context["page"] : null))) {
// line 80
echo " <h2";
echo <API key>($this->env, $this->getAttribute((isset($context["title_attributes"]) ? $context["title_attributes"] : null), "addClass", array(0 => "node__title"), "method"), "html", null, true);
echo ">
<a href=\"";
// line 81
echo <API key>($this->env, (isset($context["url"]) ? $context["url"] : null), "html", null, true);
echo "\" rel=\"bookmark\">";
echo <API key>($this->env, (isset($context["label"]) ? $context["label"] : null), "html", null, true);
echo "</a>
</h2>
";
}
// line 84
echo " ";
echo <API key>($this->env, (isset($context["title_suffix"]) ? $context["title_suffix"] : null), "html", null, true);
echo "
";
// line 85
if ((isset($context["display_submitted"]) ? $context["display_submitted"] : null)) {
// line 86
echo " <div class=\"node__meta\">
";
// line 87
echo <API key>($this->env, (isset($context["author_picture"]) ? $context["author_picture"] : null), "html", null, true);
echo "
<span";
// line 88
echo <API key>($this->env, (isset($context["author_attributes"]) ? $context["author_attributes"] : null), "html", null, true);
echo ">
";
// line 89
echo t("Submitted by !author_name on !date", array("!author_name" => (isset($context["author_name"]) ? $context["author_name"] : null), "!date" => (isset($context["date"]) ? $context["date"] : null), ));
// line 90
echo " </span>
";
// line 91
echo <API key>($this->env, (isset($context["metadata"]) ? $context["metadata"] : null), "html", null, true);
echo "
</div>
";
}
// line 94
echo " </header>
<div";
// line 95
echo <API key>($this->env, $this->getAttribute((isset($context["content_attributes"]) ? $context["content_attributes"] : null), "addClass", array(0 => "node__content", 1 => "clearfix"), "method"), "html", null, true);
echo ">
";
// line 96
echo <API key>($this->env, twig_without((isset($context["content"]) ? $context["content"] : null), "comment", "links"), "html", null, true);
echo "
</div>
";
// line 98
if ($this->getAttribute((isset($context["content"]) ? $context["content"] : null), "links", array())) {
// line 99
echo " <div class=\"node__links\">";
echo <API key>($this->env, $this->getAttribute((isset($context["content"]) ? $context["content"] : null), "links", array()), "html", null, true);
echo "</div>
";
}
// line 101
echo " ";
echo <API key>($this->env, $this->getAttribute((isset($context["content"]) ? $context["content"] : null), "comment", array()), "html", null, true);
echo "
</article>
";
}
public function getTemplateName()
{
return "core/themes/bartik/templates/node.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 95 => 101, 89 => 99, 87 => 98, 82 => 96, 78 => 95, 75 => 94, 69 => 91, 66 => 90, 64 => 89, 60 => 88, 56 => 87, 53 => 86, 51 => 85, 46 => 84, 38 => 81, 33 => 80, 31 => 79, 27 => 78, 21 => 76, 19 => 66,);
}
} |
#if defined(<API key>) && defined(CONFIG_MAGIC_SYSRQ)
#define SUPPORT_SYSRQ
#endif
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <linux/console.h>
#include <linux/sysrq.h>
#include <linux/device.h>
#include <linux/tty.h>
#include <linux/tty_flip.h>
#include <linux/serial_core.h>
#include <linux/serial.h>
#include <asm/l4.h>
/* This is the same major as the sa1100 one */
#define SERIAL_L4SER_MAJOR 204
#define MINOR_START 5
#define PORT0_NAME "log"
#define NR_ADDITIONAL_PORTS 3
static int ports_to_add_pos;
#define L4SER_REQUESTED 1
#define L4SER_NOECHO 0x8000
static char _shared_mem[1024] __attribute__((aligned(4096)));
static void karma_ser_write(unsigned long opcode, unsigned long val)
{
karma_hypercall1(KARMA_MAKE_COMMAND(KARMA_DEVICE_ID(ser), opcode), &val);
}
static int karma_ser_read(unsigned long opcode)
{
KARMA_READ_IMPL(ser, opcode);
}
struct l4ser_uart_port {
struct uart_port port;
char cap_name[20];
int flags, inited;
};
static struct l4ser_uart_port l4ser_port[1 + NR_ADDITIONAL_PORTS];
static void l4ser_stop_tx(struct uart_port *port)
{
}
static void l4ser_stop_rx(struct uart_port *port)
{
}
static void l4ser_enable_ms(struct uart_port *port)
{
}
static int
l4ser_getchar(struct l4ser_uart_port *l4port)
{
int c;
c = (int)karma_ser_read(karma_ser_df_read);
return c;
}
static void
l4ser_rx_chars(struct uart_port *port)
{
struct l4ser_uart_port *l4port = (struct l4ser_uart_port *)port;
struct tty_port *tty_port = &port->state->port;
unsigned int flg;
int ch;
while (1) {
ch = l4ser_getchar(l4port);
if (ch == -1) // -1 denotes end of line
break;
port->icount.rx++;
flg = TTY_NORMAL;
// ^ can be used as a sysrq starter
#if 0
if (ch == '^') {
if (port->sysrq)
port->sysrq = 0;
else {
port->icount.brk++;
uart_handle_break(port);
continue;
}
}
#endif
if (<API key>(port, ch))
continue;
<API key>(tty_port, ch, flg);
}
<API key>(tty_port);
return;
}
/*
* Interrupts are disabled on entering
*/
static void
l4ser_console_write(struct console *co, const char *s, unsigned int count)
{
if (count > sizeof(_shared_mem))
count = sizeof(_shared_mem);
memcpy(_shared_mem, s, count);
karma_ser_write(<API key>, count);
}
static void l4ser_tx_chars(struct uart_port *port)
{
struct circ_buf *xmit = &port->state->xmit;
int c;
if (port->x_char) {
l4ser_console_write(NULL, &port->x_char, 1);
port->icount.tx++;
port->x_char = 0;
return;
}
while (!uart_circ_empty(xmit)) {
c = CIRC_CNT_TO_END(xmit->head, xmit->tail, UART_XMIT_SIZE);
l4ser_console_write(NULL, &xmit->buf[xmit->tail], c);
xmit->tail = (xmit->tail + c) & (UART_XMIT_SIZE - 1);
port->icount.tx += c;
}
}
static void l4ser_start_tx(struct uart_port *port)
{
l4ser_tx_chars(port);
}
static irqreturn_t l4ser_int(int irq, void *dev_id)
{
struct uart_port *sport = dev_id;
l4ser_rx_chars(sport);
return IRQ_HANDLED;
}
static unsigned int l4ser_tx_empty(struct uart_port *port)
{
return TIOCSER_TEMT;
}
static unsigned int l4ser_get_mctrl(struct uart_port *port)
{
return 0;
}
static void l4ser_set_mctrl(struct uart_port *port, unsigned int mctrl)
{
}
static void l4ser_break_ctl(struct uart_port *port, int break_state)
{
}
static int l4ser_startup(struct uart_port *port)
{
int retval;
struct l4ser_uart_port *l4port = &l4ser_port[port->line];
if (l4port->flags & L4SER_NOECHO) {
struct ktermios new_termios;
new_termios = l4port->port.state->port.tty->termios;
new_termios.c_lflag &= ~ECHO;
tty_set_termios(l4port->port.state->port.tty, &new_termios);
}
if (port->irq) {
retval = request_irq(port->irq, l4ser_int, 0, "karma_uart", port);
if (retval)
return retval;
l4ser_rx_chars(port);
}
return 0;
}
static void l4ser_shutdown(struct uart_port *port)
{
if (port->irq)
free_irq(port->irq, port);
}
static void l4ser_set_termios(struct uart_port *port, struct ktermios *termios,
struct ktermios *old)
{
}
static const char *l4ser_type(struct uart_port *port)
{
return port->type == PORT_SA1100 ? "L4" : NULL;
}
static int l4ser_request_port(struct uart_port *port)
{
return 0;
}
static void l4ser_release_port(struct uart_port *port)
{
}
static void l4ser_config_port(struct uart_port *port, int flags)
{
if (flags & UART_CONFIG_TYPE)
port->type = PORT_SA1100;
}
static int
l4ser_verify_port(struct uart_port *port, struct serial_struct *ser)
{
return 0;
}
static struct uart_ops l4ser_pops = {
.tx_empty = l4ser_tx_empty,
.set_mctrl = l4ser_set_mctrl,
.get_mctrl = l4ser_get_mctrl,
.stop_tx = l4ser_stop_tx,
.start_tx = l4ser_start_tx,
.stop_rx = l4ser_stop_rx,
.enable_ms = l4ser_enable_ms,
.break_ctl = l4ser_break_ctl,
.startup = l4ser_startup,
.shutdown = l4ser_shutdown,
.set_termios = l4ser_set_termios,
.type = l4ser_type,
.release_port = l4ser_release_port,
.request_port = l4ser_request_port,
.config_port = l4ser_config_port,
.verify_port = l4ser_verify_port,
};
static int __init l4ser_init_port(int num, const char *name)
{
static int first = 1;
if (!first)
return 0;
first = 0;
l4ser_port[num].port.uartclk = 3686400;
l4ser_port[num].port.ops = &l4ser_pops;
l4ser_port[num].port.fifosize = 8;
l4ser_port[num].port.line = num;
l4ser_port[num].port.iotype = UPIO_MEM;
l4ser_port[num].port.membase = (void *)1;
l4ser_port[num].port.mapbase = 1;
l4ser_port[num].port.flags = UPF_BOOT_AUTOCONF;
l4ser_port[num].port.irq = karma_irq_ser; // fixed...
karma_ser_write(karma_ser_df_init, (unsigned long)&_shared_mem);
return 0;
}
static int __init
l4ser_console_setup(struct console *co, char *options)
{
struct uart_port *up;
if (co->index >= 1 + NR_ADDITIONAL_PORTS)
co->index = 0;
up = &l4ser_port[co->index].port;
if (!up)
return -ENODEV;
return uart_set_options(up, co, 115200, 'n', 8, 'n');
}
static struct uart_driver l4ser_reg;
static struct console l4ser_console = {
.name = "ttyLv",
.write = l4ser_console_write,
.device = uart_console_device,
.setup = l4ser_console_setup,
.flags = CON_PRINTBUFFER,
.index = -1,
.data = &l4ser_reg,
};
static int __init <API key>(void)
{
if (l4ser_init_port(0, PORT0_NAME))
return -ENODEV;
register_console(&l4ser_console);
return 0;
}
console_initcall(<API key>);
#define L4SER_CONSOLE &l4ser_console
static struct uart_driver l4ser_reg = {
.owner = THIS_MODULE,
.driver_name = "ttyLv",
.dev_name = "ttyLv",
.major = SERIAL_L4SER_MAJOR,
.minor = MINOR_START,
.nr = 1 + NR_ADDITIONAL_PORTS,
.cons = L4SER_CONSOLE,
};
static int __init l4ser_serial_init(void)
{
int ret, i;
printk(KERN_INFO "[KARMA SER] Karma serial driver\n");
if (l4ser_init_port(0, PORT0_NAME))
return -ENODEV;
ret = <API key>(&l4ser_reg);
if (ret)
return ret;
ret = uart_add_one_port(&l4ser_reg, &l4ser_port[0].port);
for (i = 1; i <= NR_ADDITIONAL_PORTS; ++i) {
if (!(l4ser_port[i].flags & L4SER_REQUESTED)) { // add dummy port
continue;
}
if (l4ser_init_port(i, l4ser_port[i].cap_name)) {
printk(KERN_WARNING "[KARMA SER] Failed to initialize additional port '%s'.\n", l4ser_port[i].cap_name);
continue;
}
ret = uart_add_one_port(&l4ser_reg, &l4ser_port[i].port);
}
return 0;
}
static void __exit l4ser_serial_exit(void)
{
int i;
<API key>(&l4ser_reg, &l4ser_port[0].port);
for (i = 1; i <= NR_ADDITIONAL_PORTS; ++i)
<API key>(&l4ser_reg, &l4ser_port[i].port);
<API key>(&l4ser_reg);
}
module_init(l4ser_serial_init);
module_exit(l4ser_serial_exit);
/* This function is called much earlier than module_init, esp. there's
* no kmalloc available */
static int l4ser_setup(const char *val, struct kernel_param *kp)
{
struct l4ser_uart_port *next_port;
const char *opts = strchr(val, ',');
if (ports_to_add_pos >= NR_ADDITIONAL_PORTS) {
printk(KERN_WARNING "[KARMA SER] Too many additional ports specified, ignoring \"%s\"\n", val);
return 1;
}
next_port = &l4ser_port[ports_to_add_pos+1];
next_port->flags |= L4SER_REQUESTED;
if (opts && !strcmp(opts+1, "noecho")) {
// really process options starting at opts[1]
next_port->flags |= L4SER_NOECHO;
}
strlcpy(next_port->cap_name, val, sizeof(next_port->cap_name));
if (opts && ((opts - val) < sizeof(next_port->cap_name)))
next_port->cap_name[opts-val] = 0;
ports_to_add_pos++;
return 0;
}
module_param_call(add, l4ser_setup, NULL, NULL, 0200);
MODULE_PARM_DESC(add, "Use karma_ser.add=name to add an another port, name queried in cap environment");
MODULE_AUTHOR("Steffen Liebergeld <steffen@sec.t-labs,tu-berlin.de>");
MODULE_DESCRIPTION("Karma serial driver");
MODULE_LICENSE("GPL");
<API key>(SERIAL_L4SER_MAJOR); |
#include <panda/types/Point.h>
#include <panda/types/Path.h>
#include <panda/data/DataFactory.h>
namespace
{
using panda::types::Point;
// This code may be freely used and modified for any purpose
// liable for any real or imagined damage resulting from its use.
// Users of this code must verify correctness for their application.
// isLeft(): tests if a point is Left|On|Right of an infinite line.
// Input: three points P0, P1, and P2
// Return: >0 for P2 left of the line through P0 and P1
// =0 for P2 on the line
// <0 for P2 right of the line
// See: Algorithm 1 "Area of Triangles and Polygons"
inline float isLeft( Point P0, Point P1, Point P2 )
{
return ( (P1.x - P0.x) * (P2.y - P0.y)
- (P2.x - P0.x) * (P1.y - P0.y) );
}
// wn_PnPoly(): winding number test for a point in a polygon
// Input: P = a point,
// V[] = vertex points of a polygon V[n+1] with V[n]=V[0]
// Return: wn = the winding number (=0 only when P is outside)
int wn_PnPoly( Point P, const Point* V, int n )
{
int wn = 0; // the winding number counter
// loop through all edges of the polygon
for (int i=0; i<n; i++) { // edge from V[i] to V[i+1]
if (V[i].y <= P.y) { // start y <= P.y
if (V[i+1].y > P.y) // an upward crossing
if (isLeft( V[i], V[i+1], P) > 0) // P left of edge
++wn; // have a valid up intersect
}
else { // start y > P.y (no test needed)
if (V[i+1].y <= P.y) // a downward crossing
if (isLeft( V[i], V[i+1], P) < 0) // P right of edge
--wn; // have a valid down intersect
}
}
return wn;
}
}
namespace panda
{
namespace types
{
Path Path::operator+(const Point& p) const
{
const int nb = points.size();
std::vector<Point> tmp(nb);
for (int i = 0; i < nb; ++i)
tmp[i] = points[i] + p;
return tmp;
}
Path Path::operator-(const Point& p) const
{
const int nb = points.size();
std::vector<Point> tmp(nb);
for (int i = 0; i < nb; ++i)
tmp[i] = points[i] - p;
return tmp;
}
Path Path::operator*(float v) const
{
const int nb = points.size();
std::vector<Point> tmp(nb);
for (int i = 0; i < nb; ++i)
tmp[i] = points[i] * v;
return tmp;
}
Path Path::operator/(float v) const
{
const int nb = points.size();
std::vector<Point> tmp(nb);
for (int i = 0; i < nb; ++i)
tmp[i] = points[i] / v;
return tmp;
}
Path operator*(float v, const Path& p)
{
const int nb = p.points.size();
std::vector<Point> tmp(nb);
for (int i = 0; i < nb; ++i)
tmp[i] = p.points[i] * v;
return tmp;
}
Path Path::linearProduct(const Point& p) const
{
const int nb = points.size();
std::vector<Point> tmp(nb);
for (int i = 0; i < nb; ++i)
tmp[i] = points[i].linearProduct(p);
return tmp;
}
Path Path::linearDivision(const Point& p) const
{
const int nb = points.size();
std::vector<Point> tmp(nb);
for (int i = 0; i < nb; ++i)
tmp[i] = points[i].linearDivision(p);
return tmp;
}
Path Path::reversed() const
{
auto tmp = points;
std::reverse(tmp.begin(), tmp.end());
return tmp;
}
void Path::reverse()
{
std::reverse(points.begin(), points.end());
}
void rotate(Path& path, const Point& center, float angle)
{
auto& points = path.points;
int nb = points.size();
float ca = cos(angle), sa = sin(angle);
for (int i = 0; i < nb; ++i)
{
Point pt = points[i] - center;
points[i] = center + Point(pt.x*ca-pt.y*sa, pt.x*sa+pt.y*ca);
}
}
Path rotated(const Path& path, const Point& center, float angle)
{
const auto& points = path.points;
int nb = points.size();
std::vector<Point> tmp(nb);
float ca = cos(angle), sa = sin(angle);
for (int i = 0; i < nb; ++i)
{
Point pt = points[i] - center;
tmp[i] = center + Point(pt.x*ca-pt.y*sa, pt.x*sa+pt.y*ca);
}
return tmp;
}
//
float areaOfPolygon(const Path& poly)
{
const auto& points = poly.points;
int nbPts = points.size();
float area = 0;
for (int i = 0; i < nbPts; ++i)
{
Point p1 = points[i], p2 = points[(i+1) % nbPts];
area += p1.cross(p2);
}
return area / 2;
}
types::Point centroidOfPolygon(const Path& poly)
{
const auto& points = poly.points;
int nbPts = points.size();
Point pt;
for (int i = 0; i < nbPts; ++i)
{
Point p1 = points[i], p2 = points[(i+1)%nbPts];
pt += (p1 + p2) * p1.cross(p2);
}
return pt / (6 * areaOfPolygon(poly));
}
bool <API key>(const Path &poly, types::Point pt)
{
return wn_PnPoly(pt, poly.points.data(), poly.points.size() - 1) != 0;
}
void reorientPolygon(Path& poly)
{
auto& points = poly.points;
std::reverse(points.begin(), points.end());
}
//
template<> PANDA_CORE_API std::string DataTrait<Path>::valueTypeName() { return "path"; }
template<> PANDA_CORE_API unsigned int DataTrait<Path>::typeColor() { return 0xCD8CB3; }
template<>
PANDA_CORE_API void DataTrait<Path>::writeValue(XmlElement& elem, const Path& path)
{
auto pointTrait = DataTraitsList::getTraitOf<Point>();
for(const auto& pt : path.points)
{
auto ptNode = elem.addChild("Point");
pointTrait->writeValue(ptNode, &pt);
}
}
template<>
PANDA_CORE_API void DataTrait<Path>::readValue(const XmlElement& elem, Path& path)
{
auto& points = path.points;
points.clear();
auto pointTrait = DataTraitsList::getTraitOf<Point>();
for(auto ptNode = elem.firstChild("Point"); ptNode; ptNode = ptNode.nextSibling("Point"))
{
Point pt;
pointTrait->readValue(ptNode, &pt);
points.push_back(pt);
}
}
} // namespace types
template class PANDA_CORE_API Data<types::Path>;
template class PANDA_CORE_API Data<std::vector<types::Path>>;
int pathDataClass = RegisterData<types::Path>();
int pathVectorDataClass = RegisterData< std::vector<types::Path>>();
} // namespace panda
void convertType(const panda::types::Path& from, std::vector<panda::types::Point>& to)
{ to = from.points; }
void convertType(const std::vector<panda::types::Point>& from, panda::types::Path& to)
{ to.points = from; }
panda::types::<API key><panda::types::Path, std::vector<panda::types::Point> > PathPointsConverter;
panda::types::<API key><std::vector<panda::types::Point>, panda::types::Path> PointsPathConverter; |
var path = require('path')
var config = require('../config')
var utils = require('./utils')
var projectRoot = path.resolve(__dirname, '../')
var env = process.env.NODE_ENV
// check env & config/index.js to decide weither to enable CSS Sourcemaps for the
// various preprocessor loaders added to vue-loader at the end of this file
var cssSourceMapDev = (env === 'development' && config.dev.cssSourceMap)
var cssSourceMapProd = (env === 'production' && config.build.productionSourceMap)
var useCssSourceMap = cssSourceMapDev || cssSourceMapProd
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath,
filename: '[name].js'
},
resolve: {
extensions: ['', '.js', '.vue'],
fallback: [path.join(__dirname, '../node_modules')],
alias: {
'vue$': 'vue/dist/vue.common.js',
'src': path.resolve(__dirname, '../src'),
'assets': path.resolve(__dirname, '../src/assets'),
'components': path.resolve(__dirname, '../src/components')
}
},
resolveLoader: {
fallback: [path.join(__dirname, '../node_modules')]
},
module: {
preLoaders: [
{
test: /\.vue$/,
loader: 'eslint',
include: projectRoot,
exclude: /node_modules/
},
{
test: /\.js$/,
loader: 'eslint',
include: projectRoot,
exclude: /node_modules/
}
],
loaders: [
{
test: /\.vue$/,
loader: 'vue'
}, {
test: /\.html$/,
loader: 'vue-html'
},
{
test: /\.js$/,
loader: 'babel',
include: projectRoot,
exclude: /node_modules/
},
{
test: /\.json$/,
loader: 'json'
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url',
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
},
eslint: {
formatter: require('<API key>')
},
vue: {
loaders: utils.cssLoaders({sourceMap: useCssSourceMap}),
postcss: [
require('autoprefixer')({
browsers: ['last 2 versions']
})
]
}
} |
import json
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
s = Student('Bob', 20, 88)
print(json.dumps(s)) |
# General
This file contains the description of the language which can be interpreted by the vala_interpreter.
The language description will be done in the EBNF (http://de.wikipedia.org/wiki/<API key>)
# Constants
## Numbers
ebnf
digit_without_zero = "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
digit = "0" | digit_without_zero ;
hex_digit = digit | "a" | "b" | "c" | "d" | "e" | "f" | "A" | "B" | "C" | "D" | "E" | "F" ;
decimal_number = [ "-" ] , digit_without_zero { digit } | "0" ;
hex_number = [ "-" ] "0x" hex_digit { hex_digit } ;
number = decimal_number | hex_number ;
## Boolean
ebnf
boolean_value = "true" | "false" ;
## Strings
ebnf
character = ? all unicode characters ? ;
<API key> = ? a-z, A-Z ? ;
string = """ { character } """ ;
## Types
ebnf
integer_types = "uint8" |
"int8" |
"uint16" |
"int16" |
"uint32" |
"int32" |
"uint64" |
"int64" |
"uint" |
"int" |
"ulong" |
"long" ;
character_types = "char" | "uchar" | "unichar" ;
string_types = "string" ;
type = integer_types | character_types | string_types | "void" | "bool" ;
# Expressions
ebnf
literal = "null" | number | boolean_value | string ;
<API key> = <API key> | digit | "_" ;
identifier = <API key> { <API key> } ;
expression = <API key> | boolean_expression | literal | idetifier | assignment | declaration | method_call | "(" expression ")";
<API key> = addition | subtraction | multiplication | division ;
addition = expression "+" expression ;
subtraction = expression "-" expression ;
multiplication = expression "*" expression ;
division = expression "/" expression ;
boolean_expression = boolean_value |
compare_expression |
boolean_expression logical_operator boolean_expression |
"!" boolean_expression |
"(" boolean_expression ")" ;
logical_operator = "&&" | "||" ;
compare_operator = "<" | "<=" | "==" | ">=" | ">" ;
compare_expression = expression compare_operator expression ;
assignment = identifier "=" expression ;
declaration = type identifier { "," identifier } | type assignment { "," assignment } ;
method_call = identifier "(" [ call_parameter_list ] ")"
call_parameter_list = expression { "," call_parameter_list }
# Statements & Blocks
ebnf
statement = expression ";" |
if_statement |
while_statement ;
block_or_statement = block | statement ;
while_statement = "while" "(" boolean_expression ")" block_or_statement ;
if_statement = "if" "(" boolean_expression ")" block_or_statement { elseif_statement } { else_statement } ;
elseif_statement = "else if" "(" boolean_expression ")" block_or_statement ;
else_statement = "else" block_or_statement ;
block = "{" { statement } "}" ;
method_declaration = type identifier "(" [ parameter_list ] ")" block ;
parameter = type identifier ;
parameter_list = parameter { "," parameter } ;
program = { block | statement | method_declaration } ; |
#define pr_fmt(fmt) "PKCS7key: "fmt
#include <linux/key.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/verification.h>
#include <linux/key-type.h>
#include <keys/user-type.h>
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("PKCS#7 testing key type");
static unsigned pkcs7_usage;
module_param_named(usage, pkcs7_usage, uint, S_IWUSR | S_IRUGO);
MODULE_PARM_DESC(pkcs7_usage,
"Usage to specify when verifying the PKCS#7 message");
/*
* Retrieve the PKCS#7 message content.
*/
static int pkcs7_view_content(void *ctx, const void *data, size_t len,
size_t asn1hdrlen)
{
struct <API key> *prep = ctx;
const void *saved_prep_data;
size_t saved_prep_datalen;
int ret;
saved_prep_data = prep->data;
saved_prep_datalen = prep->datalen;
prep->data = data;
prep->datalen = len;
ret = user_preparse(prep);
prep->data = saved_prep_data;
prep->datalen = saved_prep_datalen;
return ret;
}
/*
* Preparse a PKCS#7 wrapped and validated data blob.
*/
static int pkcs7_preparse(struct <API key> *prep)
{
enum key_being_used_for usage = pkcs7_usage;
if (usage >= <API key>) {
pr_err("Invalid usage type %d\n", usage);
return -EINVAL;
}
return <API key>(NULL, 0,
prep->data, prep->datalen,
NULL, usage,
pkcs7_view_content, prep);
}
/*
* user defined keys take an arbitrary string as the description and an
* arbitrary blob of data as the payload
*/
static struct key_type key_type_pkcs7 = {
.name = "pkcs7_test",
.preparse = pkcs7_preparse,
.free_preparse = user_free_preparse,
.instantiate = <API key>,
.revoke = user_revoke,
.destroy = user_destroy,
.describe = user_describe,
.read = user_read,
};
/*
* Module stuff
*/
static int __init pkcs7_key_init(void)
{
return register_key_type(&key_type_pkcs7);
}
static void __exit pkcs7_key_cleanup(void)
{
unregister_key_type(&key_type_pkcs7);
}
module_init(pkcs7_key_init);
module_exit(pkcs7_key_cleanup); |
<?php
/**
* The template for displaying pages
* Template Name: Gallery Page
*
* @package WordPress
* @subpackage cap
* @since cap 1.0
*/
get_header(); ?>
<article id="artc_page_content" class="artc-page-content">
<div class="row dv-gallery-wrapper">
<div class="col-sm-3 col-xs-12">
<?php wp_nav_menu(array(
'theme_location' => 'gallery_left',
'menu' => 'gallery_left',
'depth' => 0,
'container' => false,
'menu_class' => '<API key>',
'walker' => ''
)); ?>
</div>
<div class="col-sm-9 col-xs-12">
<h1 id="h_page_title" class="h-page-title">Gallery</h1>
</div>
<div class="col-xs-12">
<div class="row">
<?php $type = get_post_meta($post->ID, '_gallery_value', true);
$args = array(
'post_type' => $type,
'post_status' => 'publish',
'posts_per_page' => -1,
'caller_get_posts' => 1,
'orderby' => 'meta_value',
'order' => 'ASC'
);
$my_query = null;
$my_query = new WP_Query($args);
if($my_query->have_posts()) {
while ($my_query->have_posts()) {
$my_query->the_post(); ?>
<div class="col-sm-3 col-xs-6">
<a href="<?php echo <API key>(<API key>($post->ID)); ?>">
<img src="<?php echo <API key>(<API key>($post->ID)); ?>" class="img-gallery-photo" />
</a>
</div>
<?php } }
wp_reset_query(); ?>
</div>
</div>
</div>
</article>
<?php get_footer(); ?> |
<?php
declare(strict_types=1);
namespace Magento\Framework\App\Action;
use Magento\Framework\App\ActionInterface;
/**
* Marker for actions processing PUT requests.
*/
interface <API key> extends ActionInterface
{
} |
package com.jnsw.core.http;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import org.apache.http.*;
import org.apache.http.client.<API key>;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.<API key>;
import org.apache.http.client.entity.<API key>;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.conn.ssl.<API key>;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.<API key>;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.*;
import org.apache.http.util.EntityUtils;
import org.apache.http.util.EntityUtilsHC4;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.<API key>;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.List;
import java.util.UUID;
public class HttpClientDemo {
private static void Demo(){
SSLContext sslContext = SSLContexts.createSystemDefault();
<API key> sslsf = new <API key>(
sslContext,
<API key>.<API key>);
// getConfigBuilder = RequestConfig.custom().<API key>(30*1000).setMaxRedirects(10).setRedirectsEnabled(true).setSocketTimeout(60*1000);
// postConfigBuilder = RequestConfig.custom().<API key>(false).<API key>(30*1000).setConnectTimeout(30 * 1000).setMaxRedirects(10).setSocketTimeout(60 * 1000);
CloseableHttpClient hc = HttpClients.custom().setSSLSocketFactory(sslsf).build();
HttpGetHC4 getHC4 = new HttpGetHC4();
getHC4.setURI(URI.create("http://baidu.com"));
try {
<API key> response = hc.execute(getHC4);
String body= EntityUtilsHC4.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
} |
<?php if ( is_active_sidebar( '<API key>' ) ) : ?>
<div class="span3">
<?php dynamic_sidebar( '<API key>' ); ?>
</div>
<?php endif; // end sidebar widget area ?>
<?php if ( is_active_sidebar( '<API key>' ) ) : ?>
<div class="span3">
<?php dynamic_sidebar( '<API key>' ); ?>
</div>
<?php endif; // end sidebar widget area ?>
<?php if ( is_active_sidebar( '<API key>' ) ) : ?>
<div class="span3">
<?php dynamic_sidebar( '<API key>' ); ?>
</div>
<?php endif; // end sidebar widget area ?>
<?php if ( is_active_sidebar( '<API key>' ) ) : ?>
<div class="span3">
<?php dynamic_sidebar( '<API key>' ); ?>
</div>
<?php endif; // end sidebar widget area ?> |
utils = require('../utils.js')
//var interface = require('../cmd_interface.js')
function random(slba, nblk,size) {
var BLK_NUM = nblk
var PART_NUM = 8
var bord_addr = new Array()
var temp_size = size / PART_NUM
var pat_buf1 = new Array()
var wri_buf1 = new Array()
var part_size = Math.floor(size/PART_NUM)
var part_comm = Math.ceil(part_size/BLK_NUM)
for(var i = 1 ;i<= PART_NUM;i++)
{
bord_addr.push(i*part_size+slba)
}
//console.log(bord_addr)
var pres_size = size-part_size*PART_NUM
//console.log('part size =',part_size,pres_size)
utils.set_rand_seed(11)
for (var i = 0;i<part_comm;i++){
pat_buf1[i] =i
}
for (var i = 0;i<part_comm;i++){
var k = utils.get_random(i, part_comm-1)
wri_buf1[i]=pat_buf1[k]
pat_buf1[k]=pat_buf1[i]
}
function tfor(cb, fin) {
var zonesize = size
var start //= slba
var block_num = 0
var total_blks = 0
for (var i = 0 ; total_blks <size; i++)
{
start = slba + wri_buf1[i%part_comm] * BLK_NUM + Math.floor(i/part_comm) * part_size
//console.log(i,i%part_comm,wri_buf1[i%part_comm],Math.floor(i/part_comm),part_size,Math.floor(i/part_comm) * part_size)
block_num = nblk//utils.get_write_block(nblk)
//if (start+block_num>slba + zonesize) break
if ((start+block_num) > bord_addr[Math.floor(i/part_comm)])
{
var res_blk = bord_addr[Math.floor(i/part_comm)]-start
ret = cb(start, res_blk,zonesize)
if(ret==-3){
info("write fail")
return -3
}
else if(ret==-2){
info("Miscompare")
return -2
}
else if(ret==1){
info("timeout")
return 1
}
total_blks = total_blks + res_blk
}
else
{
ret = cb(start,BLK_NUM,zonesize)
if(ret==-3){
info("write fail")
return -3
}
else if(ret==-2){
info("Miscompare")
return -2
}
else if(ret==1){
info("timeout")
return 1
}
total_blks = total_blks + block_num
}
}
start = wri_buf1[i]
//console.log('block_num:%d,start:%d',block_num,start)
if (start < slba+zonesize)
{
ret = cb(start, zonesize+slba - start,zonesize)
if(ret==-3){
info("write fail")
return -3
}
else if(ret==-2){
info("Miscompare")
return -2
}
else if(ret==1){
info("timeout")
return 1
}
total_blks = total_blks + zonesize+slba - start
}
if (fin != undefined){
ret = fin()
if(ret==-3){
return -3
}
if(ret==-2){
return -2
}
else if(ret==1){
info("timeout")
return 1
}
}
return 0
//console.log("total_blks:%d",total_blks)
}
function abc(me) {
me(slba,5)
}
return {forEach:tfor, aBc:abc}
}
exports.random=random
if (require.main === module) {
var it = random(10, 8,748)
function tfin()
{
console.log("finished.")
}
//it.forEach(interface.nvme_write, tfin)
//it.aBc()
it.forEach(console.log, tfin)
//it.aBc()
} |
/**
@file innodb_cb_api.h
Created 03/15/2011 Jimmy Yang
*******************************************************/
#ifndef innodb_cb_api_h
#define innodb_cb_api_h
#include "api0api.h"
/** Following are callback function defines for InnoDB APIs, mapped to
functions defined in api0api.c */
typedef
ib_err_t
(*cb_open_table_t)(
const char* name,
ib_trx_t ib_trx,
ib_crsr_t* ib_crsr);
typedef
ib_err_t
(*cb_read_row_t)(
ib_crsr_t ib_crsr,
ib_tpl_t ib_tpl,
void** row_buf,
ib_ulint_t* row_buf_len);
typedef
ib_err_t
(*cb_insert_row_t)(
ib_crsr_t ib_crsr,
const ib_tpl_t ib_tpl);
typedef
ib_err_t
(*<API key>)(
ib_crsr_t ib_crsr);
typedef
ib_err_t
(*<API key>)(
ib_crsr_t ib_crsr,
const ib_tpl_t ib_old_tpl,
const ib_tpl_t ib_new_tpl);
typedef
ib_err_t
(*cb_cursor_moveto_t)(
ib_crsr_t ib_crsr,
ib_tpl_t ib_tpl,
ib_srch_mode_t ib_srch_mode);
typedef
ib_tpl_t
(*<API key>)(
ib_crsr_t ib_crsr) ;
typedef
ib_tpl_t
(*<API key>)(
ib_crsr_t ib_crsr);
typedef
void
(*cb_tuple_delete_t)(
ib_tpl_t ib_tpl);
typedef
ib_err_t
(*cb_tuple_copy_t)(
ib_tpl_t ib_dst_tpl,
const ib_tpl_t ib_src_tpl);
typedef
ib_err_t
(*cb_tuple_read_u8_t)(
ib_tpl_t ib_tpl,
ib_ulint_t i,
ib_u8_t* ival) ;
typedef
ib_err_t
(*cb_tuple_read_u16_t)(
ib_tpl_t ib_tpl,
ib_ulint_t i,
ib_u16_t* ival) ;
typedef
ib_err_t
(*cb_tuple_read_u32_t)(
ib_tpl_t ib_tpl,
ib_ulint_t i,
ib_u32_t* ival) ;
typedef
ib_err_t
(*cb_tuple_read_u64_t)(
ib_tpl_t ib_tpl,
ib_ulint_t i,
ib_u64_t* ival) ;
typedef
ib_err_t
(*cb_tuple_write_u8_t)(
ib_tpl_t ib_tpl,
int col_no,
ib_u8_t val) ;
typedef
ib_err_t
(*<API key>)(
ib_tpl_t ib_tpl,
int col_no,
ib_u16_t val) ;
typedef
ib_err_t
(*<API key>)(
ib_tpl_t ib_tpl,
int col_no,
ib_u32_t val) ;
typedef
ib_err_t
(*<API key>)(
ib_tpl_t ib_tpl,
int col_no,
ib_u64_t val);
typedef
ib_err_t
(*cb_tuple_read_i8_t)(
ib_tpl_t ib_tpl,
ib_ulint_t i,
ib_i8_t* ival);
typedef
ib_err_t
(*cb_tuple_read_i16_t)(
ib_tpl_t ib_tpl,
ib_ulint_t i,
ib_i16_t* ival);
typedef
ib_err_t
(*cb_tuple_read_i32_t)(
ib_tpl_t ib_tpl,
ib_ulint_t i,
ib_i32_t* ival);
typedef
ib_err_t
(*cb_tuple_read_i64_t)(
ib_tpl_t ib_tpl,
ib_ulint_t i,
ib_i64_t* ival);
typedef
ib_err_t
(*cb_tuple_write_i8_t)(
ib_tpl_t ib_tpl,
int col_no,
ib_i8_t val);
typedef
ib_err_t
(*<API key>)(
ib_tpl_t ib_tpl,
int col_no,
ib_i16_t val);
typedef
ib_err_t
(*<API key>)(
ib_tpl_t ib_tpl,
int col_no,
ib_i32_t val);
typedef
ib_err_t
(*<API key>)(
ib_tpl_t ib_tpl,
int col_no,
ib_i64_t val);
typedef
ib_err_t
(*cb_col_set_value_t)(
ib_tpl_t ib_tpl,
ib_ulint_t col_no,
const void* src,
ib_ulint_t len,
bool need_cpy) ;
typedef
const void*
(*cb_col_get_value_t)(
ib_tpl_t ib_tpl,
ib_ulint_t i);
typedef
ib_ulint_t
(*cb_col_get_meta_t)(
ib_tpl_t ib_tpl,
ib_ulint_t i,
ib_col_meta_t* ib_col_meta);
typedef
ib_trx_t
(*cb_trx_begin_t)(
ib_trx_level_t ib_trx_level,
bool read_write,
bool auto_commit);
typedef
ib_err_t
(*cb_trx_commit_t)(
ib_trx_t ib_trx);
typedef
ib_err_t
(*cb_trx_rollback_t)(
ib_trx_t ib_trx);
typedef
ib_err_t
(*cb_trx_start_t)(
ib_trx_t ib_trx,
ib_trx_level_t ib_trx_level,
bool read_write,
bool auto_commit,
void* thd);
typedef
ib_trx_state_t
(*cb_trx_state_t)(
ib_trx_t ib_trx);
typedef
ib_trx_state_t
(*cb_trx_release_t)(
ib_trx_t ib_trx);
typedef
ib_ulint_t
(*<API key>)(
const ib_tpl_t ib_tpl);
typedef
void
(*<API key>)(
ib_crsr_t ib_crsr,
ib_match_mode_t match_mode);
typedef
ib_err_t
(*cb_cursor_lock_t)(
ib_crsr_t ib_crsr,
ib_lck_mode_t ib_lck_mode);
typedef
ib_err_t
(*<API key>)(
ib_crsr_t ib_crsr,
ib_lck_mode_t ib_lck_mode);
typedef
ib_err_t
(*cb_cursor_close_t)(
ib_crsr_t ib_crsr);
typedef
void*
(*<API key>)(
const char* name);
typedef
ib_err_t
(*cb_cursor_new_trx_t)(
ib_crsr_t ib_crsr,
ib_trx_t ib_trx);
typedef
ib_err_t
(*cb_cursor_reset_t)(
ib_crsr_t ib_crsr);
typedef
char*
(*cb_col_get_name_t)(
ib_crsr_t ib_crsr,
ib_ulint_t i);
typedef
char*
(*<API key>)(
ib_crsr_t ib_crsr,
ib_ulint_t i);
typedef
ib_err_t
(*cb_table_truncate_t)(
const char* table_name,
ib_id_u64_t* table_id);
typedef
ib_err_t
(*cb_cursor_first_t)(
ib_crsr_t ib_crsr);
typedef
ib_err_t
(*cb_cursor_next_t)(
ib_crsr_t ib_crsr);
typedef
ib_err_t
(*cb_cursor_last_t)(
ib_crsr_t ib_crsr);
typedef
void
(*<API key>)(
ib_crsr_t ib_crsr);
typedef
ib_err_t
(*cb_close_thd_t)(
void* thd);
typedef
int
(*cb_get_cfg_t)();
typedef
ib_err_t
(*<API key>)(
ib_crsr_t ib_crsr,
ib_bool_t flag);
typedef
ib_err_t
(*<API key>)(
ib_crsr_t ib_open_crsr,
const char* index_name,
ib_crsr_t* ib_crsr,
int* idx_type,
ib_id_u64_t* idx_id);
typedef
void
(*<API key>)(
ib_crsr_t ib_crsr);
typedef
ib_err_t
(*<API key>)(
ib_crsr_t ib_crsr,
ib_trx_t ib_trx);
typedef
int
(*cb_cfg_trx_level_t)();
typedef
ib_ulint_t
(*cb_get_n_user_cols)(
const ib_tpl_t ib_tpl);
typedef
ib_err_t
(*<API key>)(
ib_trx_t ib_trx);
typedef
ib_ulint_t
(*<API key>)();
typedef
ib_err_t
(*<API key>)(
ib_crsr_t ib_crsr);
cb_open_table_t ib_cb_open_table;
cb_read_row_t ib_cb_read_row;
cb_insert_row_t ib_cb_insert_row;
<API key> ib_cb_delete_row;
<API key> ib_cb_update_row;
cb_cursor_moveto_t ib_cb_moveto;
<API key> <API key>;
<API key> <API key>;
cb_tuple_delete_t ib_cb_tuple_delete;
cb_tuple_copy_t ib_cb_tuple_copy;
cb_tuple_read_u8_t ib_cb_tuple_read_u8;
cb_tuple_read_u16_t <API key>;
cb_tuple_read_u32_t <API key>;
cb_tuple_read_u64_t <API key>;
cb_tuple_write_u8_t <API key>;
<API key> <API key>;
<API key> <API key>;
<API key> <API key>;
cb_tuple_read_i8_t ib_cb_tuple_read_i8;
cb_tuple_read_i16_t <API key>;
cb_tuple_read_i32_t <API key>;
cb_tuple_read_i64_t <API key>;
cb_tuple_write_i8_t <API key>;
<API key> <API key>;
<API key> <API key>;
<API key> <API key>;
cb_col_set_value_t ib_cb_col_set_value;
cb_col_get_value_t ib_cb_col_get_value;
cb_col_get_meta_t ib_cb_col_get_meta;
cb_trx_begin_t ib_cb_trx_begin;
cb_trx_commit_t ib_cb_trx_commit;
cb_trx_rollback_t ib_cb_trx_rollback;
cb_trx_start_t ib_cb_trx_start;
cb_trx_state_t ib_cb_trx_state;
cb_trx_release_t ib_cb_trx_release;
<API key> <API key>;
<API key> <API key>;
cb_cursor_lock_t ib_cb_cursor_lock;
cb_cursor_close_t ib_cb_cursor_close;
cb_cursor_new_trx_t <API key>;
<API key> <API key>;
cb_cursor_reset_t ib_cb_cursor_reset;
cb_col_get_name_t ib_cb_col_get_name;
<API key> <API key>;
cb_table_truncate_t <API key>;
cb_cursor_first_t ib_cb_cursor_first;
cb_cursor_next_t ib_cb_cursor_next;
cb_cursor_last_t ib_cb_cursor_last;
<API key> <API key>;
cb_close_thd_t ib_cb_close_thd;
cb_get_cfg_t ib_cb_get_cfg;
<API key> <API key>;
<API key> <API key>;
<API key> <API key>;
cb_cfg_trx_level_t ib_cb_cfg_trx_level;
cb_get_n_user_cols <API key>;
<API key> <API key>;
<API key> <API key>;
<API key> <API key>;
<API key> <API key>;
<API key> <API key>;
#endif /* innodb_cb_api_h */ |
/**
* @file
* Cook compatible decoder. Bastardization of the G.722.1 standard.
* This decoder handles RealNetworks, RealAudio G2 data.
* Cook is identified by the codec name cook in RM files.
*
* To use this decoder, a calling application must supply the extradata
* bytes provided from the RM container; 8+ bytes for mono streams and
* 16+ for stereo streams (maybe more).
*
* Codec technicalities (all this assume a buffer length of 1024):
* Cook works with several different techniques to achieve its compression.
* In the timedomain the buffer is divided into 8 pieces and quantized. If
* two neighboring pieces have different quantization index a smooth
* quantization curve is used to get a smooth overlap between the different
* pieces.
* To get to the transformdomain Cook uses a modulated lapped transform.
* The transform domain has 50 subbands with 20 elements each. This
* means only a maximum of 50*20=1000 coefficients are used out of the 1024
* available.
*/
#include "libavutil/channel_layout.h"
#include "libavutil/lfg.h"
#include "audiodsp.h"
#include "avcodec.h"
#include "get_bits.h"
#include "bytestream.h"
#include "fft.h"
#include "internal.h"
#include "sinewin.h"
#include "unary.h"
#include "cookdata.h"
/* the different Cook versions */
#define MONO 0x1000001
#define STEREO 0x1000002
#define JOINT_STEREO 0x1000003
#define MC_COOK 0x2000000 // multichannel Cook, not supported
#define SUBBAND_SIZE 20
#define MAX_SUBPACKETS 5
typedef struct {
int *now;
int *previous;
} cook_gains;
typedef struct {
int ch_idx;
int size;
int num_channels;
int cookversion;
int subbands;
int js_subband_start;
int js_vlc_bits;
int samples_per_channel;
int log2_numvector_size;
unsigned int channel_mask;
VLC channel_coupling;
int joint_stereo;
int bits_per_subpacket;
int bits_per_subpdiv;
int total_subbands;
int numvector_size; // 1 << log2_numvector_size;
float <API key>[1024];
float <API key>[1024];
cook_gains gains1;
cook_gains gains2;
int gain_1[9];
int gain_2[9];
int gain_3[9];
int gain_4[9];
} COOKSubpacket;
typedef struct cook {
/*
* The following 5 functions provide the lowlevel arithmetic on
* the internal audio buffers.
*/
void (*scalar_dequant)(struct cook *q, int index, int quant_index,
int *subband_coef_index, int *subband_coef_sign,
float *mlt_p);
void (*decouple)(struct cook *q,
COOKSubpacket *p,
int subband,
float f1, float f2,
float *decode_buffer,
float *mlt_buffer1, float *mlt_buffer2);
void (*imlt_window)(struct cook *q, float *buffer1,
cook_gains *gains_ptr, float *previous_buffer);
void (*interpolate)(struct cook *q, float *buffer,
int gain_index, int gain_index_next);
void (*saturate_output)(struct cook *q, float *out);
AVCodecContext* avctx;
AudioDSPContext adsp;
GetBitContext gb;
/* stream data */
int num_vectors;
int samples_per_channel;
/* states */
AVLFG random_state;
int discarded_packets;
/* transform data */
FFTContext mdct_ctx;
float* mlt_window;
/* VLC data */
VLC <API key>[13];
VLC sqvh[7]; // scalar quantization
/* generatable tables and related variables */
int gain_size_factor;
float gain_table[23];
/* data buffers */
uint8_t* <API key>;
DECLARE_ALIGNED(32, float, mono_mdct_output)[2048];
float decode_buffer_1[1024];
float decode_buffer_2[1024];
float decode_buffer_0[1060]; /* static allocation for joint decode */
const float *cplscales[5];
int num_subpackets;
COOKSubpacket subpacket[MAX_SUBPACKETS];
} COOKContext;
static float pow2tab[127];
static float rootpow2tab[127];
/* table generator */
static av_cold void init_pow2table(void)
{
int i;
for (i = -63; i < 64; i++) {
pow2tab[63 + i] = pow(2, i);
rootpow2tab[63 + i] = sqrt(pow(2, i));
}
}
/* table generator */
static av_cold void init_gain_table(COOKContext *q)
{
int i;
q->gain_size_factor = q->samples_per_channel / 8;
for (i = 0; i < 23; i++)
q->gain_table[i] = pow(pow2tab[i + 52],
(1.0 / (double) q->gain_size_factor));
}
static av_cold int <API key>(COOKContext *q)
{
int i, result;
result = 0;
for (i = 0; i < 13; i++) {
result |= init_vlc(&q-><API key>[i], 9, 24,
<API key>[i], 1, 1,
<API key>[i], 2, 2, 0);
}
av_log(q->avctx, AV_LOG_DEBUG, "sqvh VLC init\n");
for (i = 0; i < 7; i++) {
result |= init_vlc(&q->sqvh[i], vhvlcsize_tab[i], vhsize_tab[i],
cvh_huffbits[i], 1, 1,
cvh_huffcodes[i], 2, 2, 0);
}
for (i = 0; i < q->num_subpackets; i++) {
if (q->subpacket[i].joint_stereo == 1) {
result |= init_vlc(&q->subpacket[i].channel_coupling, 6,
(1 << q->subpacket[i].js_vlc_bits) - 1,
ccpl_huffbits[q->subpacket[i].js_vlc_bits - 2], 1, 1,
ccpl_huffcodes[q->subpacket[i].js_vlc_bits - 2], 2, 2, 0);
av_log(q->avctx, AV_LOG_DEBUG, "subpacket %i Joint-stereo VLC used.\n", i);
}
}
av_log(q->avctx, AV_LOG_DEBUG, "VLC tables initialized.\n");
return result;
}
static av_cold int init_cook_mlt(COOKContext *q)
{
int j, ret;
int mlt_size = q->samples_per_channel;
if ((q->mlt_window = av_malloc_array(mlt_size, sizeof(*q->mlt_window))) == 0)
return AVERROR(ENOMEM);
/* Initialize the MLT window: simple sine window. */
ff_sine_window_init(q->mlt_window, mlt_size);
for (j = 0; j < mlt_size; j++)
q->mlt_window[j] *= sqrt(2.0 / q->samples_per_channel);
/* Initialize the MDCT. */
if ((ret = ff_mdct_init(&q->mdct_ctx, av_log2(mlt_size) + 1, 1, 1.0 / 32768.0))) {
av_freep(&q->mlt_window);
return ret;
}
av_log(q->avctx, AV_LOG_DEBUG, "MDCT initialized, order = %d.\n",
av_log2(mlt_size) + 1);
return 0;
}
static av_cold void <API key>(COOKContext *q)
{
int i;
for (i = 0; i < 5; i++)
q->cplscales[i] = cplscales[i];
}
#define DECODE_BYTES_PAD1(bytes) (3 - ((bytes) + 3) % 4)
#define DECODE_BYTES_PAD2(bytes) ((bytes) % 4 + DECODE_BYTES_PAD1(2 * (bytes)))
/**
* Cook indata decoding, every 32 bits are XORed with 0x37c511f2.
* Why? No idea, some checksum/error detection method maybe.
*
* Out buffer size: extra bytes are needed to cope with
* padding/misalignment.
* Subpackets passed to the decoder can contain two, consecutive
* half-subpackets, of identical but arbitrary size.
* 1234 1234 1234 1234 extraA extraB
* Case 1: AAAA BBBB 0 0
* Case 2: AAAA ABBB BB-- 3 3
* Case 3: AAAA AABB BBBB 2 2
* Case 4: AAAA AAAB BBBB BB-- 1 5
*
* Nice way to waste CPU cycles.
*
* @param inbuffer pointer to byte array of indata
* @param out pointer to byte array of outdata
* @param bytes number of bytes
*/
static inline int decode_bytes(const uint8_t *inbuffer, uint8_t *out, int bytes)
{
static const uint32_t tab[4] = {
AV_BE2NE32C(0x37c511f2u), AV_BE2NE32C(0xf237c511u),
AV_BE2NE32C(0x11f237c5u), AV_BE2NE32C(0xc511f237u),
};
int i, off;
uint32_t c;
const uint32_t *buf;
uint32_t *obuf = (uint32_t *) out;
/* FIXME: 64 bit platforms would be able to do 64 bits at a time.
* I'm too lazy though, should be something like
* for (i = 0; i < bitamount / 64; i++)
* (int64_t) out[i] = 0x37c511f237c511f2 ^ av_be2ne64(int64_t) in[i]);
* Buffer alignment needs to be checked. */
off = (intptr_t) inbuffer & 3;
buf = (const uint32_t *) (inbuffer - off);
c = tab[off];
bytes += 3 + off;
for (i = 0; i < bytes / 4; i++)
obuf[i] = c ^ buf[i];
return off;
}
static av_cold int cook_decode_close(AVCodecContext *avctx)
{
int i;
COOKContext *q = avctx->priv_data;
av_log(avctx, AV_LOG_DEBUG, "Deallocating memory.\n");
/* Free allocated memory buffers. */
av_freep(&q->mlt_window);
av_freep(&q-><API key>);
/* Free the transform. */
ff_mdct_end(&q->mdct_ctx);
/* Free the VLC tables. */
for (i = 0; i < 13; i++)
ff_free_vlc(&q-><API key>[i]);
for (i = 0; i < 7; i++)
ff_free_vlc(&q->sqvh[i]);
for (i = 0; i < q->num_subpackets; i++)
ff_free_vlc(&q->subpacket[i].channel_coupling);
av_log(avctx, AV_LOG_DEBUG, "Memory deallocated.\n");
return 0;
}
/**
* Fill the gain array for the timedomain quantization.
*
* @param gb pointer to the GetBitContext
* @param gaininfo array[9] of gain indexes
*/
static void decode_gain_info(GetBitContext *gb, int *gaininfo)
{
int i, n;
n = get_unary(gb, 0, get_bits_left(gb)); // amount of elements*2 to update
i = 0;
while (n
int index = get_bits(gb, 3);
int gain = get_bits1(gb) ? get_bits(gb, 4) - 7 : -1;
while (i <= index)
gaininfo[i++] = gain;
}
while (i <= 8)
gaininfo[i++] = 0;
}
/**
* Create the quant index table needed for the envelope.
*
* @param q pointer to the COOKContext
* @param quant_index_table pointer to the array
*/
static int decode_envelope(COOKContext *q, COOKSubpacket *p,
int *quant_index_table)
{
int i, j, vlc_index;
quant_index_table[0] = get_bits(&q->gb, 6) - 6; // This is used later in categorize
for (i = 1; i < p->total_subbands; i++) {
vlc_index = i;
if (i >= p->js_subband_start * 2) {
vlc_index -= p->js_subband_start;
} else {
vlc_index /= 2;
if (vlc_index < 1)
vlc_index = 1;
}
if (vlc_index > 13)
vlc_index = 13; // the VLC tables >13 are identical to No. 13
j = get_vlc2(&q->gb, q-><API key>[vlc_index - 1].table,
q-><API key>[vlc_index - 1].bits, 2);
quant_index_table[i] = quant_index_table[i - 1] + j - 12; // differential encoding
if (quant_index_table[i] > 63 || quant_index_table[i] < -63) {
av_log(q->avctx, AV_LOG_ERROR,
"Invalid quantizer %d at position %d, outside [-63, 63] range\n",
quant_index_table[i], i);
return AVERROR_INVALIDDATA;
}
}
return 0;
}
/**
* Calculate the category and category_index vector.
*
* @param q pointer to the COOKContext
* @param quant_index_table pointer to the array
* @param category pointer to the category array
* @param category_index pointer to the category_index array
*/
static void categorize(COOKContext *q, COOKSubpacket *p, const int *quant_index_table,
int *category, int *category_index)
{
int exp_idx, bias, tmpbias1, tmpbias2, bits_left, num_bits, index, v, i, j;
int exp_index2[102] = { 0 };
int exp_index1[102] = { 0 };
int <API key>[128 * 2] = { 0 };
int <API key> = p->numvector_size;
int <API key> = p->numvector_size;
bits_left = p->bits_per_subpacket - get_bits_count(&q->gb);
if (bits_left > q->samples_per_channel)
bits_left = q->samples_per_channel +
((bits_left - q->samples_per_channel) * 5) / 8;
bias = -32;
/* Estimate bias. */
for (i = 32; i > 0; i = i / 2) {
num_bits = 0;
index = 0;
for (j = p->total_subbands; j > 0; j
exp_idx = av_clip((i - quant_index_table[index] + bias) / 2, 0, 7);
index++;
num_bits += expbits_tab[exp_idx];
}
if (num_bits >= bits_left - 32)
bias += i;
}
/* Calculate total number of bits. */
num_bits = 0;
for (i = 0; i < p->total_subbands; i++) {
exp_idx = av_clip((bias - quant_index_table[i]) / 2, 0, 7);
num_bits += expbits_tab[exp_idx];
exp_index1[i] = exp_idx;
exp_index2[i] = exp_idx;
}
tmpbias1 = tmpbias2 = num_bits;
for (j = 1; j < p->numvector_size; j++) {
if (tmpbias1 + tmpbias2 > 2 * bits_left) {
int max = -999999;
index = -1;
for (i = 0; i < p->total_subbands; i++) {
if (exp_index1[i] < 7) {
v = (-2 * exp_index1[i]) - quant_index_table[i] + bias;
if (v >= max) {
max = v;
index = i;
}
}
}
if (index == -1)
break;
<API key>[<API key>++] = index;
tmpbias1 -= expbits_tab[exp_index1[index]] -
expbits_tab[exp_index1[index] + 1];
++exp_index1[index];
} else {
int min = 999999;
index = -1;
for (i = 0; i < p->total_subbands; i++) {
if (exp_index2[i] > 0) {
v = (-2 * exp_index2[i]) - quant_index_table[i] + bias;
if (v < min) {
min = v;
index = i;
}
}
}
if (index == -1)
break;
<API key>[--<API key>] = index;
tmpbias2 -= expbits_tab[exp_index2[index]] -
expbits_tab[exp_index2[index] - 1];
--exp_index2[index];
}
}
for (i = 0; i < p->total_subbands; i++)
category[i] = exp_index2[i];
for (i = 0; i < p->numvector_size - 1; i++)
category_index[i] = <API key>[<API key>++];
}
/**
* Expand the category vector.
*
* @param q pointer to the COOKContext
* @param category pointer to the category array
* @param category_index pointer to the category_index array
*/
static inline void expand_category(COOKContext *q, int *category,
int *category_index)
{
int i;
for (i = 0; i < q->num_vectors; i++)
{
int idx = category_index[i];
if (++category[idx] >= FF_ARRAY_ELEMS(dither_tab))
--category[idx];
}
}
/**
* The real requantization of the mltcoefs
*
* @param q pointer to the COOKContext
* @param index index
* @param quant_index quantisation index
* @param subband_coef_index array of indexes to quant_centroid_tab
* @param subband_coef_sign signs of coefficients
* @param mlt_p pointer into the mlt buffer
*/
static void <API key>(COOKContext *q, int index, int quant_index,
int *subband_coef_index, int *subband_coef_sign,
float *mlt_p)
{
int i;
float f1;
for (i = 0; i < SUBBAND_SIZE; i++) {
if (subband_coef_index[i]) {
f1 = quant_centroid_tab[index][subband_coef_index[i]];
if (subband_coef_sign[i])
f1 = -f1;
} else {
/* noise coding if subband_coef_index[i] == 0 */
f1 = dither_tab[index];
if (av_lfg_get(&q->random_state) < 0x80000000)
f1 = -f1;
}
mlt_p[i] = f1 * rootpow2tab[quant_index + 63];
}
}
/**
* Unpack the subband_coef_index and subband_coef_sign vectors.
*
* @param q pointer to the COOKContext
* @param category pointer to the category array
* @param subband_coef_index array of indexes to quant_centroid_tab
* @param subband_coef_sign signs of coefficients
*/
static int unpack_SQVH(COOKContext *q, COOKSubpacket *p, int category,
int *subband_coef_index, int *subband_coef_sign)
{
int i, j;
int vlc, vd, tmp, result;
vd = vd_tab[category];
result = 0;
for (i = 0; i < vpr_tab[category]; i++) {
vlc = get_vlc2(&q->gb, q->sqvh[category].table, q->sqvh[category].bits, 3);
if (p->bits_per_subpacket < get_bits_count(&q->gb)) {
vlc = 0;
result = 1;
}
for (j = vd - 1; j >= 0; j
tmp = (vlc * invradix_tab[category]) / 0x100000;
subband_coef_index[vd * i + j] = vlc - tmp * (kmax_tab[category] + 1);
vlc = tmp;
}
for (j = 0; j < vd; j++) {
if (subband_coef_index[i * vd + j]) {
if (get_bits_count(&q->gb) < p->bits_per_subpacket) {
subband_coef_sign[i * vd + j] = get_bits1(&q->gb);
} else {
result = 1;
subband_coef_sign[i * vd + j] = 0;
}
} else {
subband_coef_sign[i * vd + j] = 0;
}
}
}
return result;
}
/**
* Fill the mlt_buffer with mlt coefficients.
*
* @param q pointer to the COOKContext
* @param category pointer to the category array
* @param quant_index_table pointer to the array
* @param mlt_buffer pointer to mlt coefficients
*/
static void decode_vectors(COOKContext *q, COOKSubpacket *p, int *category,
int *quant_index_table, float *mlt_buffer)
{
/* A zero in this table means that the subband coefficient is
random noise coded. */
int subband_coef_index[SUBBAND_SIZE];
/* A zero in this table means that the subband coefficient is a
positive multiplicator. */
int subband_coef_sign[SUBBAND_SIZE];
int band, j;
int index = 0;
for (band = 0; band < p->total_subbands; band++) {
index = category[band];
if (category[band] < 7) {
if (unpack_SQVH(q, p, category[band], subband_coef_index, subband_coef_sign)) {
index = 7;
for (j = 0; j < p->total_subbands; j++)
category[band + j] = 7;
}
}
if (index >= 7) {
memset(subband_coef_index, 0, sizeof(subband_coef_index));
memset(subband_coef_sign, 0, sizeof(subband_coef_sign));
}
q->scalar_dequant(q, index, quant_index_table[band],
subband_coef_index, subband_coef_sign,
&mlt_buffer[band * SUBBAND_SIZE]);
}
/* FIXME: should this be removed, or moved into loop above? */
if (p->total_subbands * SUBBAND_SIZE >= q->samples_per_channel)
return;
}
static int mono_decode(COOKContext *q, COOKSubpacket *p, float *mlt_buffer)
{
int category_index[128] = { 0 };
int category[128] = { 0 };
int quant_index_table[102];
int res, i;
if ((res = decode_envelope(q, p, quant_index_table)) < 0)
return res;
q->num_vectors = get_bits(&q->gb, p->log2_numvector_size);
categorize(q, p, quant_index_table, category, category_index);
expand_category(q, category, category_index);
for (i=0; i<p->total_subbands; i++) {
if (category[i] > 7)
return AVERROR_INVALIDDATA;
}
decode_vectors(q, p, category, quant_index_table, mlt_buffer);
return 0;
}
/**
* the actual requantization of the timedomain samples
*
* @param q pointer to the COOKContext
* @param buffer pointer to the timedomain buffer
* @param gain_index index for the block multiplier
* @param gain_index_next index for the next block multiplier
*/
static void interpolate_float(COOKContext *q, float *buffer,
int gain_index, int gain_index_next)
{
int i;
float fc1, fc2;
fc1 = pow2tab[gain_index + 63];
if (gain_index == gain_index_next) { // static gain
for (i = 0; i < q->gain_size_factor; i++)
buffer[i] *= fc1;
} else { // smooth gain
fc2 = q->gain_table[11 + (gain_index_next - gain_index)];
for (i = 0; i < q->gain_size_factor; i++) {
buffer[i] *= fc1;
fc1 *= fc2;
}
}
}
/**
* Apply transform window, overlap buffers.
*
* @param q pointer to the COOKContext
* @param inbuffer pointer to the mltcoefficients
* @param gains_ptr current and previous gains
* @param previous_buffer pointer to the previous buffer to be used for overlapping
*/
static void imlt_window_float(COOKContext *q, float *inbuffer,
cook_gains *gains_ptr, float *previous_buffer)
{
const float fc = pow2tab[gains_ptr->previous[0] + 63];
int i;
/* The weird thing here, is that the two halves of the time domain
* buffer are swapped. Also, the newest data, that we save away for
* next frame, has the wrong sign. Hence the subtraction below.
* Almost sounds like a complex conjugate/reverse data/FFT effect.
*/
/* Apply window and overlap */
for (i = 0; i < q->samples_per_channel; i++)
inbuffer[i] = inbuffer[i] * fc * q->mlt_window[i] -
previous_buffer[i] * q->mlt_window[q->samples_per_channel - 1 - i];
}
/**
* The modulated lapped transform, this takes transform coefficients
* and transforms them into timedomain samples.
* Apply transform window, overlap buffers, apply gain profile
* and buffer management.
*
* @param q pointer to the COOKContext
* @param inbuffer pointer to the mltcoefficients
* @param gains_ptr current and previous gains
* @param previous_buffer pointer to the previous buffer to be used for overlapping
*/
static void imlt_gain(COOKContext *q, float *inbuffer,
cook_gains *gains_ptr, float *previous_buffer)
{
float *buffer0 = q->mono_mdct_output;
float *buffer1 = q->mono_mdct_output + q->samples_per_channel;
int i;
/* Inverse modified discrete cosine transform */
q->mdct_ctx.imdct_calc(&q->mdct_ctx, q->mono_mdct_output, inbuffer);
q->imlt_window(q, buffer1, gains_ptr, previous_buffer);
/* Apply gain profile */
for (i = 0; i < 8; i++)
if (gains_ptr->now[i] || gains_ptr->now[i + 1])
q->interpolate(q, &buffer1[q->gain_size_factor * i],
gains_ptr->now[i], gains_ptr->now[i + 1]);
/* Save away the current to be previous block. */
memcpy(previous_buffer, buffer0,
q->samples_per_channel * sizeof(*previous_buffer));
}
/**
* function for getting the jointstereo coupling information
*
* @param q pointer to the COOKContext
* @param decouple_tab decoupling array
*/
static int decouple_info(COOKContext *q, COOKSubpacket *p, int *decouple_tab)
{
int i;
int vlc = get_bits1(&q->gb);
int start = cplband[p->js_subband_start];
int end = cplband[p->subbands - 1];
int length = end - start + 1;
if (start > end)
return 0;
if (vlc)
for (i = 0; i < length; i++)
decouple_tab[start + i] = get_vlc2(&q->gb,
p->channel_coupling.table,
p->channel_coupling.bits, 2);
else
for (i = 0; i < length; i++) {
int v = get_bits(&q->gb, p->js_vlc_bits);
if (v == (1<<p->js_vlc_bits)-1) {
av_log(q->avctx, AV_LOG_ERROR, "decouple value too large\n");
return AVERROR_INVALIDDATA;
}
decouple_tab[start + i] = v;
}
return 0;
}
/**
* function decouples a pair of signals from a single signal via multiplication.
*
* @param q pointer to the COOKContext
* @param subband index of the current subband
* @param f1 multiplier for channel 1 extraction
* @param f2 multiplier for channel 2 extraction
* @param decode_buffer input buffer
* @param mlt_buffer1 pointer to left channel mlt coefficients
* @param mlt_buffer2 pointer to right channel mlt coefficients
*/
static void decouple_float(COOKContext *q,
COOKSubpacket *p,
int subband,
float f1, float f2,
float *decode_buffer,
float *mlt_buffer1, float *mlt_buffer2)
{
int j, tmp_idx;
for (j = 0; j < SUBBAND_SIZE; j++) {
tmp_idx = ((p->js_subband_start + subband) * SUBBAND_SIZE) + j;
mlt_buffer1[SUBBAND_SIZE * subband + j] = f1 * decode_buffer[tmp_idx];
mlt_buffer2[SUBBAND_SIZE * subband + j] = f2 * decode_buffer[tmp_idx];
}
}
/**
* function for decoding joint stereo data
*
* @param q pointer to the COOKContext
* @param mlt_buffer1 pointer to left channel mlt coefficients
* @param mlt_buffer2 pointer to right channel mlt coefficients
*/
static int joint_decode(COOKContext *q, COOKSubpacket *p,
float *mlt_buffer_left, float *mlt_buffer_right)
{
int i, j, res;
int decouple_tab[SUBBAND_SIZE] = { 0 };
float *decode_buffer = q->decode_buffer_0;
int idx, cpl_tmp;
float f1, f2;
const float *cplscale;
memset(decode_buffer, 0, sizeof(q->decode_buffer_0));
/* Make sure the buffers are zeroed out. */
memset(mlt_buffer_left, 0, 1024 * sizeof(*mlt_buffer_left));
memset(mlt_buffer_right, 0, 1024 * sizeof(*mlt_buffer_right));
if ((res = decouple_info(q, p, decouple_tab)) < 0)
return res;
if ((res = mono_decode(q, p, decode_buffer)) < 0)
return res;
/* The two channels are stored interleaved in decode_buffer. */
for (i = 0; i < p->js_subband_start; i++) {
for (j = 0; j < SUBBAND_SIZE; j++) {
mlt_buffer_left[i * 20 + j] = decode_buffer[i * 40 + j];
mlt_buffer_right[i * 20 + j] = decode_buffer[i * 40 + 20 + j];
}
}
/* When we reach js_subband_start (the higher frequencies)
the coefficients are stored in a coupling scheme. */
idx = (1 << p->js_vlc_bits) - 1;
for (i = p->js_subband_start; i < p->subbands; i++) {
cpl_tmp = cplband[i];
idx -= decouple_tab[cpl_tmp];
cplscale = q->cplscales[p->js_vlc_bits - 2]; // choose decoupler table
f1 = cplscale[decouple_tab[cpl_tmp] + 1];
f2 = cplscale[idx];
q->decouple(q, p, i, f1, f2, decode_buffer,
mlt_buffer_left, mlt_buffer_right);
idx = (1 << p->js_vlc_bits) - 1;
}
return 0;
}
/**
* First part of subpacket decoding:
* decode raw stream bytes and read gain info.
*
* @param q pointer to the COOKContext
* @param inbuffer pointer to raw stream data
* @param gains_ptr array of current/prev gain pointers
*/
static inline void <API key>(COOKContext *q, COOKSubpacket *p,
const uint8_t *inbuffer,
cook_gains *gains_ptr)
{
int offset;
offset = decode_bytes(inbuffer, q-><API key>,
p->bits_per_subpacket / 8);
init_get_bits(&q->gb, q-><API key> + offset,
p->bits_per_subpacket);
decode_gain_info(&q->gb, gains_ptr->now);
/* Swap current and previous gains */
FFSWAP(int *, gains_ptr->now, gains_ptr->previous);
}
/**
* Saturate the output signal and interleave.
*
* @param q pointer to the COOKContext
* @param out pointer to the output vector
*/
static void <API key>(COOKContext *q, float *out)
{
q->adsp.vector_clipf(out, q->mono_mdct_output + q->samples_per_channel,
-1.0f, 1.0f, FFALIGN(q->samples_per_channel, 8));
}
/**
* Final part of subpacket decoding:
* Apply modulated lapped transform, gain compensation,
* clip and convert to integer.
*
* @param q pointer to the COOKContext
* @param decode_buffer pointer to the mlt coefficients
* @param gains_ptr array of current/prev gain pointers
* @param previous_buffer pointer to the previous buffer to be used for overlapping
* @param out pointer to the output buffer
*/
static inline void <API key>(COOKContext *q, float *decode_buffer,
cook_gains *gains_ptr, float *previous_buffer,
float *out)
{
imlt_gain(q, decode_buffer, gains_ptr, previous_buffer);
if (out)
q->saturate_output(q, out);
}
/**
* Cook subpacket decoding. This function returns one decoded subpacket,
* usually 1024 samples per channel.
*
* @param q pointer to the COOKContext
* @param inbuffer pointer to the inbuffer
* @param outbuffer pointer to the outbuffer
*/
static int decode_subpacket(COOKContext *q, COOKSubpacket *p,
const uint8_t *inbuffer, float **outbuffer)
{
int sub_packet_size = p->size;
int res;
memset(q->decode_buffer_1, 0, sizeof(q->decode_buffer_1));
<API key>(q, p, inbuffer, &p->gains1);
if (p->joint_stereo) {
if ((res = joint_decode(q, p, q->decode_buffer_1, q->decode_buffer_2)) < 0)
return res;
} else {
if ((res = mono_decode(q, p, q->decode_buffer_1)) < 0)
return res;
if (p->num_channels == 2) {
<API key>(q, p, inbuffer + sub_packet_size / 2, &p->gains2);
if ((res = mono_decode(q, p, q->decode_buffer_2)) < 0)
return res;
}
}
<API key>(q, q->decode_buffer_1, &p->gains1,
p-><API key>,
outbuffer ? outbuffer[p->ch_idx] : NULL);
if (p->num_channels == 2) {
if (p->joint_stereo)
<API key>(q, q->decode_buffer_2, &p->gains1,
p-><API key>,
outbuffer ? outbuffer[p->ch_idx + 1] : NULL);
else
<API key>(q, q->decode_buffer_2, &p->gains2,
p-><API key>,
outbuffer ? outbuffer[p->ch_idx + 1] : NULL);
}
return 0;
}
static int cook_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
AVFrame *frame = data;
const uint8_t *buf = avpkt->data;
int buf_size = avpkt->size;
COOKContext *q = avctx->priv_data;
float **samples = NULL;
int i, ret;
int offset = 0;
int chidx = 0;
if (buf_size < avctx->block_align)
return buf_size;
/* get output buffer */
if (q->discarded_packets >= 2) {
frame->nb_samples = q->samples_per_channel;
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
samples = (float **)frame->extended_data;
}
/* estimate subpacket sizes */
q->subpacket[0].size = avctx->block_align;
for (i = 1; i < q->num_subpackets; i++) {
q->subpacket[i].size = 2 * buf[avctx->block_align - q->num_subpackets + i];
q->subpacket[0].size -= q->subpacket[i].size + 1;
if (q->subpacket[0].size < 0) {
av_log(avctx, AV_LOG_DEBUG,
"frame subpacket size total > avctx->block_align!\n");
return AVERROR_INVALIDDATA;
}
}
/* decode supbackets */
for (i = 0; i < q->num_subpackets; i++) {
q->subpacket[i].bits_per_subpacket = (q->subpacket[i].size * 8) >>
q->subpacket[i].bits_per_subpdiv;
q->subpacket[i].ch_idx = chidx;
av_log(avctx, AV_LOG_DEBUG,
"subpacket[%i] size %i js %i %i block_align %i\n",
i, q->subpacket[i].size, q->subpacket[i].joint_stereo, offset,
avctx->block_align);
if ((ret = decode_subpacket(q, &q->subpacket[i], buf + offset, samples)) < 0)
return ret;
offset += q->subpacket[i].size;
chidx += q->subpacket[i].num_channels;
av_log(avctx, AV_LOG_DEBUG, "subpacket[%i] %i %i\n",
i, q->subpacket[i].size * 8, get_bits_count(&q->gb));
}
/* Discard the first two frames: no valid audio. */
if (q->discarded_packets < 2) {
q->discarded_packets++;
*got_frame_ptr = 0;
return avctx->block_align;
}
*got_frame_ptr = 1;
return avctx->block_align;
}
#ifdef DEBUG
static void dump_cook_context(COOKContext *q)
{
//int i=0;
#define PRINT(a, b) av_dlog(q->avctx, " %s = %d\n", a, b);
av_dlog(q->avctx, "COOKextradata\n");
av_dlog(q->avctx, "cookversion=%x\n", q->subpacket[0].cookversion);
if (q->subpacket[0].cookversion > STEREO) {
PRINT("js_subband_start", q->subpacket[0].js_subband_start);
PRINT("js_vlc_bits", q->subpacket[0].js_vlc_bits);
}
av_dlog(q->avctx, "COOKContext\n");
PRINT("nb_channels", q->avctx->channels);
PRINT("bit_rate", q->avctx->bit_rate);
PRINT("sample_rate", q->avctx->sample_rate);
PRINT("samples_per_channel", q->subpacket[0].samples_per_channel);
PRINT("subbands", q->subpacket[0].subbands);
PRINT("js_subband_start", q->subpacket[0].js_subband_start);
PRINT("log2_numvector_size", q->subpacket[0].log2_numvector_size);
PRINT("numvector_size", q->subpacket[0].numvector_size);
PRINT("total_subbands", q->subpacket[0].total_subbands);
}
#endif
/**
* Cook initialization
*
* @param avctx pointer to the AVCodecContext
*/
static av_cold int cook_decode_init(AVCodecContext *avctx)
{
COOKContext *q = avctx->priv_data;
const uint8_t *edata_ptr = avctx->extradata;
const uint8_t *edata_ptr_end = edata_ptr + avctx->extradata_size;
int extradata_size = avctx->extradata_size;
int s = 0;
unsigned int channel_mask = 0;
int samples_per_frame = 0;
int ret;
q->avctx = avctx;
/* Take care of the codec specific extradata. */
if (extradata_size <= 0) {
av_log(avctx, AV_LOG_ERROR, "Necessary extradata missing!\n");
return AVERROR_INVALIDDATA;
}
av_log(avctx, AV_LOG_DEBUG, "codecdata_length=%d\n", avctx->extradata_size);
/* Take data from the AVCodecContext (RM container). */
if (!avctx->channels) {
av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
return AVERROR_INVALIDDATA;
}
/* Initialize RNG. */
av_lfg_init(&q->random_state, 0);
ff_audiodsp_init(&q->adsp);
while (edata_ptr < edata_ptr_end) {
/* 8 for mono, 16 for stereo, ? for multichannel
Swap to right endianness so we don't need to care later on. */
if (extradata_size >= 8) {
q->subpacket[s].cookversion = bytestream_get_be32(&edata_ptr);
samples_per_frame = bytestream_get_be16(&edata_ptr);
q->subpacket[s].subbands = bytestream_get_be16(&edata_ptr);
extradata_size -= 8;
}
if (extradata_size >= 8) {
bytestream_get_be32(&edata_ptr); // Unknown unused
q->subpacket[s].js_subband_start = bytestream_get_be16(&edata_ptr);
if (q->subpacket[s].js_subband_start >= 51) {
av_log(avctx, AV_LOG_ERROR, "js_subband_start %d is too large\n", q->subpacket[s].js_subband_start);
return AVERROR_INVALIDDATA;
}
q->subpacket[s].js_vlc_bits = bytestream_get_be16(&edata_ptr);
extradata_size -= 8;
}
/* Initialize extradata related variables. */
q->subpacket[s].samples_per_channel = samples_per_frame / avctx->channels;
q->subpacket[s].bits_per_subpacket = avctx->block_align * 8;
/* Initialize default data states. */
q->subpacket[s].log2_numvector_size = 5;
q->subpacket[s].total_subbands = q->subpacket[s].subbands;
q->subpacket[s].num_channels = 1;
/* Initialize version-dependent variables */
av_log(avctx, AV_LOG_DEBUG, "subpacket[%i].cookversion=%x\n", s,
q->subpacket[s].cookversion);
q->subpacket[s].joint_stereo = 0;
switch (q->subpacket[s].cookversion) {
case MONO:
if (avctx->channels != 1) {
<API key>(avctx, "Container channels != 1");
return <API key>;
}
av_log(avctx, AV_LOG_DEBUG, "MONO\n");
break;
case STEREO:
if (avctx->channels != 1) {
q->subpacket[s].bits_per_subpdiv = 1;
q->subpacket[s].num_channels = 2;
}
av_log(avctx, AV_LOG_DEBUG, "STEREO\n");
break;
case JOINT_STEREO:
if (avctx->channels != 2) {
<API key>(avctx, "Container channels != 2");
return <API key>;
}
av_log(avctx, AV_LOG_DEBUG, "JOINT_STEREO\n");
if (avctx->extradata_size >= 16) {
q->subpacket[s].total_subbands = q->subpacket[s].subbands +
q->subpacket[s].js_subband_start;
q->subpacket[s].joint_stereo = 1;
q->subpacket[s].num_channels = 2;
}
if (q->subpacket[s].samples_per_channel > 256) {
q->subpacket[s].log2_numvector_size = 6;
}
if (q->subpacket[s].samples_per_channel > 512) {
q->subpacket[s].log2_numvector_size = 7;
}
break;
case MC_COOK:
av_log(avctx, AV_LOG_DEBUG, "MULTI_CHANNEL\n");
if (extradata_size >= 4)
channel_mask |= q->subpacket[s].channel_mask = bytestream_get_be32(&edata_ptr);
if (<API key>(q->subpacket[s].channel_mask) > 1) {
q->subpacket[s].total_subbands = q->subpacket[s].subbands +
q->subpacket[s].js_subband_start;
q->subpacket[s].joint_stereo = 1;
q->subpacket[s].num_channels = 2;
q->subpacket[s].samples_per_channel = samples_per_frame >> 1;
if (q->subpacket[s].samples_per_channel > 256) {
q->subpacket[s].log2_numvector_size = 6;
}
if (q->subpacket[s].samples_per_channel > 512) {
q->subpacket[s].log2_numvector_size = 7;
}
} else
q->subpacket[s].samples_per_channel = samples_per_frame;
break;
default:
<API key>(avctx, "Cook version %d",
q->subpacket[s].cookversion);
return <API key>;
}
if (s > 1 && q->subpacket[s].samples_per_channel != q->samples_per_channel) {
av_log(avctx, AV_LOG_ERROR, "different number of samples per channel!\n");
return AVERROR_INVALIDDATA;
} else
q->samples_per_channel = q->subpacket[0].samples_per_channel;
/* Initialize variable relations */
q->subpacket[s].numvector_size = (1 << q->subpacket[s].log2_numvector_size);
/* Try to catch some obviously faulty streams, othervise it might be exploitable */
if (q->subpacket[s].total_subbands > 53) {
<API key>(avctx, "total_subbands > 53");
return <API key>;
}
if ((q->subpacket[s].js_vlc_bits > 6) ||
(q->subpacket[s].js_vlc_bits < 2 * q->subpacket[s].joint_stereo)) {
av_log(avctx, AV_LOG_ERROR, "js_vlc_bits = %d, only >= %d and <= 6 allowed!\n",
q->subpacket[s].js_vlc_bits, 2 * q->subpacket[s].joint_stereo);
return AVERROR_INVALIDDATA;
}
if (q->subpacket[s].subbands > 50) {
<API key>(avctx, "subbands > 50");
return <API key>;
}
if (q->subpacket[s].subbands == 0) {
<API key>(avctx, "subbands = 0");
return <API key>;
}
q->subpacket[s].gains1.now = q->subpacket[s].gain_1;
q->subpacket[s].gains1.previous = q->subpacket[s].gain_2;
q->subpacket[s].gains2.now = q->subpacket[s].gain_3;
q->subpacket[s].gains2.previous = q->subpacket[s].gain_4;
if (q->num_subpackets + q->subpacket[s].num_channels > q->avctx->channels) {
av_log(avctx, AV_LOG_ERROR, "Too many subpackets %d for channels %d\n", q->num_subpackets, q->avctx->channels);
return AVERROR_INVALIDDATA;
}
q->num_subpackets++;
s++;
if (s > FFMIN(MAX_SUBPACKETS, avctx->block_align)) {
<API key>(avctx, "subpackets > %d", FFMIN(MAX_SUBPACKETS, avctx->block_align));
return <API key>;
}
}
/* Generate tables */
init_pow2table();
init_gain_table(q);
<API key>(q);
if ((ret = <API key>(q)))
return ret;
if (avctx->block_align >= UINT_MAX / 2)
return AVERROR(EINVAL);
/* Pad the databuffer with:
DECODE_BYTES_PAD1 or DECODE_BYTES_PAD2 for decode_bytes(),
<API key>, for the bitstreamreader. */
q-><API key> =
av_mallocz(avctx->block_align
+ DECODE_BYTES_PAD1(avctx->block_align)
+ <API key>);
if (!q-><API key>)
return AVERROR(ENOMEM);
/* Initialize transform. */
if ((ret = init_cook_mlt(q)))
return ret;
/* Initialize COOK signal arithmetic handling */
if (1) {
q->scalar_dequant = <API key>;
q->decouple = decouple_float;
q->imlt_window = imlt_window_float;
q->interpolate = interpolate_float;
q->saturate_output = <API key>;
}
/* Try to catch some obviously faulty streams, othervise it might be exploitable */
if (q->samples_per_channel != 256 && q->samples_per_channel != 512 &&
q->samples_per_channel != 1024) {
<API key>(avctx, "samples_per_channel = %d",
q->samples_per_channel);
return <API key>;
}
avctx->sample_fmt = AV_SAMPLE_FMT_FLTP;
if (channel_mask)
avctx->channel_layout = channel_mask;
else
avctx->channel_layout = (avctx->channels == 2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;
#ifdef DEBUG
dump_cook_context(q);
#endif
return 0;
}
AVCodec ff_cook_decoder = {
.name = "cook",
.long_name = <API key>("Cook / Cooker / Gecko (RealAudio G2)"),
.type = AVMEDIA_TYPE_AUDIO,
.id = AV_CODEC_ID_COOK,
.priv_data_size = sizeof(COOKContext),
.init = cook_decode_init,
.close = cook_decode_close,
.decode = cook_decode_frame,
.capabilities = CODEC_CAP_DR1,
.sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_FLTP,
AV_SAMPLE_FMT_NONE },
}; |
<?php
/**
@class <API key>
*/
class <API key> extends BasicModel
{
protected $name = "houseVirtualCoupons";
protected $preferred_db = 'op';
protected $columns = array(
'card_no' => array('type'=>'INT', 'primary_key'=>true),
'coupID' => array('type'=>'INT', 'primary_key'=>true),
'description' => array('type'=>'VARCHAR(100)'),
'start_date' => array('type'=>'DATETIME'),
'end_date' => array('type'=>'DATETIME'),
);
/* START ACCESSOR FUNCTIONS */
public function card_no()
{
if(func_num_args() == 0) {
if(isset($this->instance["card_no"])) {
return $this->instance["card_no"];
} elseif(isset($this->columns["card_no"]["default"])) {
return $this->columns["card_no"]["default"];
} else {
return null;
}
} else {
$this->instance["card_no"] = func_get_arg(0);
}
}
public function coupID()
{
if(func_num_args() == 0) {
if(isset($this->instance["coupID"])) {
return $this->instance["coupID"];
} elseif(isset($this->columns["coupID"]["default"])) {
return $this->columns["coupID"]["default"];
} else {
return null;
}
} else {
$this->instance["coupID"] = func_get_arg(0);
}
}
public function description()
{
if(func_num_args() == 0) {
if(isset($this->instance["description"])) {
return $this->instance["description"];
} elseif(isset($this->columns["description"]["default"])) {
return $this->columns["description"]["default"];
} else {
return null;
}
} else {
$this->instance["description"] = func_get_arg(0);
}
}
public function start_date()
{
if(func_num_args() == 0) {
if(isset($this->instance["start_date"])) {
return $this->instance["start_date"];
} elseif(isset($this->columns["start_date"]["default"])) {
return $this->columns["start_date"]["default"];
} else {
return null;
}
} else {
$this->instance["start_date"] = func_get_arg(0);
}
}
public function end_date()
{
if(func_num_args() == 0) {
if(isset($this->instance["end_date"])) {
return $this->instance["end_date"];
} elseif(isset($this->columns["end_date"]["default"])) {
return $this->columns["end_date"]["default"];
} else {
return null;
}
} else {
$this->instance["end_date"] = func_get_arg(0);
}
}
/* END ACCESSOR FUNCTIONS */
} |
// This file has been auto-generated. Don't change it by hand!
#ifndef <API key>
#define <API key>
#include "dml-baseTypes.hpp"
namespace drawingml
{
using namespace ::xio;
using namespace ::xio::xml::schema;
class CT_LightRig;
class ST_LightRigType
{
static String _literals[];
String _value;
public:
enum value { balanced, brightRoom, chilly, contrasting, flat, flood, freezing, glow, harsh, legacyFlat1, legacyFlat2, legacyFlat3, legacyFlat4, legacyHarsh1, legacyHarsh2, legacyHarsh3, legacyHarsh4, legacyNormal1, legacyNormal2, legacyNormal3, legacyNormal4, morning, soft, sunrise, sunset, threePt, twoPt };
static const String balanced_literal;
static const String brightRoom_literal;
static const String chilly_literal;
static const String contrasting_literal;
static const String flat_literal;
static const String flood_literal;
static const String freezing_literal;
static const String glow_literal;
static const String harsh_literal;
static const String legacyFlat1_literal;
static const String legacyFlat2_literal;
static const String legacyFlat3_literal;
static const String legacyFlat4_literal;
static const String <API key>;
static const String <API key>;
static const String <API key>;
static const String <API key>;
static const String <API key>;
static const String <API key>;
static const String <API key>;
static const String <API key>;
static const String morning_literal;
static const String soft_literal;
static const String sunrise_literal;
static const String sunset_literal;
static const String threePt_literal;
static const String twoPt_literal;
ST_LightRigType() : _value(legacyFlat1_literal) {}
ST_LightRigType(value val) : _value(convert(val)) {}
ST_LightRigType(const String& str) : _value(str) {}
static value convert(const String& str) { return (value)::xio::util::binary_search(str, _literals, 27, 0); }
static String convert(value v) { return _literals[(int)v]; }
bool operator == (const String& str) const { return str == _value; }
bool operator == (value val) const {return convert(val) == _value; }
bool operator != (const String& str) const { return str != _value; }
bool operator != (value val) const {return convert(val) != _value; }
const String& operator = (const String& str) { _value = str; return str; }
const value& operator = (const value& val) { _value = convert(val); return val; }
operator const String& () const { return _value; }
operator String& () { return _value; }
operator value () const { return convert(_value); }
String serialize() const { return _value; }
};
class <API key>
{
static String _literals[];
String _value;
public:
enum value { b, bl, br, l, r, t, tl, tr };
static const String b_literal;
static const String bl_literal;
static const String br_literal;
static const String l_literal;
static const String r_literal;
static const String t_literal;
static const String tl_literal;
static const String tr_literal;
<API key>() : _value(tl_literal) {}
<API key>(value val) : _value(convert(val)) {}
<API key>(const String& str) : _value(str) {}
static value convert(const String& str) { return (value)::xio::util::binary_search(str, _literals, 8, 0); }
static String convert(value v) { return _literals[(int)v]; }
bool operator == (const String& str) const { return str == _value; }
bool operator == (value val) const {return convert(val) == _value; }
bool operator != (const String& str) const { return str != _value; }
bool operator != (value val) const {return convert(val) != _value; }
const String& operator = (const String& str) { _value = str; return str; }
const value& operator = (const value& val) { _value = convert(val); return val; }
operator const String& () const { return _value; }
operator String& () { return _value; }
operator value () const { return convert(_value); }
String serialize() const { return _value; }
};
class CT_LightRig
{
public:
poptional< CT_SphereCoords > rot;
ST_LightRigType rig;
<API key> dir;
};
}
#endif |
package org.xbrlapi.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import org.xbrlapi.Arc;
import org.xbrlapi.ArcEnd;
import org.xbrlapi.ExtendedLink;
import org.xbrlapi.Locator;
import org.xbrlapi.Resource;
import org.xbrlapi.XlinkDocumentation;
import org.xbrlapi.utilities.Constants;
import org.xbrlapi.utilities.XBRLException;
/**
* @author Geoffrey Shuetrim (geoff@galexy.net)
*/
public class ExtendedLinkImpl extends LinkImpl implements ExtendedLink {
private static final long serialVersionUID = -<API key>;
/**
* @see org.xbrlapi.ExtendedLink#getLocators()
*/
public List<Locator> getLocators() throws XBRLException {
List<Locator> locators = this.<Locator>getChildren("org.xbrlapi.impl.LocatorImpl");
return locators;
}
/**
* @see org.xbrlapi.ExtendedLink#getArcEndsWithLabel(String)
*/
public <E extends ArcEnd> List<E> getArcEndsWithLabel(String label) throws XBRLException {
String xpath = "#roots#[@parentIndex='" + getIndex() + "' and "+ Constants.XBRLAPIPrefix+ ":" + "data/*/@xlink:label='" + label + "']";
List<E> ends = getStore().<E><API key>(xpath);
logger.debug("Extended link " + getIndex() + " has " + ends.size() + " ends with label " + label);
return ends;
}
/**
* @see org.xbrlapi.ExtendedLink#<API key>(String)
*/
public List<Locator> <API key>(String label) throws XBRLException {
String xpath = "#roots#[@parentIndex='" + getIndex() + "' and @type='org.xbrlapi.impl.LocatorImpl' and " + Constants.XBRLAPIPrefix + ":" + "data/link:loc/@xlink:label='" + label + "']";
return getStore().<Locator><API key>(xpath);
}
/**
* @see org.xbrlapi.ExtendedLink#getLocatorsWithHref(String)
*/
public List<Locator> getLocatorsWithHref(String href) throws XBRLException {
String xpath = "#roots#[@parentIndex='" + getIndex() + "' and @type='org.xbrlapi.impl.LocatorImpl' and @absoluteHref='" + href + "']";
return getStore().<Locator><API key>(xpath);
}
/**
* @see org.xbrlapi.ExtendedLink#getArcs()
*/
public List<Arc> getArcs() throws XBRLException {
String xpath = "#roots#[@parentIndex='" + getIndex() + "' and " + Constants.XBRLAPIPrefix + ":" + "data/*/@xlink:type='arc']";
return getStore().<Arc><API key>(xpath);
}
/**
* @see org.xbrlapi.ExtendedLink#getArcsWithToLabel(String)
*/
public List<Arc> getArcsWithToLabel(String to) throws XBRLException {
String query = "#roots#[@parentIndex='" + getIndex() + "' and xbrlapi:data/*/@xlink:to='" + to + "']";
logger.debug(query);
return getStore().<Arc><API key>(query);
}
/**
* @see org.xbrlapi.ExtendedLink#<API key>(String)
*/
public List<Arc> <API key>(String from) throws XBRLException {
String xpath = "#roots#[@parentIndex='" + getIndex() + "' and "+ Constants.XBRLAPIPrefix+ ":" + "data/*/@xlink:from='" + from + "']";
List<Arc> arcs = getStore().<Arc><API key>(xpath);
return arcs;
}
/**
* @see org.xbrlapi.ExtendedLink#<API key>(String,String)
*/
public List<Arc> <API key>(String from, String arcrole) throws XBRLException {
String xpath = "#roots#[@parentIndex='" + getIndex() + "' and */*[@xlink:from='" + from + "' and @xlink:arcrole='" + arcrole + "']]";
List<Arc> arcs = getStore().<Arc><API key>(xpath);
return arcs;
}
/**
* @see org.xbrlapi.ExtendedLink#getArcsWithArcrole(String)
*/
public List<Arc> getArcsWithArcrole(String arcrole) throws XBRLException {
String xpath = "#roots#[@parentIndex='" + getIndex() + "' and */*/@xlink:arcrole='" + arcrole + "']";
List<Arc> arcs = getStore().<Arc><API key>(xpath);
return arcs;
}
/**
* @see org.xbrlapi.ExtendedLink#<API key>(String,String)
*/
public List<Arc> <API key>(String to, String arcrole) throws XBRLException {
/**
* @see org.xbrlapi.ExtendedLink#getResources()
*
*/
public List<Resource> getResources() throws XBRLException {
String xpath = "#roots#[@parentIndex='" + getIndex() + "' and " + Constants.XBRLAPIPrefix + ":" + "data/*/@xlink:type='resource']";
return getStore().<Resource><API key>(xpath);
}
/**
* @see org.xbrlapi.ExtendedLink#<API key>(String)
*/
public List<Resource> <API key>(String label) throws XBRLException {
/**
* Get the list of documentation fragments contained by the extended link.
* Returns the list of documentation fragments in the extended link.
* @throws XBRLException
* @see org.xbrlapi.ExtendedLink#getDocumentations()
*/
public List<XlinkDocumentation> getDocumentations() throws XBRLException {
return this.<XlinkDocumentation>getChildren("org.xbrlapi.impl.<API key>");
}
/**
* @see org.xbrlapi.ExtendedLink#<API key>()
*/
public Map<String,List<String>> <API key>() throws XBRLException {
Map<String,List<String>> result = new HashMap<String,List<String>>();
String query = "for $fragment in #roots#[@parentIndex='" + getIndex() + "' and */*[@xlink:type='resource' or @xlink:type='locator']] return concat($fragment/@index,' ',$fragment/*/*/@xlink:label)";
Set<String> pairs = getStore().queryForStrings(query);
for (String pair: pairs) {
int split = pair.indexOf(" ");
String index = pair.substring(0,split);
String label = pair.substring(split+1);
if (result.containsKey(label)) {
result.get(label).add(index);
} else {
List<String> list = new Vector<String>();
list.add(index);
result.put(label,list);
}
}
return result;
}
/**
* @see org.xbrlapi.ExtendedLink#<API key>()
*/
public Map<String,String> <API key>() throws XBRLException {
Map<String,String> result = new HashMap<String,String>();
String query = "for $locator in #roots#[@parentIndex='" + getIndex() + "' and */*/@xlink:type='locator'] return concat($locator/@index,' ',#roots#[@uri=$locator/@targetDocumentURI and $locator/@targetPointerValue=" + Constants.XBRLAPIPrefix + ":xptr/@value]/@index)";
Set<String> pairs = getStore().queryForStrings(query);
for (String pair: pairs) {
int split = pair.indexOf(" ");
String locatorIndex = pair.substring(0,split);
String targetIndex = pair.substring(split+1);
result.put(locatorIndex,targetIndex);
}
return result;
}
} |
// Exclude rarely-used stuff from Windows headers
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
namespace BWAPI
{
class Game;
class AIModule;
class TournamentModule;
Game* Broodwar;
}
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved);
/**
* Creates standard AIModule. Used mainly for testing in Debug mode.
*/
extern "C" __declspec(dllexport) BWAPI::AIModule* newAIModule(BWAPI::Game* game);
/**
* Creates bot's AIModule.
*/
extern "C" __declspec(dllexport) BWAPI::AIModule* newTournamentAI(BWAPI::Game* game);
/**
* Creates tournament module.
*/
extern "C" __declspec(dllexport) BWAPI::TournamentModule* newTournamentModule(); |
<?php namespace XoopsModules\Xasset;
use XoopsModules\Xasset;
/**
* Class <API key>
*/
class <API key> extends Xasset\BaseObject
{
public $weight;
/**
* @param null $id
*/
public function __construct($id = null)
{
$this->initVar('id', XOBJ_DTYPE_INT, null, false);
$this->initVar('uid', XOBJ_DTYPE_INT, null, false);
$this->initVar('order_detail_id', XOBJ_DTYPE_INT, null, false);
$this->initVar('group_id', XOBJ_DTYPE_INT, null, false);
$this->initVar('expiry_date', XOBJ_DTYPE_INT, null, false);
$this->initVar('sent_warning', XOBJ_DTYPE_INT, null, false);
$this->weight = 17;
if (null !== $id) {
if (is_array($id)) {
$this->assignVars($id);
}
} else {
$this->setNew();
}
}
/**
* @return mixed
*/
public function uid()
{
return $this->getVar('uid');
}
/**
* @return bool
*/
public function sentOverADayAgo()
{
//check if it has been 24 hours since
if ($this->getVar('sent_warning') > 0) {
return (time() - $this->getVar('sent_warning')) > 60 * 60 * 24;
}
return true;
}
public function setSentWarning()
{
$this->setVar('sent_warning', time());
}
/**
* @param string $format
*
* @return bool|mixed|string
*/
public function expiryDate($format = 'n')
{
switch ($format) {
case 'n':
return $this->getVar('expiry_date');
break;
case 's':
return date('Y-m-d', $this->getVar('expiry_date'));
break;
case 'l':
return date('l dS \of F Y h:i:s A', $this->getVar('expiry_date'));
}
}
/**
* @return bool|void
*/
public function &getOrderDetails()
{
$hOrderDetail = new Xasset\OrderDetailHandler($GLOBALS['xoopsDB']);
return $hOrderDetail->get($this->getVar('order_detail_id'));
}
} |
#include "precomp.h"
#include <commoncontrols.h>
#include <shlwapi_undoc.h>
#include <uxtheme.h>
#include <vssym32.h>
#include "CMenuBand.h"
#include "CMenuToolbars.h"
#define IDS_MENU_EMPTY 34561
#define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp))
#define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp))
<API key>(CMenuToolbars);
// FIXME: Enable if/when wine comctl supports this flag properly
#define <API key> 0
// User-defined timer ID used while hot-tracking around the menu
#define TIMERID_HOTTRACK 1
LRESULT CMenuToolbarBase::OnWinEventWrap(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
LRESULT lr;
bHandled = OnWinEvent(m_hWnd, uMsg, wParam, lParam, &lr) != S_FALSE;
return lr;
}
HRESULT CMenuToolbarBase::OnWinEvent(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT *theResult)
{
NMHDR * hdr;
*theResult = 0;
switch (uMsg)
{
case WM_COMMAND:
//return OnCommand(wParam, lParam, theResult);
return S_OK;
case WM_NOTIFY:
hdr = reinterpret_cast<LPNMHDR>(lParam);
switch (hdr->code)
{
case TBN_DELETINGBUTTON:
return OnDeletingButton(reinterpret_cast<LPNMTOOLBAR>(hdr));
case PGN_CALCSIZE:
return OnPagerCalcSize(reinterpret_cast<LPNMPGCALCSIZE>(hdr));
case TBN_DROPDOWN:
return ProcessClick(reinterpret_cast<LPNMTOOLBAR>(hdr)->iItem);
case TBN_HOTITEMCHANGE:
//return OnHotItemChange(reinterpret_cast<LPNMTBHOTITEM>(hdr), theResult);
return S_OK;
case NM_CUSTOMDRAW:
return OnCustomDraw(reinterpret_cast<LPNMTBCUSTOMDRAW>(hdr), theResult);
case TBN_GETINFOTIP:
return OnGetInfoTip(reinterpret_cast<LPNMTBGETINFOTIP>(hdr));
// Silence unhandled items so that they don't print as unknown
case RBN_CHILDSIZE:
return S_OK;
case TTN_GETDISPINFO:
return S_OK;
case NM_RELEASEDCAPTURE:
break;
case NM_CLICK:
case NM_RDOWN:
case NM_LDOWN:
break;
case TBN_GETDISPINFO:
break;
case TBN_BEGINDRAG:
case TBN_ENDDRAG:
break;
case NM_TOOLTIPSCREATED:
break;
// Unknown
case -714: return S_FALSE;
default:
TRACE("WM_NOTIFY unknown code %d, %d\n", hdr->code, hdr->idFrom);
return S_OK;
}
return S_FALSE;
}
return S_FALSE;
}
HRESULT CMenuToolbarBase::DisableMouseTrack(BOOL bDisable)
{
if (m_disableMouseTrack != bDisable)
{
m_disableMouseTrack = bDisable;
TRACE("DisableMouseTrack %d\n", bDisable);
}
return S_OK;
}
HRESULT CMenuToolbarBase::OnPagerCalcSize(LPNMPGCALCSIZE csize)
{
SIZE tbs;
GetSizes(NULL, &tbs, NULL);
if (csize->dwFlag == PGF_CALCHEIGHT)
{
csize->iHeight = tbs.cy;
}
else if (csize->dwFlag == PGF_CALCWIDTH)
{
csize->iWidth = tbs.cx;
}
return S_OK;
}
HRESULT CMenuToolbarBase::OnCustomDraw(LPNMTBCUSTOMDRAW cdraw, LRESULT * theResult)
{
bool isHot, isPopup;
TBBUTTONINFO btni;
switch (cdraw->nmcd.dwDrawStage)
{
case CDDS_PREPAINT:
*theResult = CDRF_NOTIFYITEMDRAW;
return S_OK;
case CDDS_ITEMPREPAINT:
// The item with an active submenu gets the CHECKED flag.
isHot = m_hotBar == this && (int) cdraw->nmcd.dwItemSpec == m_hotItem;
isPopup = m_popupBar == this && (int) cdraw->nmcd.dwItemSpec == m_popupItem;
if ((m_initFlags & SMINIT_VERTICAL))
{
COLORREF clrText;
HBRUSH bgBrush;
RECT rc = cdraw->nmcd.rc;
HDC hdc = cdraw->nmcd.hdc;
// Remove HOT and CHECKED flags (will restore HOT if necessary)
cdraw->nmcd.uItemState &= ~(CDIS_HOT | CDIS_CHECKED);
// Decide on the colors
if (isHot || (m_hotItem < 0 && isPopup))
{
cdraw->nmcd.uItemState |= CDIS_HOT;
clrText = GetSysColor(COLOR_HIGHLIGHTTEXT);
bgBrush = GetSysColorBrush(m_useFlatMenus ? COLOR_MENUHILIGHT : COLOR_HIGHLIGHT);
}
else
{
clrText = GetSysColor(COLOR_MENUTEXT);
bgBrush = GetSysColorBrush(COLOR_MENU);
}
// Paint the background color with the selected color
FillRect(hdc, &rc, bgBrush);
// Set the text color in advance, this color will be assigned when the ITEMPOSTPAINT triggers
SetTextColor(hdc, clrText);
// Set the text color, will be used by the internal drawing code
cdraw->clrText = clrText;
cdraw->iListGap += 4;
// Tell the default drawing code we don't want any fanciness, not even a background.
*theResult = <API key> | TBCDRF_NOBACKGROUND | TBCDRF_NOEDGES | TBCDRF_NOOFFSET | TBCDRF_NOMARK | 0x00800000; // FIXME: the last bit is Vista+, useful for debugging only
}
else
{
// Remove HOT and CHECKED flags (will restore HOT if necessary)
cdraw->nmcd.uItemState &= ~CDIS_HOT;
// Decide on the colors
if (isHot || (m_hotItem < 0 && isPopup))
{
cdraw->nmcd.uItemState |= CDIS_HOT;
}
*theResult = 0;
}
return S_OK;
case CDDS_ITEMPOSTPAINT:
// Fetch the button style
btni.cbSize = sizeof(btni);
btni.dwMask = TBIF_STYLE;
GetButtonInfo(cdraw->nmcd.dwItemSpec, &btni);
// Check if we need to draw a submenu arrow
if (btni.fsStyle & BTNS_DROPDOWN)
{
// TODO: Support RTL text modes by drawing a leftwards arrow aligned to the left of the control
// "8" is the rightwards dropdown arrow in the Marlett font
WCHAR text [] = L"8";
// Configure the font to draw with Marlett, keeping the current background color as-is
SelectObject(cdraw->nmcd.hdc, m_marlett);
SetBkMode(cdraw->nmcd.hdc, TRANSPARENT);
// Tweak the alignment by 1 pixel so the menu draws like the Windows start menu.
RECT rc = cdraw->nmcd.rc;
rc.right += 1;
// The arrow is drawn at the right of the item's rect, aligned vertically.
DrawTextEx(cdraw->nmcd.hdc, text, 1, &rc, DT_NOCLIP | DT_VCENTER | DT_RIGHT | DT_SINGLELINE, NULL);
}
*theResult = TRUE;
return S_OK;
}
return S_OK;
}
CMenuToolbarBase::CMenuToolbarBase(CMenuBand *menuBand, BOOL usePager) :
m_pager(this, 1),
m_useFlatMenus(FALSE),
m_SubclassOld(NULL),
m_disableMouseTrack(FALSE),
m_timerEnabled(FALSE),
m_menuBand(menuBand),
m_dwMenuFlags(0),
m_hasSizes(FALSE),
m_usePager(usePager),
m_hotBar(NULL),
m_hotItem(-1),
m_popupBar(NULL),
m_popupItem(-1),
m_isTrackingPopup(FALSE),
m_cancelingPopup(FALSE)
{
m_idealSize.cx = 0;
m_idealSize.cy = 0;
m_itemSize.cx = 0;
m_itemSize.cy = 0;
m_marlett = CreateFont(
0, 0, 0, 0, 0, 0, 0, 0, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
DEFAULT_QUALITY, FF_DONTCARE, L"Marlett");
}
CMenuToolbarBase::~CMenuToolbarBase()
{
if (m_hWnd)
DestroyWindow();
if (m_pager.m_hWnd)
m_pager.DestroyWindow();
DeleteObject(m_marlett);
}
void CMenuToolbarBase::InvalidateDraw()
{
InvalidateRect(NULL, FALSE);
}
HRESULT CMenuToolbarBase::ShowDW(BOOL fShow)
{
ShowWindow(fShow ? SW_SHOW : SW_HIDE);
// Ensure that the right image list is assigned to the toolbar
UpdateImageLists();
// For custom-drawing
if (IsAppThemed())
GetThemeSysBool(GetWindowTheme(m_hWnd), TMT_FLATMENUS);
else
<API key>(SPI_GETFLATMENU, 0, &m_useFlatMenus, 0);
return S_OK;
}
HRESULT CMenuToolbarBase::UpdateImageLists()
{
if ((m_initFlags & (SMINIT_TOPLEVEL | SMINIT_VERTICAL)) == SMINIT_TOPLEVEL) // not vertical.
{
// No image list, prevents the buttons from having a margin at the left side
SetImageList(NULL);
return S_OK;
}
// Assign the correct imagelist and padding based on the current icon size
int shiml;
if (m_menuBand->UseBigIcons())
{
shiml = SHIL_LARGE;
SetPadding(4, 0);
}
else
{
shiml = SHIL_SMALL;
SetPadding(4, 4);
}
IImageList * piml;
HRESULT hr = SHGetImageList(shiml, IID_PPV_ARG(IImageList, &piml));
if (FAILED_UNEXPECTEDLY(hr))
{
SetImageList(NULL);
}
else
{
SetImageList((HIMAGELIST)piml);
}
return S_OK;
}
HRESULT CMenuToolbarBase::Close()
{
if (m_hWnd)
DestroyWindow();
if (m_pager.m_hWnd)
m_pager.DestroyWindow();
return S_OK;
}
HRESULT CMenuToolbarBase::CreateToolbar(HWND hwndParent, DWORD dwFlags)
{
LONG tbStyles = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
TBSTYLE_TOOLTIPS | TBSTYLE_TRANSPARENT | <API key> | TBSTYLE_LIST | TBSTYLE_FLAT | TBSTYLE_CUSTOMERASE |
CCS_NODIVIDER | CCS_NOPARENTALIGN | CCS_NORESIZE | CCS_TOP;
LONG tbExStyles = <API key> | WS_EX_TOOLWINDOW;
if (dwFlags & SMINIT_VERTICAL)
{
// Activate vertical semantics
tbStyles |= CCS_VERT;
#if <API key>
tbExStyles |= TBSTYLE_EX_VERTICAL;
#endif
}
m_initFlags = dwFlags;
// Get a temporary rect to use while creating the toolbar window.
// Ensure that it is not a null rect.
RECT rc;
if (!::GetClientRect(hwndParent, &rc) ||
(rc.left == rc.right) ||
(rc.top == rc.bottom))
{
rc.left = 0;
rc.top = 0;
rc.right = 1;
rc.bottom = 1;
}
SubclassWindow(CToolbar::Create(hwndParent, tbStyles, tbExStyles));
SetWindowTheme(m_hWnd, L"", L"");
if (IsAppThemed())
GetThemeSysBool(GetWindowTheme(m_hWnd), TMT_FLATMENUS);
else
<API key>(SPI_GETFLATMENU, 0, &m_useFlatMenus, 0);
m_menuBand->AdjustForTheme(m_useFlatMenus);
// If needed, create the pager.
if (m_usePager)
{
LONG pgStyles = PGS_VERT | WS_CHILD | WS_VISIBLE;
LONG pgExStyles = 0;
HWND hwndPager = CreateWindowEx(
pgExStyles, WC_PAGESCROLLER, NULL,
pgStyles, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top,
hwndParent, NULL, _AtlBaseModule.GetModuleInstance(), 0);
m_pager.SubclassWindow(hwndPager);
::SetParent(m_hWnd, hwndPager);
m_pager.SendMessageW(PGM_SETCHILD, 0, reinterpret_cast<LPARAM>(m_hWnd));
}
// Configure the image lists
UpdateImageLists();
return S_OK;
}
HRESULT CMenuToolbarBase::GetSizes(SIZE* pMinSize, SIZE* pMaxSize, SIZE* pIntegralSize)
{
if (pMinSize)
*pMinSize = m_idealSize;
if (pMaxSize)
*pMaxSize = m_idealSize;
if (pIntegralSize)
*pIntegralSize = m_itemSize;
if (m_hasSizes)
return S_OK;
TRACE("Sizes out of date, recalculating.\n");
if (!m_hWnd)
{
return S_OK;
}
// Obtain the ideal size, to be used as min and max
GetMaxSize(&m_idealSize);
GetIdealSize((m_initFlags & SMINIT_VERTICAL) != 0, &m_idealSize);
TRACE("Ideal Size: (%d, %d) for %d buttons\n", m_idealSize, GetButtonCount());
// Obtain the button size, to be used as the integral size
DWORD size = GetButtonSize();
m_itemSize.cx = GET_X_LPARAM(size);
m_itemSize.cy = GET_Y_LPARAM(size);
m_hasSizes = TRUE;
if (pMinSize)
*pMinSize = m_idealSize;
if (pMaxSize)
*pMaxSize = m_idealSize;
if (pIntegralSize)
*pIntegralSize = m_itemSize;
return S_OK;
}
HRESULT CMenuToolbarBase::SetPosSize(int x, int y, int cx, int cy)
{
// Update the toolbar or pager to fit the requested rect
// If we have a pager, set the toolbar height to the ideal height of the toolbar
if (m_pager.m_hWnd)
{
SetWindowPos(NULL, x, y, cx, m_idealSize.cy, 0);
m_pager.SetWindowPos(NULL, x, y, cx, cy, 0);
}
else
{
SetWindowPos(NULL, x, y, cx, cy, 0);
}
// In a vertical menu, resize the buttons to fit the width
if (m_initFlags & SMINIT_VERTICAL)
{
DWORD btnSize = GetButtonSize();
SetButtonSize(cx, GET_Y_LPARAM(btnSize));
}
return S_OK;
}
HRESULT CMenuToolbarBase::IsWindowOwner(HWND hwnd)
{
if (m_hWnd && m_hWnd == hwnd) return S_OK;
if (m_pager.m_hWnd && m_pager.m_hWnd == hwnd) return S_OK;
return S_FALSE;
}
HRESULT CMenuToolbarBase::GetWindow(HWND *phwnd)
{
if (!phwnd)
return E_FAIL;
if (m_pager.m_hWnd)
*phwnd = m_pager.m_hWnd;
else
*phwnd = m_hWnd;
return S_OK;
}
HRESULT CMenuToolbarBase::OnGetInfoTip(NMTBGETINFOTIP * tip)
{
INT index;
DWORD_PTR dwData;
INT iItem = tip->iItem;
GetDataFromId(iItem, &index, &dwData);
return InternalGetTooltip(iItem, index, dwData, tip->pszText, tip->cchTextMax);
}
HRESULT CMenuToolbarBase::OnPopupTimer(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if (wParam != TIMERID_HOTTRACK)
{
bHandled = FALSE;
return 0;
}
KillTimer(TIMERID_HOTTRACK);
if (!m_timerEnabled)
return 0;
m_timerEnabled = FALSE;
if (m_hotItem < 0)
return 0;
// Returns S_FALSE if the current item did not show a submenu
HRESULT hr = PopupItem(m_hotItem, FALSE);
if (hr != S_FALSE)
return 0;
// If we didn't switch submenus, cancel the current popup regardless
if (m_popupBar)
{
HRESULT hr = CancelCurrentPopup();
if (FAILED_UNEXPECTEDLY(hr))
return 0;
}
return 0;
}
HRESULT CMenuToolbarBase::KillPopupTimer()
{
if (m_timerEnabled)
{
m_timerEnabled = FALSE;
KillTimer(TIMERID_HOTTRACK);
return S_OK;
}
return S_FALSE;
}
HRESULT CMenuToolbarBase::ChangeHotItem(CMenuToolbarBase * toolbar, INT item, DWORD dwFlags)
{
// Ignore the change if it already matches the stored info
if (m_hotBar == toolbar && m_hotItem == item)
return S_FALSE;
// Prevent a change of hot item if the change was triggered by the mouse,
// and mouse tracking is disabled.
if (m_disableMouseTrack && dwFlags & HICF_MOUSE)
{
TRACE("Hot item change prevented by DisableMouseTrack\n");
return S_OK;
}
// Notify the toolbar if the hot-tracking left this toolbar
if (m_hotBar == this && toolbar != this)
{
SetHotItem(-1);
}
TRACE("Hot item changed from %p %p, to %p %p\n", m_hotBar, m_hotItem, toolbar, item);
m_hotBar = toolbar;
m_hotItem = item;
if (m_hotBar == this)
{
if (m_isTrackingPopup && !(m_initFlags & SMINIT_VERTICAL))
{
// If the menubar has an open submenu, switch to the new item's submenu immediately
PopupItem(m_hotItem, FALSE);
}
else if (dwFlags & HICF_MOUSE)
{
// Vertical menus show/hide the submenu after a delay,
// but only with the mouse.
if (m_initFlags & SMINIT_VERTICAL)
{
DWORD elapsed = 0;
<API key>(<API key>, 0, &elapsed, 0);
SetTimer(TIMERID_HOTTRACK, elapsed);
m_timerEnabled = TRUE;
TRACE("SetTimer called with m_hotItem=%d\n", m_hotItem);
}
}
else
{
TBBUTTONINFO info;
info.cbSize = sizeof(info);
info.dwMask = 0;
int index = GetButtonInfo(item, &info);
SetHotItem(index);
}
}
InvalidateDraw();
return S_OK;
}
HRESULT CMenuToolbarBase::ChangePopupItem(CMenuToolbarBase * toolbar, INT item)
{
// Ignore the change if it already matches the stored info
if (m_popupBar == toolbar && m_popupItem == item)
return S_FALSE;
// Notify the toolbar if the popup-tracking this toolbar
if (m_popupBar == this && toolbar != this)
{
CheckButton(m_popupItem, FALSE);
m_isTrackingPopup = FALSE;
}
m_popupBar = toolbar;
m_popupItem = item;
if (m_popupBar == this)
{
CheckButton(m_popupItem, TRUE);
}
InvalidateDraw();
return S_OK;
}
LRESULT CMenuToolbarBase::IsTrackedItem(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
TBBUTTON btn;
INT idx = (INT)wParam;
if (m_hotBar != this)
return S_FALSE;
if (idx < 0)
return S_FALSE;
if (!GetButton(idx, &btn))
return E_FAIL;
if (m_hotItem == btn.idCommand)
return S_OK;
if (m_popupItem == btn.idCommand)
return S_OK;
return S_FALSE;
}
LRESULT CMenuToolbarBase::ChangeTrackedItem(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
TBBUTTON btn;
BOOL wasTracking = LOWORD(lParam);
BOOL mouse = HIWORD(lParam);
INT idx = (INT)wParam;
if (idx < 0)
{
m_isTrackingPopup = FALSE;
return m_menuBand->_ChangeHotItem(NULL, -1, HICF_MOUSE);
}
if (!GetButton(idx, &btn))
return E_FAIL;
TRACE("ChangeTrackedItem %d, %d\n", idx, wasTracking);
m_isTrackingPopup = wasTracking;
return m_menuBand->_ChangeHotItem(this, btn.idCommand, mouse ? HICF_MOUSE : 0);
}
HRESULT CMenuToolbarBase::PopupSubMenu(UINT iItem, UINT index, IShellMenu* childShellMenu, BOOL keyInitiated)
{
// Calculate the submenu position and exclude area
RECT rc = { 0 };
if (!GetItemRect(index, &rc))
return E_FAIL;
POINT a = { rc.left, rc.top };
POINT b = { rc.right, rc.bottom };
ClientToScreen(m_hWnd, &a);
ClientToScreen(m_hWnd, &b);
POINTL pt = { a.x, b.y };
RECTL rcl = { a.x, a.y, b.x, b.y };
if (m_initFlags & SMINIT_VERTICAL)
{
// FIXME: Hardcoding this here feels hacky.
if (IsAppThemed())
{
pt.x = b.x - 1;
pt.y = a.y - 1;
}
else
{
pt.x = b.x - 3;
pt.y = a.y - 3;
}
}
// Display the submenu
m_isTrackingPopup = TRUE;
m_menuBand->_ChangePopupItem(this, iItem);
m_menuBand->_OnPopupSubMenu(childShellMenu, &pt, &rcl, keyInitiated);
return S_OK;
}
HRESULT CMenuToolbarBase::PopupSubMenu(UINT iItem, UINT index, HMENU menu)
{
// Calculate the submenu position and exclude area
RECT rc = { 0 };
if (!GetItemRect(index, &rc))
return E_FAIL;
POINT a = { rc.left, rc.top };
POINT b = { rc.right, rc.bottom };
ClientToScreen(m_hWnd, &a);
ClientToScreen(m_hWnd, &b);
POINT pt = { a.x, b.y };
RECT rcl = { a.x, a.y, b.x, b.y };
if (m_initFlags & SMINIT_VERTICAL)
{
pt.x = b.x;
pt.y = a.y;
}
HMENU popup = GetSubMenu(menu, index);
// Display the submenu
m_isTrackingPopup = TRUE;
m_menuBand->_ChangePopupItem(this, iItem);
m_menuBand->_TrackSubMenu(popup, pt.x, pt.y, rcl);
m_menuBand->_ChangePopupItem(NULL, -1);
m_isTrackingPopup = FALSE;
return S_OK;
}
HRESULT CMenuToolbarBase::TrackContextMenu(IContextMenu* contextMenu, POINT pt)
{
// Cancel submenus
m_menuBand->_KillPopupTimers();
if (m_popupBar)
m_menuBand->_CancelCurrentPopup();
// Display the context menu
return m_menuBand->_TrackContextMenu(contextMenu, pt.x, pt.y);
}
HRESULT CMenuToolbarBase::BeforeCancelPopup()
{
m_cancelingPopup = TRUE;
TRACE("BeforeCancelPopup\n");
return S_OK;
}
HRESULT CMenuToolbarBase::ProcessClick(INT iItem)
{
if (m_disableMouseTrack)
{
TRACE("Item click prevented by DisableMouseTrack\n");
return S_OK;
}
// If a button is clicked while a submenu was open, cancel the submenu.
if (!(m_initFlags & SMINIT_VERTICAL) && m_isTrackingPopup)
{
TRACE("OnCommand cancelled because it was tracking submenu.\n");
return S_FALSE;
}
if (PopupItem(iItem, FALSE) == S_OK)
{
TRACE("PopupItem returned S_OK\n");
return S_FALSE;
}
TRACE("Executing...\n");
return m_menuBand->_MenuItemSelect(MPOS_EXECUTE);
}
HRESULT CMenuToolbarBase::ProcessContextMenu(INT iItem)
{
INT index;
DWORD_PTR data;
GetDataFromId(iItem, &index, &data);
DWORD pos = GetMessagePos();
POINT pt = { GET_X_LPARAM(pos), GET_Y_LPARAM(pos) };
return InternalContextMenu(iItem, index, data, pt);
}
HRESULT CMenuToolbarBase::MenuBarMouseDown(INT iIndex, BOOL isLButton)
{
TBBUTTON btn;
GetButton(iIndex, &btn);
if (!isLButton)
return ProcessContextMenu(btn.idCommand);
if ((m_initFlags & SMINIT_VERTICAL)
|| m_popupBar
|| m_cancelingPopup)
{
m_cancelingPopup = FALSE;
return S_OK;
}
return ProcessClick(btn.idCommand);
}
HRESULT CMenuToolbarBase::MenuBarMouseUp(INT iIndex)
{
TBBUTTON btn;
m_cancelingPopup = FALSE;
if (!(m_initFlags & SMINIT_VERTICAL))
return S_OK;
GetButton(iIndex, &btn);
return ProcessClick(btn.idCommand);
}
HRESULT CMenuToolbarBase::PrepareExecuteItem(INT iItem)
{
this->m_menuBand->_KillPopupTimers();
m_executeItem = iItem;
return GetDataFromId(iItem, &m_executeIndex, &m_executeData);
}
HRESULT CMenuToolbarBase::ExecuteItem()
{
return InternalExecuteItem(m_executeItem, m_executeItem, m_executeData);
}
HRESULT CMenuToolbarBase::KeyboardItemChange(DWORD dwSelectType)
{
int prev = m_hotItem;
int index = -1;
if (dwSelectType != 0xFFFFFFFF)
{
int count = GetButtonCount();
if (dwSelectType == VK_HOME)
{
index = 0;
dwSelectType = VK_DOWN;
}
else if (dwSelectType == VK_END)
{
index = count - 1;
dwSelectType = VK_UP;
}
else
{
if (m_hotItem >= 0)
{
TBBUTTONINFO info = { 0 };
info.cbSize = sizeof(TBBUTTONINFO);
info.dwMask = 0;
index = GetButtonInfo(m_hotItem, &info);
}
if (index < 0)
{
if (dwSelectType == VK_UP)
{
index = count - 1;
}
else if (dwSelectType == VK_DOWN)
{
index = 0;
}
}
else
{
if (dwSelectType == VK_UP)
{
index
}
else if (dwSelectType == VK_DOWN)
{
index++;
}
}
}
TBBUTTON btn = { 0 };
while (index >= 0 && index < count)
{
DWORD res = GetButton(index, &btn);
if (!res)
return E_FAIL;
if (btn.dwData)
{
if (prev != btn.idCommand)
{
TRACE("Setting Hot item to %d\n", index);
if (!(m_initFlags & SMINIT_VERTICAL) && m_isTrackingPopup)
{
HWND tlw;
m_menuBand->_GetTopLevelWindow(&tlw);
SendMessageW(tlw, WM_CANCELMODE, 0, 0);
PostMessageW(m_hWnd, <API key>, index, MAKELPARAM(m_isTrackingPopup, FALSE));
}
else
m_menuBand->_ChangeHotItem(this, btn.idCommand, 0);
}
return S_OK;
}
if (dwSelectType == VK_UP)
{
index
}
else if (dwSelectType == VK_DOWN)
{
index++;
}
}
return S_FALSE;
}
if (prev != -1)
{
TRACE("Setting Hot item to null\n");
m_menuBand->_ChangeHotItem(NULL, -1, 0);
}
return S_FALSE;
}
HRESULT CMenuToolbarBase::AddButton(DWORD commandId, LPCWSTR caption, BOOL hasSubMenu, INT iconId, DWORD_PTR buttonData, BOOL last)
{
TBBUTTON tbb = { 0 };
tbb.fsState = TBSTATE_ENABLED;
#if !<API key>
if (!last && (m_initFlags & SMINIT_VERTICAL))
tbb.fsState |= TBSTATE_WRAP;
#endif
tbb.fsStyle = BTNS_CHECKGROUP;
if (hasSubMenu && (m_initFlags & SMINIT_VERTICAL))
tbb.fsStyle |= BTNS_DROPDOWN;
if (!(m_initFlags & SMINIT_VERTICAL))
tbb.fsStyle |= BTNS_AUTOSIZE;
tbb.iString = (INT_PTR) caption;
tbb.idCommand = commandId;
tbb.iBitmap = iconId;
tbb.dwData = buttonData;
m_hasSizes = FALSE;
if (!AddButtons(1, &tbb))
return HRESULT_FROM_WIN32(GetLastError());
return S_OK;
}
HRESULT CMenuToolbarBase::AddSeparator(BOOL last)
{
TBBUTTON tbb = { 0 };
tbb.fsState = TBSTATE_ENABLED;
#if !<API key>
if (!last && (m_initFlags & SMINIT_VERTICAL))
tbb.fsState |= TBSTATE_WRAP;
#endif
tbb.fsStyle = BTNS_SEP;
tbb.iBitmap = 0;
m_hasSizes = FALSE;
if (!AddButtons(1, &tbb))
return HRESULT_FROM_WIN32(GetLastError());
return S_OK;
}
HRESULT CMenuToolbarBase::AddPlaceholder()
{
TBBUTTON tbb = { 0 };
WCHAR MenuString[128];
LoadStringW(GetModuleHandle(L"shell32.dll"), IDS_MENU_EMPTY, MenuString, _countof(MenuString));
tbb.fsState = 0;
tbb.fsStyle = 0;
tbb.iString = (INT_PTR) MenuString;
tbb.iBitmap = -1;
m_hasSizes = FALSE;
if (!AddButtons(1, &tbb))
return HRESULT_FROM_WIN32(GetLastError());
return S_OK;
}
HRESULT CMenuToolbarBase::ClearToolbar()
{
while (DeleteButton(0))
{
// empty;
}
m_hasSizes = FALSE;
return S_OK;
}
HRESULT CMenuToolbarBase::GetDataFromId(INT iItem, INT* pIndex, DWORD_PTR* pData)
{
if (pData)
*pData = NULL;
if (pIndex)
*pIndex = -1;
if (iItem < 0)
return S_OK;
TBBUTTONINFO info = { 0 };
info.cbSize = sizeof(TBBUTTONINFO);
info.dwMask = TBIF_COMMAND | TBIF_LPARAM;
int index = GetButtonInfo(iItem, &info);
if (index < 0)
return E_FAIL;
if (pIndex)
*pIndex = index;
if (pData)
*pData = info.lParam;
return S_OK;
}
HRESULT CMenuToolbarBase::CancelCurrentPopup()
{
return m_menuBand->_CancelCurrentPopup();
}
HRESULT CMenuToolbarBase::PopupItem(INT iItem, BOOL keyInitiated)
{
INT index;
DWORD_PTR dwData;
if (iItem < 0)
return S_OK;
if (m_popupBar == this && m_popupItem == iItem)
return S_OK;
GetDataFromId(iItem, &index, &dwData);
HRESULT hr = InternalHasSubMenu(iItem, index, dwData);
if (hr != S_OK)
return hr;
if (m_popupBar)
{
HRESULT hr = CancelCurrentPopup();
if (FAILED_UNEXPECTEDLY(hr))
return hr;
}
if (!(m_initFlags & SMINIT_VERTICAL))
{
TRACE("PopupItem non-vertical %d %d\n", index, iItem);
m_menuBand->_ChangeHotItem(this, iItem, 0);
}
return InternalPopupItem(iItem, index, dwData, keyInitiated);
}
CMenuStaticToolbar::CMenuStaticToolbar(CMenuBand *menuBand) :
CMenuToolbarBase(menuBand, FALSE),
m_hmenu(NULL),
m_hwndMenu(NULL)
{
}
CMenuStaticToolbar::~CMenuStaticToolbar()
{
}
HRESULT CMenuStaticToolbar::GetMenu(
_Out_opt_ HMENU *phmenu,
_Out_opt_ HWND *phwnd,
_Out_opt_ DWORD *pdwFlags)
{
if (phmenu)
*phmenu = m_hmenu;
if (phwnd)
*phwnd = m_hwndMenu;
if (pdwFlags)
*pdwFlags = m_dwMenuFlags;
return S_OK;
}
HRESULT CMenuStaticToolbar::SetMenu(
HMENU hmenu,
HWND hwnd,
DWORD dwFlags)
{
m_hmenu = hmenu;
m_hwndMenu = hwnd;
m_dwMenuFlags = dwFlags;
ClearToolbar();
return S_OK;
}
HRESULT CMenuStaticToolbar::FillToolbar(BOOL clearFirst)
{
int i;
int ic = GetMenuItemCount(m_hmenu);
if (clearFirst)
{
ClearToolbar();
}
int count = 0;
for (i = 0; i < ic; i++)
{
BOOL last = i + 1 == ic;
MENUITEMINFOW info;
info.cbSize = sizeof(info);
info.dwTypeData = NULL;
info.fMask = MIIM_FTYPE | MIIM_STRING | MIIM_ID;
if (!GetMenuItemInfoW(m_hmenu, i, TRUE, &info))
{
TRACE("Error obtaining info for menu item at pos=%d\n", i);
continue;
}
count++;
if (info.fType & MFT_SEPARATOR)
{
AddSeparator(last);
}
else if (!(info.fType & MFT_BITMAP))
{
info.cch++;
info.dwTypeData = (PWSTR) HeapAlloc(GetProcessHeap(), 0, (info.cch + 1) * sizeof(WCHAR));
info.fMask = MIIM_STRING | MIIM_SUBMENU | MIIM_ID;
GetMenuItemInfoW(m_hmenu, i, TRUE, &info);
SMINFO * sminfo = new SMINFO();
sminfo->dwMask = SMIM_ICON | SMIM_FLAGS;
HRESULT hr = m_menuBand->_CallCBWithItemId(info.wID, SMC_GETINFO, 0, reinterpret_cast<LPARAM>(sminfo));
if (FAILED_UNEXPECTEDLY(hr))
{
delete sminfo;
return hr;
}
AddButton(info.wID, info.dwTypeData, info.hSubMenu != NULL, sminfo->iIcon, reinterpret_cast<DWORD_PTR>(sminfo), last);
HeapFree(GetProcessHeap(), 0, info.dwTypeData);
}
}
return S_OK;
}
HRESULT CMenuStaticToolbar::InternalGetTooltip(INT iItem, INT index, DWORD_PTR dwData, LPWSTR pszText, INT cchTextMax)
{
//SMINFO * info = reinterpret_cast<SMINFO*>(dwData);
UNIMPLEMENTED;
return E_NOTIMPL;
}
HRESULT CMenuStaticToolbar::OnDeletingButton(const NMTOOLBAR * tb)
{
delete reinterpret_cast<SMINFO*>(tb->tbButton.dwData);
return S_OK;
}
HRESULT CMenuStaticToolbar::InternalContextMenu(INT iItem, INT index, DWORD_PTR dwData, POINT pt)
{
CComPtr<IContextMenu> contextMenu;
HRESULT hr = m_menuBand->_CallCBWithItemId(iItem, SMC_GETOBJECT,
reinterpret_cast<WPARAM>(&IID_IContextMenu), reinterpret_cast<LPARAM>(&contextMenu));
if (hr != S_OK)
return hr;
return TrackContextMenu(contextMenu, pt);
}
HRESULT CMenuStaticToolbar::InternalExecuteItem(INT iItem, INT index, DWORD_PTR data)
{
return m_menuBand->_CallCBWithItemId(iItem, SMC_EXEC, 0, 0);
}
HRESULT CMenuStaticToolbar::InternalPopupItem(INT iItem, INT index, DWORD_PTR dwData, BOOL keyInitiated)
{
SMINFO * nfo = reinterpret_cast<SMINFO*>(dwData);
if (!nfo)
return E_FAIL;
if (nfo->dwFlags&SMIF_TRACKPOPUP)
{
return PopupSubMenu(iItem, index, m_hmenu);
}
else
{
CComPtr<IShellMenu> shellMenu;
HRESULT hr = m_menuBand->_CallCBWithItemId(iItem, SMC_GETOBJECT, reinterpret_cast<WPARAM>(&IID_IShellMenu), reinterpret_cast<LPARAM>(&shellMenu));
if (FAILED_UNEXPECTEDLY(hr))
return hr;
return PopupSubMenu(iItem, index, shellMenu, keyInitiated);
}
}
HRESULT CMenuStaticToolbar::InternalHasSubMenu(INT iItem, INT index, DWORD_PTR dwData)
{
return ::GetSubMenu(m_hmenu, index) ? S_OK : S_FALSE;
}
CMenuSFToolbar::CMenuSFToolbar(CMenuBand * menuBand) :
CMenuToolbarBase(menuBand, TRUE),
m_shellFolder(NULL),
m_idList(NULL),
m_hKey(NULL)
{
}
CMenuSFToolbar::~CMenuSFToolbar()
{
}
int CALLBACK PidlListSort(void* item1, void* item2, LPARAM lParam)
{
IShellFolder * psf = (IShellFolder*) lParam;
PCUIDLIST_RELATIVE pidl1 = (PCUIDLIST_RELATIVE) item1;
PCUIDLIST_RELATIVE pidl2 = (PCUIDLIST_RELATIVE) item2;
HRESULT hr = psf->CompareIDs(0, pidl1, pidl2);
if (FAILED(hr))
{
// No way to cancel, so sort to equal.
return 0;
}
return (int)(short)LOWORD(hr);
}
HRESULT CMenuSFToolbar::FillToolbar(BOOL clearFirst)
{
HRESULT hr;
CComPtr<IEnumIDList> eidl;
hr = m_shellFolder->EnumObjects(GetToolbar(), SHCONTF_FOLDERS | SHCONTF_NONFOLDERS, &eidl);
if (FAILED_UNEXPECTEDLY(hr))
return hr;
HDPA dpaSort = DPA_Create(10);
LPITEMIDLIST item = NULL;
hr = eidl->Next(1, &item, NULL);
while (hr == S_OK)
{
if (m_menuBand->_CallCBWithItemPidl(item, 0x10000000, 0, 0) == S_FALSE)
{
DPA_AppendPtr(dpaSort, ILClone(item));
}
hr = eidl->Next(1, &item, NULL);
}
// If no items were added, show the "empty" placeholder
if (DPA_GetPtrCount(dpaSort) == 0)
{
return AddPlaceholder();
}
TRACE("FillToolbar added %d items to the DPA\n", DPA_GetPtrCount(dpaSort));
DPA_Sort(dpaSort, PidlListSort, (LPARAM) m_shellFolder.p);
for (int i = 0; i<DPA_GetPtrCount(dpaSort);)
{
PWSTR MenuString;
INT index = 0;
INT indexOpen = 0;
STRRET sr = { STRRET_CSTR, { 0 } };
item = (LPITEMIDLIST)DPA_GetPtr(dpaSort, i);
hr = m_shellFolder->GetDisplayNameOf(item, SIGDN_NORMALDISPLAY, &sr);
if (FAILED_UNEXPECTEDLY(hr))
return hr;
StrRetToStr(&sr, NULL, &MenuString);
index = <API key>(m_shellFolder, item, &indexOpen);
LPCITEMIDLIST itemc = item;
SFGAOF attrs = SFGAO_FOLDER;
hr = m_shellFolder->GetAttributesOf(1, &itemc, &attrs);
DWORD_PTR dwData = reinterpret_cast<DWORD_PTR>(item);
// Fetch next item already, so we know if the current one is the last
i++;
AddButton(i, MenuString, attrs & SFGAO_FOLDER, index, dwData, i >= DPA_GetPtrCount(dpaSort));
CoTaskMemFree(MenuString);
}
DPA_Destroy(dpaSort);
return hr;
}
HRESULT CMenuSFToolbar::InternalGetTooltip(INT iItem, INT index, DWORD_PTR dwData, LPWSTR pszText, INT cchTextMax)
{
//ITEMIDLIST * pidl = reinterpret_cast<LPITEMIDLIST>(dwData);
UNIMPLEMENTED;
return E_NOTIMPL;
}
HRESULT CMenuSFToolbar::OnDeletingButton(const NMTOOLBAR * tb)
{
ILFree(reinterpret_cast<LPITEMIDLIST>(tb->tbButton.dwData));
return S_OK;
}
HRESULT CMenuSFToolbar::SetShellFolder(IShellFolder *psf, LPCITEMIDLIST pidlFolder, HKEY hKey, DWORD dwFlags)
{
m_shellFolder = psf;
m_idList = ILClone(pidlFolder);
m_hKey = hKey;
m_dwMenuFlags = dwFlags;
ClearToolbar();
return S_OK;
}
HRESULT CMenuSFToolbar::GetShellFolder(DWORD *pdwFlags, LPITEMIDLIST *ppidl, REFIID riid, void **ppv)
{
HRESULT hr;
hr = m_shellFolder->QueryInterface(riid, ppv);
if (FAILED_UNEXPECTEDLY(hr))
return hr;
if (pdwFlags)
*pdwFlags = m_dwMenuFlags;
if (ppidl)
{
LPITEMIDLIST pidl = NULL;
if (m_idList)
{
pidl = ILClone(m_idList);
if (!pidl)
{
ERR("ILClone failed!\n");
(*reinterpret_cast<IUnknown**>(ppv))->Release();
return E_FAIL;
}
}
*ppidl = pidl;
}
return hr;
}
HRESULT CMenuSFToolbar::InternalContextMenu(INT iItem, INT index, DWORD_PTR dwData, POINT pt)
{
HRESULT hr;
CComPtr<IContextMenu> contextMenu = NULL;
LPCITEMIDLIST pidl = reinterpret_cast<LPCITEMIDLIST>(dwData);
hr = m_shellFolder->GetUIObjectOf(GetToolbar(), 1, &pidl, IID_NULL_PPV_ARG(IContextMenu, &contextMenu));
if (FAILED_UNEXPECTEDLY(hr))
{
return hr;
}
hr = TrackContextMenu(contextMenu, pt);
return hr;
}
HRESULT CMenuSFToolbar::InternalExecuteItem(INT iItem, INT index, DWORD_PTR data)
{
return m_menuBand->_CallCBWithItemPidl(reinterpret_cast<LPITEMIDLIST>(data), SMC_SFEXEC, 0, 0);
}
HRESULT CMenuSFToolbar::InternalPopupItem(INT iItem, INT index, DWORD_PTR dwData, BOOL keyInitiated)
{
HRESULT hr;
UINT uId;
UINT uIdAncestor;
DWORD flags;
CComPtr<IShellMenuCallback> psmc;
CComPtr<IShellMenu> shellMenu;
LPITEMIDLIST pidl = reinterpret_cast<LPITEMIDLIST>(dwData);
if (!pidl)
return E_FAIL;
hr = <API key>(IID_PPV_ARG(IShellMenu, &shellMenu));
if (FAILED_UNEXPECTEDLY(hr))
return hr;
m_menuBand->GetMenuInfo(&psmc, &uId, &uIdAncestor, &flags);
// FIXME: not sure what to use as uId/uIdAncestor here
hr = shellMenu->Initialize(psmc, 0, uId, SMINIT_VERTICAL);
if (FAILED_UNEXPECTEDLY(hr))
return hr;
CComPtr<IShellFolder> childFolder;
hr = m_shellFolder->BindToObject(pidl, NULL, IID_PPV_ARG(IShellFolder, &childFolder));
if (FAILED_UNEXPECTEDLY(hr))
return hr;
hr = shellMenu->SetShellFolder(childFolder, NULL, NULL, 0);
if (FAILED_UNEXPECTEDLY(hr))
return hr;
return PopupSubMenu(iItem, index, shellMenu, keyInitiated);
}
HRESULT CMenuSFToolbar::InternalHasSubMenu(INT iItem, INT index, DWORD_PTR dwData)
{
HRESULT hr;
LPCITEMIDLIST pidl = reinterpret_cast<LPITEMIDLIST>(dwData);
SFGAOF attrs = SFGAO_FOLDER;
hr = m_shellFolder->GetAttributesOf(1, &pidl, &attrs);
if (FAILED_UNEXPECTEDLY(hr))
return hr;
return (attrs & SFGAO_FOLDER) ? S_OK : S_FALSE;
} |
#include "Window.h"
#include <strsafe.h>
#include <iostream>
Nena::Application::Window::Window()
: ScreenWidth(800)
, ScreenHeight(600)
, Width(800)
, Height(600)
, Instance(::GetModuleHandle(NULL))
, Style(GameWindowStyle)
, Name(__TEXT("NenaWindowClass"))
, Fullscreen(false)
, Raw(nullptr)
, TrustDxgi(FALSE)
{
::OutputDebugStringA("Nena::Application::Window::Window()\n");
}
Nena::Application::Window::~Window()
{
::OutputDebugStringA("Nena::Application::Window::~Window()\n");
OnClosed();
}
void Nena::Application::Window::Close()
{
::OutputDebugStringA("Nena::Application::Window::Close()\n");
if (Raw) ::SendMessage(Raw, WM_CLOSE, NULL, NULL);
}
void Nena::Application::Window::Initialize(
_In_ Nena::Application::Window::Callback proc,
_In_opt_ Nena::Application::Window::Boolean cursor
)
{
if (Raw) return;
::OutputDebugStringA("Nena::Application::Window::Initialize()\n");
Window::WindowClass wc;
Window::ScreenSettings screen;
::INT status = 0;
::HMONITOR monitorHandle;
::MONITORINFOEXA monitorInfo;
status = FALSE;
monitorHandle = NULL;
ZeroMemory(&screen, sizeof Window::ScreenSettings);
ZeroMemory(&wc, sizeof Window::WindowClass);
// Setup windows class with default settings.
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wc.hbrBackground = (::HBRUSH)GetStockObject(BLACK_BRUSH);
wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.cbSize = sizeof(WindowClass);
wc.lpszClassName = Name.c_str();
wc.lpszMenuName = NULL;
wc.lpfnWndProc = proc;
wc.hIconSm = wc.hIcon;
wc.hInstance = Instance;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
// Register window class.
auto atom = ::RegisterClassExA(&wc);
if (atom == INVALID_ATOM)
{
auto error = GetLastError();
return;
}
else status = TRUE;
status = TRUE;
POINT point = { 0 };
// in the virtual screen space, primary display rect starts from (0, 0),
// so it should return a handle to a default device
monitorHandle = ::MonitorFromPoint(point, <API key>);
if (monitorHandle == <API key> || monitorHandle == NULL)
OutputDebugStringA("\tFailed to get current monitor handle\n"),
status = FALSE;
ZeroMemory(&monitorInfo, sizeof MONITORINFOEXA);
monitorInfo.cbSize = sizeof MONITORINFOEXA;
if (status && !::GetMonitorInfoA(monitorHandle, &monitorInfo))
OutputDebugStringA("\tFailed to get current monitor info\n"),
status = FALSE;
if (!status)
{
// an attempt to find monitor manually
// or return the last one if ok
status = EnumDisplayMonitors(NULL, NULL,
(MONITORENUMPROC)[](
HMONITOR monitor, HDC context,
LPRECT rect, LPARAM data
)
{
_CRT_UNUSED(context);
((HMONITOR &) data) = monitor;
if (rect->left == 0 && rect->top == 0) return FALSE;
else return TRUE;
},
(LPARAM) (HMONITOR &) monitorHandle
);
if (status) status =
monitorHandle != <API key> &&
monitorHandle != NULL;
}
if (status)
{
// current monitor was found
ScreenWidth = (decltype(ScreenWidth)) (monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left);
ScreenHeight = (decltype(ScreenHeight)) (monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top);
X = (Int16) (monitorInfo.rcMonitor.left + (ScreenWidth - Width) / 2);
Y = (Int16) (monitorInfo.rcMonitor.top + (ScreenHeight - Height) / 2);
}
else // all the attempts to find monitor device failed, try another approach
{
::ZeroMemory(&screen, sizeof ScreenSettings);
if (!::<API key>(nullptr, <API key>, &screen))
OutputDebugStringA("\tFailed to get current display device\n"),
status = FALSE,
ScreenWidth = 0,
ScreenHeight = 0;
else
ScreenWidth = (UInt16)screen.dmPelsWidth,
ScreenHeight = (UInt16)screen.dmPelsHeight,
X = (Int16)((ScreenWidth - Width) / 2),
Y = (Int16)((ScreenHeight - Height) / 2);
}
if (Fullscreen) Raw = ::CreateWindowExA(
WS_EX_APPWINDOW, Name.c_str(), Name.c_str(), Style,
X, Y, ScreenWidth, ScreenHeight, nullptr, nullptr, Instance,
nullptr
);
else Raw = ::CreateWindowExA(
WS_EX_APPWINDOW, Name.c_str(), Name.c_str(), Style,
X, Y, Width, Height, nullptr, nullptr, Instance,
nullptr
);
if (Raw) // if window was created
{
::ShowWindow(Raw, SW_SHOW);
::SetForegroundWindow(Raw);
::SetFocus(Raw);
::ShowCursor(cursor);
// adjust window
Fullscreen = !Fullscreen;
ToggleFullscreen();
}
// notify a developer about window was created
// (or was not, should check a handle)
Created(this);
}
Nena::Application::Window::Boolean Nena::Application::Window::EnablePointerEvents(
_In_opt_ BOOL enable
)
{
BOOL result = FALSE;
if (enable && (result = ::<API key>())) return TRUE;
if (!enable && !(result = ::<API key>())) return TRUE;
result = ::<API key>(enable);
#if <API key>
DWORD error;
if (!result)
{
error = ::GetLastError();
__NENA_WINDOW_DbgPs __NENA_WINDOW_LibNm
" >> ErrorCode = %x", error
__NENA_WINDOW_DbgPe
}
#endif
return result;
}
void Nena::Application::Window::OnClosed()
{
if (!Raw) return;
::OutputDebugStringA("Nena::Application::Window::OnClosed()\n");
Closing(this);
::ShowCursor(true);
if (Fullscreen) ::<API key>(nullptr, 0);
::DestroyWindow(Raw);
::UnregisterClass(Name.c_str(), Instance);
Instance = nullptr;
Raw = nullptr;
Closed(this);
}
void Nena::Application::Window::SetIcon(
Window::String spath,
Window::String bpath,
UINT32 swpx, UINT32 shpx,
UINT32 bwpx, UINT32 bhpx
)
{
::OutputDebugStringA("Nena::Application::Window::SetIcon()\n");
HANDLE sico = ::LoadImage(Instance, spath.c_str(), IMAGE_ICON, swpx, shpx, LR_LOADFROMFILE);
HANDLE bico = ::LoadImage(Instance, bpath.c_str(), IMAGE_ICON, bwpx, bhpx, LR_LOADFROMFILE);
if (sico) ::SendMessage(Raw, WM_SETICON, ICON_SMALL, (LPARAM) sico);
if (bico) ::SendMessage(Raw, WM_SETICON, ICON_BIG, (LPARAM) bico);
}
void Nena::Application::Window::SetTitle(
Window::String text
)
{
::OutputDebugStringA("Nena::Application::Window::SetTitle()\n");
::SetWindowTextA(Raw, text.c_str());
}
void Nena::Application::Window::UpdateSizePosition()
{
::BOOL status;
::HMONITOR monitorHandle;
::MONITORINFOEXA monitorInfo;
::OutputDebugStringA("Nena::Application::Window::UpdateSizePosition()\n");
ZeroMemory(&monitorInfo, sizeof MONITORINFOEXA);
monitorInfo.cbSize = sizeof MONITORINFOEXA;
monitorHandle = ::MonitorFromWindow(Raw, <API key>);
if (monitorHandle == <API key> || monitorHandle == NULL)
{
::OutputDebugStringA("\tFailed to get current monitor handle\n");
return;
}
if (!::GetMonitorInfoA(monitorHandle, &monitorInfo))
{
::OutputDebugStringA("\tFailed to get current monitor info\n");
return;
}
//Style &= ~WS_THICKFRAME;
ScreenWidth = (decltype(ScreenWidth)) (monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left);
ScreenHeight = (decltype(ScreenHeight)) (monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top);
if (Fullscreen)
{
::RECT clientRect = { 0 };
status = ::GetClientRect(Raw, &clientRect);
Width = (decltype(Width)) clientRect.right;
Height = (decltype(Height)) clientRect.bottom;
Window::ScreenSettings screen;
ZeroMemory(&screen, sizeof ScreenSettings);
memcpy(&screen.dmDeviceName, monitorInfo.szDevice,
min(sizeof screen.dmDeviceName, sizeof monitorInfo.szDevice));
screen.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
screen.dmSize = sizeof ScreenSettings;
screen.dmPelsHeight = ScreenHeight;
screen.dmPelsWidth = ScreenWidth;
screen.dmBitsPerPel = 32;
X = (Int16) (monitorInfo.rcMonitor.left);
Y = (Int16) (monitorInfo.rcMonitor.top);
}
else
{
RECT rect;
rect.right = Width;
rect.bottom = Height;
rect.top = monitorInfo.rcMonitor.top;
rect.left = monitorInfo.rcMonitor.left;
X = (Int16) ((ScreenWidth - Width) / 2 + monitorInfo.rcMonitor.left);
Y = (Int16) ((ScreenHeight - Height) / 2 + monitorInfo.rcMonitor.top);
}
}
Nena::Application::Window::Boolean Nena::Application::Window::ToggleFullscreen()
{
::BOOL status;
::HMONITOR monitorHandle;
::MONITORINFOEXA monitorInfo;
::OutputDebugStringA("Nena::Application::Window::ToggleFullscreen()\n");
ZeroMemory(&monitorInfo, sizeof MONITORINFOEXA);
monitorInfo.cbSize = sizeof MONITORINFOEXA;
monitorHandle = ::MonitorFromWindow(Raw, <API key>);
if (monitorHandle == <API key> || monitorHandle == NULL)
{
::OutputDebugStringA("\tFailed to get current monitor handle\n");
return FALSE;
}
if (!::GetMonitorInfoA(monitorHandle, &monitorInfo))
{
::OutputDebugStringA("\tFailed to get current monitor info\n");
return FALSE;
}
//Style &= ~WS_THICKFRAME;
ScreenWidth = (decltype(ScreenWidth)) (monitorInfo.rcMonitor.right - monitorInfo.rcMonitor.left);
ScreenHeight = (decltype(ScreenHeight)) (monitorInfo.rcMonitor.bottom - monitorInfo.rcMonitor.top);
if (!Fullscreen)
{
::RECT clientRect = { 0 };
status = ::GetClientRect(Raw, &clientRect);
Width = (decltype(Width)) clientRect.right;
Height = (decltype(Height)) clientRect.bottom;
Window::ScreenSettings screen;
ZeroMemory(&screen, sizeof ScreenSettings);
memcpy(&screen.dmDeviceName, monitorInfo.szDevice,
min(sizeof screen.dmDeviceName, sizeof monitorInfo.szDevice));
screen.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
screen.dmSize = sizeof ScreenSettings;
screen.dmPelsHeight = ScreenHeight;
screen.dmPelsWidth = ScreenWidth;
screen.dmBitsPerPel = 32;
X = (Int16) (monitorInfo.rcMonitor.left);
Y = (Int16) (monitorInfo.rcMonitor.top);
::SetWindowLongPtrA(Raw, GWL_STYLE, GameWindowStyle);
status = ::<API key>(&screen, CDS_FULLSCREEN);
status = ::SetWindowPos(Raw, HWND_TOPMOST, X, Y, ScreenWidth, ScreenHeight, SWP_SHOWWINDOW | SWP_FRAMECHANGED);
status = ::PostMessageA(Raw, WM_EXITSIZEMOVE, 0, 0);
Fullscreen = TRUE;
Toggled(this);
}
else
{
RECT rect;
rect.right = Width;
rect.bottom = Height;
rect.top = monitorInfo.rcMonitor.top;
rect.left = monitorInfo.rcMonitor.left;
::SetWindowLongPtrA(Raw, GWL_STYLE, Style);
::AdjustWindowRect(&rect, Style, FALSE);
X = (Int16) ((ScreenWidth - Width) / 2 + monitorInfo.rcMonitor.left);
Y = (Int16) ((ScreenHeight - Height) / 2 + monitorInfo.rcMonitor.top);
status = ::<API key>(nullptr, 0);
status = ::SetWindowPos(Raw, HWND_TOP, X, Y, Width, Height, SWP_SHOWWINDOW | SWP_FRAMECHANGED);
status = ::PostMessageA(Raw, WM_EXITSIZEMOVE, 0, 0);
Fullscreen = FALSE;
Toggled(this);
}
return true;
}
void Nena::Application::Window::TerminateProcess(const char *criticalPlace)
{
::OutputDebugStringA("Nena::Application::Window::TerminateProcess()\n");
LPVOID messageBuffer;
LPVOID <API key>;
auto lastError = GetLastError();
::FormatMessageA(
<API key> | <API key> | <API key>,
NULL, lastError, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (char *) &messageBuffer, 0, NULL
);
auto sz = (::lstrlenA((const char *) messageBuffer) + ::lstrlenA((const char *) criticalPlace) + 40) * sizeof(char);
<API key> = (LPVOID) ::LocalAlloc(LMEM_ZEROINIT, sz);
auto result = ::StringCchPrintfA(
(char *) <API key>,
::LocalSize(<API key>) / sizeof(char),
"%s failed with error %d: %s",
criticalPlace, lastError, messageBuffer
);
#if _DEBUG
::OutputDebugStringA((const char *) <API key>);
#else
//if (Raw && Fullscreen) ToggleFullscreen();
if (SUCCEEDED(result) && (::GetConsoleWindow() || ::AllocConsole()))
::std::cout << (char *) <API key> << ::std::endl,
::std::cout << "Press any key to exit ..." << ::std::endl,
::getchar();
#endif
::LocalFree(messageBuffer);
::LocalFree(<API key>);
::PostQuitMessage(lastError);
::ExitProcess(lastError);
}
@todo add option to find the largest screen, or just use primary |
#ifndef <API key>
#define <API key>
#include <glib-object.h>
#include <gst/gst.h>
G_BEGIN_DECLS
#define <API key> (<API key> ())
#define GST_CHILD_PROXY(obj) (<API key> ((obj), <API key>, GstChildProxy))
#define GST_IS_CHILD_PROXY(obj) (<API key> ((obj), <API key>))
#define <API key>(obj) (<API key> ((obj), <API key>, <API key>))
/**
* GstChildProxy:
*
* Opaque #GstChildProxy data structure.
*/
typedef struct _GstChildProxy GstChildProxy; /* dummy object */
typedef struct <API key> <API key>;
/**
* <API key>:
* @parent: parent interface type.
* @get_child_by_name: virtual method to fetch the child by name
* @get_child_by_index: virtual method to fetch the child by index
* @get_children_count: virtual method to get the children count
*
* #GstChildProxy interface.
*/
struct <API key>
{
GTypeInterface parent;
/* methods */
GObject * (*get_child_by_name) (GstChildProxy * parent, const gchar * name);
GObject * (*get_child_by_index) (GstChildProxy * parent, guint index);
guint (*get_children_count) (GstChildProxy * parent);
/*< private >*/
/* signals */
void (*child_added) (GstChildProxy * parent, GObject * child, const gchar * name);
void (*child_removed) (GstChildProxy * parent, GObject * child, const gchar * name);
/*< private >*/
gpointer _gst_reserved[GST_PADDING];
};
GType <API key> (void);
GObject * <API key> (GstChildProxy * parent, const gchar * name);
guint <API key> (GstChildProxy * parent);
GObject * <API key> (GstChildProxy * parent, guint index);
gboolean <API key> (GstChildProxy *object, const gchar *name,
GObject **target, GParamSpec **pspec);
void <API key> (GstChildProxy * object, const gchar *name,
GValue *value);
void <API key> (GstChildProxy * object,
const gchar * first_property_name,
va_list var_args);
void gst_child_proxy_get (GstChildProxy * object,
const gchar * first_property_name,
) <API key>;
void <API key> (GstChildProxy * object, const gchar *name,
const GValue *value);
void <API key> (GstChildProxy* object,
const gchar * first_property_name,
va_list var_args);
void gst_child_proxy_set (GstChildProxy * object,
const gchar * first_property_name,
) <API key>;
void <API key> (GstChildProxy * parent, GObject * child,
const gchar *name);
void <API key> (GstChildProxy * parent, GObject * child,
const gchar *name);
G_END_DECLS
#endif /* <API key> */ |
package net.pms.util;
import java.io.<API key>;
import java.io.IOException;
import java.io.StringWriter;
import java.io.<API key>;
import java.io.Writer;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.JEditorPane;
import javax.swing.JTextPane;
import javax.swing.text.html.HTMLEditorKit;
import javax.xml.parsers.<API key>;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.<API key>;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.<API key>;
import javax.xml.xpath.XPathFactory;
import static org.apache.commons.lang3.StringUtils.isBlank;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.apache.commons.text.translate.UnicodeUnescaper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class StringUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(StringUtil.class);
private static final int[] MULTIPLIER = new int[] {3600, 60, 1};
public static final String SEC_TIME_FORMAT = "%02d:%02d:%02.0f";
public static final String <API key> = "%02d:%02d:%05.2f";
public static final String <API key> = "%01d:%02d:%06.3f";
public static final String NEWLINE_CHARACTER = System.getProperty("line.separator");
/** A {@link Pattern} that matches lower-case characters */
public static final Pattern LOWER = Pattern.compile("[\\p{Lower}]+", Pattern.<API key>);
/** A {@link Pattern} that matches upper-case characters */
public static final Pattern UPPER = Pattern.compile("[\\p{Upper}]+", Pattern.<API key>);
/** A {@link Pattern} that matches new-lines */
public static final Pattern NEWLINE = Pattern.compile("\\r\\n|\\r|\\n");
/** A {@link Pattern} that matches whitespace */
public static final Pattern WHITESPACE = Pattern.compile("\\s+", Pattern.<API key>);
/**
* Appends "<<u>tag</u> " to the StringBuilder. This is a typical HTML/DIDL/XML tag opening.
*
* @param sb String to append the tag beginning to.
* @param tag String that represents the tag
*/
public static void openTag(StringBuilder sb, String tag) {
sb.append("<");
sb.append(tag);
}
/**
* Appends the closing symbol > to the StringBuilder. This is a typical HTML/DIDL/XML tag closing.
*
* @param sb String to append the ending character of a tag.
*/
public static void endTag(StringBuilder sb) {
sb.append(">");
}
/**
* Appends "</<u>tag</u>>" to the StringBuilder. This is a typical closing HTML/DIDL/XML tag.
*
* @param sb
* @param tag
*/
public static void closeTag(StringBuilder sb, String tag) {
sb.append("</");
sb.append(tag);
sb.append(">");
}
public static void addAttribute(StringBuilder sb, String attribute, Object value) {
sb.append(' ');
sb.append(attribute);
sb.append("=\"");
sb.append(value);
sb.append("\"");
}
public static void <API key>(StringBuilder sb, String tag, Object value) {
sb.append("<");
sb.append(tag);
sb.append(">");
sb.append(value);
sb.append("</");
sb.append(tag);
sb.append(">");
}
/**
* Does double transformations between &<> characters and their XML representation with ampersands.
*
* @param s String to be encoded
* @return Encoded String
*/
public static String encodeXML(String s) {
s = s.replace("&", "&");
s = s.replace("<", "<");
s = s.replace(">", ">");
/* Skip encoding/escaping ' and " for compatibility with some renderers
* This might need to be made into a renderer option if some renderers require them to be encoded
* s = s.replace("\"", """);
* s = s.replace("'", "'");
*/
// The second encoding/escaping of & is not a bug, it's what effectively adds the second layer of encoding/escaping
s = s.replace("&", "&");
return s;
}
/**
* Removes xml character representations.
*
* @param s String to be cleaned
* @return Encoded String
*/
public static String unEncodeXML(String s) {
// Note: ampersand substitution must be first in order to undo double transformations
// TODO: support ' and " if/when required, see encodeXML() above
return s.replace("&", "&").replace("<", "<").replace(">", ">");
}
/**
* Converts a URL string to a more canonical form
*
* @param url String to be converted
* @return Converted String.
*/
public static String <API key>(String url) {
url = url.replace('/', '\u00b5');
url = url.replace('\\', '\u00b5');
url = url.replace(':', '\u00b5');
url = url.replace('?', '\u00b5');
url = url.replace('*', '\u00b5');
url = url.replace('|', '\u00b5');
url = url.replace('<', '\u00b5');
url = url.replace('>', '\u00b5');
return url;
}
/**
* Translates the specified string into
* {@code application/<API key>} format using {@code UTF-8}.
*
* @param s the {@link String} to encode.
* @return The encoded {@link String}.
*/
public static String urlEncode(String s) {
try {
return URLEncoder.encode(s, StandardCharsets.UTF_8.name());
} catch (<API key> e) {
throw new AssertionError("UTF-8 is unsupported");
}
}
/**
* Decodes an {@code application/<API key>} string using
* {@code UTF-8}.
*
* @param s the {@link String} to decode.
* @return The decoded {@link String}.
*/
public static String urlDecode(String s) {
try {
return URLDecoder.decode(s, StandardCharsets.UTF_8.name());
} catch (<API key> e) {
throw new AssertionError("UTF-8 is unsupported");
}
}
/**
* Parse as double, or if it's not just one number, handles {hour}:{minute}:{seconds}
*
* @param time
* @return
*/
public static double convertStringToTime(String time) throws <API key> {
if (isBlank(time)) {
throw new <API key>("time String should not be blank.");
}
try {
return Double.parseDouble(time);
} catch (<API key> e) {
String[] arguments = time.split(":");
double sum = 0;
int i = 0;
for (String argument : arguments) {
sum += Double.parseDouble(argument.replace(",", ".")) * MULTIPLIER[i];
i++;
}
return sum;
}
}
/**
* Converts time to string.
*
* @param d the time in seconds.
* @param timeFormat Format string e.g. "%02d:%02d:%02f" or use the
* predefined constants {@link #SEC_TIME_FORMAT},
* {@link #<API key>}.
*
* @return The converted {@link String}.
*/
public static String convertTimeToString(double d, String timeFormat) {
StringBuilder sb = new StringBuilder();
try (Formatter formatter = new Formatter(sb, Locale.US)) {
double s = d % 60;
int h = (int) (d / 3600);
int m = ((int) (d / 60)) % 60;
formatter.format(timeFormat, h, m, s);
}
return sb.toString();
}
/**
* Converts a duration in seconds to the DIDL-Lite specified duration
* format.
*
* @param duration the duration in seconds.
* @return The formatted duration.
*/
@Nonnull
public static String formatDLNADuration(double duration) {
double seconds;
int hours;
int minutes;
if (duration < 0) {
seconds = 0.0;
hours = 0;
minutes = 0;
} else {
seconds = duration % 60;
hours = (int) (duration / 3600);
minutes = ((int) (duration / 60)) % 60;
}
if (hours > 99999) {
// As per DLNA standard
hours = 99999;
}
StringBuilder sb = new StringBuilder();
try (Formatter formatter = new Formatter(sb, Locale.ROOT)) {
formatter.format(<API key>, hours, minutes, seconds);
}
return sb.toString();
}
/**
* Returns a formatted duration string in the form
* {@code y years d days HH:mm:ss[.SSS]} where the specified {@code double}
* value is interpreted as the number of seconds. If years or days are zero
* they are omitted, the same applies to hours and minutes unless a larger
* element is already included.
*
* @param duration the duration in seconds.
* @param includeMilliseconds if {@code true} the number of milliseconds
* will be included, if {@code false} the second will be rounded
* to the closest integer value.
* @return The formatted duration.
*/
public static String formatDuration(double duration, boolean includeMilliseconds) {
return formatDuration((long) (duration * 1000), includeMilliseconds);
}
/**
* Returns a formatted duration string in the form
* {@code y years d days HH:mm:ss[.SSS]} where the specified {@code long}
* value is interpreted as the number of milliseconds. If years or days are
* zero they are omitted, the same applies to hours and minutes unless a
* larger element is already included.
*
* @param duration the duration in milliseconds.
* @param includeMilliseconds if {@code true} the number of milliseconds
* will be included, if {@code false} the second will be rounded
* to the closest integer value.
* @return The formatted duration.
*/
public static String formatDuration(long duration, boolean includeMilliseconds) {
long delta;
int hours;
int minutes;
int seconds;
long ms = duration < 0 ? -duration : duration;
StringBuilder sb = new StringBuilder();
delta = ms / 31536000000L; // 365 days
if (delta > 0) {
sb.append(delta).append(delta == 1 ? " year" : " years");
ms = ms % 31536000000L;
}
delta = ms / 86400000L; // 24 hours
if (delta > 0) {
if (sb.length() > 0) {
sb.append(" ");
}
sb.append(delta).append(delta == 1 ? " day" : " days");
ms = ms % 86400000L;
}
delta = ms / 1000;
if (delta > 0 || (includeMilliseconds && ms > 0)) {
if (sb.length() > 0) {
sb.append(" ");
}
boolean includeAll = ms < duration;
hours = (int) (delta / 3600);
minutes = ((int) (delta / 60)) % 60;
seconds = includeMilliseconds ? (int) (delta % 60) : (int) Math.round((ms % 60000) / 1000d);
ms = ms % 1000;
if (includeAll || hours > 0) {
if (includeAll && hours < 10) {
sb.append(String.format((Locale) null, "%02d:", hours));
} else {
sb.append(hours).append(":");
}
}
if (includeAll || hours > 0) {
sb.append(String.format((Locale) null, "%02d:", minutes));
} else if (minutes > 0) {
sb.append(minutes).append(":");
}
if (includeAll || hours > 0 || minutes > 0) {
sb.append(String.format((Locale) null, "%02d", seconds));
} else {
sb.append(seconds);
}
if (includeMilliseconds) {
sb.append(".").append(String.format((Locale) null, "%03d", ms));
}
}
return sb.toString();
}
/**
* Returns an unlocalized, formatted time string in the form
* {@code HH:mm:ss} for the specified {@link Calendar}.
*
* @param calendar the {@link Calendar}.
* @return The formatted {@link String}.
* @throws <API key> If {@code calendar} is {@code null}.
*/
@Nonnull
public static String formatTime(@Nonnull Calendar calendar) {
if (calendar == null) {
throw new <API key>("calendar cannot be null");
}
return formatDateTime(calendar.getTime().getTime(), false);
}
/**
* Returns an unlocalized, formatted time string in the form
* {@code HH:mm:ss} for the specified {@link Date}.
*
* @param date the {@link Date}.
* @return The formatted {@link String}.
* @throws <API key> If {@code date} is {@code null}.
*/
@Nonnull
public static String formatTime(@Nonnull Date date) {
if (date == null) {
throw new <API key>("date cannot be null");
}
return formatDateTime(date.getTime(), false);
}
/**
* Returns an unlocalized, formatted time string in the form
* {@code HH:mm:ss} for the specified {@link Timestamp}.
*
* @param timestamp the {@link Timestamp}.
* @return The formatted {@link String}.
* @throws <API key> If {@code timestamp} is {@code null}.
*/
@Nonnull
public static String formatTime(@Nonnull Timestamp timestamp) {
if (timestamp == null) {
throw new <API key>("timestamp cannot be null");
}
return formatDateTime(timestamp.getTime(), false);
}
/**
* Returns an unlocalized, formatted time string in the form
* {@code HH:mm:ss} where the specified long value is interpreted as the
* number of milliseconds since January 1, 1970, 00:00:00 GMT (epoch).
*
* @param time the number of milliseconds since January 1, 1970, 00:00:00
* GMT.
* @return The formatted {@link String}.
*/
@Nonnull
public static String formatTime(long time) {
return formatDateTime(time, false);
}
/**
* Returns an unlocalized, formatted date and time string in the form
* {@code yyyy-MM-dd HH:mm:ss} for the specified {@link Date}.
*
* @param date the {@link Date}.
* @return The formatted {@link String}.
* @throws <API key> If {@code date} is {@code null}.
*/
@Nonnull
public static String formatDateTime(@Nonnull Date date) {
if (date == null) {
throw new <API key>("date cannot be null");
}
return formatDateTime(date.getTime(), true);
}
/**
* Returns an unlocalized, formatted date and time string in the form
* {@code yyyy-MM-dd HH:mm:ss} for the specified {@link Timestamp}.
*
* @param timestamp the {@link Timestamp}.
* @return The formatted {@link String}.
* @throws <API key> If {@code timestamp} is {@code null}.
*/
@Nonnull
public static String formatDateTime(@Nonnull Timestamp timestamp) {
if (timestamp == null) {
throw new <API key>("timestamp cannot be null");
}
return formatDateTime(timestamp.getTime(), true);
}
/**
* Returns an unlocalized, formatted date and time string in the form
* {@code yyyy-MM-dd HH:mm:ss} where the specified long value is interpreted
* as the number of milliseconds since January 1, 1970, 00:00:00 GMT
* (epoch).
*
* @param time the number of milliseconds since January 1, 1970, 00:00:00
* GMT.
* @return The formatted {@link String}.
*/
@Nonnull
public static String formatDateTime(long time) {
return formatDateTime(time, true);
}
/**
* Returns an unlocalized, formatted date and time string in the form
* {@code yyyy-MM-dd HH:mm:ss} for the specified {@link Calendar}.
*
* @param calendar the {@link Calendar}.
* @return The formatted {@link String}.
* @throws <API key> If {@code calendar} is {@code null}.
*/
@Nonnull
public static String formatDateTime(@Nonnull Calendar calendar) {
if (calendar == null) {
throw new <API key>("calendar cannot be null");
}
return formatDateTime(calendar, true);
}
/**
* Returns an unlocalized, formatted date and time string in the form
* {@code HH:mm:ss} or {@code yyyy-MM-dd HH:mm:ss} where the specified long
* value is interpreted as the number of milliseconds since January 1, 1970,
* 00:00:00 GMT (epoch). The date part is only included if the date is
* different from the current date.
*
* @param time the number of milliseconds since January 1, 1970, 00:00:00
* GMT.
* @return The formatted {@link String}.
*/
@Nonnull
public static String formatDateTimeAuto(long time) {
long now = System.currentTimeMillis();
TimeZone localTimeZone = TimeZone.getDefault();
now += localTimeZone.getOffset(now);
long localTime = time + localTimeZone.getOffset(time);
return formatDateTime(time, now / 86400000L != localTime / 86400000L);
}
/**
* Returns an unlocalized, formatted date and time string in the form
* {@code HH:mm:ss} or {@code yyyy-MM-dd HH:mm:ss} where the specified long
* value is interpreted as the number of milliseconds since January 1, 1970,
* 00:00:00 GMT (epoch).
*
* @param time the number of milliseconds since January 1, 1970, 00:00:00
* GMT.
* @param includeDate {@code true} to include the date part, {@code false}
* to only show the time.
* @return The formatted {@link String}.
*/
@Nonnull
public static String formatDateTime(long time, boolean includeDate) {
return time == Long.MAX_VALUE ?
"Never" :
String.format(Locale.ROOT, includeDate ? "%tY-%<tm-%<td %<tH:%<tM:%<tS" : "%tH:%<tM:%<tS", time);
}
/**
* Returns an unlocalized, formatted date and time string in the form
* {@code HH:mm:ss} or {@code yyyy-MM-dd HH:mm:ss} for the specified
* {@link Calendar}.
*
* @param calendar the {@link Calendar}.
* @param includeDate {@code true} to include the date part, {@code false}
* to only show the time.
* @return The formatted {@link String}.
* @throws <API key> If {@code calendar} is {@code null}.
*/
@Nonnull
public static String formatDateTime(@Nonnull Calendar calendar, boolean includeDate) {
if (calendar == null) {
throw new <API key>("calendar cannot be null");
}
return String.format(Locale.ROOT, includeDate ? "%tY-%<tm-%<td %<tH:%<tM:%<tS" : "%tH:%<tM:%<tS", calendar);
}
/**
* Removes leading zeros up to the nth char of an hh:mm:ss time string,
* normalizing it first if necessary.
*
* @param time the time string.
* @param n position to stop checking
*
* @return the Shortened String.
*/
@Nonnull
public static String shortTime(@Nullable String time, int n) {
n = n < 8 ? n : 8;
if (!isBlank(time)) {
if (time.startsWith("NOT_IMPLEMENTED")) {
return time.length() > 15 ? time.substring(15) : " ";
}
int i = time.indexOf('.');
// Throw out the decimal portion, if any
if (i > -1) {
time = time.substring(0, i);
}
int l = time.length();
// Normalize if necessary
if (l < 8) {
time = "00:00:00".substring(0, 8 - l) + time;
} else if (l > 8) {
time = time.substring(l - 8);
}
for (i = 0; i < n; i++) {
if (time.charAt(i) != "00:00:00".charAt(i)) {
break;
}
}
return time.substring(i);
}
return "00:00:00".substring(n);
}
public static boolean isZeroTime(@Nullable String t) {
return isBlank(t) || "00:00:00.000".contains(t);
}
/**
* Returns the first four digit number that can look like a year from the
* specified {@link CharSequence}.
*
* @param date the {@link CharSequence} from which to extract the year.
* @return The extracted year or {@code -1} if no valid year is found.
*/
public static int getYear(@Nullable CharSequence date) {
if (isBlank(date)) {
return -1;
}
Pattern pattern = Pattern.compile("\\b\\d{4}\\b");
Matcher matcher = pattern.matcher(date);
while (matcher.find()) {
int result = Integer.parseInt(matcher.group());
if (result > 1600 && result < 2100) {
return result;
}
}
return -1;
}
/**
* Extracts the first four digit number that can look like a year from both
* {@link CharSequence}s and compares them.
*
* @param firstDate the first {@link CharSequence} containing a year.
* @param secondDate the second {@link CharSequence} containing a year.
* @return {@code true} if a year can be extracted from both
* {@link CharSequence}s and they have the same numerical value,
* {@code false} otherwise.
*/
public static boolean isSameYear(@Nullable CharSequence firstDate, @Nullable CharSequence secondDate) {
int first = getYear(firstDate);
if (first < 0) {
return false;
}
int second = getYear(secondDate);
if (second < 0) {
return false;
}
return first == second;
}
/**
* Compares the specified {@link String}s for equality. Either
* {@link String} can be {@code null}, and they are considered equal if both
* are {@code null}.
*
* @param first the first {@link String} to compare.
* @param second the second {@link String} to compare.
* @return {@code true} if the two {@link String}s are equal, {@code false}
* otherwise.
* @throws <API key> if an invalid combination of parameters
* is specified.
* @throws <API key> if {@code fromIdx} or {@code toIdx} is
* positive and outside the bounds of {@code first} or
* {@code second}.
*/
public static boolean isEqual(
@Nullable String first,
@Nullable String second
) {
return isEqual(first, second, false, false, false, null, false, 0, -1, -1);
}
/**
* Compares the specified {@link String}s for equality. Either
* {@link String} can be {@code null}, and they are considered equal if both
* are {@code null}.
*
* @param first the first {@link String} to compare.
* @param second the second {@link String} to compare.
* @param blankIsNull if {@code true} a blank {@link String} will be equal
* to any other blank {@link String} or {@code null}.
* @return {@code true} if the two {@link String}s are equal according to
* the rules set by the parameters, {@code false} otherwise.
* @throws <API key> if an invalid combination of parameters
* is specified.
* @throws <API key> if {@code fromIdx} or {@code toIdx} is
* positive and outside the bounds of {@code first} or
* {@code second}.
*/
public static boolean isEqual(
@Nullable String first,
@Nullable String second,
boolean blankIsNull
) {
return isEqual(first, second, blankIsNull, false, false, null, false, 0, -1, -1);
}
/**
* Compares the specified {@link String}s for equality according to the
* rules set by the parameters. Either {@link String} can be {@code null},
* and they are considered equal if both are {@code null}.
*
* @param first the first {@link String} to compare.
* @param second the second {@link String} to compare.
* @param blankIsNull if {@code true} a blank {@link String} will be equal
* to any other blank {@link String} or {@code null}.
* @param trim {@code true} to {@link String#trim()} both {@link String}s
* before comparison, {@code false} otherwise.
* @param ignoreCase {@code true} to convert both {@link String}s to
* lower-case using the specified {@link Locale} before
* comparison, {@code false} otherwise.
* @param locale the {@link Locale} to use when converting both
* {@link String}s to lower-case if {@code ignoreCase} is
* {@code true}. Ignored if {@code ignoreCase} is {@code false}.
* If {@code null}, {@link Locale#ROOT} will be used.
* @return {@code true} if the two {@link String}s are equal according to
* the rules set by the parameters, {@code false} otherwise.
*/
public static boolean isEqual(
@Nullable String first,
@Nullable String second,
boolean blankIsNull,
boolean trim,
boolean ignoreCase,
@Nullable Locale locale
) {
return isEqual(first, second, blankIsNull, trim, ignoreCase, locale, false, 0, -1, -1);
}
/**
* Compares the specified {@link String}s for equality according to the
* rules set by the parameters. Either {@link String} can be {@code null},
* and they are considered equal if both are {@code null}.
*
* @param first the first {@link String} to compare.
* @param second the second {@link String} to compare.
* @param blankIsNull if {@code true} a blank {@link String} will be equal
* to any other blank {@link String} or {@code null}.
* @param trim {@code true} to {@link String#trim()} both {@link String}s
* before comparison, {@code false} otherwise.
* @param ignoreCase {@code true} to convert both {@link String}s to
* lower-case using the specified {@link Locale} before
* comparison, {@code false} otherwise.
* @param locale the {@link Locale} to use when converting both
* {@link String}s to lower-case if {@code ignoreCase} is
* {@code true}. Ignored if {@code ignoreCase} is {@code false}.
* If {@code null}, {@link Locale#ROOT} will be used.
* @param shortest {@code true} to only compare the length of the shortest
* of the two {@link String}s.
* @param minLength the minimum length to compare if {@code shortest} is
* true. If this is zero, an empty {@link String} will equal any
* {@link String}.
* @return {@code true} if the two {@link String}s are equal according to
* the rules set by the parameters, {@code false} otherwise.
*/
public static boolean isEqual(
@Nullable String first,
@Nullable String second,
boolean blankIsNull,
boolean trim,
boolean ignoreCase,
@Nullable Locale locale,
boolean shortest,
int minLength
) {
return isEqual(first, second, blankIsNull, trim, ignoreCase, locale, shortest, minLength, -1, -1);
}
/**
* Compares the specified {@link String}s for equality according to the
* rules set by the parameters. Either {@link String} can be {@code null},
* and they are considered equal if both are {@code null}.
*
* @param first the first {@link String} to compare.
* @param second the second {@link String} to compare.
* @param blankIsNull if {@code true} a blank {@link String} will be equal
* to any other blank {@link String} or {@code null}.
* @param ignoreCase {@code true} to convert both {@link String}s to
* lower-case using the specified {@link Locale} before
* comparison, {@code false} otherwise.
* @param locale the {@link Locale} to use when converting both
* {@link String}s to lower-case if {@code ignoreCase} is
* {@code true}. Ignored if {@code ignoreCase} is {@code false}.
* If {@code null}, {@link Locale#ROOT} will be used.
* @param fromIdx compare only from the character of this index.
* @return {@code true} if the two {@link String}s are equal according to
* the rules set by the parameters, {@code false} otherwise.
* @throws <API key> {@code toIdx} is positive and is smaller
* than {@code fromIdx}.
* @throws <API key> if {@code fromIdx} or {@code toIdx} is
* positive and outside the bounds of {@code first} or
* {@code second}.
*/
public static boolean isEqualFrom(
@Nullable String first,
@Nullable String second,
boolean blankIsNull,
boolean ignoreCase,
@Nullable Locale locale,
int fromIdx
) {
return isEqual(first, second, blankIsNull, false, ignoreCase, locale, false, 0, fromIdx, -1);
}
/**
* Compares the specified {@link String}s for equality according to the
* rules set by the parameters. Either {@link String} can be {@code null},
* and they are considered equal if both are {@code null}.
*
* @param first the first {@link String} to compare.
* @param second the second {@link String} to compare.
* @param blankIsNull if {@code true} a blank {@link String} will be equal
* to any other blank {@link String} or {@code null}.
* @param ignoreCase {@code true} to convert both {@link String}s to
* lower-case using the specified {@link Locale} before
* comparison, {@code false} otherwise.
* @param locale the {@link Locale} to use when converting both
* {@link String}s to lower-case if {@code ignoreCase} is
* {@code true}. Ignored if {@code ignoreCase} is {@code false}.
* If {@code null}, {@link Locale#ROOT} will be used.
* @param toIdx compare only to (not including) the character of this index.
* To compare to the end of the {@link String}, use {@code -1} or
* the index position after the last character (the same as the
* length).
* @return {@code true} if the two {@link String}s are equal according to
* the rules set by the parameters, {@code false} otherwise.
* @throws <API key> {@code toIdx} is positive and is smaller
* than {@code fromIdx}.
* @throws <API key> if {@code fromIdx} or {@code toIdx} is
* positive and outside the bounds of {@code first} or
* {@code second}.
*/
public static boolean isEqualTo(
@Nullable String first,
@Nullable String second,
boolean blankIsNull,
boolean ignoreCase,
@Nullable Locale locale,
int toIdx
) {
return isEqual(first, second, blankIsNull, false, ignoreCase, locale, false, 0, -1, toIdx);
}
/**
* Compares the specified {@link String}s for equality according to the
* rules set by the parameters. Either {@link String} can be {@code null},
* and they are considered equal if both are {@code null}.
*
* @param first the first {@link String} to compare.
* @param second the second {@link String} to compare.
* @param blankIsNull if {@code true} a blank {@link String} will be equal
* to any other blank {@link String} or {@code null}.
* @param ignoreCase {@code true} to convert both {@link String}s to
* lower-case using the specified {@link Locale} before
* comparison, {@code false} otherwise.
* @param locale the {@link Locale} to use when converting both
* {@link String}s to lower-case if {@code ignoreCase} is
* {@code true}. Ignored if {@code ignoreCase} is {@code false}.
* If {@code null}, {@link Locale#ROOT} will be used.
* @param fromIdx compare only from the character of this index.
* @param toIdx compare only to (not including) the character of this index.
* To compare to the end of the {@link String}, use {@code -1} or
* the index position after the last character (the same as the
* length).
* @return {@code true} if the two {@link String}s are equal according to
* the rules set by the parameters, {@code false} otherwise.
* @throws <API key> {@code toIdx} is positive and is smaller
* than {@code fromIdx}.
* @throws <API key> if {@code fromIdx} or {@code toIdx} is
* positive and outside the bounds of {@code first} or
* {@code second}.
*/
public static boolean isEqual(
@Nullable String first,
@Nullable String second,
boolean blankIsNull,
boolean ignoreCase,
@Nullable Locale locale,
int fromIdx,
int toIdx
) {
return isEqual(first, second, blankIsNull, false, ignoreCase, locale, false, 0, fromIdx, toIdx);
}
/**
* Compares the specified {@link String}s for equality according to the
* rules set by the parameters. Either {@link String} can be {@code null},
* and they are considered equal if both are {@code null}.
*
* @param first the first {@link String} to compare.
* @param second the second {@link String} to compare.
* @param blankIsNull if {@code true} a blank {@link String} will be equal
* to any other blank {@link String} or {@code null}.
* @param trim {@code true} to {@link String#trim()} both {@link String}s
* before comparison, {@code false} otherwise. Cannot be used
* together with {@code fromIdx} or {@code toIdx}.
* @param ignoreCase {@code true} to convert both {@link String}s to
* lower-case using the specified {@link Locale} before
* comparison, {@code false} otherwise.
* @param locale the {@link Locale} to use when converting both
* {@link String}s to lower-case if {@code ignoreCase} is
* {@code true}. Ignored if {@code ignoreCase} is {@code false}.
* If {@code null}, {@link Locale#ROOT} will be used.
* @param shortest {@code true} to only compare the length of the shortest
* of the two {@link String}s. Cannot be used together with
* {@code fromIdx} or {@code toIdx}.
* @param minLength the minimum length to compare if {@code shortest} is
* true. If this is zero, an empty {@link String} will equal any
* {@link String}.
* @param fromIdx compare only from the character of this index. Cannot be
* used together with {@code trim} or {@code shortest}.
* @param toIdx compare only to (not including) the character of this index.
* To compare to the end of the {@link String}, use {@code -1} or
* the index position after the last character (the same as the
* length). Cannot be used together with {@code trim} or
* {@code shortest}.
* @return {@code true} if the two {@link String}s are equal according to
* the rules set by the parameters, {@code false} otherwise.
* @throws <API key> if an invalid combination of parameters
* is specified.
* @throws <API key> if {@code fromIdx} or {@code toIdx} is
* positive and outside the bounds of {@code first} or
* {@code second}.
*/
protected static boolean isEqual(
@Nullable String first,
@Nullable String second,
boolean blankIsNull,
boolean trim,
boolean ignoreCase,
@Nullable Locale locale,
boolean shortest,
int minLength,
int fromIdx,
int toIdx
) {
if ((trim || shortest) && (fromIdx >= 0 || toIdx >= 0)) {
throw new <API key>("trim or shortest and index range can't be used together");
}
if (blankIsNull) {
if (first == null) {
first = "";
}
if (second == null) {
second = "";
}
} else {
if (first == null || second == null) {
return first == null && second == null;
}
}
// No null after this point
if (trim) {
first = first.trim();
second = second.trim();
}
if (ignoreCase) {
if (locale == null) {
locale = Locale.ROOT;
}
first = first.toLowerCase(locale);
second = second.toLowerCase(locale);
}
if (shortest) {
if (first.length() != second.length()) {
int shortestIdx = Math.max(Math.min(first.length(), second.length()), minLength);
first = first.substring(0, Math.min(shortestIdx, first.length()));
second = second.substring(0, Math.min(shortestIdx, second.length()));
}
} else if (fromIdx >= 0 || toIdx >= 0) {
if (fromIdx == toIdx) {
return true;
}
if (fromIdx > toIdx && toIdx >= 0) {
throw new <API key>("fromIdx (" + fromIdx + ") > toIdx (" + toIdx + ")");
}
if (fromIdx >= first.length() || fromIdx >= second.length()) {
throw new <API key>(
"fromIdx=" + fromIdx + ", first length=" + first.length() + ", second length=" + second.length()
);
}
if (toIdx > first.length() || toIdx > second.length()) {
throw new <API key>(
"toIdx=" + fromIdx + ", first length=" + first.length() + ", second length=" + second.length()
);
}
if (fromIdx < 0) {
fromIdx = 0;
}
if (toIdx < 0) {
first = first.substring(fromIdx);
second = second.substring(fromIdx);
} else {
first = first.substring(fromIdx, toIdx);
second = second.substring(fromIdx, toIdx);
}
}
if (blankIsNull && (isBlank(first) || isBlank(second))) {
return isBlank(first) && isBlank(second);
}
return first.equals(second);
}
/**
* A unicode unescaper that translates unicode escapes, e.g. {@code \u005c},
* while leaving intact any sequences that can't be interpreted as escaped
* unicode.
*/
public static class LaxUnicodeUnescaper extends UnicodeUnescaper {
@Override
public int translate(CharSequence input, int index, Writer out) throws IOException {
try {
return super.translate(input, index, out);
} catch (<API key> e) {
// Leave it alone and continue
}
return 0;
}
}
/**
* Returns the argument string surrounded with quotes if it contains a space,
* otherwise returns the string as is.
*
* @param arg The argument string
* @return The string, optionally in quotes.
*/
public static String quoteArg(String arg) {
if (arg != null && arg.indexOf(' ') > -1) {
return "\"" + arg + "\"";
}
return arg;
}
/**
* Fill a string in a unicode safe way.
*
* @param subString The <code>String</code> to be filled with
* @param count The number of times to repeat the <code>String</code>
* @return The filled string
*/
public static String fillString(String subString, int count) {
StringBuilder sb = new StringBuilder(subString.length() * count);
for (int i = 0; i < count; i++) {
sb.append(subString);
}
return sb.toString();
}
/**
* Fill a string in a unicode safe way provided that the char array contains
* a valid unicode sequence.
*
* @param chars The <code>char[]</code> to be filled with
* @param count The number of times to repeat the <code>char[]</code>
* @return The filled string
*/
public static String fillString(char[] chars, int count) {
StringBuilder sb = new StringBuilder(chars.length * count);
for (int i = 0; i < count; i++) {
sb.append(chars);
}
return sb.toString();
}
/**
* Fill a string in a unicode safe way. 8 bit (< 256) code points
* equals ISO 8859-1 codes.
*
* @param codePoint The unicode code point to be filled with
* @param count The number of times to repeat the unicode code point
* @return The filled string
*/
public static String fillString(int codePoint, int count) {
return fillString(Character.toChars(codePoint), count);
}
/**
* Returns the <code>body</code> of a HTML {@link String} formatted by
* {@link HTMLEditorKit} as typically used by {@link JEditorPane} and
* {@link JTextPane} stripped for tags, newline, indentation and with
* <code><br></code> tags converted to newline.<br>
* <br>
* <strong>Note: This is not a universal or sophisticated HTML stripping
* method, but is purpose built for these circumstances.</strong>
*
* @param html the HTML formatted text as described above
* @return The "deHTMLified" text
*/
public static String stripHTML(String html) {
Pattern pattern = Pattern.compile("<body>(.*)</body>", Pattern.CASE_INSENSITIVE + Pattern.DOTALL);
Matcher matcher = pattern.matcher(html);
if (matcher.find()) {
return matcher.group(1).replaceAll("\n ", "").trim().replaceAll("(?i)<br>", "\n").replaceAll("<.*?>", "");
}
throw new <API key>("HTML text not as expected, must have <body> section");
}
/**
* Replaces a case-insensitive substring with the same substring in its
* provided capitalization. Used to make sure a given part of a
* {@link CharSequence} is capitalized in a defined manner.
*
* @param target the {@link CharSequence} to replace occurrences in.
* @param subString the {@link String} in its correctly capitalized form.
* @return The resulting {@link String}.
*/
public static String caseReplace(CharSequence target, String subString) {
return Pattern.compile(subString, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(target).replaceAll(subString);
}
/**
* Evaluates whether all the alphabetic characters are in upper-case in the
* specified {@link CharSequence}.
*
* @param cs the {@link CharSequence} to evaluate.
* @return {@code true} if all the alphabetic characters in {@code cs} are
* in upper-case, {@code false} otherwise.
*/
public static boolean isUpperCase(CharSequence cs) {
return !LOWER.matcher(cs).find();
}
/**
* Evaluates whether all the alphabetic characters are in lower-case in the
* specified {@link CharSequence}.
*
* @param cs the {@link CharSequence} to evaluate.
* @return {@code true} if all the alphabetic characters in {@code cs} are
* in lower-case, {@code false} otherwise.
*/
public static boolean isLowerCase(CharSequence cs) {
return !UPPER.matcher(cs).find();
}
/**
* Evaluates whether all the alphabetic characters are in the same case
* (either upper or lower) in the specified {@link CharSequence}.
*
* @param cs the {@link CharSequence} to evaluate.
* @return {@code true} if all the alphabetic characters in {@code cs} are
* in the same case (either upper or lower), {@code false}
* otherwise.
*/
public static boolean isSameCase(CharSequence cs) {
return isLowerCase(cs) || isUpperCase(cs);
}
/**
* Escapes {@link org.apache.lucene} special characters with backslash.
*
* @param s the {@link String} to evaluate.
* @return The converted String.
*/
@SuppressFBWarnings("<API key>")
public static String luceneEscape(final String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case '+':
case '-':
case '&':
case '|':
case '!':
case '(':
case ')':
case '{':
case '}':
case '[':
case ']':
case '^':
case '\"':
case '~':
case '*':
case '?':
case ':':
case '\\':
case '/':
sb.append("\\");
default:
sb.append(ch);
}
}
return sb.toString();
}
/**
* Escapes special characters with backslashes for FFmpeg subtitles.
*
* @param s the {@link String} to evaluate.
* @return The converted String.
*/
public static String ffmpegEscape(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case '\'':
sb.append("\\\\\\'");
break;
case ':':
sb.append("\\\\:");
break;
case '\\':
sb.append("/");
break;
case ']':
case '[':
case ',':
case ';':
sb.append("\\");
// Fall through
default:
sb.append(ch);
break;
}
}
return sb.toString();
}
/**
* Formats a XML string to be easier to read with newlines and indentations.
*
* @param xml the {@link String} to "prettify".
* @param indentWidth the width of one indentation in number of characters.
* @return The "prettified" {@link String}.
* @throws SAXException If a parsing error occurs.
* @throws <API key> If a parsing error occurs.
* @throws <API key> If a parsing error occurs.
* @throws <API key> If a parsing error occurs.
*/
public static String prettifyXML(
String xml,
int indentWidth
) throws SAXException, <API key>, <API key>, <API key> {
try {
// Turn XML string into a document
Document xmlDocument =
<API key>.newInstance().
newDocumentBuilder().
parse(new InputSource(new <API key>(xml.getBytes("utf-8"))));
// Remove whitespaces outside tags
xmlDocument.normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.evaluate(
"//text()[normalize-space()='']",
xmlDocument,
XPathConstants.NODESET
);
for (int i = 0; i < nodeList.getLength(); ++i) {
Node node = nodeList.item(i);
node.getParentNode().removeChild(node);
}
// Setup pretty print options
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", indentWidth);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.<API key>, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// Return pretty print XML string
StringWriter stringWriter = new StringWriter();
transformer.transform(new DOMSource(xmlDocument), new StreamResult(stringWriter));
return stringWriter.toString();
} catch (IOException e) {
LOGGER.warn("Failed to read XML document, returning the source document: {}", e.getMessage());
LOGGER.trace("", e);
return xml;
}
}
/**
* Creates a "readable" string by combining the objects in {@code elements}
* while inserting "{@code ,}" and "{@code and}" as appropriate. The
* resulting {@link String} is in the form
* {@code "element 1, element2 and element3"}.
*
* @param elements the {@link Collection} of {@link String} to combine.
* @return The combined "readable" {@link String}.
*/
public static String <API key>(Collection<? extends Object> elements) {
return <API key>(elements, false, null, null);
}
/**
* Creates a "readable" string by combining the objects in {@code elements}
* while inserting "{@code ,}" and "{@code and}" as appropriate. The
* resulting {@link String} is in the form
* {@code "element 1, element2 and element3"}.
*
* @param elements the {@link Collection} of {@link Object} to combine.
* @param quote if {@code true}, all elements will be quoted in
* double-quotes.
* @return The combined "readable" {@link String}.
*/
public static String <API key>(Collection<? extends Object> elements, boolean quote) {
return <API key>(elements, quote, null, null);
}
/**
* Creates a "readable" string by combining the objects in {@code elements}
* while inserting {@code separator} and {@code lastSeparator} as
* appropriate. The resulting {@link String} is in the form
* {@code "element 1<separator> element2 <lastSeparator> element3"}.
*
* @param elements the {@link Collection} of {@link Object} to combine.
* @param separator the "normal" separator used everywhere except between
* the last two elements.
* @param lastSeparator the separator used between the last two elements.
* @return The combined "readable" {@link String}.
*/
public static String <API key>(Collection<? extends Object> elements, String separator, String lastSeparator) {
if (elements == null || elements.isEmpty()) {
return "";
}
return <API key>(elements.toArray(new Object[elements.size()]), false, separator, lastSeparator);
}
/**
* Creates a "readable" string by combining the objects in {@code elements}
* while inserting {@code separator} and {@code lastSeparator} as
* appropriate. The resulting {@link String} is in the form
* {@code "element 1<separator> element2 <lastSeparator> element"}.
*
* @param elements the {@link Collection} of {@link Object} to combine.
* @param quote if {@code true}, all elements will be quoted in
* double-quotes.
* @param separator the "normal" separator used everywhere except between
* the last two elements.
* @param lastSeparator the separator used between the last two elements.
* @return The combined "readable" {@link String}.
*/
public static String <API key>(
Collection<? extends Object> elements,
boolean quote,
String separator,
String lastSeparator
) {
if (elements == null || elements.isEmpty()) {
return "";
}
return <API key>(elements.toArray(new Object[elements.size()]), quote, separator, lastSeparator);
}
/**
* Creates a "readable" string by combining the objects in {@code elements}
* while inserting "{@code ,}" and "{@code and}" as appropriate. The
* resulting {@link String} is in the form
* {@code "element 1, element2 and element3}.
*
* @param elements the elements to combine.
* @return The combined "readable" {@link String}.
*/
@Nonnull
public static String <API key>(@Nullable Object[] elements) {
return <API key>(elements, false, null, null);
}
/**
* Creates a "readable" string by combining the objects in {@code elements}
* while inserting "{@code ,}" and "{@code and}" as appropriate. The
* resulting {@link String} is in the form
* {@code "element 1, element2 and element3"}.
*
* @param elements the elements to combine.
* @param quote if {@code true}, all elements will be quoted in
* double-quotes.
* @return The combined "readable" {@link String}.
*/
public static String <API key>(@Nullable Object[] elements, boolean quote) {
return <API key>(elements, quote, null, null);
}
/**
* Creates a "readable" string by combining the objects in {@code elements}
* while inserting {@code separator} and {@code lastSeparator} as
* appropriate. The resulting {@link String} is in the form
* {@code "element 1<separator> element2 <lastSeparator> element3"}.
*
* @param elements the elements to combine.
* @param separator the "normal" separator used everywhere except between
* the last two elements.
* @param lastSeparator the separator used between the last two elements.
* @return The combined "readable" {@link String}.
*/
@Nonnull
public static String <API key>(
@Nullable Object[] elements,
@Nullable String separator,
@Nullable String lastSeparator
) {
return <API key>(elements, false, separator, lastSeparator);
}
/**
* Creates a "readable" string by combining the objects in {@code elements}
* while inserting {@code separator} and {@code lastSeparator} as
* appropriate. The resulting {@link String} is in the form
* {@code "element 1<separator> element2 <lastSeparator> element3"}.
*
* @param elements the elements to combine.
* @param quote if {@code true}, all elements will be quoted in
* double-quotes.
* @param separator the "normal" separator used everywhere except between
* the last two elements.
* @param lastSeparator the separator used between the last two elements.
* @return The combined "readable" {@link String}.
*/
@Nonnull
public static String <API key>(
@Nullable Object[] elements,
boolean quote,
@Nullable String separator,
@Nullable String lastSeparator
) {
if (elements == null || elements.length == 0) {
return "";
}
if (elements.length == 1 && elements[0] instanceof Collection<?>) {
// This method will catch a Collection<?> argument as well, convert it to an array
elements = ((Collection<?>) elements[0]).toArray();
}
if (separator == null) {
separator = ", ";
} else {
separator += " ";
}
if (isBlank(lastSeparator)) {
lastSeparator = " and ";
} else {
if (!lastSeparator.substring(0, 1).equals(" ")) {
lastSeparator = " " + lastSeparator;
}
if (!lastSeparator.substring(lastSeparator.length() - 1).equals(" ")) {
lastSeparator += " ";
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < elements.length; i++) {
if (i > 0) {
if (i == elements.length - 1) {
sb.append(lastSeparator);
} else {
sb.append(separator);
}
}
if (quote) {
sb.append("\"").append(elements[i]).append("\"");
} else {
sb.append(elements[i]);
}
}
return sb.toString();
}
/**
* An {@code enum} representing letter cases.
*/
public enum LetterCase {
/** Upper-case, uppercase, capital or majuscule */
UPPER,
/** Lower-case, lowercase or minuscule */
LOWER
}
} |
#ifndef <API key>
#define <API key>
/* Structure of desriptor for Page Directory Entry or Page Table Entry */
struct pageEntry
{
uint32_t mapped:1; /* 1=mapped, 0=free */
uint32_t write:1; /* 0=read-only, 1=RW */
uint32_t privilege:1; /* 0=kernel mode, 1=user mode */
uint32_t writeThrough:1; /* 0=the page has not been written to, 1=the page has been written to (since last refresh) */
uint32_t cacheDisabled:1; /* 1=cache disabled, 0=cache enabled */
uint32_t accessed:1; /* 1=RW access */
uint32_t reserved1:1;
uint32_t pageSize:1; /* 0=4Ko, 1=4Mo or > */
uint32_t reserved2:1;
uint32_t custom:3;
uint32_t address:20; /* address to Page Table or Page Frame*/
} __attribute__ ((packed));
typedef struct pageEntry pageEntry_t;
typedef struct pageTable
{
pageEntry_t pageFrame[1024]; // one Page Table is an array of Page Frame
} pageTable_t;
typedef struct pageDirectory
{
pageTable_t *tables[1024]; // Array of pointers to Pages Tables
/* the page directoty must hold physical adresses */
uint32_t physTableAddresses[1024]; // physical location of Page Tables (for CR3) in an array of addresses
uint32_t physicalAddr; // the physical address of physTableAddresses (array of physical addesses)
} pageDirectory_t;
void initPaging();
void switchPageDirectory(pageDirectory_t *new);
pageEntry_t *getPage(uint32_t address, int make, pageDirectory_t *dir);
#endif |
#include <kernels/cbe_accel/cvmul.hpp>
typedef example::Cvmul_kernel kernel_type;
#include <vsip_csl/ukernel/cbe_accel/alf_base.hpp> |
package enginuity.newmaps.ecudata;
import enginuity.newmaps.ecumetadata.Table3DMetadata;
import enginuity.newmaps.exception.<API key>;
import enginuity.newmaps.util.ECUDataUtil;
public class Table3DData extends TableData {
private DataCell[][] values;
private AxisData xAxis;
private AxisData yAxis;
public Table3DData(byte[] data, Table3DMetadata metadata) throws <API key> {
this.metadata = metadata;
xAxis = new AxisData(data, metadata.getXaxis());
yAxis = new AxisData(data, metadata.getYaxis());
populate(data);
}
public DataCell[][] getValues() {
return values;
}
public DataCell getValueAt(int x, int y) throws <API key> {
return values[x][y];
}
public byte[] returnValues() {
// Returns updated byte values to ECUData
// TODO: Find return values (using ECUDataUtil)
return null;
}
public boolean populate(byte[] data) {
// populate axes first
xAxis.populate(data);
yAxis.populate(data);
// Now populate the table itself
values = ECUDataUtil.buildValues(data, (Table3DMetadata)metadata);
return true;
}
} |
package org.inria.myriads.snoozenode.message;
/**
*
* Management message type.
*
* @author msimonin
*
*/
public enum <API key>
{
/** pending.*/
PENDING,
/** error.*/
ERROR,
/** processed.*/
PROCESSED,
} |
#include <algorithm>
#include <cstring>
#include "Common/CommonFuncs.h"
#include "Common/CPUDetect.h"
#include "Common/Hash.h"
#include "Common/Intrinsics.h"
static u64(*ptrHashFunction)(const u8* src, u32 len, u32 samples) = &GetMurmurHash3;
// uint32_t
// WARNING - may read one more byte!
// Implementation from Wikipedia.
u32 HashFletcher(const u8* data_u8, size_t length)
{
const u16* data = (const u16*)data_u8; /* Pointer to the data to be summed */
size_t len = (length + 1) / 2; /* Length in 16-bit words */
u32 sum1 = 0xffff, sum2 = 0xffff;
while (len)
{
size_t tlen = len > 360 ? 360 : len;
len -= tlen;
do
{
sum1 += *data++;
sum2 += sum1;
} while (--tlen);
sum1 = (sum1 & 0xffff) + (sum1 >> 16);
sum2 = (sum2 & 0xffff) + (sum2 >> 16);
}
// Second reduction step to reduce sums to 16 bits
sum1 = (sum1 & 0xffff) + (sum1 >> 16);
sum2 = (sum2 & 0xffff) + (sum2 >> 16);
return(sum2 << 16 | sum1);
}
// Implementation from Wikipedia
// Slightly slower than Fletcher above, but slightly more reliable.
// data: Pointer to the data to be summed; len is in bytes
u32 HashAdler32(const u8* data, size_t len)
{
static const u32 MOD_ADLER = 65521;
u32 a = 1, b = 0;
while (len)
{
size_t tlen = len > 5550 ? 5550 : len;
len -= tlen;
do
{
a += *data++;
b += a;
} while (--tlen);
a = (a & 0xffff) + (a >> 16) * (65536 - MOD_ADLER);
b = (b & 0xffff) + (b >> 16) * (65536 - MOD_ADLER);
}
// It can be shown that a <= 0x1013a here, so a single subtract will do.
if (a >= MOD_ADLER)
{
a -= MOD_ADLER;
}
// It can be shown that b can reach 0xfff87 here.
b = (b & 0xffff) + (b >> 16) * (65536 - MOD_ADLER);
if (b >= MOD_ADLER)
{
b -= MOD_ADLER;
}
return((b << 16) | a);
}
// Stupid hash - but can't go back now :)
// Don't use for new things. At least it's reasonably fast.
u32 HashEctor(const u8* ptr, int length)
{
u32 crc = 0;
for (int i = 0; i < length; i++)
{
crc ^= ptr[i];
crc = (crc << 3) | (crc >> 29);
}
return(crc);
}
#if _ARCH_64
// Block read - if your platform needs to do endian-swapping or can only
// handle aligned reads, do the conversion here
inline u64 getblock(const u64* p, int i)
{
return p[i];
}
// Block mix - combine the key bits with the hash bits and scramble everything
inline void bmix64(u64 & h1, u64 & h2, u64 & k1, u64 & k2, u64 & c1, u64 & c2)
{
k1 *= c1;
k1 = _rotl64(k1, 23);
k1 *= c2;
h1 ^= k1;
h1 += h2;
h2 = _rotl64(h2, 41);
k2 *= c2;
k2 = _rotl64(k2, 23);
k2 *= c1;
h2 ^= k2;
h2 += h1;
h1 = h1 * 3 + 0x52dce729;
h2 = h2 * 3 + 0x38495ab5;
c1 = c1 * 5 + 0x7b7d159c;
c2 = c2 * 5 + 0x6bce6396;
}
// Finalization mix - avalanches all bits to within 0.05% bias
inline u64 fmix64(u64 k)
{
k ^= k >> 33;
k *= 0xff51afd7ed558ccd;
k ^= k >> 33;
k *= 0xc4ceb9fe1a85ec53;
k ^= k >> 33;
return k;
}
u64 GetMurmurHash3(const u8* src, u32 len, u32 samples)
{
const u8* data = (const u8*)src;
const int nblocks = len / 16;
u32 Step = (len / 8);
if (samples == 0)
samples = std::max(Step, 1u);
Step = Step / samples;
if (Step < 1)
Step = 1;
u64 h1 = 0x9368e53c2f6af274;
u64 h2 = 0x586dcd208f7cd3fd;
u64 c1 = 0x87c37b91114253d5;
u64 c2 = 0x4cf5ad432745937f;
// body
const u64* blocks = (const u64*)(data);
for (int i = 0; i < nblocks; i += Step)
{
u64 k1 = getblock(blocks, i * 2 + 0);
u64 k2 = getblock(blocks, i * 2 + 1);
bmix64(h1, h2, k1, k2, c1, c2);
}
// tail
const u8* tail = (const u8*)(data + nblocks * 16);
u64 k1 = 0;
u64 k2 = 0;
switch (len & 15)
{
case 15: k2 ^= u64(tail[14]) << 48;
case 14: k2 ^= u64(tail[13]) << 40;
case 13: k2 ^= u64(tail[12]) << 32;
case 12: k2 ^= u64(tail[11]) << 24;
case 11: k2 ^= u64(tail[10]) << 16;
case 10: k2 ^= u64(tail[9]) << 8;
case 9: k2 ^= u64(tail[8]) << 0;
case 8: k1 ^= u64(tail[7]) << 56;
case 7: k1 ^= u64(tail[6]) << 48;
case 6: k1 ^= u64(tail[5]) << 40;
case 5: k1 ^= u64(tail[4]) << 32;
case 4: k1 ^= u64(tail[3]) << 24;
case 3: k1 ^= u64(tail[2]) << 16;
case 2: k1 ^= u64(tail[1]) << 8;
case 1: k1 ^= u64(tail[0]) << 0;
bmix64(h1, h2, k1, k2, c1, c2);
};
// finalization
h2 ^= len;
h1 += h2;
h2 += h1;
h1 = fmix64(h1);
h2 = fmix64(h2);
h1 += h2;
return h1;
}
// CRC32 hash using the SSE4.2 instruction
#if defined(_M_X86_64)
<API key>
u64 GetCRC32(const u8* src, u32 len, u32 samples)
{
u64 h[4] = { len, 0, 0, 0 };
u32 Step = (len / 8);
const u64* data = (const u64*)src;
const u64* end = data + Step;
if (samples == 0)
samples = std::max(Step, 1u);
Step = Step / samples;
if (Step < 1)
Step = 1;
while (data < end - Step * 3)
{
h[0] = _mm_crc32_u64(h[0], data[Step * 0]);
h[1] = _mm_crc32_u64(h[1], data[Step * 1]);
h[2] = _mm_crc32_u64(h[2], data[Step * 2]);
h[3] = _mm_crc32_u64(h[3], data[Step * 3]);
data += Step * 4;
}
if (data < end - Step * 0)
h[0] = _mm_crc32_u64(h[0], data[Step * 0]);
if (data < end - Step * 1)
h[1] = _mm_crc32_u64(h[1], data[Step * 1]);
if (data < end - Step * 2)
h[2] = _mm_crc32_u64(h[2], data[Step * 2]);
if (len & 7)
{
u64 temp = 0;
memcpy(&temp, end, len & 7);
h[0] = _mm_crc32_u64(h[0], temp);
}
// FIXME: is there a better way to combine these partial hashes?
return h[0] + (h[1] << 10) + (h[2] << 21) + (h[3] << 32);
}
#elif defined(_M_ARM_64)
u64 GetCRC32(const u8* src, u32 len, u32 samples)
{
u64 h[4] = { len, 0, 0, 0 };
u32 Step = (len / 8);
const u64* data = (const u64*)src;
const u64* end = data + Step;
if (samples == 0)
samples = std::max(Step, 1u);
Step = Step / samples;
if (Step < 1)
Step = 1;
// We should be able to use intrinsics for this
// Too bad the intrinsics for this instruction was added in GCC 4.9.1
// The Android NDK (as of r10e) only has GCC 4.9
// Once the Android NDK has a newer GCC version, update these to use intrinsics
while (data < end - Step * 3)
{
asm("crc32x %w[res], %w[two], %x[three]"
: [res] "=r"(h[0])
: [two] "r"(h[0]), [three] "r"(data[Step * 0]));
asm("crc32x %w[res], %w[two], %x[three]"
: [res] "=r"(h[1])
: [two] "r"(h[1]), [three] "r"(data[Step * 1]));
asm("crc32x %w[res], %w[two], %x[three]"
: [res] "=r"(h[2])
: [two] "r"(h[2]), [three] "r"(data[Step * 2]));
asm("crc32x %w[res], %w[two], %x[three]"
: [res] "=r"(h[3])
: [two] "r"(h[3]), [three] "r"(data[Step * 3]));
data += Step * 4;
}
if (data < end - Step * 0)
asm("crc32x %w[res], %w[two], %x[three]"
: [res] "=r"(h[0])
: [two] "r"(h[0]), [three] "r"(data[Step * 0]));
if (data < end - Step * 1)
asm("crc32x %w[res], %w[two], %x[three]"
: [res] "=r"(h[1])
: [two] "r"(h[1]), [three] "r"(data[Step * 1]));
if (data < end - Step * 2)
asm("crc32x %w[res], %w[two], %x[three]"
: [res] "=r"(h[2])
: [two] "r"(h[2]), [three] "r"(data[Step * 2]));
if (len & 7)
{
u64 temp = 0;
memcpy(&temp, end, len & 7);
asm("crc32x %w[res], %w[two], %x[three]"
: [res] "=r"(h[0])
: [two] "r"(h[0]), [three] "r"(temp));
}
// FIXME: is there a better way to combine these partial hashes?
return h[0] + (h[1] << 10) + (h[2] << 21) + (h[3] << 32);
}
#else
u64 GetCRC32(const u8* src, u32 len, u32 samples)
{
return 0;
}
#endif
/*
* NOTE: This hash function is used for custom texture loading/dumping, so
* it should not be changed, which would require all custom textures to be
* recalculated for their new hash values. If the hashing function is
* changed, make sure this one is still used when the legacy parameter is
* true.
*/
u64 GetHashHiresTexture(const u8* src, u32 len, u32 samples)
{
const u64 m = 0xc6a4a7935bd1e995;
u64 h = len * m;
const int r = 47;
u32 Step = (len / 8);
const u64* data = (const u64*)src;
const u64* end = data + Step;
if (samples == 0)
samples = std::max(Step, 1u);
Step = Step / samples;
if (Step < 1)
Step = 1;
while (data < end)
{
u64 k = data[0];
data += Step;
k *= m;
k ^= k >> r;
k *= m;
h ^= k;
h *= m;
}
const u8 * data2 = (const u8*)end;
switch (len & 7)
{
case 7: h ^= u64(data2[6]) << 48;
case 6: h ^= u64(data2[5]) << 40;
case 5: h ^= u64(data2[4]) << 32;
case 4: h ^= u64(data2[3]) << 24;
case 3: h ^= u64(data2[2]) << 16;
case 2: h ^= u64(data2[1]) << 8;
case 1: h ^= u64(data2[0]);
h *= m;
};
h ^= h >> r;
h *= m;
h ^= h >> r;
return h;
}
#else
// CRC32 hash using the SSE4.2 instruction
#if defined(_M_X86)
<API key>
u64 GetCRC32(const u8* src, u32 len, u32 samples)
{
u32 h = len;
u32 Step = (len / 4);
const u32* data = (const u32*)src;
const u32* end = data + Step;
if (samples == 0)
samples = std::max(Step, 1u);
Step = Step / samples;
if (Step < 1)
Step = 1;
while (data < end)
{
h = _mm_crc32_u32(h, data[0]);
data += Step;
}
const u8* data2 = (const u8*)end;
return (u64)_mm_crc32_u32(h, u32(data2[0]));
}
#else
u64 GetCRC32(const u8* src, u32 len, u32 samples)
{
return 0;
}
#endif
// Block read - if your platform needs to do endian-swapping or can only
// handle aligned reads, do the conversion here
inline u32 getblock(const u32* p, int i)
{
return p[i];
}
// Finalization mix - force all bits of a hash block to avalanche
// avalanches all bits to within 0.25% bias
inline u32 fmix32(u32 h)
{
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
h ^= h >> 16;
return h;
}
inline void bmix32(u32 & h1, u32 & h2, u32 & k1, u32 & k2, u32 & c1, u32 & c2)
{
k1 *= c1;
k1 = _rotl(k1, 11);
k1 *= c2;
h1 ^= k1;
h1 += h2;
h2 = _rotl(h2, 17);
k2 *= c2;
k2 = _rotl(k2, 11);
k2 *= c1;
h2 ^= k2;
h2 += h1;
h1 = h1 * 3 + 0x52dce729;
h2 = h2 * 3 + 0x38495ab5;
c1 = c1 * 5 + 0x7b7d159c;
c2 = c2 * 5 + 0x6bce6396;
}
u64 GetMurmurHash3(const u8* src, u32 len, u32 samples)
{
const u8* data = (const u8*)src;
u32 out[2];
const int nblocks = len / 8;
u32 Step = (len / 4);
if (samples == 0)
samples = std::max(Step, 1u);
Step = Step / samples;
if (Step < 1)
Step = 1;
u32 h1 = 0x8de1c3ac;
u32 h2 = 0xbab98226;
u32 c1 = 0x95543787;
u32 c2 = 0x2ad7eb25;
// body
const u32* blocks = (const u32*)(data + nblocks * 8);
for (int i = -nblocks; i < 0; i += Step)
{
u32 k1 = getblock(blocks, i * 2 + 0);
u32 k2 = getblock(blocks, i * 2 + 1);
bmix32(h1, h2, k1, k2, c1, c2);
}
// tail
const u8* tail = (const u8*)(data + nblocks * 8);
u32 k1 = 0;
u32 k2 = 0;
switch (len & 7)
{
case 7: k2 ^= tail[6] << 16;
case 6: k2 ^= tail[5] << 8;
case 5: k2 ^= tail[4] << 0;
case 4: k1 ^= tail[3] << 24;
case 3: k1 ^= tail[2] << 16;
case 2: k1 ^= tail[1] << 8;
case 1: k1 ^= tail[0] << 0;
bmix32(h1, h2, k1, k2, c1, c2);
};
// finalization
h2 ^= len;
h1 += h2;
h2 += h1;
h1 = fmix32(h1);
h2 = fmix32(h2);
h1 += h2;
h2 += h1;
out[0] = h1;
out[1] = h2;
return *((u64*)&out);
}
/*
* FIXME: The old 32-bit version of this hash made different hashes than the
* 64-bit version. Until someone can make a new version of the 32-bit one that
* makes identical hashes, this is just a c/p of the 64-bit one.
*/
u64 GetHashHiresTexture(const u8* src, u32 len, u32 samples)
{
const u64 m = <API key>;
u64 h = len * m;
const int r = 47;
u32 Step = (len / 8);
const u64* data = (const u64*)src;
const u64* end = data + Step;
if (samples == 0)
samples = std::max(Step, 1u);
Step = Step / samples;
if (Step < 1)
Step = 1;
while (data < end)
{
u64 k = data[0];
data += Step;
k *= m;
k ^= k >> r;
k *= m;
h ^= k;
h *= m;
}
const u8* data2 = (const u8*)end;
switch (len & 7)
{
case 7: h ^= u64(data2[6]) << 48;
case 6: h ^= u64(data2[5]) << 40;
case 5: h ^= u64(data2[4]) << 32;
case 4: h ^= u64(data2[3]) << 24;
case 3: h ^= u64(data2[2]) << 16;
case 2: h ^= u64(data2[1]) << 8;
case 1: h ^= u64(data2[0]);
h *= m;
};
h ^= h >> r;
h *= m;
h ^= h >> r;
return h;
}
#endif
u64 GetHash64(const u8* src, u32 len, u32 samples)
{
return ptrHashFunction(src, len, samples);
}
// sets the hash function used for the texture cache
void SetHash64Function()
{
#if defined(_M_X86_64) || defined(_M_X86)
if (cpu_info.bSSE4_2) // sse crc32 version
{
ptrHashFunction = &GetCRC32;
}
else
#elif defined(_M_ARM_64)
if (cpu_info.bCRC32)
{
ptrHashFunction = &GetCRC32;
}
else
#endif
{
ptrHashFunction = &GetMurmurHash3;
}
} |
--<<card >>
local super = require "script.card.neutral.card163025"
ccard263025 = class("ccard263025",super,{
sid = 263025,
race = 6,
name = "",
type = 201,
magic_immune = 0,
assault = 0,
sneer = 0,
atkcnt = 1,
shield = 0,
warcry = 1,
dieeffect = 0,
sneak = 0,
magic_hurt_adden = 0,
cure_to_hurt = 0,
recoverhp_multi = 1,
magic_hurt_multi = 1,
max_amount = 2,
composechip = 100,
decomposechip = 10,
atk = 2,
maxhp = 2,
crystalcost = 2,
targettype = 22,
halo = nil,
desc = "",
effect = {
onuse = nil,
ondie = nil,
onhurt = nil,
onrecoverhp = nil,
onbeginround = nil,
onendround = nil,
ondelsecret = nil,
onputinwar = nil,
onremovefromwar = nil,
onaddweapon = nil,
onputinhand = nil,
before_die = nil,
after_die = nil,
before_hurt = nil,
after_hurt = nil,
before_recoverhp = nil,
after_recoverhp = nil,
before_beginround = nil,
after_beginround = nil,
before_endround = nil,
after_endround = nil,
before_attack = nil,
after_attack = nil,
before_playcard = nil,
after_playcard = nil,
before_putinwar = nil,
after_putinwar = nil,
<API key> = nil,
after_removefromwar = nil,
before_addsecret = nil,
after_addsecret = nil,
before_delsecret = nil,
after_delsecret = nil,
before_addweapon = nil,
after_addweapon = nil,
before_delweapon = nil,
after_delweapon = nil,
before_putinhand = nil,
after_putinhand = nil,
<API key> = nil,
<API key> = nil,
},
})
function ccard263025:init(conf)
super.init(self,conf)
--<<card >>
end
function ccard263025:load(data)
if not data or not next(data) then
return
end
super.load(self,data)
-- todo: load data
end
function ccard263025:save()
local data = super.save(self)
-- todo: save data
return data
end
return ccard263025 |
<?php
// Moodle - Modular Object-Oriented Dynamic Learning Environment //
// This program is free software; you can redistribute it and/or modify //
// (at your option) any later version. //
// This program is distributed in the hope that it will be useful, //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
require_once($CFG->dirroot.'/message/output/lib.php');
class <API key> extends message_output {
/**
* Processes the message (sends by email).
* @param object $message the message to be sent
*/
function send_message($message) {
global $DB;
//send an email
//if fails saved as read message
//first try to get preference
$usertoemail = <API key>( '<API key>', '', $message->useridto);
//if fails use user profile default
if ( $usertoemail == NULL){
$userto = $DB->get_record('user', array('id' => $message->useridto));
$usertoemail = $userto->email;
}
$userfrom = $DB->get_record('user', array('id' => $message->useridfrom));
if ( email_to_user($usertoemail, $userfrom->email,
$message->subject, $message->fullmessage,
$message->fullmessagehtml)
){
Move the entry to the other table
$message->timeread = time();
$messageid = $message->id;
unset($message->id);
//if there is no more processor that want to process this can move message
if ( $DB->count_records('message_working', array('unreadmessageid' => $messageid)) == 0){
if ($DB->insert_record('message_read', $message)) {
$DB->delete_records('message', array('id' => $messageid));
}
}
}else{
//delete what we've processed and check if can move message
if ( $DB->count_records('message_working', array('unreadmessageid' => $messageid)) == 0){
if ($DB->insert_record('message_read', $message)) {
$DB->delete_records('message', array('id' => $messageid));
}
}
}
return true;
}
/**
* Creates necessary fields in the messaging config form.
* @param object $mform preferences form class
*/
function config_form($preferences){
global $USER;
$string = get_string('email').': <input size="30" name="email_email" value="'.$preferences->email_email.'" />';
if (empty($preferences->email_email)) {
$string .= ' ('.get_string('default').': '.$USER->email.')';
}
return $string;
}
/**
* Parses the form submited data and saves it into preferences array.
* @param object $mform preferences form class
* @param array $preferences preferences array
*/
function process_form($form, &$preferences){
$preferences['<API key>'] = $form->email_email;
}
/**
* Loads the config data from database to put on the form (initial load)
* @param array $preferences preferences array
* @param int $userid the user id
*/
function load_data(&$preferences, $userid){
$preferences->email_email = <API key>( '<API key>', '', $userid);
}
} |
\section{\-Errors and logs handling}
\label{<API key>}\index{\-Errors and logs handling@{\-Errors and logs handling}}
\-Collaboration diagram for \-Errors and logs handling\-:
\subsection*{\-Defines}
\begin{DoxyCompactItemize}
\item
\#define {\bf lldpctl\-\_\-last\-\_\-strerror}(conn)~{\bf lldpctl\-\_\-strerror}({\bf lldpctl\-\_\-last\-\_\-error}(conn))
\end{DoxyCompactItemize}
\subsection*{\-Enumerations}
\begin{DoxyCompactItemize}
\item
enum {\bf lldpctl\-\_\-error\-\_\-t} \{ \*
{\bf \-L\-L\-D\-P\-C\-T\-L\-\_\-\-N\-O\-\_\-\-E\-R\-R\-O\-R} = 0,
{\bf \-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-W\-O\-U\-L\-D\-B\-L\-O\-C\-K} = -\/501,
{\bf \-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-E\-O\-F} = -\/502,
{\bf \-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-N\-O\-T\-\_\-\-E\-X\-I\-S\-T} = -\/503,
\*
{\bf \-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-C\-O\-N\-N\-E\-C\-T} = -\/504,
{\bf \-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-I\-N\-C\-O\-R\-R\-E\-C\-T\-\_\-\-A\-T\-O\-M\-\_\-\-T\-Y\-P\-E} = -\/505,
{\bf \-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-S\-E\-R\-I\-A\-L\-I\-Z\-A\-T\-I\-O\-N} = -\/506,
{\bf \-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-I\-N\-V\-A\-L\-I\-D\-\_\-\-S\-T\-A\-T\-E} = -\/507,
\*
{\bf \-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-I\-T\-E\-R\-A\-T\-E} = -\/508,
{\bf \-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-B\-A\-D\-\_\-\-V\-A\-L\-U\-E} = -\/509,
{\bf \-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-C\-R\-E\-A\-T\-E} = -\/510,
{\bf \-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-F\-A\-T\-A\-L} = -\/900,
\*
{\bf \-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-N\-O\-M\-E\-M} = -\/901,
{\bf \-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-L\-L\-B\-A\-C\-K\-\_\-\-F\-A\-I\-L\-U\-R\-E} = -\/902
\}
\end{DoxyCompactItemize}
\subsection*{\-Functions}
\begin{DoxyCompactItemize}
\item
void {\bf lldpctl\-\_\-log\-\_\-callback} (void($\ast$cb)(int severity, const char $\ast${\bf msg}))
\item
const char $\ast$ {\bf lldpctl\-\_\-strerror} ({\bf lldpctl\-\_\-error\-\_\-t} error)
\item
{\bf lldpctl\-\_\-error\-\_\-t} {\bf lldpctl\-\_\-last\-\_\-error} ({\bf lldpctl\-\_\-conn\-\_\-t} $\ast$conn)
\end{DoxyCompactItemize}
\subsection{\-Detailed \-Description}
\-Error codes and logs handling.
\-When a function returns a pointer, it may return {\ttfamily \-N\-U\-L\-L} to indicate an error condition. \-In this case, it is possible to use \doxyref{lldpctl\-\_\-last\-\_\-error()}{p.}{<API key>} to get the related error code which is one of the values in \doxyref{lldpctl\-\_\-error\-\_\-t}{p.}{<API key>} enumeration. \-For display purpose \doxyref{lldpctl\-\_\-strerror()}{p.}{<API key>} may be used to translate this error code.
\-When a function returns an integer, it may return a negative value. \-It usually means this is an error but some functions may return a legetimate negative value (for example \doxyref{lldpctl\-\_\-atom\-\_\-get\-\_\-int()}{p.}{<API key>}). \-When there is a doubt, \doxyref{lldpctl\-\_\-last\-\_\-error()}{p.}{<API key>} should be checked.
\-An error is attached to a connection. \-If there is no connection, no error handling is available. \-Most functions use a connection or an atom as first argument and therefore are attached to a connection. \-To get the connection related to an atom, use \doxyref{lldpctl\-\_\-atom\-\_\-get\-\_\-connection()}{p.}{<API key>}.
\-Also have a look at \doxyref{lldpctl\-\_\-log\-\_\-callback()}{p.}{<API key>} function if you want a custom log handling.
\subsection{\-Define \-Documentation}
\index{\-Errors and logs handling@{\-Errors and logs handling}!lldpctl\-\_\-last\-\_\-strerror@{lldpctl\-\_\-last\-\_\-strerror}}
\index{lldpctl\-\_\-last\-\_\-strerror@{lldpctl\-\_\-last\-\_\-strerror}!Errors and logs handling@{\-Errors and logs handling}}
\subsubsection[{lldpctl\-\_\-last\-\_\-strerror}]{\setlength{\rightskip}{0pt plus 5cm}\#define {\bf lldpctl\-\_\-last\-\_\-strerror}(
\begin{DoxyParamCaption}
\item[{}]{conn}
\end{DoxyParamCaption}
)~{\bf lldpctl\-\_\-strerror}({\bf lldpctl\-\_\-last\-\_\-error}(conn))}\label{<API key>}
\-Describe the last error associate to a connection.
\begin{DoxyParams}{\-Parameters}
{\em conn} & \-Previously allocated handler to a connection to lldpd. \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{\-Returns}
\-Statically allocated string describing the error
\end{DoxyReturn}
\subsection{\-Enumeration \-Type \-Documentation}
\index{\-Errors and logs handling@{\-Errors and logs handling}!lldpctl\-\_\-error\-\_\-t@{lldpctl\-\_\-error\-\_\-t}}
\index{lldpctl\-\_\-error\-\_\-t@{lldpctl\-\_\-error\-\_\-t}!Errors and logs handling@{\-Errors and logs handling}}
\subsubsection[{lldpctl\-\_\-error\-\_\-t}]{\setlength{\rightskip}{0pt plus 5cm}enum {\bf lldpctl\-\_\-error\-\_\-t}}\label{<API key>}
\-Possible error codes for functions that return negative integers on this purpose or for {\ttfamily \doxyref{lldpctl\-\_\-last\-\_\-error()}{p.}{<API key>}}. \begin{Desc}
\item[\-Enumerator\-: ]\par
\begin{description}
\index{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-N\-O\-\_\-\-E\-R\-R\-O\-R@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-N\-O\-\_\-\-E\-R\-R\-O\-R}!\-Errors and logs handling@{\-Errors and logs handling}}\index{\-Errors and logs handling@{\-Errors and logs handling}!\-L\-L\-D\-P\-C\-T\-L\-\_\-\-N\-O\-\_\-\-E\-R\-R\-O\-R@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-N\-O\-\_\-\-E\-R\-R\-O\-R}}\item[{\em
\-L\-L\-D\-P\-C\-T\-L\-\_\-\-N\-O\-\_\-\-E\-R\-R\-O\-R\label{group__lldpctl__errors__logs_ggad9b373c0bb7b1cf850f5b1901b33e822a86a058533661e23a1fac644808144e3c}
}]\-No error has happened (yet). \index{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-W\-O\-U\-L\-D\-B\-L\-O\-C\-K@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-W\-O\-U\-L\-D\-B\-L\-O\-C\-K}!\-Errors and logs handling@{\-Errors and logs handling}}\index{\-Errors and logs handling@{\-Errors and logs handling}!\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-W\-O\-U\-L\-D\-B\-L\-O\-C\-K@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-W\-O\-U\-L\-D\-B\-L\-O\-C\-K}}\item[{\em
\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-W\-O\-U\-L\-D\-B\-L\-O\-C\-K\label{group__lldpctl__errors__logs_ggad9b373c0bb7b1cf850f5b1901b33e822a29adacee5e8970e0bc3a3e6b95a299ef}
}]\-A \-I\-O related operation would block if performed. \index{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-E\-O\-F@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-E\-O\-F}!\-Errors and logs handling@{\-Errors and logs handling}}\index{\-Errors and logs handling@{\-Errors and logs handling}!\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-E\-O\-F@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-E\-O\-F}}\item[{\em
\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-E\-O\-F\label{group__lldpctl__errors__logs_ggad9b373c0bb7b1cf850f5b1901b33e822abd5dce58f6b3cc46e374c8992414bc82}
}]\-A \-I\-O related operation has reached a end of file condition. \index{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-N\-O\-T\-\_\-\-E\-X\-I\-S\-T@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-N\-O\-T\-\_\-\-E\-X\-I\-S\-T}!\-Errors and logs handling@{\-Errors and logs handling}}\index{\-Errors and logs handling@{\-Errors and logs handling}!\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-N\-O\-T\-\_\-\-E\-X\-I\-S\-T@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-N\-O\-T\-\_\-\-E\-X\-I\-S\-T}}\item[{\em
\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-N\-O\-T\-\_\-\-E\-X\-I\-S\-T\label{group__lldpctl__errors__logs_ggad9b373c0bb7b1cf850f5b1901b33e822a115bfa1f1be7bc1d86d269a69f311415}
}]\-The requested information does not exist. \-For example, when requesting an inexistant information from an atom. \index{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-C\-O\-N\-N\-E\-C\-T@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-C\-O\-N\-N\-E\-C\-T}!\-Errors and logs handling@{\-Errors and logs handling}}\index{\-Errors and logs handling@{\-Errors and logs handling}!\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-C\-O\-N\-N\-E\-C\-T@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-C\-O\-N\-N\-E\-C\-T}}\item[{\em
\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-C\-O\-N\-N\-E\-C\-T\label{group__lldpctl__errors__logs_ggad9b373c0bb7b1cf850f5b1901b33e822a18924712f405037e2ae3f30601a7a838}
}]\-Cannot connect to the lldpd daemon. \-This error only happens with default synchronous handlers. \index{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-I\-N\-C\-O\-R\-R\-E\-C\-T\-\_\-\-A\-T\-O\-M\-\_\-\-T\-Y\-P\-E@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-I\-N\-C\-O\-R\-R\-E\-C\-T\-\_\-\-A\-T\-O\-M\-\_\-\-T\-Y\-P\-E}!\-Errors and logs handling@{\-Errors and logs handling}}\index{\-Errors and logs handling@{\-Errors and logs handling}!\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-I\-N\-C\-O\-R\-R\-E\-C\-T\-\_\-\-A\-T\-O\-M\-\_\-\-T\-Y\-P\-E@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-I\-N\-C\-O\-R\-R\-E\-C\-T\-\_\-\-A\-T\-O\-M\-\_\-\-T\-Y\-P\-E}}\item[{\em
\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-I\-N\-C\-O\-R\-R\-E\-C\-T\-\_\-\-A\-T\-O\-M\-\_\-\-T\-Y\-P\-E\label{group__lldpctl__errors__logs_ggad9b373c0bb7b1cf850f5b1901b33e822a576e5eff5f89035313a1ca0ca0fee462}
}]\-Atom is of incorrect type for the requested operation. \index{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-S\-E\-R\-I\-A\-L\-I\-Z\-A\-T\-I\-O\-N@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-S\-E\-R\-I\-A\-L\-I\-Z\-A\-T\-I\-O\-N}!\-Errors and logs handling@{\-Errors and logs handling}}\index{\-Errors and logs handling@{\-Errors and logs handling}!\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-S\-E\-R\-I\-A\-L\-I\-Z\-A\-T\-I\-O\-N@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-S\-E\-R\-I\-A\-L\-I\-Z\-A\-T\-I\-O\-N}}\item[{\em
\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-S\-E\-R\-I\-A\-L\-I\-Z\-A\-T\-I\-O\-N\label{group__lldpctl__errors__logs_ggad9b373c0bb7b1cf850f5b1901b33e822ab7289f09cb2d6c1dd8d107f5e5f095fd}
}]\-An error occurred during serialization of message. \index{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-I\-N\-V\-A\-L\-I\-D\-\_\-\-S\-T\-A\-T\-E@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-I\-N\-V\-A\-L\-I\-D\-\_\-\-S\-T\-A\-T\-E}!\-Errors and logs handling@{\-Errors and logs handling}}\index{\-Errors and logs handling@{\-Errors and logs handling}!\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-I\-N\-V\-A\-L\-I\-D\-\_\-\-S\-T\-A\-T\-E@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-I\-N\-V\-A\-L\-I\-D\-\_\-\-S\-T\-A\-T\-E}}\item[{\em
\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-I\-N\-V\-A\-L\-I\-D\-\_\-\-S\-T\-A\-T\-E\label{group__lldpctl__errors__logs_ggad9b373c0bb7b1cf850f5b1901b33e822ac708f4faeb630abcff3ba19b5deeafe1}
}]\-The requested operation cannot be performed because we have another operation already running. \index{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-I\-T\-E\-R\-A\-T\-E@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-I\-T\-E\-R\-A\-T\-E}!\-Errors and logs handling@{\-Errors and logs handling}}\index{\-Errors and logs handling@{\-Errors and logs handling}!\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-I\-T\-E\-R\-A\-T\-E@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-I\-T\-E\-R\-A\-T\-E}}\item[{\em
\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-I\-T\-E\-R\-A\-T\-E\label{group__lldpctl__errors__logs_ggad9b373c0bb7b1cf850f5b1901b33e822aeaf981f3f0778ce569d505efd6058736}
}]\-The provided atom cannot be iterated. \index{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-B\-A\-D\-\_\-\-V\-A\-L\-U\-E@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-B\-A\-D\-\_\-\-V\-A\-L\-U\-E}!\-Errors and logs handling@{\-Errors and logs handling}}\index{\-Errors and logs handling@{\-Errors and logs handling}!\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-B\-A\-D\-\_\-\-V\-A\-L\-U\-E@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-B\-A\-D\-\_\-\-V\-A\-L\-U\-E}}\item[{\em
\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-B\-A\-D\-\_\-\-V\-A\-L\-U\-E\label{group__lldpctl__errors__logs_ggad9b373c0bb7b1cf850f5b1901b33e822a797376fa40d5b4d32f1899fef7ce68c9}
}]\-The provided value is invalid. \index{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-C\-R\-E\-A\-T\-E@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-C\-R\-E\-A\-T\-E}!\-Errors and logs handling@{\-Errors and logs handling}}\index{\-Errors and logs handling@{\-Errors and logs handling}!\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-C\-R\-E\-A\-T\-E@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-C\-R\-E\-A\-T\-E}}\item[{\em
\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-N\-N\-O\-T\-\_\-\-C\-R\-E\-A\-T\-E\label{group__lldpctl__errors__logs_ggad9b373c0bb7b1cf850f5b1901b33e822a90971aae52e1aeefe06ca231d625a8a7}
}]\-No new element can be created for this element. \index{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-F\-A\-T\-A\-L@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-F\-A\-T\-A\-L}!\-Errors and logs handling@{\-Errors and logs handling}}\index{\-Errors and logs handling@{\-Errors and logs handling}!\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-F\-A\-T\-A\-L@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-F\-A\-T\-A\-L}}\item[{\em
\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-F\-A\-T\-A\-L\label{group__lldpctl__errors__logs_ggad9b373c0bb7b1cf850f5b1901b33e822ae0814fd7ee7ea913f1f89d5cf24b9a07}
}]\-The library is under unexpected conditions and cannot process any further data reliably. \index{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-N\-O\-M\-E\-M@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-N\-O\-M\-E\-M}!\-Errors and logs handling@{\-Errors and logs handling}}\index{\-Errors and logs handling@{\-Errors and logs handling}!\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-N\-O\-M\-E\-M@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-N\-O\-M\-E\-M}}\item[{\em
\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-N\-O\-M\-E\-M\label{group__lldpctl__errors__logs_ggad9b373c0bb7b1cf850f5b1901b33e822a5e96a41552fd290493e2610c620141f1}
}]\-Out of memory condition. \-Things may get havoc here but we should be able to recover. \index{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-L\-L\-B\-A\-C\-K\-\_\-\-F\-A\-I\-L\-U\-R\-E@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-L\-L\-B\-A\-C\-K\-\_\-\-F\-A\-I\-L\-U\-R\-E}!\-Errors and logs handling@{\-Errors and logs handling}}\index{\-Errors and logs handling@{\-Errors and logs handling}!\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-L\-L\-B\-A\-C\-K\-\_\-\-F\-A\-I\-L\-U\-R\-E@{\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-L\-L\-B\-A\-C\-K\-\_\-\-F\-A\-I\-L\-U\-R\-E}}\item[{\em
\-L\-L\-D\-P\-C\-T\-L\-\_\-\-E\-R\-R\-\_\-\-C\-A\-L\-L\-B\-A\-C\-K\-\_\-\-F\-A\-I\-L\-U\-R\-E\label{group__lldpctl__errors__logs_ggad9b373c0bb7b1cf850f5b1901b33e822ab853925dc583e4e7f0a9385ad8a1c93b}
}]\-An error occurred in a user provided callback. \end{description}
\end{Desc}
\subsection{\-Function \-Documentation}
\index{\-Errors and logs handling@{\-Errors and logs handling}!lldpctl\-\_\-last\-\_\-error@{lldpctl\-\_\-last\-\_\-error}}
\index{lldpctl\-\_\-last\-\_\-error@{lldpctl\-\_\-last\-\_\-error}!Errors and logs handling@{\-Errors and logs handling}}
\subsubsection[{lldpctl\-\_\-last\-\_\-error}]{\setlength{\rightskip}{0pt plus 5cm}{\bf lldpctl\-\_\-error\-\_\-t} {\bf lldpctl\-\_\-last\-\_\-error} (
\begin{DoxyParamCaption}
\item[{{\bf lldpctl\-\_\-conn\-\_\-t} $\ast$}]{conn}
\end{DoxyParamCaption}
)}\label{<API key>}
\-Get the last error associated to a connection to lldpd.
\begin{DoxyParams}{\-Parameters}
{\em conn} & \-Previously allocated handler to a connection to lldpd. \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{\-Returns}
0 if no error is currently registered. \-A negative integer otherwise.
\end{DoxyReturn}
\-For functions returning int, this function will return the same error number. \-For functions returning something else, you can use this function to get the appropriate error number.
\-Here is the caller graph for this function\-:
\index{\-Errors and logs handling@{\-Errors and logs handling}!lldpctl\-\_\-log\-\_\-callback@{lldpctl\-\_\-log\-\_\-callback}}
\index{lldpctl\-\_\-log\-\_\-callback@{lldpctl\-\_\-log\-\_\-callback}!Errors and logs handling@{\-Errors and logs handling}}
\subsubsection[{lldpctl\-\_\-log\-\_\-callback}]{\setlength{\rightskip}{0pt plus 5cm}void {\bf lldpctl\-\_\-log\-\_\-callback} (
\begin{DoxyParamCaption}
\item[{void($\ast$)(int severity, const char $\ast${\bf msg})}]{cb}
\end{DoxyParamCaption}
)}\label{<API key>}
\-Setup log handlers.
\-By default, liblldpctl will log to stderr. \-The following function will register another callback for this purpose. \-Messages logged through this callback may be cryptic. \-They are targeted for the developer. \-Message for end users should rely on return codes. \index{\-Errors and logs handling@{\-Errors and logs handling}!lldpctl\-\_\-strerror@{lldpctl\-\_\-strerror}}
\index{lldpctl\-\_\-strerror@{lldpctl\-\_\-strerror}!Errors and logs handling@{\-Errors and logs handling}}
\subsubsection[{lldpctl\-\_\-strerror}]{\setlength{\rightskip}{0pt plus 5cm}const char$\ast$ {\bf lldpctl\-\_\-strerror} (
\begin{DoxyParamCaption}
\item[{{\bf lldpctl\-\_\-error\-\_\-t}}]{error}
\end{DoxyParamCaption}
)}\label{<API key>}
\-Describe a provided error code.
\begin{DoxyParams}{\-Parameters}
{\em error} & \-Error code to be described. \\
\hline
\end{DoxyParams}
\begin{DoxyReturn}{\-Returns}
\-Statically allocated string describing the error.
\end{DoxyReturn} |
/*
* @file gtkstatusbox.c GTK+ Status Selection Widget
* @ingroup pidgin
*/
/*
* The status box is made up of two main pieces:
* - The box that displays the current status, which is made
* of a GtkListStore ("status_box->store") and GtkCellView
* ("status_box->cell_view"). There is always exactly 1 row
* in this list store. Only the TYPE_ICON and TYPE_TEXT
* columns are used in this list store.
* - The dropdown menu that lets users select a status, which
* is made of a GtkComboBox ("status_box") and GtkListStore
* ("status_box->dropdown_store"). This dropdown is shown
* when the user clicks on the box that displays the current
* status. This list store contains one row for Available,
* one row for Away, etc., a few rows for popular statuses,
* and the "New..." and "Saved..." options.
*/
#include <gdk/gdkkeysyms.h>
#include "internal.h"
#include "account.h"
#include "buddyicon.h"
#include "core.h"
#include "imgstore.h"
#include "network.h"
#include "request.h"
#include "savedstatuses.h"
#include "status.h"
#include "debug.h"
#include "pidgin.h"
#include "gtksavedstatuses.h"
#include "pidginstock.h"
#include "gtkstatusbox.h"
#include "gtkutils.h"
#ifdef USE_GTKSPELL
# include <gtkspell/gtkspell.h>
# ifdef _WIN32
# include "wspell.h"
# endif
#endif
#define TYPING_TIMEOUT 4000
static void imhtml_changed_cb(GtkTextBuffer *buffer, void *data);
static void <API key>(GtkIMHtml *imhtml, GtkIMHtmlButtons buttons, void *data);
static void remove_typing_cb(PidginStatusBox *box);
static void update_size (PidginStatusBox *box);
static gint get_statusbox_index(PidginStatusBox *box, PurpleSavedStatus *saved_status);
static PurpleAccount* <API key>(void);
static void <API key>(PidginStatusBox *status_box);
static void <API key>(PidginStatusBox *status_box);
static void <API key>(PidginStatusBox *status_box);
static void <API key>(PidginStatusBox *status_box);
static void <API key>(PidginStatusBox *box);
static void <API key> (GtkWidget *widget, GtkRequisition *requisition);
static void <API key> (GtkWidget *widget, GtkAllocation *allocation);
static gboolean <API key> (GtkWidget *widget, GdkEventExpose *event);
static void <API key>(PidginStatusBox *status_box);
static void <API key> (GtkContainer *container, gboolean include_internals, GtkCallback callback, gpointer callback_data);
static void <API key>(PidginStatusBox *box);
static void <API key>(PidginStatusBox *box);
static void do_colorshift (GdkPixbuf *dest, GdkPixbuf *src, int shift);
static void icon_choose_cb(const char *filename, gpointer data);
static void <API key>(GtkWidget *w, PidginStatusBox *box);
enum {
/** A <API key> */
TYPE_COLUMN,
/**
* This is a GdkPixbuf (the other columns are strings).
* This column is visible.
*/
ICON_COLUMN,
/** The text displayed on the status box. This column is visible. */
TEXT_COLUMN,
/** The plain-English title of this item */
TITLE_COLUMN,
/** A plain-English description of this item */
DESC_COLUMN,
/**
* This value depends on TYPE_COLUMN. For POPULAR types,
* this is the creation time. For PRIMITIVE types,
* this is the <API key>.
*/
DATA_COLUMN,
/**
* This column stores the GdkPixbuf for the status emblem. Currently only 'saved' is stored.
* In the GtkTreeModel for the dropdown, this is the stock-id (gchararray), and for the
* GtkTreeModel for the cell_view (for the account-specific statusbox), this is the prpl-icon
* (GdkPixbuf) of the account.
*/
EMBLEM_COLUMN,
/**
* This column stores whether to show the emblem.
*/
<API key>,
NUM_COLUMNS
};
enum {
PROP_0,
PROP_ACCOUNT,
PROP_ICON_SEL,
};
GtkContainerClass *parent_class = NULL;
static void <API key> (<API key> *klass);
static void <API key> (PidginStatusBox *status_box);
GType
<API key> (void)
{
static GType status_box_type = 0;
if (!status_box_type)
{
static const GTypeInfo status_box_info =
{
sizeof (<API key>),
NULL, /* base_init */
NULL, /* base_finalize */
(GClassInitFunc) <API key>,
NULL, /* class_finalize */
NULL, /* class_data */
sizeof (PidginStatusBox),
0,
(GInstanceInitFunc) <API key>,
NULL /* value_table */
};
status_box_type = <API key>(GTK_TYPE_CONTAINER,
"PidginStatusBox",
&status_box_info,
0);
}
return status_box_type;
}
static void
<API key>(GObject *object, guint param_id,
GValue *value, GParamSpec *psec)
{
PidginStatusBox *statusbox = PIDGIN_STATUS_BOX(object);
switch (param_id) {
case PROP_ACCOUNT:
g_value_set_pointer(value, statusbox->account);
break;
case PROP_ICON_SEL:
g_value_set_boolean(value, statusbox->icon_box != NULL);
break;
default:
<API key>(object, param_id, psec);
break;
}
}
static void
<API key>(PidginStatusBox *status_box, PurpleAccount *account, PurpleStatus *newstatus)
{
GList *l;
int status_no = -1;
const PurpleStatusType *statustype = NULL;
const char *message;
statustype = <API key>((GList *)<API key>(account),
(char *)<API key>(<API key>(newstatus)));
for (l = <API key>(account); l != NULL; l = l->next) {
PurpleStatusType *status_type = (PurpleStatusType *)l->data;
if (!<API key>(status_type) ||
<API key>(status_type))
continue;
status_no++;
if (statustype == status_type)
break;
}
if (status_no != -1) {
GtkTreePath *path;
<API key>(GTK_WIDGET(status_box), FALSE);
path = <API key>(status_no, -1);
if (status_box->active_row)
<API key>(status_box->active_row);
status_box->active_row = <API key>(GTK_TREE_MODEL(status_box->dropdown_store), path);
gtk_tree_path_free(path);
message = <API key>(newstatus, "message");
if (!message || !*message)
{
gtk_widget_hide_all(status_box->vbox);
status_box->imhtml_visible = FALSE;
}
else
{
gtk_widget_show_all(status_box->vbox);
status_box->imhtml_visible = TRUE;
gtk_imhtml_clear(GTK_IMHTML(status_box->imhtml));
<API key>(GTK_IMHTML(status_box->imhtml));
<API key>(GTK_IMHTML(status_box->imhtml), message, 0);
}
<API key>(GTK_WIDGET(status_box), TRUE);
<API key>(status_box);
}
}
static void
<API key>(PurpleAccount *account, PurpleStatus *oldstatus, PurpleStatus *newstatus, PidginStatusBox *status_box)
{
if (status_box->account == account)
<API key>(status_box, account, newstatus);
else if (status_box-><API key> == account)
<API key>(status_box);
}
static gboolean
icon_box_press_cb(GtkWidget *widget, GdkEventButton *event, PidginStatusBox *box)
{
if (event->button == 3) {
GtkWidget *menu_item;
if (box->icon_box_menu)
gtk_widget_destroy(box->icon_box_menu);
box->icon_box_menu = gtk_menu_new();
menu_item = <API key>(box->icon_box_menu, _("Remove"), GTK_STOCK_REMOVE,
G_CALLBACK(<API key>),
box, 0, 0, NULL);
if (<API key>(PIDGIN_PREFS_ROOT "/accounts/buddyicon") == NULL)
<API key>(menu_item, FALSE);
gtk_menu_popup(GTK_MENU(box->icon_box_menu), NULL, NULL, NULL, NULL,
event->button, event->time);
} else {
if (box->buddy_icon_sel) {
gtk_window_present(GTK_WINDOW(box->buddy_icon_sel));
return FALSE;
}
box->buddy_icon_sel = <API key>(GTK_WINDOW(<API key>(widget)), icon_choose_cb, box);
gtk_widget_show_all(box->buddy_icon_sel);
}
return FALSE;
}
static void
icon_box_dnd_cb(GtkWidget *widget, GdkDragContext *dc, gint x, gint y,
GtkSelectionData *sd, guint info, guint t, PidginStatusBox *box)
{
gchar *name = (gchar *)sd->data;
if ((sd->length >= 0) && (sd->format == 8)) {
/* Well, it looks like the drag event was cool.
* Let's do something with it */
if (!g_ascii_strncasecmp(name, "file:
GError *converr = NULL;
gchar *tmp, *rtmp;
if(!(tmp = g_filename_from_uri(name, NULL, &converr))) {
purple_debug(PURPLE_DEBUG_ERROR, "buddyicon", "%s\n",
(converr ? converr->message :
"g_filename_from_uri error"));
return;
}
if ((rtmp = strchr(tmp, '\r')) || (rtmp = strchr(tmp, '\n')))
*rtmp = '\0';
icon_choose_cb(tmp, box);
g_free(tmp);
}
gtk_drag_finish(dc, TRUE, FALSE, t);
}
gtk_drag_finish(dc, FALSE, FALSE, t);
}
static void
statusbox_got_url(<API key> *url_data, gpointer user_data,
const gchar *themedata, size_t len, const gchar *error_message)
{
FILE *f;
gchar *path;
size_t wc;
if ((error_message != NULL) || (len == 0))
return;
f = purple_mkstemp(&path, TRUE);
wc = fwrite(themedata, len, 1, f);
if (wc != 1) {
<API key>("theme_got_url", "Unable to write theme data.\n");
fclose(f);
g_unlink(path);
g_free(path);
return;
}
fclose(f);
icon_choose_cb(path, user_data);
g_unlink(path);
g_free(path);
}
static gboolean
<API key>(const char *proto, const char *cmd, GHashTable *params, void *data)
{
const char *src;
if (g_ascii_strcasecmp(proto, "aim"))
return FALSE;
if (g_ascii_strcasecmp(cmd, "buddyicon"))
return FALSE;
src = g_hash_table_lookup(params, "account");
if (src == NULL)
return FALSE;
<API key>(src, TRUE, NULL, FALSE, statusbox_got_url, data);
return TRUE;
}
static gboolean
icon_box_enter_cb(GtkWidget *widget, GdkEventCrossing *event, PidginStatusBox *box)
{
<API key>(widget->window, box->hand_cursor);
<API key>(GTK_IMAGE(box->icon), box->buddy_icon_hover);
return FALSE;
}
static gboolean
icon_box_leave_cb(GtkWidget *widget, GdkEventCrossing *event, PidginStatusBox *box)
{
<API key>(widget->window, box->arrow_cursor);
<API key>(GTK_IMAGE(box->icon), box->buddy_icon) ;
return FALSE;
}
static const GtkTargetEntry dnd_targets[] = {
{"text/plain", 0, 0},
{"text/uri-list", 0, 1},
{"STRING", 0, 2}
};
static void
setup_icon_box(PidginStatusBox *status_box)
{
if (status_box->icon_box != NULL)
return;
status_box->icon = gtk_image_new();
status_box->icon_box = gtk_event_box_new();
<API key>(status_box->icon_box, GTK_WIDGET(status_box));
gtk_widget_show(status_box->icon_box);
#if GTK_CHECK_VERSION(2,12,0)
<API key>(status_box->icon_box,
status_box->account ? _("Click to change your buddyicon for this account.") :
_("Click to change your buddyicon for all accounts."));
#endif
if (status_box->account &&
!<API key>(status_box->account, "<API key>", TRUE))
{
PurpleStoredImage *img = <API key>(status_box->account);
<API key>(status_box, img);
<API key>(img);
}
else
{
const char *filename = <API key>(PIDGIN_PREFS_ROOT "/accounts/buddyicon");
PurpleStoredImage *img = NULL;
if (filename != NULL)
img = <API key>(filename);
<API key>(status_box, img);
if (img)
/*
* purple_imgstore_new gives us a reference and
* <API key> also takes one.
*/
<API key>(img);
}
status_box->hand_cursor = gdk_cursor_new (GDK_HAND2);
status_box->arrow_cursor = gdk_cursor_new (GDK_LEFT_PTR);
/* Set up DND */
gtk_drag_dest_set(status_box->icon_box,
<API key> |
<API key>,
dnd_targets,
sizeof(dnd_targets) / sizeof(GtkTargetEntry),
GDK_ACTION_COPY);
g_signal_connect(G_OBJECT(status_box->icon_box), "drag_data_received", G_CALLBACK(icon_box_dnd_cb), status_box);
g_signal_connect(G_OBJECT(status_box->icon_box), "enter-notify-event", G_CALLBACK(icon_box_enter_cb), status_box);
g_signal_connect(G_OBJECT(status_box->icon_box), "leave-notify-event", G_CALLBACK(icon_box_leave_cb), status_box);
g_signal_connect(G_OBJECT(status_box->icon_box), "button-press-event", G_CALLBACK(icon_box_press_cb), status_box);
gtk_container_add(GTK_CONTAINER(status_box->icon_box), status_box->icon);
gtk_widget_show(status_box->icon);
}
static void
destroy_icon_box(PidginStatusBox *statusbox)
{
if (statusbox->icon_box == NULL)
return;
gtk_widget_destroy(statusbox->icon_box);
gdk_cursor_unref(statusbox->hand_cursor);
gdk_cursor_unref(statusbox->arrow_cursor);
<API key>(statusbox->buddy_icon_img);
g_object_unref(G_OBJECT(statusbox->buddy_icon));
g_object_unref(G_OBJECT(statusbox->buddy_icon_hover));
if (statusbox->buddy_icon_sel)
gtk_widget_destroy(statusbox->buddy_icon_sel);
if (statusbox->icon_box_menu)
gtk_widget_destroy(statusbox->icon_box_menu);
statusbox->icon = NULL;
statusbox->icon_box = NULL;
statusbox->icon_box_menu = NULL;
statusbox->buddy_icon_img = NULL;
statusbox->buddy_icon = NULL;
statusbox->buddy_icon_hover = NULL;
statusbox->hand_cursor = NULL;
statusbox->arrow_cursor = NULL;
}
static void
<API key>(GObject *object, guint param_id,
const GValue *value, GParamSpec *pspec)
{
PidginStatusBox *statusbox = PIDGIN_STATUS_BOX(object);
switch (param_id) {
case PROP_ICON_SEL:
if (g_value_get_boolean(value)) {
if (statusbox->account) {
PurplePlugin *plug = <API key>(<API key>(statusbox->account));
if (plug) {
<API key> *prplinfo = <API key>(plug);
if (prplinfo && prplinfo->icon_spec.format != NULL)
setup_icon_box(statusbox);
}
} else {
setup_icon_box(statusbox);
}
} else {
destroy_icon_box(statusbox);
}
break;
case PROP_ACCOUNT:
statusbox->account = g_value_get_pointer(value);
if (statusbox->account)
statusbox-><API key> = NULL;
else
statusbox-><API key> = <API key>();
<API key>(statusbox);
break;
default:
<API key>(object, param_id, pspec);
break;
}
}
static void
<API key>(GObject *obj)
{
PidginStatusBox *statusbox = PIDGIN_STATUS_BOX(obj);
int i;
<API key>(statusbox);
<API key>(statusbox);
destroy_icon_box(statusbox);
if (statusbox->active_row)
<API key>(statusbox->active_row);
for (i = 0; i < G_N_ELEMENTS(statusbox->connecting_pixbufs); i++) {
if (statusbox->connecting_pixbufs[i] != NULL)
gdk_pixbuf_unref(statusbox->connecting_pixbufs[i]);
}
for (i = 0; i < G_N_ELEMENTS(statusbox->typing_pixbufs); i++) {
if (statusbox->typing_pixbufs[i] != NULL)
gdk_pixbuf_unref(statusbox->typing_pixbufs[i]);
}
g_object_unref(G_OBJECT(statusbox->store));
g_object_unref(G_OBJECT(statusbox->dropdown_store));
G_OBJECT_CLASS(parent_class)->finalize(obj);
}
static GType
<API key> (GtkContainer *container)
{
return GTK_TYPE_WIDGET;
}
static void
<API key> (<API key> *klass)
{
GObjectClass *object_class;
GtkWidgetClass *widget_class;
GtkContainerClass *container_class = (GtkContainerClass*)klass;
parent_class = <API key>(klass);
widget_class = (GtkWidgetClass*)klass;
widget_class->size_request = <API key>;
widget_class->size_allocate = <API key>;
widget_class->expose_event = <API key>;
container_class->child_type = <API key>;
container_class->forall = <API key>;
container_class->remove = NULL;
object_class = (GObjectClass *)klass;
object_class->finalize = <API key>;
object_class->get_property = <API key>;
object_class->set_property = <API key>;
<API key>(object_class,
PROP_ACCOUNT,
<API key>("account",
"Account",
"The account, or NULL for all accounts",
G_PARAM_READWRITE
)
);
<API key>(object_class,
PROP_ICON_SEL,
<API key>("iconsel",
"Icon Selector",
"Whether the icon selector should be displayed or not.",
FALSE,
G_PARAM_READWRITE
)
);
}
static GdkPixbuf *
<API key>(PidginStatusBox *status_box, <API key> prim)
{
GdkPixbuf *pixbuf;
GtkIconSize icon_size = <API key>(<API key>);
if (prim == <API key>)
pixbuf = <API key> (GTK_WIDGET(status_box), <API key>,
icon_size, "PidginStatusBox");
else if (prim == PURPLE_STATUS_AWAY)
pixbuf = <API key> (GTK_WIDGET(status_box), <API key>,
icon_size, "PidginStatusBox");
else if (prim == <API key>)
pixbuf = <API key> (GTK_WIDGET(status_box), <API key>,
icon_size, "PidginStatusBox");
else if (prim == <API key>)
pixbuf = <API key> (GTK_WIDGET(status_box), <API key>,
icon_size, "PidginStatusBox");
else if (prim == <API key>)
pixbuf = <API key> (GTK_WIDGET(status_box), <API key>,
icon_size, "PidginStatusBox");
else
pixbuf = <API key> (GTK_WIDGET(status_box), <API key>,
icon_size, "PidginStatusBox");
return pixbuf;
}
/**
* This updates the text displayed on the status box so that it shows
* the current status. This is the only function in this file that
* should modify status_box->store
*/
static void
<API key>(PidginStatusBox *status_box)
{
GtkIconSize icon_size;
GtkStyle *style;
char aa_color[8];
PurpleSavedStatus *saved_status;
char *primary, *secondary, *text;
GdkPixbuf *pixbuf, *emblem = NULL;
GtkTreePath *path;
gboolean account_status = FALSE;
PurpleAccount *acct = (status_box->account) ? status_box->account : status_box-><API key>;
icon_size = <API key>(<API key>);
style = <API key>(GTK_WIDGET(status_box));
snprintf(aa_color, sizeof(aa_color), "#%02x%02x%02x",
style->text_aa[GTK_STATE_NORMAL].red >> 8,
style->text_aa[GTK_STATE_NORMAL].green >> 8,
style->text_aa[GTK_STATE_NORMAL].blue >> 8);
saved_status = <API key>();
if (status_box->account || (status_box-><API key>
&& <API key>(saved_status)))
account_status = TRUE;
/* Primary */
if (status_box->typing != 0)
{
GtkTreeIter iter;
<API key> type;
gpointer data;
/* Primary (get the status selected in the dropdown) */
path = <API key>(status_box->active_row);
if (!<API key> (GTK_TREE_MODEL(status_box->dropdown_store), &iter, path))
return;
gtk_tree_path_free(path);
gtk_tree_model_get(GTK_TREE_MODEL(status_box->dropdown_store), &iter,
TYPE_COLUMN, &type,
DATA_COLUMN, &data,
-1);
if (type == <API key>)
primary = g_strdup(<API key>(GPOINTER_TO_INT(data)));
else
/* This should never happen, but just in case... */
primary = g_strdup("New status");
}
else if (account_status)
primary = g_strdup(<API key>(<API key>(acct)));
else if (<API key>(saved_status))
primary = g_strdup(<API key>(<API key>(saved_status)));
else
primary = <API key>(<API key>(saved_status), -1);
/* Secondary */
if (status_box->typing != 0)
secondary = g_strdup(_("Typing"));
else if (status_box->connecting)
secondary = g_strdup(_("Connecting"));
else if (!status_box->network_available)
secondary = g_strdup(_("Waiting for network connection"));
else if (<API key>(saved_status))
secondary = NULL;
else
{
const char *message;
char *tmp;
message = <API key>(saved_status);
if (message != NULL)
{
tmp = <API key>(message);
<API key>(tmp, '\n', ' ');
secondary = <API key>(tmp, -1);
g_free(tmp);
}
else
secondary = NULL;
}
/* Pixbuf */
if (status_box->typing != 0)
pixbuf = status_box->typing_pixbufs[status_box->typing_index];
else if (status_box->connecting)
pixbuf = status_box->connecting_pixbufs[status_box->connecting_index];
else
{
PurpleStatusType *status_type;
<API key> prim;
if (account_status) {
status_type = <API key>(<API key>(acct));
prim = <API key>(status_type);
} else {
prim = <API key>(saved_status);
}
pixbuf = <API key>(status_box, prim);
}
if (status_box->account != NULL) {
text = g_strdup_printf("%s - <span size=\"smaller\" color=\"%s\">%s</span>",
<API key>(status_box->account),
aa_color, secondary ? secondary : primary);
emblem = <API key>(status_box->account, <API key>);
} else if (secondary != NULL) {
text = g_strdup_printf("%s<span size=\"smaller\" color=\"%s\"> - %s</span>",
primary, aa_color, secondary);
} else {
text = g_strdup(primary);
}
g_free(primary);
g_free(secondary);
/*
* Only two columns are used in this list store (does it
* really need to be a list store?)
*/
gtk_list_store_set(status_box->store, &(status_box->iter),
ICON_COLUMN, pixbuf,
TEXT_COLUMN, text,
EMBLEM_COLUMN, emblem,
<API key>, (emblem != NULL),
-1);
if ((status_box->typing == 0) && (!status_box->connecting))
g_object_unref(pixbuf);
g_free(text);
if (emblem)
g_object_unref(emblem);
/* Make sure to activate the only row in the tree view */
path = <API key>("0");
<API key>(GTK_CELL_VIEW(status_box->cell_view), path);
gtk_tree_path_free(path);
update_size(status_box);
}
static PurpleStatusType *
<API key>(const PurpleAccount *account, gint active)
{
GList *l = <API key>(account);
gint i;
for (i = 0; l; l = l->next) {
PurpleStatusType *status_type = l->data;
if (!<API key>(status_type) ||
<API key>(status_type))
continue;
if (active == i)
return status_type;
i++;
}
return NULL;
}
/**
* This updates the GtkTreeView so that it correctly shows the state
* we are currently using. It is used when the current state is
* updated from somewhere other than the GtkStatusBox (from a plugin,
* or when signing on with the "-n" option, for example). It is
* also used when the user selects the "New..." option.
*
* Maybe we could accomplish this by triggering off the mouse and
* keyboard signals instead of the changed signal?
*/
static void
<API key>(PidginStatusBox *status_box)
{
PurpleSavedStatus *saved_status;
<API key> primitive;
gint index;
const char *message;
GtkTreePath *path = NULL;
/* this function is inappropriate for ones with accounts */
if (status_box->account)
return;
saved_status = <API key>();
/*
* Suppress the "changed" signal because the status
* was changed programmatically.
*/
<API key>(GTK_WIDGET(status_box), FALSE);
/*
* If there is a token-account, then select the primitive from the
* dropdown using a loop. Otherwise select from the default list.
*/
primitive = <API key>(saved_status);
if (!status_box-><API key> && <API key>(saved_status) &&
((primitive == <API key>) || (primitive == PURPLE_STATUS_AWAY) ||
(primitive == <API key>) || (primitive == <API key>) ||
(primitive == <API key>)) &&
(!<API key>(saved_status)))
{
index = get_statusbox_index(status_box, saved_status);
path = <API key>(index, -1);
}
else
{
GtkTreeIter iter;
<API key> type;
gpointer data;
/* If this saved status is in the list store, then set it as the active item */
if (<API key>(GTK_TREE_MODEL(status_box->dropdown_store), &iter))
{
do
{
gtk_tree_model_get(GTK_TREE_MODEL(status_box->dropdown_store), &iter,
TYPE_COLUMN, &type,
DATA_COLUMN, &data,
-1);
/* This is a special case because Primitives for the <API key> are actually
* saved statuses with substatuses for the enabled accounts */
if (status_box-><API key> && <API key>(saved_status)
&& type == <API key> && primitive == GPOINTER_TO_INT(data))
{
char *name;
const char *acct_status_name = <API key>(
<API key>(status_box-><API key>));
gtk_tree_model_get(GTK_TREE_MODEL(status_box->dropdown_store), &iter,
TEXT_COLUMN, &name, -1);
if (!<API key>(saved_status)
|| !strcmp(name, acct_status_name))
{
/* Found! */
path = <API key>(GTK_TREE_MODEL(status_box->dropdown_store), &iter);
g_free(name);
break;
}
g_free(name);
} else if ((type == <API key>) &&
(GPOINTER_TO_INT(data) == <API key>(saved_status)))
{
/* Found! */
path = <API key>(GTK_TREE_MODEL(status_box->dropdown_store), &iter);
break;
}
} while (<API key>(GTK_TREE_MODEL(status_box->dropdown_store), &iter));
}
}
if (status_box->active_row)
<API key>(status_box->active_row);
if (path) { /* path should never be NULL */
status_box->active_row = <API key>(GTK_TREE_MODEL(status_box->dropdown_store), path);
gtk_tree_path_free(path);
} else
status_box->active_row = NULL;
message = <API key>(saved_status);
if (!<API key>(saved_status) || !message || !*message)
{
status_box->imhtml_visible = FALSE;
gtk_widget_hide_all(status_box->vbox);
}
else
{
status_box->imhtml_visible = TRUE;
gtk_widget_show_all(status_box->vbox);
/*
* Suppress the "changed" signal because the status
* was changed programmatically.
*/
<API key>(GTK_WIDGET(status_box->imhtml), FALSE);
gtk_imhtml_clear(GTK_IMHTML(status_box->imhtml));
<API key>(GTK_IMHTML(status_box->imhtml));
<API key>(GTK_IMHTML(status_box->imhtml), message, 0);
<API key>(GTK_WIDGET(status_box->imhtml), TRUE);
}
update_size(status_box);
/* Stop suppressing the "changed" signal. */
<API key>(GTK_WIDGET(status_box), TRUE);
}
static void
<API key>(PidginStatusBox *statusbox)
{
GList *list, *cur;
GdkPixbuf *pixbuf;
list = <API key>(6);
if (list == NULL)
/* Odd... oh well, nothing we can do about it. */
return;
<API key>(statusbox);
for (cur = list; cur != NULL; cur = cur->next)
{
PurpleSavedStatus *saved = cur->data;
const gchar *message;
gchar *stripped = NULL;
<API key> prim;
<API key> type = <API key>;
/* Get an appropriate status icon */
prim = <API key>(saved);
pixbuf = <API key>(statusbox, prim);
if (<API key>(saved))
{
/*
* Transient statuses do not have a title, so the savedstatus
* API returns the message when <API key>() is
* called, so we don't need to get the message a second time.
*/
}
else
{
message = <API key>(saved);
if (message != NULL)
{
stripped = <API key>(message);
<API key>(stripped, '\n', ' ');
}
type = <API key>;
}
<API key>(statusbox, type,
pixbuf, <API key>(saved), stripped,
GINT_TO_POINTER(<API key>(saved)));
g_free(stripped);
if (pixbuf != NULL)
g_object_unref(G_OBJECT(pixbuf));
}
g_list_free(list);
}
/* This returns NULL if the active accounts don't have identical
* statuses and a token account if they do */
static PurpleAccount* <API key>(void)
{
PurpleAccount *acct = NULL, *acct2;
GList *tmp, *tmp2, *active_accts = <API key>();
GList *s, *s1, *s2;
for (tmp = active_accts; tmp; tmp = tmp->next) {
acct = tmp->data;
s = <API key>(acct);
for (tmp2 = tmp->next; tmp2; tmp2 = tmp2->next) {
acct2 = tmp2->data;
/* Only actually look at the statuses if the accounts use the same prpl */
if (strcmp(<API key>(acct), <API key>(acct2))) {
acct = NULL;
break;
}
s2 = <API key>(acct2);
s1 = s;
while (s1 && s2) {
PurpleStatusType *st1 = s1->data, *st2 = s2->data;
/* TODO: Are these enough to consider the statuses identical? */
if (<API key>(st1) != <API key>(st2)
|| strcmp(<API key>(st1), <API key>(st2))
|| strcmp(<API key>(st1), <API key>(st2))) {
acct = NULL;
break;
}
s1 = s1->next;
s2 = s2->next;
}
if (s1 != s2) {/* Will both be NULL if matched */
acct = NULL;
break;
}
}
if (!acct)
break;
}
g_list_free(active_accts);
return acct;
}
static void
<API key>(PidginStatusBox *status_box, PurpleAccount *account)
{
/* Per-account */
GList *l;
GdkPixbuf *pixbuf;
for (l = <API key>(account); l != NULL; l = l->next)
{
PurpleStatusType *status_type = (PurpleStatusType *)l->data;
<API key> prim;
if (!<API key>(status_type) ||
<API key>(status_type))
continue;
prim = <API key>(status_type);
pixbuf = <API key>(status_box, prim);
<API key>(PIDGIN_STATUS_BOX(status_box),
<API key>, pixbuf,
<API key>(status_type),
NULL,
GINT_TO_POINTER(<API key>(status_type)));
if (pixbuf != NULL)
g_object_unref(pixbuf);
}
}
static void
<API key>(PidginStatusBox *status_box)
{
GdkPixbuf *pixbuf, *pixbuf2, *pixbuf3, *pixbuf4, *pixbuf5;
GtkIconSize icon_size;
icon_size = <API key>(<API key>);
/* Unset the model while clearing it */
<API key>(GTK_TREE_VIEW(status_box->tree_view), NULL);
<API key>(status_box->dropdown_store);
/* Don't set the model until the new statuses have been added to the box.
* What is presumably a bug in Gtk < 2.4 causes things to get all confused
* if we do this here. */
/* <API key>(GTK_COMBO_BOX(status_box), GTK_TREE_MODEL(status_box->dropdown_store)); */
if (status_box->account == NULL)
{
pixbuf = <API key> (GTK_WIDGET(status_box->vbox), <API key>,
icon_size, "PidginStatusBox");
/* Do all the currently enabled accounts have the same statuses?
* If so, display them instead of our global list.
*/
if (status_box-><API key>) {
<API key>(status_box, status_box-><API key>);
} else {
/* Global */
pixbuf2 = <API key> (GTK_WIDGET(status_box->vbox), <API key>,
icon_size, "PidginStatusBox");
pixbuf3 = <API key> (GTK_WIDGET(status_box->vbox), <API key>,
icon_size, "PidginStatusBox");
pixbuf4 = <API key> (GTK_WIDGET(status_box->vbox), <API key>,
icon_size, "PidginStatusBox");
pixbuf5 = <API key> (GTK_WIDGET(status_box->vbox), <API key>,
icon_size, "PidginStatusBox");
<API key>(PIDGIN_STATUS_BOX(status_box), <API key>, pixbuf, _("Available"), NULL, GINT_TO_POINTER(<API key>));
<API key>(PIDGIN_STATUS_BOX(status_box), <API key>, pixbuf2, _("Away"), NULL, GINT_TO_POINTER(PURPLE_STATUS_AWAY));
<API key>(PIDGIN_STATUS_BOX(status_box), <API key>, pixbuf5, _("Do not disturb"), NULL, GINT_TO_POINTER(<API key>));
<API key>(PIDGIN_STATUS_BOX(status_box), <API key>, pixbuf4, _("Invisible"), NULL, GINT_TO_POINTER(<API key>));
<API key>(PIDGIN_STATUS_BOX(status_box), <API key>, pixbuf3, _("Offline"), NULL, GINT_TO_POINTER(<API key>));
if (pixbuf2) g_object_unref(G_OBJECT(pixbuf2));
if (pixbuf3) g_object_unref(G_OBJECT(pixbuf3));
if (pixbuf4) g_object_unref(G_OBJECT(pixbuf4));
if (pixbuf5) g_object_unref(G_OBJECT(pixbuf5));
}
<API key>(status_box);
<API key>(PIDGIN_STATUS_BOX(status_box));
<API key>(PIDGIN_STATUS_BOX(status_box), <API key>, NULL, _("New status..."), NULL, NULL);
<API key>(PIDGIN_STATUS_BOX(status_box), <API key>, NULL, _("Saved statuses..."), NULL, NULL);
if (pixbuf) g_object_unref(G_OBJECT(pixbuf));
<API key>(status_box);
<API key>(status_box);
} else {
<API key>(status_box, status_box->account);
<API key>(status_box, status_box->account,
<API key>(status_box->account));
}
<API key>(GTK_TREE_VIEW(status_box->tree_view), GTK_TREE_MODEL(status_box->dropdown_store));
<API key>(GTK_TREE_VIEW(status_box->tree_view), TEXT_COLUMN);
}
static gboolean <API key>(GtkWidget *w, GdkEventScroll *event, GtkIMHtml *imhtml)
{
<API key>(PIDGIN_STATUS_BOX(w));
return TRUE;
}
static gboolean <API key>(GtkWidget *w, GdkEventScroll *event, GtkIMHtml *imhtml)
{
if (event->direction == GDK_SCROLL_UP)
gtk_imhtml_page_up(imhtml);
else if (event->direction == GDK_SCROLL_DOWN)
<API key>(imhtml);
return TRUE;
}
static gboolean imhtml_remove_focus(GtkWidget *w, GdkEventKey *event, PidginStatusBox *status_box)
{
if (event->keyval == GDK_Tab || event->keyval == GDK_KP_Tab || event->keyval == GDK_ISO_Left_Tab)
{
/* If last inserted character is a tab, then remove the focus from here */
GtkWidget *top = <API key>(w);
<API key>(G_OBJECT(top), "move_focus",
(event->state & GDK_SHIFT_MASK) ?
<API key>: GTK_DIR_TAB_FORWARD);
return TRUE;
}
if (status_box->typing == 0)
return FALSE;
/* Reset the status if Escape was pressed */
if (event->keyval == GDK_Escape)
{
g_source_remove(status_box->typing);
status_box->typing = 0;
if (status_box->account != NULL)
<API key>(status_box, status_box->account,
<API key>(status_box->account));
else {
<API key>(status_box);
<API key>(status_box);
}
return TRUE;
}
<API key>(status_box);
g_source_remove(status_box->typing);
status_box->typing = g_timeout_add(TYPING_TIMEOUT, (GSourceFunc)remove_typing_cb, status_box);
return FALSE;
}
#if GTK_CHECK_VERSION(2,6,0)
static gboolean
<API key>(GtkTreeModel *model,
GtkTreeIter *iter, gpointer data)
{
<API key> type;
gtk_tree_model_get(model, iter, TYPE_COLUMN, &type, -1);
if (type == <API key>)
return TRUE;
return FALSE;
}
#endif
static void
cache_pixbufs(PidginStatusBox *status_box)
{
GtkIconSize icon_size;
int i;
g_object_set(G_OBJECT(status_box->icon_rend), "xpad", 3, NULL);
icon_size = <API key>(<API key>);
for (i = 0; i < G_N_ELEMENTS(status_box->connecting_pixbufs); i++) {
if (status_box->connecting_pixbufs[i] != NULL)
gdk_pixbuf_unref(status_box->connecting_pixbufs[i]);
}
status_box->connecting_index = 0;
#define <API key>(index) \
status_box->connecting_pixbufs[index] = <API key> (GTK_WIDGET(status_box->vbox),\
<API key> ## index, icon_size, "PidginStatusBox")
<API key>(0);
<API key>(1);
<API key>(2);
<API key>(3);
<API key>(4);
<API key>(5);
<API key>(6);
<API key>(7);
<API key>(8);
#undef <API key>
for (i = 0; i < G_N_ELEMENTS(status_box->typing_pixbufs); i++) {
if (status_box->typing_pixbufs[i] != NULL)
gdk_pixbuf_unref(status_box->typing_pixbufs[i]);
}
status_box->typing_index = 0;
#define <API key>(index) \
status_box->typing_pixbufs[index] = <API key> (GTK_WIDGET(status_box->vbox), \
<API key> ## index, icon_size, "PidginStatusBox")
<API key>(0);
<API key>(1);
<API key>(2);
<API key>(3);
<API key>(4);
#undef <API key>
}
static void account_enabled_cb(PurpleAccount *acct, PidginStatusBox *status_box)
{
PurpleAccount *initial_token_acct = status_box-><API key>;
if (status_box->account)
return;
status_box-><API key> = <API key>();
/* Regenerate the list if it has changed */
if (initial_token_acct != status_box-><API key>) {
<API key>(status_box);
}
}
static void
<API key>(PurpleSavedStatus *now, PurpleSavedStatus *old, PidginStatusBox *status_box)
{
/* Make sure our current status is added to the list of popular statuses */
<API key>(status_box);
}
static void
<API key>(PurpleSavedStatus *status, PidginStatusBox *status_box)
{
<API key>(status_box);
}
static void
spellcheck_prefs_cb(const char *name, PurplePrefType type,
gconstpointer value, gpointer data)
{
#ifdef USE_GTKSPELL
PidginStatusBox *status_box = (PidginStatusBox *)data;
if (value)
<API key>(GTK_TEXT_VIEW(status_box->imhtml));
else
{
GtkSpell *spell;
spell = <API key>(GTK_TEXT_VIEW(status_box->imhtml));
gtkspell_detach(spell);
}
#endif
}
#if 0
static gboolean button_released_cb(GtkWidget *widget, GdkEventButton *event, PidginStatusBox *box)
{
if (event->button != 1)
return FALSE;
<API key>(GTK_TOGGLE_BUTTON(box->toggle_button), FALSE);
if (!box->imhtml_visible)
<API key>(G_OBJECT(box), "changed", NULL, NULL);
return TRUE;
}
static gboolean button_pressed_cb(GtkWidget *widget, GdkEventButton *event, PidginStatusBox *box)
{
if (event->button != 1)
return FALSE;
gtk_combo_box_popup(GTK_COMBO_BOX(box));
/* Disabled until button_released_cb works */
#if 0
<API key>(GTK_TOGGLE_BUTTON(box->toggle_button), TRUE);
#endif
return TRUE;
}
#endif
static void
<API key> (PidginStatusBox *status_box, int *x, int *y, int *width, int *height)
{
#if GTK_CHECK_VERSION(2,2,0)
GdkScreen *screen;
gint monitor_num;
GdkRectangle monitor;
#endif
GtkRequisition popup_req;
GtkPolicyType hpolicy, vpolicy;
<API key> (GTK_WIDGET(status_box)->window, x, y);
*x += GTK_WIDGET(status_box)->allocation.x;
*y += GTK_WIDGET(status_box)->allocation.y;
*width = GTK_WIDGET(status_box)->allocation.width;
hpolicy = vpolicy = GTK_POLICY_NEVER;
<API key> (GTK_SCROLLED_WINDOW (status_box->scrolled_window),
hpolicy, vpolicy);
<API key> (status_box->popup_frame, &popup_req);
if (popup_req.width > *width)
{
hpolicy = GTK_POLICY_ALWAYS;
<API key> (GTK_SCROLLED_WINDOW (status_box->scrolled_window),
hpolicy, vpolicy);
<API key> (status_box->popup_frame, &popup_req);
}
*height = popup_req.height;
#if GTK_CHECK_VERSION(2,2,0)
screen = <API key> (GTK_WIDGET (status_box));
monitor_num = <API key> (screen,
GTK_WIDGET (status_box)->window);
<API key> (screen, monitor_num, &monitor);
if (*x < monitor.x)
*x = monitor.x;
else if (*x + *width > monitor.x + monitor.width)
*x = monitor.x + monitor.width - *width;
if (*y + GTK_WIDGET(status_box)->allocation.height + *height <= monitor.y + monitor.height)
*y += GTK_WIDGET(status_box)->allocation.height;
else if (*y - *height >= monitor.y)
*y -= *height;
else if (monitor.y + monitor.height - (*y + GTK_WIDGET(status_box)->allocation.height) > *y - monitor.y)
{
*y += GTK_WIDGET(status_box)->allocation.height;
*height = monitor.y + monitor.height - *y;
}
else
{
*height = *y - monitor.y;
*y = monitor.y;
}
if (popup_req.height > *height)
{
vpolicy = GTK_POLICY_ALWAYS;
<API key> (GTK_SCROLLED_WINDOW (status_box->scrolled_window),
hpolicy, vpolicy);
}
#endif
}
static gboolean
<API key> (GdkWindow *window,
guint32 activate_time,
gboolean grab_keyboard)
{
if ((gdk_pointer_grab (window, TRUE,
<API key> | <API key> |
<API key>,
NULL, NULL, activate_time) == 0))
{
if (!grab_keyboard ||
gdk_keyboard_grab (window, TRUE,
activate_time) == 0)
return TRUE;
else
{
#if GTK_CHECK_VERSION(2,2,0)
<API key> (<API key> (window),
activate_time);
#else
gdk_pointer_ungrab(activate_time);
gdk_keyboard_ungrab(activate_time);
#endif
return FALSE;
}
}
return FALSE;
}
static void
<API key>(PidginStatusBox *box)
{
int width, height, x, y;
<API key> (box, &x, &y, &width, &height);
<API key> (box->popup_window, width, height);
gtk_window_move (GTK_WINDOW (box->popup_window), x, y);
gtk_widget_show(box->popup_window);
<API key> (box->tree_view);
if (!<API key> (box->popup_window->window,
GDK_CURRENT_TIME, TRUE)) {
gtk_widget_hide (box->popup_window);
return;
}
gtk_grab_add (box->popup_window);
/*box->popup_in_progress = TRUE;*/
<API key> (GTK_TOGGLE_BUTTON (box->toggle_button),
TRUE);
if (box->active_row) {
GtkTreePath *path = <API key>(box->active_row);
<API key>(GTK_TREE_VIEW(box->tree_view), path, NULL, FALSE);
gtk_tree_path_free(path);
}
}
static void
<API key>(PidginStatusBox *box)
{
gtk_widget_hide(box->popup_window);
box->popup_in_progress = FALSE;
<API key> (GTK_TOGGLE_BUTTON (box->toggle_button),
FALSE);
gtk_grab_remove (box->popup_window);
}
static gboolean
toggle_key_press_cb(GtkWidget *widget, GdkEventKey *event, PidginStatusBox *box)
{
switch (event->keyval) {
case GDK_Return:
case GDK_KP_Enter:
case GDK_KP_Space:
case GDK_space:
if (!box->popup_in_progress) {
<API key> (box);
box->popup_in_progress = TRUE;
} else {
<API key>(box);
}
return TRUE;
default:
return FALSE;
}
}
static gboolean
toggled_cb(GtkWidget *widget, GdkEventButton *event, PidginStatusBox *box)
{
if (!box->popup_in_progress)
<API key> (box);
else
<API key>(box);
return TRUE;
}
static void
buddy_icon_set_cb(const char *filename, PidginStatusBox *box)
{
PurpleStoredImage *img = NULL;
if (box->account) {
PurplePlugin *plug = purple_find_prpl(<API key>(box->account));
if (plug) {
<API key> *prplinfo = <API key>(plug);
if (prplinfo && prplinfo->icon_spec.format) {
gpointer data = NULL;
size_t len = 0;
if (filename)
data = <API key>(plug, filename, &len);
img = <API key>(box->account, data, len);
if (img)
/*
* set_account_icon doesn't give us a reference, but we
* unref one below (for the other code path)
*/
purple_imgstore_ref(img);
<API key>(box->account, filename);
<API key>(box->account, "<API key>", (filename != NULL));
}
}
} else {
GList *accounts;
for (accounts = <API key>(); accounts != NULL; accounts = accounts->next) {
PurpleAccount *account = accounts->data;
PurplePlugin *plug = purple_find_prpl(<API key>(account));
if (plug) {
<API key> *prplinfo = <API key>(plug);
if (prplinfo != NULL &&
<API key>(account, "<API key>", TRUE) &&
prplinfo->icon_spec.format) {
gpointer data = NULL;
size_t len = 0;
if (filename)
data = <API key>(plug, filename, &len);
<API key>(account, data, len);
<API key>(account, filename);
}
}
}
/* Even if no accounts were processed, load the icon that was set. */
if (filename != NULL)
img = <API key>(filename);
}
<API key>(box, img);
if (img)
<API key>(img);
}
static void
<API key>(GtkWidget *w, PidginStatusBox *box)
{
if (box->account == NULL)
/* The pref-connect callback does the actual work */
<API key>(PIDGIN_PREFS_ROOT "/accounts/buddyicon", NULL);
else
buddy_icon_set_cb(NULL, box);
gtk_widget_destroy(box->icon_box_menu);
box->icon_box_menu = NULL;
}
static void
icon_choose_cb(const char *filename, gpointer data)
{
PidginStatusBox *box = data;
if (filename) {
if (box->account == NULL)
/* The pref-connect callback does the actual work */
<API key>(PIDGIN_PREFS_ROOT "/accounts/buddyicon", filename);
else
buddy_icon_set_cb(filename, box);
}
box->buddy_icon_sel = NULL;
}
static void
update_buddyicon_cb(const char *name, PurplePrefType type,
gconstpointer value, gpointer data)
{
buddy_icon_set_cb(value, (PidginStatusBox*) data);
}
static void
<API key>(PidginStatusBox *status_box, GtkTreePath *path)
{
if (status_box->active_row)
<API key>(status_box->active_row);
status_box->active_row = <API key>(GTK_TREE_MODEL(status_box->dropdown_store), path);
<API key> (status_box);
<API key>(status_box);
}
static void <API key>(gpointer data)
{
PurpleSavedStatus *saved;
saved = <API key>(GPOINTER_TO_INT(data));
g_return_if_fail(saved != NULL);
if (<API key>() != saved)
<API key>(saved);
}
static void
<API key>(PidginStatusBox *status_box, GtkTreePath *path)
{
GtkTreeIter iter;
gpointer data;
PurpleSavedStatus *saved;
gchar *msg;
if (status_box->active_row) {
/* don't delete active status */
if (<API key>(path, <API key>(status_box->active_row)) == 0)
return;
}
if (!<API key> (GTK_TREE_MODEL(status_box->dropdown_store), &iter, path))
return;
gtk_tree_model_get(GTK_TREE_MODEL(status_box->dropdown_store), &iter,
DATA_COLUMN, &data,
-1);
saved = <API key>(GPOINTER_TO_INT(data));
g_return_if_fail(saved != NULL);
if (saved == <API key>())
return;
msg = g_strdup_printf(_("Are you sure you want to delete %s?"), <API key>(saved));
<API key>(saved, NULL, msg, NULL, 0,
NULL, NULL, NULL,
data, 2,
_("Delete"), <API key>,
_("Cancel"), NULL);
g_free(msg);
<API key>(status_box);
}
static gboolean
<API key>(GtkWidget *widget, GdkEventButton *event, PidginStatusBox *status_box)
{
GtkTreePath *path = NULL;
int ret;
GtkWidget *ewidget = <API key> ((GdkEvent *)event);
if (ewidget != status_box->tree_view) {
if (ewidget == status_box->toggle_button &&
status_box->popup_in_progress &&
<API key> (GTK_TOGGLE_BUTTON (status_box->toggle_button))) {
<API key> (status_box);
return TRUE;
} else if (ewidget == status_box->toggle_button) {
status_box->popup_in_progress = TRUE;
}
/* released outside treeview */
if (ewidget != status_box->toggle_button) {
<API key> (status_box);
return TRUE;
}
return FALSE;
}
ret = <API key> (GTK_TREE_VIEW (status_box->tree_view),
event->x, event->y,
&path,
NULL, NULL, NULL);
if (!ret)
return TRUE; /* clicked outside window? */
<API key>(status_box, path);
gtk_tree_path_free (path);
return TRUE;
}
static gboolean
<API key>(GtkWidget *widget,
GdkEventKey *event, PidginStatusBox *box)
{
if (box->popup_in_progress) {
if (event->keyval == GDK_Escape) {
<API key>(box);
return TRUE;
} else {
GtkTreeSelection *sel = <API key>(GTK_TREE_VIEW(box->tree_view));
GtkTreeIter iter;
GtkTreePath *path;
if (<API key>(sel, NULL, &iter)) {
gboolean ret = TRUE;
path = <API key>(GTK_TREE_MODEL(box->dropdown_store), &iter);
if (event->keyval == GDK_Return) {
<API key>(box, path);
} else if (event->keyval == GDK_Delete) {
<API key>(box, path);
} else
ret = FALSE;
gtk_tree_path_free (path);
return ret;
}
}
}
return FALSE;
}
static void
<API key>(gpointer data, GtkMovementStep step, gint count, gboolean extend,
GtkWidget *widget)
{
/* Restart the typing timeout if arrow keys are pressed while editing the message */
PidginStatusBox *status_box = data;
if (status_box->typing == 0)
return;
imhtml_changed_cb(NULL, status_box);
}
static void
<API key>(GtkTreeView *treeview, gpointer data)
{
GtkTreeSelection *sel = <API key> (treeview);
GtkTreeModel *model = GTK_TREE_MODEL (data);
GtkTreeIter iter;
GtkTreePath *cursor;
GtkTreePath *selection;
gint cmp;
if (<API key> (sel, NULL, &iter)) {
if ((selection = <API key> (model, &iter)) == NULL) {
/* Shouldn't happen, but ignore anyway */
return;
}
} else {
/* I don't think this can happen, but we'll just ignore it */
return;
}
<API key> (treeview, &cursor, NULL);
if (cursor == NULL) {
/* Probably won't happen in a 'cursor-changed' event? */
gtk_tree_path_free (selection);
return;
}
cmp = <API key> (cursor, selection);
if (cmp < 0) {
/* The cursor moved up without moving the selection, so move it up again */
gtk_tree_path_prev (cursor);
<API key> (treeview, cursor, NULL, FALSE);
} else if (cmp > 0) {
/* The cursor moved down without moving the selection, so move it down again */
gtk_tree_path_next (cursor);
<API key> (treeview, cursor, NULL, FALSE);
}
gtk_tree_path_free (selection);
gtk_tree_path_free (cursor);
}
static void
<API key> (PidginStatusBox *status_box)
{
GtkCellRenderer *text_rend;
GtkCellRenderer *icon_rend;
GtkCellRenderer *emblem_rend;
GtkTextBuffer *buffer;
GtkWidget *toplevel;
GtkTreeSelection *sel;
<API key> (status_box, GTK_NO_WINDOW);
status_box->imhtml_visible = FALSE;
status_box->network_available = <API key>();
status_box->connecting = FALSE;
status_box->typing = 0;
status_box->toggle_button = <API key>();
status_box->hbox = gtk_hbox_new(FALSE, 6);
status_box->cell_view = gtk_cell_view_new();
status_box->vsep = gtk_vseparator_new();
status_box->arrow = gtk_arrow_new (GTK_ARROW_DOWN, GTK_SHADOW_NONE);
status_box->store = gtk_list_store_new(NUM_COLUMNS, G_TYPE_INT, GDK_TYPE_PIXBUF, G_TYPE_STRING, G_TYPE_STRING,
G_TYPE_STRING, G_TYPE_POINTER, GDK_TYPE_PIXBUF, G_TYPE_BOOLEAN);
status_box->dropdown_store = gtk_list_store_new(NUM_COLUMNS, G_TYPE_INT, GDK_TYPE_PIXBUF, G_TYPE_STRING,
G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER, G_TYPE_STRING, G_TYPE_BOOLEAN);
<API key>(GTK_CELL_VIEW(status_box->cell_view), GTK_TREE_MODEL(status_box->store));
<API key>(status_box->store, &(status_box->iter));
atk_object_set_name(<API key>(status_box->toggle_button), _("Status Selector"));
gtk_container_add(GTK_CONTAINER(status_box->toggle_button), status_box->hbox);
gtk_box_pack_start(GTK_BOX(status_box->hbox), status_box->cell_view, TRUE, TRUE, 0);
gtk_box_pack_start(GTK_BOX(status_box->hbox), status_box->vsep, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(status_box->hbox), status_box->arrow, FALSE, FALSE, 0);
gtk_widget_show_all(status_box->toggle_button);
#if GTK_CHECK_VERSION(2,4,0)
<API key>(GTK_BUTTON(status_box->toggle_button), FALSE);
#endif
text_rend = <API key>();
icon_rend = <API key>();
emblem_rend = <API key>();
status_box->popup_window = gtk_window_new (GTK_WINDOW_POPUP);
toplevel = <API key> (GTK_WIDGET (status_box));
if (GTK_IS_WINDOW (toplevel)) {
<API key> (GTK_WINDOW (status_box->popup_window),
GTK_WINDOW (toplevel));
}
<API key> (GTK_WINDOW (status_box->popup_window), FALSE);
#if GTK_CHECK_VERSION(2,10,0)
<API key> (GTK_WINDOW (status_box->popup_window),
<API key>);
#endif
#if GTK_CHECK_VERSION(2,2,0)
<API key> (GTK_WINDOW (status_box->popup_window),
<API key> (GTK_WIDGET (status_box)));
#endif
status_box->popup_frame = gtk_frame_new (NULL);
<API key> (GTK_FRAME (status_box->popup_frame),
<API key>);
gtk_container_add (GTK_CONTAINER (status_box->popup_window),
status_box->popup_frame);
gtk_widget_show (status_box->popup_frame);
status_box->scrolled_window = <API key> (NULL, NULL);
<API key> (GTK_SCROLLED_WINDOW (status_box->scrolled_window),
GTK_POLICY_NEVER,
GTK_POLICY_NEVER);
<API key> (GTK_SCROLLED_WINDOW (status_box->scrolled_window),
GTK_SHADOW_NONE);
gtk_widget_show (status_box->scrolled_window);
gtk_container_add (GTK_CONTAINER (status_box->popup_frame),
status_box->scrolled_window);
status_box->tree_view = gtk_tree_view_new ();
sel = <API key> (GTK_TREE_VIEW (status_box->tree_view));
<API key> (sel, <API key>);
<API key> (GTK_TREE_VIEW (status_box->tree_view),
FALSE);
#if GTK_CHECK_VERSION(2,6,0)
<API key> (GTK_TREE_VIEW (status_box->tree_view),
TRUE);
#endif
<API key> (GTK_TREE_VIEW (status_box->tree_view),
GTK_TREE_MODEL(status_box->dropdown_store));
status_box->column = <API key> ();
<API key> (GTK_TREE_VIEW (status_box->tree_view),
status_box->column);
<API key>(status_box->column, icon_rend, FALSE);
<API key>(status_box->column, text_rend, TRUE);
<API key>(status_box->column, emblem_rend, FALSE);
<API key>(status_box->column, icon_rend, "pixbuf", ICON_COLUMN, NULL);
<API key>(status_box->column, text_rend, "markup", TEXT_COLUMN, NULL);
<API key>(status_box->column, emblem_rend, "stock-id", EMBLEM_COLUMN, "visible", <API key>, NULL);
gtk_container_add(GTK_CONTAINER(status_box->scrolled_window), status_box->tree_view);
gtk_widget_show(status_box->tree_view);
<API key>(GTK_TREE_VIEW(status_box->tree_view), TEXT_COLUMN);
<API key>(GTK_TREE_VIEW(status_box->tree_view),
<API key>, NULL, NULL);
#if GTK_CHECK_VERSION(2, 6, 0)
g_object_set(text_rend, "ellipsize", PANGO_ELLIPSIZE_END, NULL);
#endif
status_box->icon_rend = <API key>();
status_box->text_rend = <API key>();
emblem_rend = <API key>();
<API key>(GTK_CELL_LAYOUT(status_box->cell_view), status_box->icon_rend, FALSE);
<API key>(GTK_CELL_LAYOUT(status_box->cell_view), status_box->text_rend, TRUE);
<API key>(GTK_CELL_LAYOUT(status_box->cell_view), emblem_rend, FALSE);
<API key>(GTK_CELL_LAYOUT(status_box->cell_view), status_box->icon_rend, "pixbuf", ICON_COLUMN, NULL);
<API key>(GTK_CELL_LAYOUT(status_box->cell_view), status_box->text_rend, "markup", TEXT_COLUMN, NULL);
<API key>(GTK_CELL_LAYOUT(status_box->cell_view), emblem_rend, "pixbuf", EMBLEM_COLUMN, "visible", <API key>, NULL);
#if GTK_CHECK_VERSION(2, 6, 0)
g_object_set(status_box->text_rend, "ellipsize", PANGO_ELLIPSIZE_END, NULL);
#endif
status_box->vbox = gtk_vbox_new(0, FALSE);
status_box->sw = <API key>(FALSE, &status_box->imhtml, NULL, NULL);
<API key>(GTK_IMHTML(status_box->imhtml), TRUE);
buffer = <API key>(GTK_TEXT_VIEW(status_box->imhtml));
#if 0
g_signal_connect(G_OBJECT(status_box->toggle_button), "button-press-event",
G_CALLBACK(button_pressed_cb), status_box);
g_signal_connect(G_OBJECT(status_box->toggle_button), "<API key>",
G_CALLBACK(button_released_cb), status_box);
#endif
g_signal_connect(G_OBJECT(status_box->toggle_button), "key-press-event",
G_CALLBACK(toggle_key_press_cb), status_box);
g_signal_connect(G_OBJECT(status_box->toggle_button), "button-press-event",
G_CALLBACK(toggled_cb), status_box);
g_signal_connect(G_OBJECT(buffer), "changed", G_CALLBACK(imhtml_changed_cb), status_box);
g_signal_connect(G_OBJECT(status_box->imhtml), "<API key>",
G_CALLBACK(<API key>), status_box);
<API key>(G_OBJECT(status_box->imhtml), "move_cursor",
G_CALLBACK(<API key>), status_box);
g_signal_connect(G_OBJECT(status_box->imhtml), "key_press_event",
G_CALLBACK(imhtml_remove_focus), status_box);
<API key>(G_OBJECT(status_box->imhtml), "message_send", G_CALLBACK(remove_typing_cb), status_box);
<API key>(GTK_IMHTML(status_box->imhtml), TRUE);
#ifdef USE_GTKSPELL
if (<API key>(PIDGIN_PREFS_ROOT "/conversations/spellcheck"))
<API key>(GTK_TEXT_VIEW(status_box->imhtml));
#endif
<API key>(status_box->vbox, GTK_WIDGET(status_box));
gtk_widget_show_all(status_box->vbox);
<API key>(status_box->toggle_button, GTK_WIDGET(status_box));
gtk_box_pack_start(GTK_BOX(status_box->vbox), status_box->sw, TRUE, TRUE, 0);
g_signal_connect(G_OBJECT(status_box), "scroll_event", G_CALLBACK(<API key>), NULL);
g_signal_connect(G_OBJECT(status_box->imhtml), "scroll_event",
G_CALLBACK(<API key>), status_box->imhtml);
g_signal_connect(G_OBJECT(status_box->popup_window), "<API key>", G_CALLBACK(<API key>), status_box);
g_signal_connect(G_OBJECT(status_box->popup_window), "key_press_event", G_CALLBACK(<API key>), status_box);
g_signal_connect(G_OBJECT(status_box->tree_view), "cursor-changed",
G_CALLBACK(<API key>), status_box->dropdown_store);
#if GTK_CHECK_VERSION(2,6,0)
<API key>(GTK_TREE_VIEW(status_box->tree_view), <API key>, NULL, NULL);
#endif
status_box-><API key> = <API key>();
cache_pixbufs(status_box);
<API key>(status_box);
<API key>(<API key>(), "savedstatus-changed",
status_box,
PURPLE_CALLBACK(<API key>),
status_box);
<API key>(<API key>(),
"savedstatus-added", status_box,
PURPLE_CALLBACK(<API key>), status_box);
<API key>(<API key>(),
"savedstatus-deleted", status_box,
PURPLE_CALLBACK(<API key>), status_box);
<API key>(<API key>(),
"<API key>", status_box,
PURPLE_CALLBACK(<API key>), status_box);
<API key>(<API key>(), "account-enabled", status_box,
PURPLE_CALLBACK(account_enabled_cb),
status_box);
<API key>(<API key>(), "account-disabled", status_box,
PURPLE_CALLBACK(account_enabled_cb),
status_box);
<API key>(<API key>(), "<API key>", status_box,
PURPLE_CALLBACK(<API key>),
status_box);
<API key>(status_box, PIDGIN_PREFS_ROOT "/conversations/spellcheck",
spellcheck_prefs_cb, status_box);
<API key>(status_box, PIDGIN_PREFS_ROOT "/accounts/buddyicon",
update_buddyicon_cb, status_box);
<API key>(purple_get_core(), "uri-handler", status_box,
PURPLE_CALLBACK(<API key>), status_box);
}
static void
<API key>(GtkWidget *widget,
GtkRequisition *requisition)
{
GtkRequisition box_req;
gint border_width = GTK_CONTAINER (widget)->border_width;
<API key>(PIDGIN_STATUS_BOX(widget)->toggle_button, requisition);
/* Make this icon the same size as other buddy icons in the list; unless it already wants to be bigger */
requisition->height = MAX(requisition->height, 34);
requisition->height += border_width * 2;
/* If the gtkimhtml is visible, then add some additional padding */
<API key>(PIDGIN_STATUS_BOX(widget)->vbox, &box_req);
if (box_req.height > 1)
requisition->height += box_req.height + border_width * 2;
requisition->width = 1;
}
/* From gnome-panel */
static void
do_colorshift (GdkPixbuf *dest, GdkPixbuf *src, int shift)
{
gint i, j;
gint width, height, has_alpha, srcrowstride, destrowstride;
guchar *target_pixels;
guchar *original_pixels;
guchar *pixsrc;
guchar *pixdest;
int val;
guchar r,g,b;
has_alpha = <API key> (src);
width = <API key> (src);
height = <API key> (src);
srcrowstride = <API key> (src);
destrowstride = <API key> (dest);
target_pixels = <API key> (dest);
original_pixels = <API key> (src);
for (i = 0; i < height; i++) {
pixdest = target_pixels + i*destrowstride;
pixsrc = original_pixels + i*srcrowstride;
for (j = 0; j < width; j++) {
r = *(pixsrc++);
g = *(pixsrc++);
b = *(pixsrc++);
val = r + shift;
*(pixdest++) = CLAMP(val, 0, 255);
val = g + shift;
*(pixdest++) = CLAMP(val, 0, 255);
val = b + shift;
*(pixdest++) = CLAMP(val, 0, 255);
if (has_alpha)
*(pixdest++) = *(pixsrc++);
}
}
}
static void
<API key>(GtkWidget *widget,
GtkAllocation *allocation)
{
PidginStatusBox *status_box = PIDGIN_STATUS_BOX(widget);
GtkRequisition req = {0,0};
GtkAllocation parent_alc, box_alc, icon_alc;
gint border_width = GTK_CONTAINER (widget)->border_width;
<API key>(status_box->toggle_button, &req);
/* Make this icon the same size as other buddy icons in the list; unless it already wants to be bigger */
req.height = MAX(req.height, 34);
req.height += border_width * 2;
box_alc = *allocation;
box_alc.width -= (border_width * 2);
box_alc.height = MAX(1, ((allocation->height - req.height) - (border_width*2)));
box_alc.x += border_width;
box_alc.y += req.height + border_width;
<API key>(status_box->vbox, &box_alc);
parent_alc = *allocation;
parent_alc.height = MAX(1,req.height - (border_width *2));
parent_alc.width -= (border_width * 2);
parent_alc.x += border_width;
parent_alc.y += border_width;
if (status_box->icon_box)
{
GtkTextDirection dir = <API key>(widget);
parent_alc.width -= (parent_alc.height + border_width);
icon_alc = parent_alc;
icon_alc.height = MAX(1, icon_alc.height) - 2;
icon_alc.width = icon_alc.height;
if (dir == GTK_TEXT_DIR_RTL) {
icon_alc.x = parent_alc.x;
parent_alc.x += icon_alc.width + border_width;
} else {
icon_alc.x = allocation->width - (icon_alc.width + border_width + 1);
}
icon_alc.y += 1;
if (status_box->icon_size != icon_alc.height)
{
status_box->icon_size = icon_alc.height;
<API key>(status_box);
}
<API key>(status_box->icon_box, &icon_alc);
}
<API key>(status_box->toggle_button, &parent_alc);
widget->allocation = *allocation;
}
static gboolean
<API key>(GtkWidget *widget,
GdkEventExpose *event)
{
PidginStatusBox *status_box = PIDGIN_STATUS_BOX(widget);
<API key>(GTK_CONTAINER(widget), status_box->vbox, event);
<API key>(GTK_CONTAINER(widget), status_box->toggle_button, event);
if (status_box->icon_box && status_box->icon_opaque) {
gtk_paint_box(widget->style, widget->window, GTK_STATE_NORMAL, GTK_SHADOW_OUT, NULL,
status_box->icon_box, "button", status_box->icon_box->allocation.x-1, status_box->icon_box->allocation.y-1,
34, 34);
}
return FALSE;
}
static void
<API key>(GtkContainer *container,
gboolean include_internals,
GtkCallback callback,
gpointer callback_data)
{
PidginStatusBox *status_box = PIDGIN_STATUS_BOX (container);
if (include_internals)
{
(* callback) (status_box->vbox, callback_data);
(* callback) (status_box->toggle_button, callback_data);
(* callback) (status_box->arrow, callback_data);
if (status_box->icon_box)
(* callback) (status_box->icon_box, callback_data);
}
}
GtkWidget *
<API key>()
{
return g_object_new(<API key>, "account", NULL,
"iconsel", TRUE, NULL);
}
GtkWidget *
<API key>(PurpleAccount *account)
{
return g_object_new(<API key>, "account", account,
"iconsel", TRUE, NULL);
}
/**
* Add a row to the dropdown menu.
*
* @param status_box The status box itself.
* @param type A <API key>.
* @param pixbuf The icon to associate with this row in the menu.
* @param title The title of this item. For the primitive entries,
* this is something like "Available" or "Away." For
* the saved statuses, this is something like
* "My favorite away message!" This should be
* plaintext (non-markedup) (this function escapes it).
* @param desc The secondary text for this item. This will be
* placed on the row below the title, in a dimmer
* font (generally gray). This text should be plaintext
* (non-markedup) (this function escapes it).
* @param data Data to be associated with this row in the dropdown
* menu. For primitives this is the value of the
* <API key>. For saved statuses this is the
* creation timestamp.
*/
void
<API key>(PidginStatusBox *status_box, <API key> type, GdkPixbuf *pixbuf, const char *title, const char *desc, gpointer data)
{
GtkTreeIter iter;
char *text;
if (desc == NULL)
{
text = <API key>(title, -1);
}
else
{
GtkStyle *style;
char aa_color[8];
gchar *escaped_title, *escaped_desc;
style = <API key>(GTK_WIDGET(status_box));
snprintf(aa_color, sizeof(aa_color), "#%02x%02x%02x",
style->text_aa[GTK_STATE_NORMAL].red >> 8,
style->text_aa[GTK_STATE_NORMAL].green >> 8,
style->text_aa[GTK_STATE_NORMAL].blue >> 8);
escaped_title = <API key>(title, -1);
escaped_desc = <API key>(desc, -1);
text = g_strdup_printf("%s - <span color=\"%s\" size=\"smaller\">%s</span>",
escaped_title,
aa_color, escaped_desc);
g_free(escaped_title);
g_free(escaped_desc);
}
<API key>(status_box->dropdown_store, &iter);
gtk_list_store_set(status_box->dropdown_store, &iter,
TYPE_COLUMN, type,
ICON_COLUMN, pixbuf,
TEXT_COLUMN, text,
TITLE_COLUMN, title,
DESC_COLUMN, desc,
DATA_COLUMN, data,
<API key>, type == <API key>,
EMBLEM_COLUMN, GTK_STOCK_SAVE,
-1);
g_free(text);
}
void
<API key>(PidginStatusBox *status_box)
{
/* Don't do anything unless GTK actually supports
* <API key> */
#if GTK_CHECK_VERSION(2,6,0)
GtkTreeIter iter;
<API key>(status_box->dropdown_store, &iter);
gtk_list_store_set(status_box->dropdown_store, &iter,
TYPE_COLUMN, <API key>,
-1);
#endif
}
void
<API key>(PidginStatusBox *status_box, gboolean available)
{
if (!status_box)
return;
status_box->network_available = available;
<API key>(status_box);
}
void
<API key>(PidginStatusBox *status_box, gboolean connecting)
{
if (!status_box)
return;
status_box->connecting = connecting;
<API key>(status_box);
}
static void
<API key>(GdkPixbufLoader *loader, int width, int height, gpointer data)
{
#if GTK_CHECK_VERSION(2,2,0)
int w, h;
GtkIconSize icon_size = <API key>(<API key>);
<API key>(icon_size, &w, &h);
if (height > width)
w = width * h / height;
else if (width > height)
h = height * w / width;
<API key>(loader, w, h);
#endif
}
static void
<API key>(PidginStatusBox *status_box)
{
/* This is sometimes called before the box is shown, and we will not have a size */
if (status_box->icon_size <= 0)
return;
if (status_box->buddy_icon)
g_object_unref(status_box->buddy_icon);
if (status_box->buddy_icon_hover)
g_object_unref(status_box->buddy_icon_hover);
status_box->buddy_icon = NULL;
status_box->buddy_icon_hover = NULL;
if (status_box->buddy_icon_img != NULL)
{
GdkPixbufLoader *loader = <API key>();
g_signal_connect(G_OBJECT(loader), "size-prepared", G_CALLBACK(<API key>), NULL);
<API key>(loader, <API key>(status_box->buddy_icon_img),
<API key>(status_box->buddy_icon_img), NULL);
<API key>(loader, NULL);
status_box->buddy_icon = <API key>(loader);
if (status_box->buddy_icon)
g_object_ref(status_box->buddy_icon);
g_object_unref(loader);
}
if (status_box->buddy_icon == NULL)
{
/* Show a placeholder icon */
GtkIconSize icon_size = <API key>(<API key>);
status_box->buddy_icon = <API key>(GTK_WIDGET(status_box),
<API key>,
icon_size, "PidginStatusBox");
}
if (status_box->buddy_icon != NULL) {
status_box->icon_opaque = <API key>(status_box->buddy_icon);
<API key>(GTK_IMAGE(status_box->icon), status_box->buddy_icon);
status_box->buddy_icon_hover = gdk_pixbuf_copy(status_box->buddy_icon);
do_colorshift(status_box->buddy_icon_hover, status_box->buddy_icon_hover, 32);
<API key>(GTK_WIDGET(status_box));
}
}
void
<API key>(PidginStatusBox *status_box, PurpleStoredImage *img)
{
<API key>(status_box->buddy_icon_img);
status_box->buddy_icon_img = img;
if (status_box->buddy_icon_img != NULL)
purple_imgstore_ref(status_box->buddy_icon_img);
<API key>(status_box);
}
void
<API key>(PidginStatusBox *status_box)
{
if (!status_box)
return;
if (status_box->connecting_index == 8)
status_box->connecting_index = 0;
else
status_box->connecting_index++;
<API key>(status_box);
}
static void
<API key>(PidginStatusBox *status_box)
{
if (status_box->typing_index == 4)
status_box->typing_index = 0;
else
status_box->typing_index++;
<API key>(status_box);
}
static gboolean
message_changed(const char *one, const char *two)
{
if (one == NULL && two == NULL)
return FALSE;
if (one == NULL || two == NULL)
return TRUE;
return (g_utf8_collate(one, two) != 0);
}
static void
<API key>(PidginStatusBox *status_box)
{
<API key> type;
gpointer data;
gchar *title;
GtkTreeIter iter;
GtkTreePath *path;
char *message;
PurpleSavedStatus *saved_status = NULL;
gboolean changed = TRUE;
path = <API key>(status_box->active_row);
if (!<API key> (GTK_TREE_MODEL(status_box->dropdown_store), &iter, path))
return;
gtk_tree_path_free(path);
gtk_tree_model_get(GTK_TREE_MODEL(status_box->dropdown_store), &iter,
TYPE_COLUMN, &type,
DATA_COLUMN, &data,
-1);
/*
* If the currently selected status is "New..." or
* "Saved..." or a popular status then do nothing.
* Popular statuses are
* activated elsewhere, and we update the status_box
* accordingly by connecting to the savedstatus-changed
* signal and then calling <API key>()
*/
if (type != <API key>)
return;
gtk_tree_model_get(GTK_TREE_MODEL(status_box->dropdown_store), &iter,
TITLE_COLUMN, &title, -1);
message = <API key>(status_box);
if (!message || !*message)
{
gtk_widget_hide_all(status_box->vbox);
status_box->imhtml_visible = FALSE;
if (message != NULL)
{
g_free(message);
message = NULL;
}
}
if (status_box->account == NULL) {
PurpleStatusType *acct_status_type = NULL;
<API key> primitive = GPOINTER_TO_INT(data);
/* Global */
/* Save the newly selected status to prefs.xml and status.xml */
/* Has the status really been changed? */
if (status_box-><API key>) {
gint active;
PurpleStatus *status;
const char *id = NULL;
GtkTreePath *path = <API key>(status_box->active_row);
active = <API key>(path)[0];
gtk_tree_path_free(path);
status = <API key>(status_box-><API key>);
acct_status_type = <API key>(status_box-><API key>, active);
id = <API key>(acct_status_type);
if (strncmp(id, <API key>(status), strlen(id)) == 0)
{
/* Selected status and previous status is the same */
if (!message_changed(message, <API key>(status, "message")))
{
PurpleSavedStatus *ss = <API key>();
/* Make sure that statusbox displays the correct thing.
* It can get messed up if the previous selection was a
* saved status that wasn't supported by this account */
if ((<API key>(ss) == primitive)
&& <API key>(ss)
&& <API key>(ss))
changed = FALSE;
}
}
} else {
saved_status = <API key>();
if (<API key>(saved_status) == primitive &&
!<API key>(saved_status))
{
if (!message_changed(<API key>(saved_status), message))
changed = FALSE;
}
}
if (changed)
{
/* Manually find the appropriate transient acct */
if (status_box-><API key>) {
GList *iter = <API key>();
GList *tmp, *active_accts = <API key>();
for (; iter != NULL; iter = iter->next) {
PurpleSavedStatus *ss = iter->data;
const char *ss_msg = <API key>(ss);
if ((<API key>(ss) == primitive) && <API key>(ss) &&
<API key>(ss) && /* Must have substatuses */
!message_changed(ss_msg, message))
{
gboolean found = FALSE;
/* The currently enabled accounts must have substatuses for all the active accts */
for(tmp = active_accts; tmp != NULL; tmp = tmp->next) {
PurpleAccount *acct = tmp->data;
<API key> *sub = <API key>(ss, acct);
if (sub) {
const PurpleStatusType *sub_type = <API key>(sub);
const char *subtype_status_id = <API key>(sub_type);
if (subtype_status_id && !strcmp(subtype_status_id,
<API key>(acct_status_type)))
found = TRUE;
}
}
if (!found)
continue;
saved_status = ss;
break;
}
}
g_list_free(active_accts);
} else {
/* If we've used this type+message before, lookup the transient status */
saved_status = <API key>(primitive, message);
}
/* If this type+message is unique then create a new transient saved status */
if (saved_status == NULL)
{
saved_status = <API key>(NULL, primitive);
<API key>(saved_status, message);
if (status_box-><API key>) {
GList *tmp, *active_accts = <API key>();
for (tmp = active_accts; tmp != NULL; tmp = tmp->next) {
<API key>(saved_status,
(PurpleAccount*) tmp->data, acct_status_type, message);
}
g_list_free(active_accts);
}
}
/* Set the status for each account */
<API key>(saved_status);
}
} else {
/* Per-account */
gint active;
PurpleStatusType *status_type;
PurpleStatus *status;
const char *id = NULL;
status = <API key>(status_box->account);
active = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(status_box), "active"));
status_type = <API key>(status_box->account, active);
id = <API key>(status_type);
if (strncmp(id, <API key>(status), strlen(id)) == 0)
{
/* Selected status and previous status is the same */
if (!message_changed(message, <API key>(status, "message")))
changed = FALSE;
}
if (changed)
{
if (message)
<API key>(status_box->account, id,
TRUE, "message", message, NULL);
else
<API key>(status_box->account, id,
TRUE, NULL);
saved_status = <API key>();
if (<API key>(saved_status))
<API key>(saved_status, status_box->account,
status_type, message);
}
}
g_free(title);
g_free(message);
}
static void update_size(PidginStatusBox *status_box)
{
GtkTextBuffer *buffer;
GtkTextIter iter;
int wrapped_lines;
int lines;
GdkRectangle oneline;
int height;
int pad_top, pad_inside, pad_bottom;
if (!status_box->imhtml_visible)
{
if (status_box->vbox != NULL)
<API key>(status_box->vbox, -1, -1);
return;
}
buffer = <API key>(GTK_TEXT_VIEW(status_box->imhtml));
height = 0;
wrapped_lines = 1;
<API key>(buffer, &iter);
do {
<API key>(GTK_TEXT_VIEW(status_box->imhtml), &iter, &oneline);
height += oneline.height;
wrapped_lines++;
if (wrapped_lines > 4)
break;
} while (<API key>(GTK_TEXT_VIEW(status_box->imhtml), &iter));
lines = <API key>(buffer);
/* Show a maximum of 4 lines */
lines = MIN(lines, 4);
wrapped_lines = MIN(wrapped_lines, 4);
pad_top = <API key>(GTK_TEXT_VIEW(status_box->imhtml));
pad_bottom = <API key>(GTK_TEXT_VIEW(status_box->imhtml));
pad_inside = <API key>(GTK_TEXT_VIEW(status_box->imhtml));
height += (pad_top + pad_bottom) * lines;
height += (pad_inside) * (wrapped_lines - lines);
<API key>(status_box->vbox, -1, height + <API key>);
}
static void remove_typing_cb(PidginStatusBox *status_box)
{
if (status_box->typing == 0)
{
/* Nothing has changed, so we don't need to do anything */
<API key>(status_box);
return;
}
g_source_remove(status_box->typing);
status_box->typing = 0;
<API key>(status_box);
<API key>(status_box);
}
static void <API key>(PidginStatusBox *status_box)
{
GtkTreePath *path = <API key>(status_box->active_row);
GtkTreeIter iter;
<API key> type;
gpointer data;
GList *accounts = NULL, *node;
int active;
if (!<API key> (GTK_TREE_MODEL(status_box->dropdown_store), &iter, path))
return;
active = <API key>(path)[0];
gtk_tree_path_free(path);
g_object_set_data(G_OBJECT(status_box), "active", GINT_TO_POINTER(active));
gtk_tree_model_get(GTK_TREE_MODEL(status_box->dropdown_store), &iter,
TYPE_COLUMN, &type,
DATA_COLUMN, &data,
-1);
if (status_box->typing != 0)
g_source_remove(status_box->typing);
status_box->typing = 0;
if (<API key>(GTK_WIDGET(status_box)))
{
if (type == <API key> || type == <API key>)
{
PurpleSavedStatus *saved;
saved = <API key>(GPOINTER_TO_INT(data));
g_return_if_fail(saved != NULL);
<API key>(saved);
return;
}
if (type == <API key>)
{
PurpleSavedStatus *saved_status;
saved_status = <API key>();
if (<API key>(saved_status) == <API key>)
saved_status = <API key>(NULL, PURPLE_STATUS_AWAY);
<API key>(FALSE,
<API key>(saved_status)
? saved_status : NULL);
<API key>(status_box);
return;
}
if (type == <API key>)
{
<API key>();
<API key>(status_box);
return;
}
}
/*
* Show the message box whenever the primitive allows for a
* message attribute on any protocol that is enabled,
* or our protocol, if we have account set
*/
if (status_box->account)
accounts = g_list_prepend(accounts, status_box->account);
else
accounts = <API key>();
status_box->imhtml_visible = FALSE;
for (node = accounts; node != NULL; node = node->next)
{
PurpleAccount *account;
PurpleStatusType *status_type;
account = node->data;
status_type = <API key>(account, GPOINTER_TO_INT(data));
if ((status_type != NULL) &&
(<API key>(status_type, "message") != NULL))
{
status_box->imhtml_visible = TRUE;
break;
}
}
g_list_free(accounts);
if (<API key>(GTK_WIDGET(status_box)))
{
if (status_box->imhtml_visible)
{
GtkTextIter start, end;
GtkTextBuffer *buffer;
gtk_widget_show_all(status_box->vbox);
status_box->typing = g_timeout_add(TYPING_TIMEOUT, (GSourceFunc)remove_typing_cb, status_box);
<API key>(status_box->imhtml);
buffer = <API key>(GTK_TEXT_VIEW(status_box->imhtml));
<API key>(buffer, &start, &end);
<API key>(buffer, <API key>(buffer, "insert"), &end);
<API key>(buffer, <API key>(buffer, "selection_bound"), &start);
}
else
{
gtk_widget_hide_all(status_box->vbox);
<API key>(status_box); /* This is where we actually set the status */
}
}
<API key>(status_box);
}
static gint
get_statusbox_index(PidginStatusBox *box, PurpleSavedStatus *saved_status)
{
gint index = -1;
switch (<API key>(saved_status))
{
/* In reverse order */
case <API key>:
index++;
case <API key>:
index++;
case <API key>:
index++;
case PURPLE_STATUS_AWAY:
index++;
case <API key>:
index++;
break;
default:
break;
}
return index;
}
static void imhtml_changed_cb(GtkTextBuffer *buffer, void *data)
{
PidginStatusBox *status_box = (PidginStatusBox*)data;
if (<API key>(GTK_WIDGET(status_box)))
{
if (status_box->typing != 0) {
<API key>(status_box);
g_source_remove(status_box->typing);
}
status_box->typing = g_timeout_add(TYPING_TIMEOUT, (GSourceFunc)remove_typing_cb, status_box);
}
<API key>(status_box);
}
static void <API key>(GtkIMHtml *imhtml, GtkIMHtmlButtons buttons, void *data)
{
imhtml_changed_cb(NULL, data);
}
char *<API key>(PidginStatusBox *status_box)
{
if (status_box->imhtml_visible)
return <API key>(GTK_IMHTML(status_box->imhtml));
else
return NULL;
} |
package com.demo.base;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.IBean;
/**
* Generated by JFinal, do not modify this file.
*/
@SuppressWarnings("serial")
public abstract class BaseUserRecord<M extends BaseUserRecord<M>> extends Model<M> implements IBean {
public void setUserId(java.lang.Integer userId) {
set("user_id", userId);
}
public java.lang.Integer getUserId() {
return get("user_id");
}
public void setUserName(java.lang.String userName) {
set("user_name", userName);
}
public java.lang.String getUserName() {
return get("user_name");
}
public void setAge(java.lang.Integer age) {
set("age", age);
}
public java.lang.Integer getAge() {
return get("age");
}
} |
#ifndef __FCHANNELGUIDE_H__
#define __FCHANNELGUIDE_H__
#include "FWebWindow.h"
#include "Utils.h"
#include "AppSettings.h"
#define TOOLBAR_IDC_BACK 1
#define TOOLBAR_IDC_FORWARD 2
#define TOOLBAR_IDC_HOME 3
#define TOOLBAR_IDC_REFRESH 4
#define NOTFOUND_HTML "data/notfound.html"
class FChannelGuide : public FIEWindow
{
public:
<API key>("FWindowBase", 0, COLOR_WINDOW);
protected:
BEGIN_MSG_MAP(FChannelGuide);
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
MESSAGE_HANDLER(WM_SETFOCUS, OnFocus);
CHAIN_MSG_MAP(FIEWindow)
END_MSG_MAP();
LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
LRESULT OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
LRESULT OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
LRESULT OnCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
LRESULT OnFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled);
LRESULT OnEraseBackground(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
return 1;
}
protected:
void OnDocumentComplete(DWORD dwID ,BOOL bMainFrame);
BOOL OnNavigateError(DWORD dwID, BOOL bMainFrame, const tchar* pszUrl);
BOOL OnBeforeNavigate(DWORD dwID, const tchar* pszURL);
void OnNavigateComplete(DWORD dwID, const tchar* pszURL);
void OnDownloadBegin(DWORD dwID);
void OnProgressChange(DWORD dwID, long lCurrent, long lMax);
void OnActivated(BOOL bActivated);
public:
void SetToolbarAddr(const tchar* pToolbar);
void OnToolbarCommand(UINT nCmd);
void SetStation(const tchar* pszStation);
void Refresh(DWORD dwFlag = 0);
void ShowEpisodeDetails(ULONG ulEpisodeID);
void ShowLoading(BOOL bShow);
void <API key>(BOOL bShow);
HRESULT Navigate(const tchar* pszURL, DWORD dwNavFlags = 0);
void SetWBFocus();
int ShowContextMenu();
FString m_StationURL;
bool m_bNotFound;
BOOL m_bNavigating;
};
class FToolbar : public FIEWindow
{
BEGIN_MSG_MAP(FChannelGuide);
MESSAGE_HANDLER(WM_SETFOCUS, OnSetFocus);
CHAIN_MSG_MAP(FIEWindow)
END_MSG_MAP()
protected:
LRESULT OnSetFocus(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
return 0;
}
};
#endif //__FCHANNELGUIDE_H__ |
#include "Lubrication.hpp"
namespace yade {
class GenericPotential : public Serializable {
public:
/* This is where the magic happens.
* This function needs to be reimplemented by childs class.
* @param u distances between surfaces
* @param a mean radius
* @param phys Actual physics on which potential is computed
* @return The total force from potential (contact + potential)
*/
virtual Real potential(Real const& u, LubricationPhys const& phys) const;
virtual void applyPotential(Real const& u, LubricationPhys& phys, Vector3r const& n);
<API key>(GenericPotential,Serializable,
"Generic class for potential representation in <API key> law. Don't do anything. If set as potential, the result will be a lubrication-only simulation.",
// ATTRS
, // CTOR
,
);
// <API key>(GenericPotential,Serializable);
DECLARE_LOGGER;
};
<API key>(GenericPotential);
class <API key>: public <API key>{
public:
bool go(shared_ptr<IGeom>& iGeom, shared_ptr<IPhys>& iPhys, Interaction* interaction);
/*
* This function solve the lubricated interaction with provided potential. It set:
* phys.delta = log(u/a) = log(u'),
* phys.u = u,
* phys.prevDotU = dotu'/u'
* @param un dimentionless geometric distance (un/a)
* @param dt dimentionless time step
* @param a dimentionnal mean radius
* @param phys Physics
* @return false if something went wrong.
*/
bool solve_normalForce(Real const& un, Real const& dt, LubricationPhys & phys);
FUNCTOR2D(<API key>,LubricationPhys);
<API key>(<API key>,
<API key>,
"Material law for lubrication + potential between two spheres. The potential model include contact. This material law will solve the system with lubrication and the provided potential.",
// ATTR
((shared_ptr<GenericPotential>,potential, new GenericPotential(), ,"Physical potential force between spheres."))
,// CTOR
,
);
DECLARE_LOGGER;
};
<API key>(<API key>);
class <API key> : public GenericPotential {
public:
Real potential(Real const& u, LubricationPhys const& phys) const;
void applyPotential(Real const& u, LubricationPhys& phys, Vector3r const& n);
<API key>(<API key>,GenericPotential,
"Potential with only <API key> contact.",
// ATTRS
((Real, alpha, 1, , "Bulk-to-roughness stiffness ratio"))
, // CTOR
,
);
DECLARE_LOGGER;
};
<API key>(<API key>)
class <API key> : public <API key> {
public:
Real potential(Real const& u, LubricationPhys const& phys) const;
void applyPotential(Real const& u, LubricationPhys& phys, Vector3r const& n);
<API key>(<API key>, <API key>,
"CundallStrack model with adhesive part. Contact is created when $u/a-\\varepsilon < 0$ and released when $u/a-\\varepsilon > l_{adh}$, where $l_{adh} = f_{adh}/k_n$. This lead to an hysteretic attractive part.",
// ATTRS
((Real, fadh, 0, , "Adhesion force."))
, // CTOR
,
);
DECLARE_LOGGER;
};
<API key>(<API key>)
class <API key> : public <API key> {
public:
Real potential(Real const& u, LubricationPhys const& phys) const;
void applyPotential(Real const& u, LubricationPhys& phys, Vector3r const& n);
Real LinExpPotential(Real const& u_) const;
void setParameters(Real const& x_0, Real const& xe, Real const& k);
void <API key>(Real const& F0, Real const& xe, Real const& k);
void <API key>(Real const& x_e, Real const& Fe, Real const& F0);
<API key>(<API key>, <API key>,
"LinExponential Potential with only <API key> contact. The LinExponential potential formula is $F(u) = \\frac{k*(x_e-x_0)}{x_e}(u/a-x_0)\\exp\\left(\\frac{-(u/a)}{x_e-x_0}\\right)$. Where $k$ is the slope at the origin, $x_0$ is the position where the potential cross $0$ and $x_e$ is the position of the extremum. ",
// ATTRS
((Real, x0, 0, Attr::readonly, "Equilibrium distance. Potential force is 0 at $x_0$ (LinExponential)"))
((Real, xe, 1, Attr::readonly, "Extremum position. Position of local max/min of force. (LinExponential)"))
((Real, k, 1, Attr::readonly, "Slope at the origin (stiffness). (LinExponential)"))
((Real, F0, 1, Attr::readonly, "Force at contact. Force when $F_0 = F(u=0)$ (LinExponential)"))
((Real, Fe, 1, Attr::readonly, "Extremum force. Value of force at extremum. (LinExponential)"))
, // CTOR
,
.def("setParameters", &<API key>::setParameters, py::args("x0", "xe", "k"),"Set parameters of the potential")
.def("<API key>", &<API key>::<API key>, py::args("F0", "xe", "k"), "Set parameters of the potential, with $k$ computed from $F_0$")
.def("<API key>", &<API key>::<API key>, py::args("xe", "Fe", "F0"), "Set parameters of the potential, with $k$ and $x_0$ computed from $F_0$ and $F_e$")
.def("potential", &<API key>::LinExpPotential, py::args("u"), "Get potential value at any point.")
);
DECLARE_LOGGER;
};
<API key>(<API key>)
} // namespace yade |
-- -*- Mode: LUA; tab-width: 2 -*-
-- wbgen2 - a simple Wishbone slave generator
-- CERN BE-Co-HT
function ram_wire_core_ports(ram)
local prefix = ram.full_prefix;
if(match(ram.access_dev, {READ_ONLY, READ_WRITE})) then -- RAM is readable from the core - wire the data output and read strobe signals
table_join(ram.ports, { port(SLV, ram.width, "out", prefix.."_data_o", "Read data output"),
port(BIT, 0, "in", prefix.."_rd_i", "Read strobe input (active high)") });
table_join(ram.maps, { vpm ("data_b_o", prefix.."_data_o");
vpm ("rd_b_i", prefix.."_rd_i"); } );
else -- ram is not readable - the read strobe low and leave the data output open
table_join(ram.maps, { vpm ("data_b_o", vopenpin());
vpm ("rd_b_i", vi("allzeros", 0)) });
end
if(match(ram.access_dev, {WRITE_ONLY, READ_WRITE})) then
table_join(ram.ports, { port(SLV, ram.width, "in", prefix.."_data_i", "Write data input"),
port(BIT, 0, "in", prefix.."_wr_i", "Write strobe (active high)") });
table_join(ram.maps, { vpm ("data_b_i", prefix.."_data_i");
vpm ("wr_b_i", prefix.."_wr_i"); });
if(ram.byte_select == true and ram.width >= 16) then
table_join(ram.ports, { port (SLV, ram.width/8, "in", prefix.."_bwsel_i", "Byte select input (active high)") } );
table_join(ram.maps, { vpm ("bwsel_b_i", prefix.."_bwsel_i"); } );
else
table_join(ram.maps, { vpm ("bwsel_b_i", vi("allones", math.floor(ram.width/8)-1, 0)); } );
end
else
table_join(ram.maps, { vpm ("bwsel_b_i", vi("allones", math.floor(ram.width/8)-1, 0));
vpm ("data_b_i", vi("allzeros", ram.width-1 ,0));
vpm ("wr_b_i", vi("allzeros", 0)) });
end
end
function ram_wire_bus_ports(ram)
local prefix = ram.full_prefix;
-- RAM is readable from the bus?
if(match(ram.access_bus, {READ_ONLY, READ_WRITE})) then -- yes: wire rd strobe and data output
table_join(ram.signals, { signal(SLV, ram.width, prefix.."_rddata_int"),
signal(BIT, 0, prefix.."_rd_int") } );
table_join(ram.maps, { vpm ("data_a_o", vi(prefix.."_rddata_int", ram.width-1, 0));
vpm ("rd_a_i", prefix.."_rd_int"); } );
else -- not readable? - set read strobe to zero and leave the data output open
table_join(ram.maps, { vpm ("rd_a_i", vi("allzeros", 0)),
vpm ("data_a_o", vopenpin()) });
end
-- RAM is writable from the bus?
if(match(ram.access_bus, {WRITE_ONLY, READ_WRITE})) then
table_join(ram.signals, { signal(BIT, 0, prefix.."_wr_int") } );
table_join(ram.maps, { vpm ("data_a_i", vi("wrdata_reg", ram.width-1, 0));
vpm ("wr_a_i", prefix.."_wr_int"); });
if(ram.byte_select == true and ram.width >= 16) then
table_join(ram.maps, { vpm ("bwsel_a_i", vi("bwsel_reg", math.floor(ram.width/8)-1, 0)); } );
else
table_join(ram.maps, { vpm ("bwsel_a_i", vi("allones", math.floor(ram.width/8)-1, 0)); } );
end
else
table_join(ram.maps, { vpm ("bwsel_a_i", vi("allones", math.floor(ram.width/8)-1, 0));
vpm ("data_a_i", vi("allzeros", ram.width-1 ,0));
vpm ("wr_a_i", vi("allzeros", 0)) });
end
end
function gen_code_ram(ram)
local prefix = string.lower(periph.hdl_prefix.."_"..ram.hdl_prefix);
-- generate the RAM-related ports
ram.full_prefix = prefix;
ram.signals = {};
ram.maps = {};
ram.ports = { port (SLV, ram.addr_bits - ram.wrap_bits, "in", prefix.."_addr_i", "Ports for RAM: "..ram.name ) };
ram.reset_code_main = {};
-- wire the obligartory signals - address busses and clocks
table_join(ram.maps, { vpm ("clk_a_i", "clk_sys_i");
vpm ("clk_b_i", csel(ram.clock ~= nil, ram.clock, "clk_sys_i"));
vpm ("addr_b_i", prefix.."_addr_i");
vpm ("addr_a_i", vi("rwaddr_reg", log2up(ram.size)-1, 0));
});
-- evaluate the access flags (from the core) and wire the core signals to appropriate ports
ram_wire_core_ports(ram);
-- do the same for the bus signals
ram_wire_bus_ports(ram);
-- fill in all the generic mappings
table_join(ram.maps, { vgm ("g_data_width", ram.width);
vgm ("g_size", ram.size);
vgm ("g_addr_width", log2up(ram.size));
vgm ("g_dual_clock", csel(ram.clock ~= nil, "true", "false"));
vgm ("g_use_bwsel", csel(ram.byte_select == true, "true", "false"));
});
-- instantiate the RAM.
ram.extra_code = { vcomment ("RAM block instantiation for memory: "..ram.name);
vinstance (prefix.."_raminst", "wbgen2_dpssram", ram.maps );
};
ram.base = ram.select_bits * math.pow (2, address_bus_width - <API key>);
end |
using System.ComponentModel.DataAnnotations.Schema;
using Realm.DAL.Common;
using Realm.DAL.Enumerations;
namespace Realm.DAL.Models
{
[Table("ItemTools")]
public class ItemTool : Entity
{
public int ItemId { get; set; }
public virtual Item Item { get; set; }
public ToolTypes ToolType { get; set; }
}
} |
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder = 'uploads';
if (!empty($_FILES)){
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
?> |
const FILE_NAME = "<API key>";
<API key> = {
gameData: null,
// init the highScore list, from storage or new list from config
init: function (username) {
var list = new Array(10);
if (Crafty.storage(FILE_NAME)) {
list = Crafty.storage(FILE_NAME);
list.forEach(function (value, key) {
list[key] = new HighScoreItem(value)
});
} else {
list = Config.initHighScoreList();
}
this.gameData = new GameData(username, list);
},
// save a new score
saveScore: function (score) {
var scoreList = this.gameData.getScoreList();
for (var i = 0; i < 10; i++) {
if (score > scoreList[i].score) {
for (var j = 9; j > i; j
scoreList[j] = scoreList[j - 1]
}
scoreList[i] = new HighScoreItem(this.gameData.getUsername(), score);
break;
}
}
this.gameData.setScoreList(scoreList);
Crafty.storage(FILE_NAME, scoreList);
},
// whole highScoreList to string, to see all scores for the game over scene
toString: function () {
var scoreList = this.gameData.getScoreList(),
ret = '';
for (var i = 0; i < 10; i++) {
if (scoreList[i].score) {
ret += '<h2>' + (i + 1) + ': ' + scoreList[i].score + ' ' + scoreList[i].username + '</h2>'
}
}
return ret;
}
}; |
// Own includes
#include "filter.h"
#include "<API key>.h"
#include "konsole_wcwidth.h"
// System includes
#include <iostream>
// Qt includes
#include <QAction>
#include <QApplication>
#include <QClipboard>
#include <QString>
#include <QTextStream>
#include <QSharedData>
#include <QFile>
#include <QDesktopServices>
#include <QUrl>
FilterChain::~FilterChain()
{
<API key><Filter*> iter(*this);
while ( iter.hasNext() )
{
Filter* filter = iter.next();
iter.remove();
delete filter;
}
}
void FilterChain::addFilter(Filter* filter)
{
append(filter);
}
void FilterChain::removeFilter(Filter* filter)
{
removeAll(filter);
}
bool FilterChain::containsFilter(Filter* filter)
{
return contains(filter);
}
void FilterChain::reset()
{
QListIterator<Filter*> iter(*this);
while (iter.hasNext())
iter.next()->reset();
}
void FilterChain::setBuffer(const QString* buffer , const QList<int>* linePositions)
{
QListIterator<Filter*> iter(*this);
while (iter.hasNext())
iter.next()->setBuffer(buffer,linePositions);
}
void FilterChain::process()
{
QListIterator<Filter*> iter(*this);
while (iter.hasNext())
iter.next()->process();
}
void FilterChain::clear()
{
QList<Filter*>::clear();
}
Filter::HotSpot* FilterChain::hotSpotAt(int line , int column) const
{
QListIterator<Filter*> iter(*this);
while (iter.hasNext())
{
Filter* filter = iter.next();
Filter::HotSpot* spot = filter->hotSpotAt(line,column);
if ( spot != 0 )
{
return spot;
}
}
return 0;
}
QList<Filter::HotSpot*> FilterChain::hotSpots() const
{
QList<Filter::HotSpot*> list;
QListIterator<Filter*> iter(*this);
while (iter.hasNext())
{
Filter* filter = iter.next();
list << filter->hotSpots();
}
return list;
}
//QList<Filter::HotSpot*> FilterChain::hotSpotsAtLine(int line) const;
<API key>::<API key>()
: _buffer(0)
, _linePositions(0)
{
}
<API key>::~<API key>()
{
delete _buffer;
delete _linePositions;
}
void <API key>::setImage(const Character* const image , int lines , int columns, const QVector<LineProperty>& lineProperties)
{
if (empty())
return;
// reset all filters and hotspots
reset();
PlainTextDecoder decoder;
decoder.<API key>(false);
// setup new shared buffers for the filters to process on
QString* newBuffer = new QString();
QList<int>* newLinePositions = new QList<int>();
setBuffer( newBuffer , newLinePositions );
// free the old buffers
delete _buffer;
delete _linePositions;
_buffer = newBuffer;
_linePositions = newLinePositions;
QTextStream lineStream(_buffer);
decoder.begin(&lineStream);
for (int i=0 ; i < lines ; i++)
{
_linePositions->append(_buffer->length());
decoder.decodeLine(image + i*columns,columns,LINE_DEFAULT);
// pretend that each line ends with a newline character.
// this prevents a link that occurs at the end of one line
// being treated as part of a link that occurs at the start of the next line
// the downside is that links which are spread over more than one line are not
// highlighted.
// TODO - Use the "line wrapped" attribute associated with lines in a
// terminal image to avoid adding this imaginary character for wrapped
// lines
if ( !(lineProperties.value(i,LINE_DEFAULT) & LINE_WRAPPED) )
lineStream << QChar('\n');
}
decoder.end();
}
Filter::Filter() :
_linePositions(0),
_buffer(0)
{
}
Filter::~Filter()
{
QListIterator<HotSpot*> iter(_hotspotList);
while (iter.hasNext())
{
delete iter.next();
}
}
void Filter::reset()
{
_hotspots.clear();
_hotspotList.clear();
}
void Filter::setBuffer(const QString* buffer , const QList<int>* linePositions)
{
_buffer = buffer;
_linePositions = linePositions;
}
void Filter::getLineColumn(int position , int& startLine , int& startColumn)
{
Q_ASSERT( _linePositions );
Q_ASSERT( _buffer );
for (int i = 0 ; i < _linePositions->count() ; i++)
{
int nextLine = 0;
if ( i == _linePositions->count()-1 )
nextLine = _buffer->length() + 1;
else
nextLine = _linePositions->value(i+1);
if ( _linePositions->value(i) <= position && position < nextLine )
{
startLine = i;
startColumn = string_width(buffer()->mid(_linePositions->value(i),position - _linePositions->value(i)));
return;
}
}
}
/*void Filter::addLine(QString text)
{
_linePositions << _buffer.length();
_buffer.append(text);
}*/
const QString* Filter::buffer()
{
return _buffer;
}
Filter::HotSpot::~HotSpot()
{
}
void Filter::addHotSpot(HotSpot* spot)
{
_hotspotList << spot;
for (int line = spot->startLine() ; line <= spot->endLine() ; line++)
{
_hotspots.insert(line,spot);
}
}
QList<Filter::HotSpot*> Filter::hotSpots() const
{
return _hotspotList;
}
QList<Filter::HotSpot*> Filter::hotSpotsAtLine(int line) const
{
return _hotspots.values(line);
}
Filter::HotSpot* Filter::hotSpotAt(int line , int column) const
{
QListIterator<HotSpot*> spotIter(_hotspots.values(line));
while (spotIter.hasNext())
{
HotSpot* spot = spotIter.next();
if ( spot->startLine() == line && spot->startColumn() > column )
continue;
if ( spot->endLine() == line && spot->endColumn() < column )
continue;
return spot;
}
return 0;
}
Filter::HotSpot::HotSpot(int startLine , int startColumn , int endLine , int endColumn)
: _startLine(startLine)
, _startColumn(startColumn)
, _endLine(endLine)
, _endColumn(endColumn)
, _type(NotSpecified)
{
}
QString Filter::HotSpot::tooltip() const
{
return QString();
}
QList<QAction*> Filter::HotSpot::actions()
{
return QList<QAction*>();
}
int Filter::HotSpot::startLine() const
{
return _startLine;
}
int Filter::HotSpot::endLine() const
{
return _endLine;
}
int Filter::HotSpot::startColumn() const
{
return _startColumn;
}
int Filter::HotSpot::endColumn() const
{
return _endColumn;
}
Filter::HotSpot::Type Filter::HotSpot::type() const
{
return _type;
}
void Filter::HotSpot::setType(Type type)
{
_type = type;
}
RegExpFilter::RegExpFilter()
{
}
RegExpFilter::HotSpot::HotSpot(int startLine,int startColumn,int endLine,int endColumn)
: Filter::HotSpot(startLine,startColumn,endLine,endColumn)
{
setType(Marker);
}
void RegExpFilter::HotSpot::activate(QString)
{
}
void RegExpFilter::HotSpot::setCapturedTexts(QStringList texts)
{
_capturedTexts = texts;
}
QStringList RegExpFilter::HotSpot::capturedTexts() const
{
return _capturedTexts;
}
void RegExpFilter::setRegExp(const QRegExp& regExp)
{
_searchText = regExp;
}
QRegExp RegExpFilter::regExp() const
{
return _searchText;
}
/*void RegExpFilter::reset(int)
{
_buffer = QString();
}*/
void RegExpFilter::process()
{
int pos = 0;
const QString* text = buffer();
Q_ASSERT( text );
// ignore any regular expressions which match an empty string.
// otherwise the while loop below will run indefinitely
static const QString emptyString("");
if ( _searchText.exactMatch(emptyString) )
return;
while(pos >= 0)
{
pos = _searchText.indexIn(*text,pos);
if ( pos >= 0 )
{
int startLine = 0;
int endLine = 0;
int startColumn = 0;
int endColumn = 0;
getLineColumn(pos,startLine,startColumn);
getLineColumn(pos + _searchText.matchedLength(),endLine,endColumn);
RegExpFilter::HotSpot* spot = newHotSpot(startLine,startColumn,
endLine,endColumn);
spot->setCapturedTexts(_searchText.capturedTexts());
addHotSpot( spot );
pos += _searchText.matchedLength();
// if matchedLength == 0, the program will get stuck in an infinite loop
if ( _searchText.matchedLength() == 0 )
pos = -1;
}
}
}
RegExpFilter::HotSpot* RegExpFilter::newHotSpot(int startLine,int startColumn,
int endLine,int endColumn)
{
return new RegExpFilter::HotSpot(startLine,startColumn,
endLine,endColumn);
}
RegExpFilter::HotSpot* UrlFilter::newHotSpot(int startLine,int startColumn,int endLine,
int endColumn)
{
HotSpot *spot = new UrlFilter::HotSpot(startLine,startColumn,
endLine,endColumn);
connect(spot->getUrlObject(), SIGNAL(activated(QUrl)), this, SIGNAL(activated(QUrl)));
return spot;
}
UrlFilter::HotSpot::HotSpot(int startLine,int startColumn,int endLine,int endColumn)
: RegExpFilter::HotSpot(startLine,startColumn,endLine,endColumn)
, _urlObject(new FilterObject(this))
{
setType(Link);
}
QString UrlFilter::HotSpot::tooltip() const
{
QString url = capturedTexts().first();
const UrlType kind = urlType();
if ( kind == StandardUrl )
return QString();
else if ( kind == Email )
return QString();
else
return QString();
}
UrlFilter::HotSpot::UrlType UrlFilter::HotSpot::urlType() const
{
QString url = capturedTexts().first();
if ( FullUrlRegExp.exactMatch(url) )
return StandardUrl;
else if ( EmailAddressRegExp.exactMatch(url) )
return Email;
else
return Unknown;
}
void UrlFilter::HotSpot::activate(QString actionName)
{
QString url = capturedTexts().first();
const UrlType kind = urlType();
if ( actionName == "copy-action" )
{
QApplication::clipboard()->setText(url);
return;
}
if ( actionName.isEmpty() || actionName == "open-action" )
{
if ( kind == StandardUrl )
{
if (!url.contains(":
{
url.prepend("http:
}
}
else if ( kind == Email )
{
url.prepend("mailto:");
}
_urlObject->emitActivated(url);
}
}
// Note: Altering these regular expressions can have a major effect on the performance of the filters
// used for finding URLs in the text, especially if they are very general and could match very long
// pieces of text.
// Please be careful when altering them.
//regexp matches:
// full url:
const QRegExp UrlFilter::FullUrlRegExp("(www\\.(?!\\.)|[a-z][a-z0-9+.-]*:
// email address:
// [word chars, dots or dashes]@[word chars, dots or dashes].[word chars]
const QRegExp UrlFilter::EmailAddressRegExp("\\b(\\w|\\.|-)+@(\\w|\\.|-)+\\.\\w+\\b");
// matches full url or email address
const QRegExp UrlFilter::CompleteUrlRegExp('('+FullUrlRegExp.pattern()+'|'+
EmailAddressRegExp.pattern()+')');
UrlFilter::UrlFilter()
{
setRegExp( CompleteUrlRegExp );
}
UrlFilter::HotSpot::~HotSpot()
{
delete _urlObject;
}
void FilterObject::emitActivated(const QUrl& url)
{
emit activated(url);
}
void FilterObject::activated()
{
_filter->activate(sender()->objectName());
}
FilterObject* UrlFilter::HotSpot::getUrlObject() const
{
return _urlObject;
}
QList<QAction*> UrlFilter::HotSpot::actions()
{
QList<QAction*> list;
const UrlType kind = urlType();
QAction* openAction = new QAction(_urlObject);
QAction* copyAction = new QAction(_urlObject);;
Q_ASSERT( kind == StandardUrl || kind == Email );
if ( kind == StandardUrl )
{
openAction->setText(QObject::tr("Open Link"));
copyAction->setText(QObject::tr("Copy Link Address"));
}
else if ( kind == Email )
{
openAction->setText(QObject::tr("Send Email To..."));
copyAction->setText(QObject::tr("Copy Email Address"));
}
// object names are set here so that the hotspot performs the
// correct action when activated() is called with the triggered
// action passed as a parameter.
openAction->setObjectName( QLatin1String("open-action" ));
copyAction->setObjectName( QLatin1String("copy-action" ));
QObject::connect( openAction , SIGNAL(triggered()) , _urlObject , SLOT(activated()) );
QObject::connect( copyAction , SIGNAL(triggered()) , _urlObject , SLOT(activated()) );
list << openAction;
list << copyAction;
return list;
}
//#include "Filter.moc" |
#include <asm/uaccess.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/termios.h>
#include <linux/ioctl.h>
#include <linux/route.h>
#include <linux/sockios.h>
#include <linux/if.h>
#include <linux/netdevice.h>
#include <linux/if_arp.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/smp_lock.h>
#include <linux/syscalls.h>
#include <linux/compat.h>
#include <asm/kbio.h>
#define SUNOS_NR_OPEN 256
struct rtentry32 {
u32 rt_pad1;
struct sockaddr rt_dst; /* target address */
struct sockaddr rt_gateway; /* gateway addr (RTF_GATEWAY) */
struct sockaddr rt_genmask; /* target network mask (IP) */
unsigned short rt_flags;
short rt_pad2;
u32 rt_pad3;
unsigned char rt_tos;
unsigned char rt_class;
short rt_pad4;
short rt_metric; /* +1 for binary compatibility! */
/* char * */ u32 rt_dev; /* forcing the device at add */
u32 rt_mtu; /* per route MTU/Window */
u32 rt_window; /* Window clamping */
unsigned short rt_irtt; /* Initial RTT */
};
struct ifmap32 {
u32 mem_start;
u32 mem_end;
unsigned short base_addr;
unsigned char irq;
unsigned char dma;
unsigned char port;
};
struct ifreq32 {
#define IFHWADDRLEN 6
#define IFNAMSIZ 16
union {
char ifrn_name[IFNAMSIZ]; /* if name, e.g. "en0" */
} ifr_ifrn;
union {
struct sockaddr ifru_addr;
struct sockaddr ifru_dstaddr;
struct sockaddr ifru_broadaddr;
struct sockaddr ifru_netmask;
struct sockaddr ifru_hwaddr;
short ifru_flags;
int ifru_ivalue;
int ifru_mtu;
struct ifmap32 ifru_map;
char ifru_slave[IFNAMSIZ]; /* Just fits the size */
compat_caddr_t ifru_data;
} ifr_ifru;
};
struct ifconf32 {
int ifc_len; /* size of buffer */
compat_caddr_t ifcbuf;
};
extern asmlinkage int compat_sys_ioctl(unsigned int, unsigned int, u32);
asmlinkage int sunos_ioctl (int fd, u32 cmd, u32 arg)
{
int ret = -EBADF;
if(fd >= SUNOS_NR_OPEN)
goto out;
if(!fcheck(fd))
goto out;
if(cmd == TIOCSETD) {
mm_segment_t old_fs = get_fs();
int __user *p;
int ntty = N_TTY;
int tmp;
p = (int __user *) (unsigned long) arg;
ret = -EFAULT;
if(get_user(tmp, p))
goto out;
if(tmp == 2) {
set_fs(KERNEL_DS);
ret = sys_ioctl(fd, cmd, (unsigned long) &ntty);
set_fs(old_fs);
ret = (ret == -EINVAL ? -EOPNOTSUPP : ret);
goto out;
}
}
if(cmd == TIOCNOTTY) {
ret = sys_setsid();
goto out;
}
switch(cmd) {
case _IOW('r', 10, struct rtentry32):
ret = compat_sys_ioctl(fd, SIOCADDRT, arg);
goto out;
case _IOW('r', 11, struct rtentry32):
ret = compat_sys_ioctl(fd, SIOCDELRT, arg);
goto out;
case _IOW('i', 12, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCSIFADDR, arg);
goto out;
case _IOWR('i', 13, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCGIFADDR, arg);
goto out;
case _IOW('i', 14, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCSIFDSTADDR, arg);
goto out;
case _IOWR('i', 15, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCGIFDSTADDR, arg);
goto out;
case _IOW('i', 16, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCSIFFLAGS, arg);
goto out;
case _IOWR('i', 17, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCGIFFLAGS, arg);
goto out;
case _IOW('i', 18, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCSIFMEM, arg);
goto out;
case _IOWR('i', 19, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCGIFMEM, arg);
goto out;
case _IOWR('i', 20, struct ifconf32):
ret = compat_sys_ioctl(fd, SIOCGIFCONF, arg);
goto out;
case _IOW('i', 21, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCSIFMTU, arg);
goto out;
case _IOWR('i', 22, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCGIFMTU, arg);
goto out;
case _IOWR('i', 23, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCGIFBRDADDR, arg);
goto out;
case _IOW('i', 24, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCSIFBRDADDR, arg);
goto out;
case _IOWR('i', 25, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCGIFNETMASK, arg);
goto out;
case _IOW('i', 26, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCSIFNETMASK, arg);
goto out;
case _IOWR('i', 27, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCGIFMETRIC, arg);
goto out;
case _IOW('i', 28, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCSIFMETRIC, arg);
goto out;
case _IOW('i', 30, struct arpreq):
ret = compat_sys_ioctl(fd, SIOCSARP, arg);
goto out;
case _IOWR('i', 31, struct arpreq):
ret = compat_sys_ioctl(fd, SIOCGARP, arg);
goto out;
case _IOW('i', 32, struct arpreq):
ret = compat_sys_ioctl(fd, SIOCDARP, arg);
goto out;
case _IOW('i', 40, struct ifreq32): /* SIOCUPPER */
case _IOW('i', 41, struct ifreq32): /* SIOCLOWER */
case _IOW('i', 44, struct ifreq32): /* SIOCSETSYNC */
case _IOW('i', 45, struct ifreq32): /* SIOCGETSYNC */
case _IOW('i', 46, struct ifreq32): /* SIOCSSDSTATS */
case _IOW('i', 47, struct ifreq32): /* SIOCSSESTATS */
case _IOW('i', 48, struct ifreq32): /* SIOCSPROMISC */
ret = -EOPNOTSUPP;
goto out;
case _IOW('i', 49, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCADDMULTI, arg);
goto out;
case _IOW('i', 50, struct ifreq32):
ret = compat_sys_ioctl(fd, SIOCDELMULTI, arg);
goto out;
/* FDDI interface ioctls, unsupported. */
case _IOW('i', 51, struct ifreq32): /* SIOCFDRESET */
case _IOW('i', 52, struct ifreq32): /* SIOCFDSLEEP */
case _IOW('i', 53, struct ifreq32): /* SIOCSTRTFMWAR */
case _IOW('i', 54, struct ifreq32): /* SIOCLDNSTRTFW */
case _IOW('i', 55, struct ifreq32): /* SIOCGETFDSTAT */
case _IOW('i', 56, struct ifreq32): /* SIOCFDNMIINT */
case _IOW('i', 57, struct ifreq32): /* SIOCFDEXUSER */
case _IOW('i', 58, struct ifreq32): /* SIOCFDGNETMAP */
case _IOW('i', 59, struct ifreq32): /* SIOCFDGIOCTL */
printk("FDDI ioctl, returning EOPNOTSUPP\n");
ret = -EOPNOTSUPP;
goto out;
case _IOW('t', 125, int):
/* More stupid tty sunos ioctls, just
* say it worked.
*/
ret = 0;
goto out;
/* Non posix grp */
case _IOW('t', 118, int): {
int oldval, newval, __user *ptr;
cmd = TIOCSPGRP;
ptr = (int __user *) (unsigned long) arg;
ret = -EFAULT;
if(get_user(oldval, ptr))
goto out;
ret = compat_sys_ioctl(fd, cmd, arg);
__get_user(newval, ptr);
if(newval == -1) {
__put_user(oldval, ptr);
ret = -EIO;
}
if(ret == -ENOTTY)
ret = -EIO;
goto out;
}
case _IOR('t', 119, int): {
int oldval, newval, __user *ptr;
cmd = TIOCGPGRP;
ptr = (int __user *) (unsigned long) arg;
ret = -EFAULT;
if(get_user(oldval, ptr))
goto out;
ret = compat_sys_ioctl(fd, cmd, arg);
__get_user(newval, ptr);
if(newval == -1) {
__put_user(oldval, ptr);
ret = -EIO;
}
if(ret == -ENOTTY)
ret = -EIO;
goto out;
}
};
ret = compat_sys_ioctl(fd, cmd, arg);
/* so stupid... */
ret = (ret == -EINVAL ? -EOPNOTSUPP : ret);
out:
return ret;
} |
<div class="hentry-inner">
<div class="entry-wrapper grids">
<?php get_template_part('content', 'meta'); ?>
<div class="entry-content grid-10 clearfix">
<?php
if(!is_singular()){
if(get_the_excerpt() != '') echo "<p>".strip_shortcodes(get_the_excerpt())."</p>";
}else{
the_content('Continue Reading', 'stag');
wp_link_pages(array('before' => '<p><strong>'.__('Pages:', 'stag').'</strong> ', 'after' => '</p>', 'next_or_number' => 'number'));
}
?>
</div>
<span class="bottom-accent"></span>
</div>
</div> |
<?php
namespace Awf\User;
use Awf\Application\Application;
use Awf\Container\Container;
use Awf\Database\Driver;
use Awf\Session\Exception;
use Awf\Text\Text;
/**
* The User Manager class allows you to load, save, log in and log out users
*/
class Manager implements ManagerInterface
{
/**
* An array of the instances we have already created
*
* @var array[ManagerInterface]
*/
protected static $instances = array();
/**
* The container this instance of User Manager is attached to
*
* @var Container
*/
protected $container;
/**
* The name of the table where user accounts are stored
*
* @var string
*/
protected $user_table = '#__users';
/**
* The name of the class we'll use to create new user objects
*
* @var string
*/
protected $user_class = '\\Awf\\User\\User';
/**
* The current user's object
*
* @var UserInterface
*/
protected $currentUser = null;
/**
* The list of privilege plugins to load on each user object
*
* @var array
*/
protected $privileges = array();
/**
* The list of authentication plugins to load on each user object
*
* @var array
*/
protected $authentications = array();
/**
* Public constructor. Creates a new User Manager. Do not call this directly. It's best to call getInstance()
* instead.
*
* @param Container $container
*/
public function __construct(Container $container = null)
{
if (!is_object($container))
{
$container = Application::getInstance()->getContainer();
}
$this->user_table = $container->appConfig->get('user_table', '#__users');
$this->user_class = $container->appConfig->get('user_class', '\\Awf\\User\\User');
$this->container = $container;
}
/**
* Get user by numeric ID. Skip the ID (or use null) to get the currently logged in user. Use the ID=0 to get a new,
* empty user instance.
*
* @param integer $id The numeric ID of the user to load
*
* @return UserInterface|null A user object if it exists, null if it doesn't
*/
public function getUser($id = null)
{
// If we're not given an ID get the current user
if (is_null($id))
{
// We don't have a current user yet? Let's load it!
if (!is_object($this->currentUser))
{
// Get the ID from the session. If nobody is logged in we get 0 (create a new, not logged in user)
$id = $this->container->segment->get('user_id', 0);
// Load the current user
$this->currentUser = $this->getUser($id);
}
$user = $this->currentUser;
}
else
{
// Create a new user
/** @var UserInterface $user */
$user = new $this->user_class;
// Create and attach the privilege objects
if (!empty($this->privileges))
{
foreach ($this->privileges as $name => $privilegeClass)
{
$privilegeObject = new $privilegeClass();
$user-><API key>($name, $privilegeObject);
}
}
// Create and attach the authentication objects
if (!empty($this->authentications))
{
foreach ($this->authentications as $name => $authenticationClass)
{
$<API key> = new $authenticationClass();
$user->attach<API key>($name, $<API key>);
}
}
$data = null;
if (!empty($id))
{
try
{
// Load the data from the database
$db = $this->container->db;
$query = $db->getQuery(true)
->select('*')
->from($db->qn($this->user_table))
->where($db->qn('id') . ' = ' . $db->q($id));
$db->setQuery($query);
$data = $db->loadObject();
}
catch (\Exception $e)
{
$data = new \stdClass();
}
if (!is_object($data))
{
return null;
}
}
// Bind the data to the user object
if (is_object($data))
{
$user->bind($data);
}
}
// Finally, return the user object
return $user;
}
/**
* Get user by username
*
* @param string $username The username of the user to load
*
* @return UserInterface|null A user object if it exists, null if it doesn't
*/
public function getUserByUsername($username)
{
try
{
$db = $this->container->db;
$query = $db->getQuery(true)
->select($db->qn('id'))
->from($db->qn($this->user_table))
->where($db->qn('username') . ' = ' . $db->q($username));
$db->setQuery($query);
$id = $db->loadResult();
}
catch (\Exception $e)
{
$id = null;
}
if (is_null($id))
{
return null;
}
return $this->getUser($id);
}
/**
* Try to log in a user given the username, password and any additional parameters which may be required by the
* user class
*
* @param string $username The username of the user to log in
* @param string $password The (unhashed) password of the user to log in
* @param array $params [optional] Any additional parameters you may want to pass to the user object, e.g. 2FA
*
* @return boolean True on success
*
* @throws \Exception When the login fails
*/
public function loginUser($username, $password, $params = array())
{
$user = $this->getUserByUsername($username);
if (is_null($user))
{
throw new \RuntimeException(Text::_('<API key>'), 403);
}
if (!$user->verifyPassword($password, $params))
{
throw new \RuntimeException(Text::_('<API key>'), 403);
}
$this->container->segment->set('user_id', $user->getId());
$this->currentUser = $user;
}
/**
* Log out the current user. Logging out a user immediately clears the session storage.
*
* @return void
*/
public function logoutUser()
{
$this->currentUser = null;
$this->container->segment->clear();
}
/**
* Save the provided user record
*
* @param UserInterface $user The user to save
*
* @return boolean True on success
*
* @throws \RuntimeException If an error occurs when saving the user
*/
public function saveUser(UserInterface $user)
{
$user->triggerEvent('onBeforeSave');
$db = $this->container->db;
if ($user->getId())
{
$query = $db->getQuery(true)
->update($db->qn($this->user_table))
->set($db->qn('username') . ' = ' . $db->q($user->getUsername()))
->set($db->qn('name') . ' = ' . $db->q($user->getName()))
->set($db->qn('email') . ' = ' . $db->q($user->getEmail()))
->set($db->qn('password') . ' = ' . $db->q($user->getPassword()))
->set($db->qn('parameters') . ' = ' . $db->q($user->getParameters()->toString('JSON')))
->where($db->qn('id') . ' = ' . $db->q($user->getId()));
}
else
{
$query = $db->getQuery(true)
->insert($db->qn($this->user_table))
->columns(array(
$db->qn('username'),
$db->qn('name'),
$db->qn('email'),
$db->qn('password'),
$db->qn('parameters'),
))->values(
$db->q($user->getUsername()) . ', ' .
$db->q($user->getName()) . ', ' .
$db->q($user->getEmail()) . ', ' .
$db->q($user->getPassword()) . ', ' .
$db->q($user->getParameters()->toString('JSON'))
);
}
$db->setQuery($query);
$db->execute();
$user->triggerEvent('onAfterSave');
}
/**
* Delete the user given their ID
*
* @param integer $id The numeric ID of the user record to delete
*
* @return boolean True on success
*
* @throws \RuntimeException If an error occurs when saving the user
*/
public function deleteUser($id)
{
if (empty($id))
{
return null;
}
$db = $this->container->db;
$query = $db->getQuery(true)
->delete($db->qn($this->user_table))
->where($db->qn('id') . ' = ' . $db->q($id));
$db->setQuery($query);
$db->execute();
}
/**
* Register a privilege plugin class with this user manager
*
* @param string $name The name of the privilege management object
* @param string $privilege The privilege management class name we will be attaching to user objects
*
* @return void
*/
public function <API key>($name, $privilege)
{
$this->privileges[$name] = $privilege;
}
/**
* Unregister a privilege plugin class from this user manager
*
* @param string $name The name of the privilege management object to unregister
*
* @return mixed
*/
public function <API key>($name)
{
if (isset($this->privileges[$name]))
{
unset($this->privileges[$name]);
}
}
/**
* Register a user authentication class with this user manager
*
* @param string $name The name of the user authentication object
* @param string $authentication The user authentication class name we will be attaching to user objects
*
* @return void
*/
public function register<API key>($name, $authentication)
{
$this->authentications[$name] = $authentication;
}
/**
* Unregister a user authentication class from this user manager
*
* @param string $name The name of the user authentication object to unregister
*
* @return mixed
*/
public function unregister<API key>($name)
{
if (isset($this->authentications[$name]))
{
unset($this->authentications[$name]);
}
}
} |
<?php
class CNewValidator {
private $rules;
private $input = [];
private $output = [];
private $errors = [];
private $errorsFatal = [];
/**
* Parser for validation rules.
*
* @var CValidationRule
*/
private $<API key>;
public function __construct(array $input, array $rules) {
$this->input = $input;
$this->rules = $rules;
$this-><API key> = new CValidationRule();
$this->validate();
}
/**
* Returns true if the given $value is valid, or set's an error and returns false otherwise.
*/
private function validate() {
foreach ($this->rules as $field => $rule) {
$result = $this->validateField($field, $rule);
if (array_key_exists($field, $this->input)) {
$this->output[$field] = $this->input[$field];
}
}
}
private function validateField($field, $rules) {
if (false === ($rules = $this-><API key>->parse($rules))) {
$this->addError(true, $this-><API key>->getError());
return false;
}
$fatal = array_key_exists('fatal', $rules);
$flags = array_key_exists('flags', $rules) ? $rules['flags'] : 0x00;
foreach ($rules as $rule => $params) {
switch ($rule) {
/*
* 'fatal' => true
*/
case 'fatal':
// nothing to do
break;
/*
* 'not_empty' => true
*/
case 'not_empty':
if (array_key_exists($field, $this->input) && $this->input[$field] === '') {
$this->addError($fatal,
_s('Incorrect value for field "%1$s": %2$s.', $field, _('cannot be empty'))
);
return false;
}
break;
case 'json':
if (array_key_exists($field, $this->input)) {
if (!is_string($this->input[$field]) || CJs::decodeJson($this->input[$field]) === null) {
$this->addError($fatal,
_s('Incorrect value for field "%1$s": %2$s.', $field, _('JSON string is expected'))
);
return false;
}
}
break;
/*
* 'in' => array(<values>)
*/
case 'in':
if (array_key_exists($field, $this->input)) {
if (!is_string($this->input[$field]) || !in_array($this->input[$field], $params)) {
$this->addError($fatal,
_s('Incorrect value "%1$s" for "%2$s" field.', $this->input[$field], $field)
// TODO: stringify($this->input[$field]) ???
);
return false;
}
}
break;
case 'int32':
if (array_key_exists($field, $this->input)) {
if (!is_string($this->input[$field]) || !$this->is_int32($this->input[$field])) {
$this->addError($fatal,
_s('Incorrect value "%1$s" for "%2$s" field.', $this->input[$field], $field)
// TODO: stringify($this->input[$field]) ???
);
return false;
}
}
break;
case 'id':
if (array_key_exists($field, $this->input)) {
if (!is_string($this->input[$field]) || !$this->is_id($this->input[$field])) {
$this->addError($fatal,
_s('Incorrect value "%1$s" for "%2$s" field.', $this->input[$field], $field)
// TODO: stringify($this->input[$field]) ???
);
return false;
}
}
break;
/*
* 'array_id' => true
*/
case 'array_id':
if (array_key_exists($field, $this->input)) {
if (!is_array($this->input[$field]) || !$this->is_array_id($this->input[$field])) {
$this->addError($fatal,
_s('Incorrect value "%1$s" for "%2$s" field.', $this->input[$field], $field)
// TODO: stringify($this->input[$field]) ???
);
return false;
}
}
break;
/*
* 'array' => true
*/
case 'array':
if (array_key_exists($field, $this->input) && !is_array($this->input[$field])) {
$this->addError($fatal,
_s('Incorrect value "%1$s" for "%2$s" field.', $this->input[$field], $field)
);
return false;
}
break;
/*
* 'array_db' => array(
* 'table' => <table_name>,
* 'field' => <field_name>
* )
*/
case 'array_db':
if (array_key_exists($field, $this->input)) {
if (!$this->is_array_db($this->input[$field], $params['table'], $params['field'], $flags)
|| !is_array($this->input[$field])) {
$this->addError($fatal,
_s('Incorrect value "%1$s" for "%2$s" field.', $this->input[$field], $field)
// TODO: stringify($this->input[$field]) ???
);
return false;
}
}
break;
/*
* 'ge' => <value>
*/
case 'ge':
if (array_key_exists($field, $this->input)) {
if (!is_string($this->input[$field]) || !$this->is_int32($this->input[$field])
|| $this->input[$field] < $params) {
$this->addError($fatal,
_s('Incorrect value "%1$s" for "%2$s" field.', $this->input[$field], $field)
);
return false;
}
}
break;
/*
* 'le' => <value>
*/
case 'le':
if (array_key_exists($field, $this->input)) {
if (!is_string($this->input[$field]) || !$this->is_int32($this->input[$field])
|| $this->input[$field] > $params) {
$this->addError($fatal,
_s('Incorrect value "%1$s" for "%2$s" field.', $this->input[$field], $field)
);
return false;
}
}
break;
/*
* 'db' => array(
* 'table' => <table_name>,
* 'field' => <field_name>
* )
*/
case 'db':
if (array_key_exists($field, $this->input)) {
if (!$this->is_db($this->input[$field], $params['table'], $params['field'], $flags)) {
$this->addError($fatal,
_s('Incorrect value "%1$s" for "%2$s" field.', $this->input[$field], $field)
// TODO: stringify($this->input[$field]) ???
);
return false;
}
}
break;
/*
* 'required' => true
*/
case 'required':
if (!array_key_exists($field, $this->input)) {
$this->addError($fatal, _s('Field "%1$s" is mandatory.', $field));
return false;
}
break;
/*
* 'string' => true
*/
case 'string':
if (array_key_exists($field, $this->input) && !is_string($this->input[$field])) {
$this->addError($fatal,
_s('Incorrect value for field "%1$s": %2$s.', $field, _('a character string is expected'))
);
return false;
}
break;
/*
* 'time' => true
*/
case 'time':
if (array_key_exists($field, $this->input) && !$this->is_time($this->input[$field])) {
$this->addError($fatal,
_s('Incorrect value for field "%1$s": %2$s.', $field, _('a time is expected'))
);
return false;
}
break;
/*
* 'flags' => <value1> | <value2> | ... | <valueN>
*/
case 'flags':
break;
default:
// the message can be not translated because it is an internal error
$this->addError($fatal, 'Invalid validation rule "'.$rule.'".');
return false;
}
}
return true;
}
private function is_id($value) {
if (1 != preg_match('/^[0-9]+$/', $value)) {
return false;
}
// between 0 and _I64_MAX
return (bccomp($value, '0') >= 0 && bccomp($value, '9223372036854775807') <= 0);
}
public static function is_int32($value) {
if (1 != preg_match('/^\-?[0-9]+$/', $value)) {
return false;
}
// between INT_MIN and INT_MAX
return (bccomp($value, ZBX_MIN_INT32) >= 0 && bccomp($value, ZBX_MAX_INT32) <= 0);
}
public static function is_uint64($value) {
if (1 != preg_match('/^[0-9]+$/', $value)) {
return false;
}
// between 0 and _UI64_MAX
return (bccomp($value, '0') >= 0 && bccomp($value, '<API key>') <= 0);
}
/**
* Validate value against DB schema.
*
* @param array $field_schema Array of DB schema.
* @param string $field_schema['type'] Type of DB field.
* @param string $field_schema['length'] Length of DB field.
* @param string $value [IN/OUT] IN - input value, OUT - changed value according to flags.
* @param int $flags Validation flags.
*
* @return bool
*/
private function check_db_value($field_schema, &$value, $flags) {
switch ($field_schema['type']) {
case DB::FIELD_TYPE_ID:
return $this->is_id($value);
case DB::FIELD_TYPE_INT:
return $this->is_int32($value);
case DB::FIELD_TYPE_CHAR:
if ($flags & P_CRLF) {
$value = CRLFtoLF($value);
}
return (mb_strlen($value) <= $field_schema['length']);
case DB::FIELD_TYPE_TEXT:
if ($flags & P_CRLF) {
$value = CRLFtoLF($value);
}
// TODO: check length
return true;
default:
return false;
}
}
private function is_array_id(array $values) {
foreach ($values as $value) {
if (!is_string($value) || !$this->is_id($value)) {
return false;
}
}
return true;
}
/**
* Validate array of string values against DB schema.
*
* @param array $values [IN/OUT] IN - input values, OUT - changed values according to flags.
* @param string $table DB table name.
* @param string $field DB field name.
* @param int $flags Validation flags.
*
* @return bool
*/
private function is_array_db(array &$values, $table, $field, $flags) {
$table_schema = DB::getSchema($table);
foreach ($values as &$value) {
if (!is_string($value) || !$this->check_db_value($table_schema['fields'][$field], $value, $flags)) {
return false;
}
}
unset($value);
return true;
}
/**
* Validate a string value against DB schema.
*
* @param string $value [IN/OUT] IN - input value, OUT - changed value according to flags.
* @param string $table DB table name.
* @param string $field DB field name.
* @param int $flags Validation flags.
*
* @return bool
*/
private function is_db(&$value, $table, $field, $flags) {
$table_schema = DB::getSchema($table);
return (is_string($value) && $this->check_db_value($table_schema['fields'][$field], $value, $flags));
}
private function isLeapYear($year) {
return (0 == $year % 4 && (0 != $year % 100 || 0 == $year % 400));
}
private function getDaysInMonth($year, $month) {
if (in_array($month, [4, 6, 9, 11], true)) {
return 30;
}
if ($month == 2) {
return $this->isLeapYear($year) ? 29 : 28;
}
return 31;
}
private function is_time($value) {
// YYYYMMDDhhmmss
if (!is_string($value) || strlen($value) != 14 || !ctype_digit($value)) {
return false;
}
$Y = (int) substr($value, 0, 4);
$M = (int) substr($value, 4, 2);
$D = (int) substr($value, 6, 2);
$h = (int) substr($value, 8, 2);
$m = (int) substr($value, 10, 2);
$s = (int) substr($value, 12, 2);
return ($Y >= 1990 && $M >= 1 && $M <= 12 && $D >= 1 && $D <= $this->getDaysInMonth($Y, $M)
&& $h >= 0 && $h <= 23 && $m >= 0 && $m <= 59 && $s >= 0 && $s <= 59);
}
/**
* Add validation error.
*
* @return string
*/
public function addError($fatal, $error) {
if ($fatal) {
$this->errorsFatal[] = $error;
}
else {
$this->errors[] = $error;
}
}
/**
* Get valid fields.
*
* @return array of fields passed validation
*/
public function getValidInput() {
return $this->output;
}
/**
* Returns array of error messages.
*
* @return array
*/
public function getAllErrors() {
return array_merge($this->errorsFatal, $this->errors);
}
/**
* Returns true if validation failed with errors.
*
* @return bool
*/
public function isError() {
return (bool) $this->errors;
}
/**
* Returns true if validation failed with fatal errors.
*
* @return bool
*/
public function isErrorFatal() {
return (bool) $this->errorsFatal;
}
} |
<?php
<API key>( 'blue', false, dirname( plugin_basename( __FILE__ ) ) .'/lang/' );
if(is_admin()):
include( plugin_dir_path( __FILE__ ) . 'blue-logo.php');
include( plugin_dir_path( __FILE__ ) . 'blue-options.php');
endif;
add_action('<API key>', 'custom_login_style');
function custom_login_style()
{
$options = get_option('default_style');
if ($options == "BlueWorld" || $options == null){
echo '<link rel="stylesheet" type="text/css" href="' . plugins_url('css/blueStyle.css', __FILE__) . '" />';
if ( is_rtl() ) {
echo '<link rel="stylesheet" type="text/css" href="' . plugins_url('css/rtl.css', __FILE__) . '" />';
}
}
else if ($options == "DarkLight"){
echo '<link rel="stylesheet" type="text/css" href="' . plugins_url('css/darkStyle.css', __FILE__) . '" />';
if ( is_rtl() ) {
echo '<link rel="stylesheet" type="text/css" href="' . plugins_url('css/rtl2.css', __FILE__) . '" />';
}
}
else if ($options == "SimpleBlue"){
echo '<link rel="stylesheet" type="text/css" href="' . plugins_url('css/grayStyle.css', __FILE__) . '" />';
if ( is_rtl() ) {
echo '<link rel="stylesheet" type="text/css" href="' . plugins_url('css/rtl2.css', __FILE__) . '" />';
}
}
else if ($options == "BlueMount"){
echo '<link rel="stylesheet" type="text/css" href="' . plugins_url('css/BlueMount.css', __FILE__) . '" />';
if ( is_rtl() ) {
echo '<link rel="stylesheet" type="text/css" href="' . plugins_url('css/rtl2.css', __FILE__) . '" />';
}
}
else if ($options == "WoodStyle"){
echo '<link rel="stylesheet" type="text/css" href="' . plugins_url('css/woodStyle.css', __FILE__) . '" />';
if ( is_rtl() ) {
echo '<link rel="stylesheet" type="text/css" href="' . plugins_url('css/rtl2.css', __FILE__) . '" />';
}
}
else if ($options == "BlurPurple"){
echo '<link rel="stylesheet" type="text/css" href="' . plugins_url('css/blur_purple.css', __FILE__) . '" />';
if ( is_rtl() ) {
echo '<link rel="stylesheet" type="text/css" href="' . plugins_url('css/rtl2.css', __FILE__) . '" />';
}
}
}
add_action('<API key>', 'custom_login_logo');
function custom_login_logo()
{
?>
<?php
$blue_options = get_option('theme_blue_options');
if ($blue_options['logo'] != '') {
$img_url = $blue_options['logo'];
function <API key>($attachment_url)
{
global $wpdb;
$attachment_id = false;
// If there is no url, return.
if ('' == $attachment_url)
return;
// Get the upload directory paths
$upload_dir_paths = wp_upload_dir();
// Make sure the upload path base directory exists in the attachment URL, to verify that we're working with a media library image
if (false !== strpos($attachment_url, $upload_dir_paths['baseurl'])) {
// If this is the URL of an auto-generated thumbnail, get the URL of the original image
$attachment_url = preg_replace('/-\d+x\d+(?=\.(jpg|jpeg|png|gif)$)/i', '', $attachment_url);
// Remove the upload path base directory from the attachment URL
$attachment_url = str_replace($upload_dir_paths['baseurl'] . '/', '', $attachment_url);
// Finally, run a custom database query to get the attachment ID from the modified attachment URL
$attachment_id = $wpdb->get_var($wpdb->prepare("SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = '_wp_attached_file' AND wpostmeta.meta_value = '%s' AND wposts.post_type = 'attachment'", $attachment_url));
}
return $attachment_id;
}
$imgwidth = <API key>($img_url);
$image_attributes = <API key>($imgwidth,'full');
$width = $image_attributes[1];
$height = $image_attributes[2];
} else {
$blue_options['logo'] = plugins_url('images/Blue-Login-Logo.png', __FILE__);
$width = 250;
$height = 63;
}
?>
<style type="text/css">
body.login div#login h1 a {
background-image: url(<?php
echo $blue_options['logo'];
?>);
height:<?php
echo $height;
?>px;
width:<?php
echo $width;
?>px;
background-size:auto;
margin-top:10px;
margin-left: auto;
margin-right: auto;
padding-bottom:10px;
}
</style>
<?php
}
add_action('login_headerurl', 'blue_login_url',9999);
function blue_login_url()
{
return home_url();
}
add_filter('login_headertitle', 'blue_login_text',9999);
function blue_login_text()
{
return get_bloginfo();
}
add_action('login_head', 'my_login_head');
function my_login_head() {
$options = get_option('default_style');
if ($options == "DarkLight"){
remove_action('login_head', 'wp_shake_js', 12);
}
}
add_filter( 'login_message', 'the_login_message' );
function the_login_message( $message ) {
if ( empty($message) ){
$options = get_option('login_message');
if ( !empty($options) ){
return "<p class='message'>" . $options ."<br></p>";
}
} else {
return $message;
}
}
add_filter( 'login_redirect', 'blue_login_redirect' );
function blue_login_redirect() {
$options = get_option('login_redirect');
if ( !empty($options) ){
// Change this to the url to Updates page.
return $options;
}
else return admin_url();
}
add_filter( '<API key>', '<API key>' );
function <API key>() {
$options = get_option('register_redirect');
if ( !empty($options) ){
// Change this to the url to Updates page.
return $options;
}
}
add_action( 'init', '<API key>' );
function <API key>() {
$options = get_option('logout_redirect');
if ( !empty($options) ){
if( isset($_GET['loggedout']) == 'true' ) {
$redirect_link=$options;
wp_redirect($redirect_link);
exit;
}
}
else return wp_login_url();
}
?> |
#ifndef MUDLET_TTOOLBAR_H
#define MUDLET_TTOOLBAR_H
#include "pre_guard.h"
#include <QDockWidget>
#include "post_guard.h"
class TAction;
class TFlipButton;
class QGridLayout;
class TToolBar : public QDockWidget
{
Q_OBJECT
Q_DISABLE_COPY(TToolBar)
public:
TToolBar(TAction*, const QString&, QWidget* pW = 0);
void addButton(TFlipButton* pW);
void resizeEvent(QResizeEvent* e) override;
void moveEvent(QMoveEvent* e) override;
void <API key>() { <API key> = true; }
void <API key>() { <API key> = false; }
void clear();
void finalize();
TAction* mpTAction;
void recordMove() { mRecordMove = true; }
QString getName() { return mName; }
private:
bool <API key>;
QWidget* mpWidget;
QString mName;
bool mRecordMove;
QGridLayout* mpLayout;
int mItemCount;
public slots:
void slot_pressed(const bool);
void <API key>(bool);
void <API key>(Qt::DockWidgetArea);
};
#endif // MUDLET_TTOOLBAR_H |
include $(TOPDIR)/rules.mk
PKG_NAME:=kodi-pvr-hts
PKG_RELEASE:=1
PKG_SOURCE_PROTO:=git
PKG_SOURCE_URL:=https://github.com/kodi-pvr/pvr.hts.git
PKG_SOURCE_DATE:=2017-02-23
PKG_SOURCE_VERSION:=<SHA1-like>
PKG_BUILD_DEPENDS:=kodi
include $(INCLUDE_DIR)/package.mk
include $(INCLUDE_DIR)/cmake.mk
define Package/kodi-pvr-hts
SECTION:=multimedia
CATEGORY:=Multimedia
TITLE:=kodi-pvr-hts
URL:=http:
DEPENDS:=+libkodiplatform +libstdcpp
MAINTAINER:=Stijn Tintel <stijn@linux-ipv6.be>
endef
CMAKE_OPTIONS += \
-DCMAKE_MODULE_PATH=$(STAGING_DIR_ROOT)/usr/share/kodi/cmake \
-DKodi_DIR=$(STAGING_DIR_ROOT)/usr/share/kodi/cmake
EXTRA_CXXFLAGS += -I$(STAGING_DIR)/usr/include/kodi
MAKE_FLAGS += VERBOSE=1
define Package/kodi-pvr-hts/install
$(INSTALL_DIR) $(1)/usr/lib $(1)/usr/share
$(CP) $(PKG_INSTALL_DIR)/usr/lib/kodi $(1)/usr/lib
$(CP) $(PKG_INSTALL_DIR)/usr/share/kodi $(1)/usr/share
endef
$(eval $(call BuildPackage,kodi-pvr-hts)) |
# CMake script behind the 'uninstall' target.
IF(NOT EXISTS "/home/ares/Developer/speed-dream-2.0/speed/install_manifest.txt")
MESSAGE(FATAL_ERROR "Cannot find install manifest: \"/home/ares/Developer/speed-dream-2.0/speed/install_manifest.txt\"")
ENDIF(NOT EXISTS "/home/ares/Developer/speed-dream-2.0/speed/install_manifest.txt")
FILE(READ "/home/ares/Developer/speed-dream-2.0/speed/install_manifest.txt" FILES_TO_REMOVE)
STRING(REGEX REPLACE "\n" ";" FILES_TO_REMOVE "${FILES_TO_REMOVE}")
FOREACH(FILE_TO_REMOVE ${FILES_TO_REMOVE})
MESSAGE(STATUS "Uninstalling: $ENV{DESTDIR}${FILE_TO_REMOVE}")
IF(EXISTS "$ENV{DESTDIR}${FILE_TO_REMOVE}")
EXEC_PROGRAM("/usr/bin/cmake" ARGS "-E remove \"$ENV{DESTDIR}${FILE_TO_REMOVE}\""
OUTPUT_VARIABLE RM_OUT RETURN_VALUE RM_RETVAL)
IF(NOT "${RM_RETVAL}" STREQUAL "0")
MESSAGE(FATAL_ERROR "Failed to remove $ENV{DESTDIR}${FILE_TO_REMOVE} (err code ${RM_RETVAL})")
ENDIF(NOT "${RM_RETVAL}" STREQUAL "0")
ELSE(EXISTS "$ENV{DESTDIR}${FILE_TO_REMOVE}")
MESSAGE(STATUS "File \"$ENV{DESTDIR}${FILE_TO_REMOVE}\" does not exist.")
ENDIF(EXISTS "$ENV{DESTDIR}${FILE_TO_REMOVE}")
ENDFOREACH(FILE_TO_REMOVE) |
package ue03;
import java.awt.Point;
public class Contoure {
final private boolean isOutline;
final private Point [] points;
public Contoure(boolean isOut, Point [] ps){
this.isOutline = isOut;
this.points = ps;
}
public Point [] getPoints(){
return this.points;
}
public boolean isOutline(){
return this.isOutline;
}
public Point getPoint(int index){
return this.points[index];
}
} |
<?php
namespace VuFindTest\ILS\Driver;
use VuFind\ILS\Driver\NewGenLib;
class NewGenLibTest extends \VuFindTest\Unit\ILSDriverTestCase
{
/**
* Standard setup method.
*
* @return void
*/
public function setUp()
{
$this->driver = new NewGenLib();
}
} |
package com.sun.media.jai.opimage;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.awt.image.DataBufferUShort;
import java.awt.image.<API key>;
import java.awt.image.SampleModel;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.awt.image.renderable.ParameterBlock;
import java.awt.image.renderable.<API key>;
import javax.media.jai.AreaOpImage;
import javax.media.jai.BorderExtender;
import javax.media.jai.ImageLayout;
import javax.media.jai.JAI;
import javax.media.jai.KernelJAI;
import javax.media.jai.OpImage;
import javax.media.jai.RasterAccessor;
import javax.media.jai.RasterFormatTag;
import java.util.Map;
import javax.media.jai.PixelAccessor;
import javax.media.jai.PackedImageData;
/**
*
* An OpImage class to perform erosion on a source image.
*
* <p> This class implements an erosion operation.
*
* <p> <b>Grey Scale Erosion</b>
* is a spatial operation that computes
* each output sample by subtract elements of a kernel to the samples
* surrounding a particular source sample with some care.
* A mathematical expression is:
*
* <p> For a kernel K with a key position (xKey, yKey), the erosion
* of image I at (x,y) is given by:
* <pre>
* max{a: a + K(xKey+i, yKey+j) <= I(x+i,y+j): all (i,j) }
*
* all possible (i,j) means that both I(x+i,y+j) and K(xKey+i, yKey+j)
* are in bounds. Otherwise, the value is set to 0.
*
* </pre>
* <p> Intuitively, the kernel is like an unbrella and the key point
* is the handle. At every point, you try to push the umbrella up as high
* as possible but still underneath the image surface. The final height
* of the handle is the value after erosion. Thus if you want the image
* to erode from the upper right to bottom left, the following would do.
*
* <p><center>
* <table border=1>
* <tr align=center><td>0</td><td>0</td><td>X</td> </tr>
* <tr align=center><td>0</td><td>X</td><td>0</td> </tr>
* <tr align=center><td><b>X</b></td><td>0</td><td>0</td> </tr>
* </table></center>
*
* <p> Note that zero kernel erosion has effects on the image, the
* location of the key position and size of kernel all matter.
*
* <p> Pseudo code for the erosion operation is as follows.
* Assuming the kernel K is of size M rows x N cols
* and the key position is (xKey, yKey).
*
* <pre>
*
* // erosion
* for every dst pixel location (x,y){
* tmp = infinity;
* for (i = -xKey; i < M - xKey; i++){
* for (j = -yKey; j < N - yKey; j++){
* if((x+i, y+j) are in bounds of src){
* tmp = min{tmp, src[x + i][y + j] - K[xKey + i][yKey + j]};
* }
* }
* }
* dst[x][y] = tmp;
* if (dst[x][y] == infinity)
* dst[x][y] = 0;
* }
* </pre>
*
* <p> The kernel cannot be bigger in any dimension than the image data.
*
* <p> <b>Binary Image Erosion</b>
* requires the kernel to be binary as well.
* Intuitively, binary erosion slides the kernel
* key position and place it at every non-zero point (x,y) in the src image.
* The dst value at this position is set to 1 if all the kernel
* are fully supported by the src image, and the src image value is 1
* whenever the kernel has value 1.
* Otherwise, the value after erosion at (x,y) is set to 0.
* Erosion usually shrinks images, but it can fill holes
* with kernels like
* <pre> [1 0 1] </pre>
* and the key position at the center.
*
* <p> Pseudo code for the erosion operation is as follows.
*
* <pre>
* // erosion
* for every dst pixel location (x,y){
* dst[x][y] = 1;
* for (i = -xKey; i < M - xKey; i++){
* for (j = -yKey; j < N - yKey; j++){
* if((x+i,y+j) is out of bounds of src ||
* src(x+i, y+j)==0 && Key(xKey+i, yKey+j)==1){
* dst[x][y] = 0; break;
* }
* }
* }
* }
* </pre>
*
* <p> Reference: An Introduction to Nonlinear Image Processing,
* by Edward R. Bougherty and Jaakko Astola,
* Spie Optical Engineering Press, 1994.
*
*
* @see KernelJAI
*/
final class ErodeBinaryOpImage extends AreaOpImage {
/**
* The kernel with which to do the erode operation.
*/
protected KernelJAI kernel;
/** Kernel variables. */
private int kw, kh, kx, ky;
private int[] kdataPack; // Pack kernel into integers;
private int kwPack;
// for factoring things out
private int dwidth, dheight;
private int dnumBands; // should be 1; gray images
private int bits; // per packed unit, 8, 16 or 32
//private int dstBandOffsets[];
private int dstDBOffset;
private int dstScanlineStride;
private int <API key>;
private int dstMinX, dstMinY, dstTransX, dstTransY;
private int dstDataBitOffset;
//private int srcBandOffsets[];
private int srcDBOffset;
private int srcScanlineStride;
private int <API key>;
private int srcMinX, srcMinY, srcTransX, srcTransY;
private int srcDataBitOffset;
// Since this operation deals with packed binary data, we do not need
// to expand the IndexColorModel
private static Map configHelper(Map configuration) {
Map config;
if (configuration == null) {
config = new RenderingHints(JAI.<API key>,
Boolean.FALSE);
} else {
config = configuration;
if (!(config.containsKey(JAI.<API key>))) {
RenderingHints hints = (RenderingHints)configuration;
config = (RenderingHints)hints.clone();
config.put(JAI.<API key>, Boolean.FALSE);
}
}
return config;
}
/**
* Creates a ErodeBinaryOpImage given a ParameterBlock containing the image
* source and pre-rotated erosion kernel. The image dimensions are
* derived
* from the source image. The tile grid layout, SampleModel, and
* ColorModel may optionally be specified by an ImageLayout
* object.
*
* @param source a RenderedImage.
* @param extender a BorderExtender, or null.
* @param layout an ImageLayout optionally containing the tile grid layout,
* SampleModel, and ColorModel, or null.
* @param kernel the pre-rotated erosion KernelJAI.
*/
public ErodeBinaryOpImage(RenderedImage source,
BorderExtender extender,
Map config,
ImageLayout layout,
KernelJAI kernel) {
super(source,
layout,
configHelper(config),
true,
extender,
kernel.getLeftPadding(),
kernel.getRightPadding(),
kernel.getTopPadding(),
kernel.getBottomPadding());
this.kernel = kernel;
kw = kernel.getWidth();
kh = kernel.getHeight();
kx = kernel.getXOrigin();
ky = kernel.getYOrigin();
kwPack = (kw+31)/32;
kdataPack = packKernel(kernel);
}
/**
* Performs erosion on a specified rectangle. The sources are
* cobbled.
*
* @param sources an array of source Rasters, guaranteed to provide all
* necessary source data for computing the output.
* @param dest a WritableRaster tile containing the area to be computed.
* @param destRect the rectangle within dest to be processed.
*/
protected void computeRect(Raster[] sources,
WritableRaster dest,
Rectangle destRect) {
Raster source = sources[0];
PixelAccessor pa = new PixelAccessor(source.getSampleModel(), null);
PackedImageData srcIm =
pa.getPackedPixels(source, source.getBounds(), false, false);
pa = new PixelAccessor(dest.getSampleModel(), null);
PackedImageData dstIm =
pa.getPackedPixels(dest, destRect, true, false);
// src data under kernel, packed in int.
int[] srcUK = new int [kwPack * kh];
// sliding the kernel row by row
// general the packed matrix under the row
int dheight = destRect.height;
int dwidth = destRect.width;
int sOffset = srcIm.offset;
int dOffset = dstIm.offset;
for (int j = 0; j < dheight; j++) {
int selement, val, dindex, delement;
// reset srcUK for each row beginning
// src[sOffset +[-kx:kw-kx, -ky:kh-ky]] placed in srcUK
for (int m = 0; m < srcUK.length; m++){
srcUK[m] = 0;
}
// initial srcUK
// first shift left the packed bits under the sliding kernel by 1 bit
// then fill (compute) in the last bit of each row
for(int i = 0; i < kw -1; i++){
bitShiftMatrixLeft(srcUK, kh, kwPack); // expand for speedup?
int lastCol = kwPack - 1;
int bitLoc = srcIm.bitOffset + i;
int byteLoc = bitLoc >> 3;
bitLoc = 7 - (bitLoc & 7);
for(int m=0, sOffsetB = sOffset;
m < kh;
m++, sOffsetB += srcIm.lineStride){
selement = (int)srcIm.data[sOffsetB + byteLoc];
val = (selement >> bitLoc) & 0x1;
srcUK[lastCol] |= val;
lastCol += kwPack;
}
}
// same as above
// also setting dest
for (int i = 0; i < dwidth; i++){
bitShiftMatrixLeft(srcUK, kh, kwPack); // expand for speedup?
int lastCol = kwPack - 1;
int bitLoc = srcIm.bitOffset + i + kw -1;
int byteLoc = bitLoc >> 3;
bitLoc = 7 - (bitLoc & 7);
for(int m=0, sOffsetB = sOffset;
m < kh;
m++, sOffsetB += srcIm.lineStride){
selement = (int)srcIm.data[sOffsetB + byteLoc];
val = (selement >> bitLoc) & 0x1;
srcUK[lastCol] |= val;
lastCol += kwPack;
}
int dBitLoc = dstIm.bitOffset + i;
int dshift = 7 - (dBitLoc & 7);
int dByteLoc= (dBitLoc >> 3) + dOffset;
delement = (int)dstIm.data[dByteLoc];
delement |= (0x1) << dshift;
for (int m = 0; m < srcUK.length; m++){
if ((srcUK[m] & kdataPack[m]) != kdataPack[m]){
delement &= ~((0x1) << dshift);
break;
}
}
dstIm.data[dByteLoc] = (byte)delement;
}
sOffset += srcIm.lineStride;
dOffset += dstIm.lineStride;
}
pa.setPackedPixels(dstIm);
}
/** pack kernel into integers by row, aligned to the right;
* extra bits on the left are filled with 0 bits
* @params kernel - the given kernel (already rotated)
* @returns an integer array of ints from packed kernel data
*/
private final int[] packKernel(KernelJAI kernel){
int kw = kernel.getWidth();
int kh = kernel.getHeight();
int kwPack = (31+kw)/32;
int kerPacked[] = new int[kwPack * kh];
float[] kdata = kernel.getKernelData();
for (int j=0; j<kw; j++){
int m = j;
int lastCol = kwPack - 1;
bitShiftMatrixLeft(kerPacked, kh, kwPack);
for (int i=0; i< kh; i++, lastCol+=kwPack, m+= kw){
if (kdata[m] > .9F){ // same as == 1.0F
kerPacked[lastCol] |= 0x1;
}
}
}
return kerPacked;
}
// to shift an integer matrix one bit left
// assuming that the matrix is row oriented
// each row is viewed as a long bit array
// rows and cols are the dimention after packing
private final static void bitShiftMatrixLeft(int[] mat, int rows, int cols){
int m = 0;
for (int i=0; i<rows; i++){
for (int j=0; j< cols-1; j++){
mat[m] = (mat[m]<< 1) | (mat[m+1] >>> 31);
m++;
}
mat[m] <<= 1;
m++;
}
}
} |
package pt.c08componentes.s02jcomponent;
import java.awt.Graphics;
import javax.swing.JComponent;
public class Bean01CirculoVisual extends JComponent implements <API key> {
private static final long serialVersionUID = <API key>;
private int raio = 50;
public Bean01CirculoVisual() {
super();
}
@Override
public int getRaio() {
return raio;
}
@Override
public void setRaio(int raio) {
this.raio = raio;
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(10, 10, raio*2, raio*2);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.