code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
<?php
/**
* @version 3.2.11 September 8, 2011
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2011 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
defined('GANTRY_VERSION') or die;
gantry_import('core.config.gantryformgroup');
gantry_import('core.config.gantryformfield');
class GantryFormGroupEnabledGroup extends GantryFormGroup
{
protected $type = 'enabledgroup';
protected $baseetype = 'group';
protected $sets = array();
protected $enabler;
public function getInput()
{
global $gantry;
$buffer = '';
// get the sets just below
foreach ($this->fields as $field)
{
if ($field->type == 'set')
{
$this->sets[] = $field;
}
}
$buffer .= "<div class='wrapper'>\n";
foreach ($this->fields as $field)
{
if ((string)$field->type != 'set')
{
$enabler = false;
if ($field->element['enabler'] && (string)$field->element['enabler'] == true){
$this->enabler = $field;
$enabler = true;
}
$itemName = $this->fieldname . "-" . $field->fieldname;
$buffer .= '<div class="chain ' . $itemName . ' chain-' . strtolower($field->type) . '">' . "\n";
if (strlen($field->getLabel())) $buffer .= '<span class="chain-label">' . JText::_($field->getLabel()) . '</span>' . "\n";
if ($enabler) $buffer .= '<div class="enabledset-enabler">'."\n";
$buffer .= $field->getInput();
if ($enabler) $buffer .= '</div>'."\n";
$buffer .= "</div>" . "\n";
}
}
$buffer .= "</div>" . "\n";
return $buffer;
}
public function render($callback)
{
$buffer = parent::render($callback);
$cls = ' enabledset-hidden-field';
if (!empty($this->sets)){
$set = array_shift($this->sets);
if (isset($this->enabler) && (int)$this->enabler->value == 0){
$cls = ' enabledset-hidden-field';
}
$buffer .= '<div class="enabledset-fields'.$cls.'" id="set-'.(string)$set->element['name'].'">';
foreach ($set->fields as $field)
{
if ($field->type == 'hidden')
$buffer .= $field->getInput();
else
{
$buffer .= $field->render($callback);
}
}
$buffer .= '</div>';
}
return $buffer;
}
} | epireve/joomla | libraries/gantry/admin/forms/groups/enabledgroup.php | PHP | gpl-2.0 | 2,633 |
# -*- coding: utf-8 -*-
import time
import EafIO
import warnings
class Eaf:
"""Read and write Elan's Eaf files.
.. note:: All times are in milliseconds and can't have decimals.
:var dict annotation_document: Annotation document TAG entries.
:var dict licences: Licences included in the file.
:var dict header: XML header.
:var list media_descriptors: Linked files, where every file is of the
form: ``{attrib}``.
:var list properties: Properties, where every property is of the form:
``(value, {attrib})``.
:var list linked_file_descriptors: Secondary linked files, where every
linked file is of the form:
``{attrib}``.
:var dict timeslots: Timeslot data of the form:
``{TimslotID -> time(ms)}``.
:var dict tiers: Tier data of the form:
``{tier_name -> (aligned_annotations,
reference_annotations, attributes, ordinal)}``,
aligned_annotations of the form:
``[{annotation_id ->
(begin_ts, end_ts, value, svg_ref)}]``,
reference annotations of the form:
``[{annotation_id ->
(reference, value, previous, svg_ref)}]``.
:var list linguistic_types: Linguistic types, where every type is of the
form: ``{id -> attrib}``.
:var list locales: Locales, where every locale is of the form:
``{attrib}``.
:var dict constraints: Constraint data of the form:
``{stereotype -> description}``.
:var dict controlled_vocabularies: Controlled vocabulary data of the
form: ``{id ->
(descriptions, entries, ext_ref)}``,
descriptions of the form:
``[(lang_ref, text)]``,
entries of the form:
``{id -> (values, ext_ref)}``,
values of the form:
``[(lang_ref, description, text)]``.
:var list external_refs: External references, where every reference is of
the form ``[id, type, value]``.
:var list lexicon_refs: Lexicon references, where every reference is of
the form: ``[{attribs}]``.
"""
def __init__(self, file_path=None, author='pympi'):
"""Construct either a new Eaf file or read on from a file/stream.
:param str file_path: Path to read from, - for stdin. If ``None`` an
empty Eaf file will be created.
:param str author: Author of the file.
"""
self.naive_gen_ann, self.naive_gen_ts = False, False
self.annotation_document = {
'AUTHOR': author,
'DATE': time.strftime("%Y-%m-%dT%H:%M:%S%z"),
'VERSION': '2.8',
'FORMAT': '2.8',
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:noNamespaceSchemaLocation':
'http://www.mpi.nl/tools/elan/EAFv2.8.xsd'}
self.constraints = {}
self.controlled_vocabularies = {}
self.header = {}
self.licences = {}
self.linguistic_types = {}
self.tiers = {}
self.timeslots = {}
self.external_refs = []
self.lexicon_refs = []
self.linked_file_descriptors = []
self.locales = []
self.media_descriptors = []
self.properties = []
self.new_time, self.new_ann = 0, 0
if file_path is None:
self.add_linguistic_type('default-lt', None)
self.constraints = {'Time_Subdivision': 'Time subdivision of paren'
't annotation\'s time interval, no time gaps a'
'llowed within this interval',
'Symbolic_Subdivision': 'Symbolic subdivision '
'of a parent annotation. Annotations refering '
'to the same parent are ordered',
'Symbolic_Association': '1-1 association with '
'a parent annotation',
'Included_In': 'Time alignable annotations wit'
'hin the parent annotation\'s time interval, g'
'aps are allowed'}
self.properties.append(('0', {'NAME': 'lastUsedAnnotation'}))
self.add_tier('default')
else:
EafIO.parse_eaf(file_path, self)
def to_file(self, file_path, pretty=True):
"""Write the object to a file, if the file already exists a backup will
be created with the ``.bak`` suffix.
:param str file_path: Path to write to, - for stdout.
:param bool pretty: Flag for pretty XML printing.
"""
EafIO.to_eaf(file_path, self, pretty)
def to_textgrid(self, excluded_tiers=[], included_tiers=[]):
"""Convert the object to a :class:`pympi.Praat.TextGrid` object.
:param list excluded_tiers: Specifically exclude these tiers.
:param list included_tiers: Only include this tiers, when empty all are
included.
:returns: :class:`pympi.Praat.TextGrid` object
:raises ImportError: If the pympi.Praat module can't be loaded.
"""
from Praat import TextGrid
tgout = TextGrid()
tiers = [a for a in self.tiers if a not in excluded_tiers]
if included_tiers:
tiers = [a for a in tiers if a in included_tiers]
for tier in tiers:
currentTier = tgout.add_tier(tier)
for interval in self.get_annotation_data_for_tier(tier):
if interval[0] == interval[1]:
continue
currentTier.add_interval(interval[0]/1000.0,
interval[1]/1000.0, interval[2])
return tgout
def extract(self, start, end):
"""Extracts the selected time frame as a new object.
:param int start: Start time.
:param int end: End time.
:returns: The extracted frame in a new object.
"""
from copy import deepcopy
eaf_out = deepcopy(self)
for tier in eaf_out.tiers.itervalues():
rems = []
for ann in tier[0]:
if eaf_out.timeslots[tier[0][ann][1]] > end or\
eaf_out.timeslots[tier[0][ann][0]] < start:
rems.append(ann)
for r in rems:
del tier[0][r]
return eaf_out
def get_linked_files(self):
"""Give all linked files."""
return self.media_descriptors
def add_linked_file(self, file_path, relpath=None, mimetype=None,
time_origin=None, ex_from=None):
"""Add a linked file.
:param str file_path: Path of the file.
:param str relpath: Relative path of the file.
:param str mimetype: Mimetype of the file, if ``None`` it tries to
guess it according to the file extension which
currently only works for wav, mpg, mpeg and xml.
:param int time_origin: Time origin for the media file.
:param str ex_from: Extracted from field.
:raises KeyError: If mimetype had to be guessed and a non standard
extension or an unknown mimetype.
"""
if mimetype is None:
mimes = {'wav': 'audio/x-wav', 'mpg': 'video/mpeg',
'mpeg': 'video/mpg', 'xml': 'text/xml'}
mimetype = mimes[file_path.split('.')[-1]]
self.media_descriptors.append({
'MEDIA_URL': file_path, 'RELATIVE_MEDIA_URL': relpath,
'MIME_TYPE': mimetype, 'TIME_ORIGIN': time_origin,
'EXTRACTED_FROM': ex_from})
def copy_tier(self, eaf_obj, tier_name):
"""Copies a tier to another :class:`pympi.Elan.Eaf` object.
:param pympi.Elan.Eaf eaf_obj: Target Eaf object.
:param str tier_name: Name of the tier.
:raises KeyError: If the tier doesn't exist.
"""
eaf_obj.remove_tier(tier_name)
eaf_obj.add_tier(tier_name, tier_dict=self.tiers[tier_name][3])
for ann in self.get_annotation_data_for_tier(tier_name):
eaf_obj.insert_annotation(tier_name, ann[0], ann[1], ann[2])
def add_tier(self, tier_id, ling='default-lt', parent=None, locale=None,
part=None, ann=None, tier_dict=None):
"""Add a tier.
:param str tier_id: Name of the tier.
:param str ling: Linguistic type, if the type is not available it will
warn and pick the first available type.
:param str parent: Parent tier name.
:param str locale: Locale.
:param str part: Participant.
:param str ann: Annotator.
:param dict tier_dict: TAG attributes, when this is not ``None`` it
will ignore all other options.
"""
if ling not in self.linguistic_types:
warnings.warn(
'add_tier: Linguistic type non existent, choosing the first')
ling = self.linguistic_types.keys()[0]
if tier_dict is None:
self.tiers[tier_id] = ({}, {}, {
'TIER_ID': tier_id,
'LINGUISTIC_TYPE_REF': ling,
'PARENT_REF': parent,
'PARTICIPANT': part,
'DEFAULT_LOCALE': locale,
'ANNOTATOR': ann}, len(self.tiers))
else:
self.tiers[tier_id] = ({}, {}, tier_dict, len(self.tiers))
def remove_tiers(self, tiers):
"""Remove multiple tiers, note that this is a lot faster then removing
them individually because of the delayed cleaning of timeslots.
:param list tiers: Names of the tier to remove.
:raises KeyError: If a tier is non existent.
"""
for a in tiers:
self.remove_tier(a, check=False, clean=False)
self.clean_time_slots()
def remove_tier(self, id_tier, clean=True):
"""Remove tier.
:param str id_tier: Name of the tier.
:param bool clean: Flag to also clean the timeslots.
:raises KeyError: If tier is non existent.
"""
del(self.tiers[id_tier])
if clean:
self.clean_time_slots()
def get_tier_names(self):
"""List all the tier names.
:returns: List of all tier names
"""
return self.tiers.keys()
def get_parameters_for_tier(self, id_tier):
"""Give the parameter dictionary, this is usaable in :func:`add_tier`.
:param str id_tier: Name of the tier.
:returns: Dictionary of parameters.
:raises KeyError: If the tier is non existent.
"""
return self.tiers[id_tier][2]
def child_tiers_for(self, id_tier):
"""Give all child tiers for a tier.
:param str id_tier: Name of the tier.
:returns: List of all children
:raises KeyError: If the tier is non existent.
"""
return [m for m in self.tiers if 'PARENT_REF' in self.tiers[m][2] and
self.tiers[m][2]['PARENT_REF'] == id_tier]
def get_annotation_data_for_tier(self, id_tier):
"""Gives a list of annotations of the form: ``(begin, end, value)``
:param str id_tier: Name of the tier.
:raises KeyError: If the tier is non existent.
"""
a = self.tiers[id_tier][0]
return [(self.timeslots[a[b][0]], self.timeslots[a[b][1]], a[b][2])
for b in a]
def get_annotation_data_at_time(self, id_tier, time):
"""Give the annotations at the given time.
:param str id_tier: Name of the tier.
:param int time: Time of the annotation.
:returns: List of annotations at that time.
:raises KeyError: If the tier is non existent.
"""
anns = self.tiers[id_tier][0]
return sorted(
[(self.timeslots[m[0]], self.timeslots[m[1]], m[2])
for m in anns.itervalues() if
self.timeslots[m[0]] <= time and
self.timeslots[m[1]] >= time])
def get_annotation_datas_between_times(self, id_tier, start, end):
"""Gives the annotations within the times.
:param str id_tier: Name of the tier.
:param int start: Start time of the annotation.
:param int end: End time of the annotation.
:returns: List of annotations within that time.
:raises KeyError: If the tier is non existent.
"""
anns = self.tiers[id_tier][0]
return sorted([
(self.timeslots[m[0]], self.timeslots[m[1]], m[2])
for m in anns.itervalues() if self.timeslots[m[1]] >= start and
self.timeslots[m[0]] <= end])
def remove_all_annotations_from_tier(self, id_tier):
"""remove all annotations from a tier
:param str id_tier: Name of the tier.
:raises KeyError: If the tier is non existent.
"""
self.tiers[id_tier][0], self.tiers[id_tier][1] = {}, {}
self.clean_time_slots()
def insert_annotation(self, id_tier, start, end, value='', svg_ref=None):
"""Insert an annotation.
:param str id_tier: Name of the tier.
:param int start: Start time of the annotation.
:param int end: End time of the annotation.
:param str value: Value of the annotation.
:param str svg_ref: Svg reference.
:raises KeyError: If the tier is non existent.
"""
start_ts = self.generate_ts_id(start)
end_ts = self.generate_ts_id(end)
self.tiers[id_tier][0][self.generate_annotation_id()] =\
(start_ts, end_ts, value, svg_ref)
def remove_annotation(self, id_tier, time, clean=True):
"""Remove an annotation in a tier, if you need speed the best thing is
to clean the timeslots after the last removal.
:param str id_tier: Name of the tier.
:param int time: Timepoint within the annotation.
:param bool clean: Flag to clean the timeslots afterwards.
:raises KeyError: If the tier is non existent.
"""
for b in [a for a in self.tiers[id_tier][0].iteritems() if
a[1][0] >= time and a[1][1] <= time]:
del(self.tiers[id_tier][0][b[0]])
if clean:
self.clean_time_slots()
def insert_ref_annotation(self, id_tier, ref, value, prev, svg_ref=None):
"""Insert a reference annotation.
:param str id_tier: Name of the tier.
:param str ref: Id of the referenced annotation.
:param str value: Value of the annotation.
:param str prev: Id of the previous annotation.
:param str svg_ref: Svg reference.
:raises KeyError: If the tier is non existent.
"""
self.tiers[id_tier][1][self.generate_annotation_id()] =\
(ref, value, prev, svg_ref)
def get_ref_annotation_data_for_tier(self, id_tier):
""""Give a list of all reference annotations of the form:
``[{id -> (ref, value, previous, svg_ref}]``
:param str id_tier: Name of the tier.
:raises KeyError: If the tier is non existent.
"""
return self.tiers[id_tier][1]
def remove_controlled_vocabulary(self, cv):
"""Remove a controlled vocabulary.
:param str cv: Controlled vocabulary id.
:raises KeyError: If the controlled vocabulary is non existent.
"""
del(self.controlled_vocabularies[cv])
def generate_annotation_id(self):
"""Generate the next annotation id, this function is mainly used
internally.
"""
if self.naive_gen_ann:
new = self.last_ann+1
self.last_ann = new
else:
new = 1
anns = {int(ann[1:]) for tier in self.tiers.itervalues()
for ann in tier[0]}
if len(anns) > 0:
newann = set(xrange(1, max(anns))).difference(anns)
if len(newann) == 0:
new = max(anns)+1
self.naive_gen_ann = True
self.last_ann = new
else:
new = sorted(newann)[0]
return 'a%d' % new
def generate_ts_id(self, time=None):
"""Generate the next timeslot id, this function is mainly used
internally
:param int time: Initial time to assign to the timeslot
"""
if self.naive_gen_ts:
new = self.last_ts+1
self.last_ts = new
else:
new = 1
tss = {int(x[2:]) for x in self.timeslots}
if len(tss) > 0:
newts = set(xrange(1, max(tss))).difference(tss)
if len(newts) == 0:
new = max(tss)+1
self.naive_gen_ts = True
self.last_ts = new
else:
new = sorted(newts)[0]
ts = 'ts%d' % new
self.timeslots[ts] = time
return ts
def clean_time_slots(self):
"""Clean up all unused timeslots.
.. warning:: This can and will take time for larger tiers. When you
want to do a lot of operations on a lot of tiers please
unset the flags for cleaning in the functions so that the
cleaning is only performed afterwards.
"""
ts_in_tier = set(sum([a[0:2] for tier in self.tiers.itervalues()
for a in tier[0].itervalues()], ()))
ts_avail = set(self.timeslots)
for a in ts_in_tier.symmetric_difference(ts_avail):
del(self.timeslots[a])
self.naive_gen_ts = False
self.naive_gen_ann = False
def generate_annotation_concat(self, tiers, start, end, sep='-'):
"""Give a string of concatenated annotation values for annotations
within a timeframe.
:param list tiers: List of tier names.
:param int start: Start time.
:param int end: End time.
:param str sep: Separator string to use.
:returns: String containing a concatenation of annotation values.
:raises KeyError: If a tier is non existent.
"""
return sep.join(
set(d[2] for t in tiers if t in self.tiers for d in
self.get_annotation_datas_between_times(t, start, end)))
def merge_tiers(self, tiers, tiernew=None, gaptresh=1):
"""Merge tiers into a new tier and when the gap is lower then the
threshhold glue the annotations together.
:param list tiers: List of tier names.
:param str tiernew: Name for the new tier, if ``None`` the name will be
generated.
:param int gapthresh: Threshhold for the gaps.
:raises KeyError: If a tier is non existent.
:raises TypeError: If there are no annotations within the tiers.
"""
if tiernew is None:
tiernew = '%s_Merged' % '_'.join(tiers)
self.remove_tier(tiernew)
self.add_tier(tiernew)
timepts = sorted(set.union(
*[set(j for j in xrange(d[0], d[1])) for d in
[ann for tier in tiers for ann in
self.get_annotation_data_for_tier(tier)]]))
if len(timepts) > 1:
start = timepts[0]
for i in xrange(1, len(timepts)):
if timepts[i]-timepts[i-1] > gaptresh:
self.insert_annotation(
tiernew, start, timepts[i-1],
self.generate_annotation_concat(tiers, start,
timepts[i-1]))
start = timepts[i]
self.insert_annotation(
tiernew, start, timepts[i-1],
self.generate_annotation_concat(tiers, start, timepts[i-1]))
def shift_annotations(self, time):
"""Shift all annotations in time, this creates a new object.
:param int time: Time shift width, negative numbers make a right shift.
:returns: Shifted :class:`pympi.Elan.Eaf' object.
"""
e = self.extract(
-1*time, self.get_full_time_interval()[1]) if time < 0 else\
self.extract(0, self.get_full_time_interval()[1]-time)
for tier in e.tiers.itervalues():
for ann in tier[0].itervalues():
e.timeslots[ann[0]] = e.timeslots[ann[0]]+time
e.timeslots[ann[1]] = e.timeslots[ann[1]]+time
e.clean_time_slots()
return e
def filterAnnotations(self, tier, tier_name=None, filtin=None,
filtex=None):
"""Filter annotations in a tier
:param str tier: Name of the tier:
:param str tier_name: Name of the new tier, when ``None`` the name will
be generated.
:param list filtin: List of strings to be included, if None all
annotations all is included.
:param list filtex: List of strings to be excluded, if None no strings
are excluded.
:raises KeyError: If the tier is non existent.
"""
if tier_name is None:
tier_name = '%s_filter' % tier
self.remove_tier(tier_name)
self.add_tier(tier_name)
for a in [b for b in self.get_annotation_data_for_tier(tier)
if (filtex is None or b[2] not in filtex) and
(filtin is None or b[2] in filtin)]:
self.insert_annotation(tier_name, a[0], a[1], a[2])
def glue_annotations_in_tier(self, tier, tier_name=None, treshhold=85,
filtin=None, filtex=None):
"""Glue annotatotions together in a tier.
:param str tier: Name of the tier.
:param str tier_name: Name of the new tier, if ``None`` the name will
be generated.
:param int threshhold: Threshhold for the maximum gap to still glue.
:param list filtin: List of strings to be included, if None all
annotations all is included.
:param list filtex: List of strings to be excluded, if None no strings
are excluded.
:raises KeyError: If the tier is non existent.
"""
if tier_name is None:
tier_name = '%s_glued' % tier
self.remove_tier(tier_name)
self.add_tier(tier_name)
tier_data = sorted(self.get_annotation_data_for_tier(tier))
tier_data = [t for t in tier_data if
(filtin is None or t[2] in filtin) and
(filtex is None or t[2] not in filtex)]
currentAnn = None
for i in xrange(0, len(tier_data)):
if currentAnn is None:
currentAnn = (tier_data[i][0], tier_data[i][1],
tier_data[i][2])
elif tier_data[i][0] - currentAnn[1] < treshhold:
currentAnn = (currentAnn[0], tier_data[i][1],
'%s_%s' % (currentAnn[2], tier_data[i][2]))
else:
self.insert_annotation(tier_name, currentAnn[0], currentAnn[1],
currentAnn[2])
currentAnn = tier_data[i]
if currentAnn is not None:
self.insert_annotation(tier_name, currentAnn[0],
tier_data[len(tier_data)-1][1],
currentAnn[2])
def get_full_time_interval(self):
"""Give the full time interval of the file.
:returns: Tuple of the form: ``(min_time, max_time``.
"""
return (min(self.timeslots.itervalues()),
max(self.timeslots.itervalues()))
def create_gaps_and_overlaps_tier(self, tier1, tier2, tier_name=None,
maxlen=-1):
"""Create a tier with the gaps and overlaps of the annotations.
For types see :func:`get_gaps_and_overlaps_duration`
:param str tier1: Name of the first tier.
:param str tier2: Name of the second tier.
:param str tier_name: Name of the new tier, if ``None`` the name will
be generated.
:param int maxlen: Maximum length of gaps (skip longer ones), if ``-1``
no maximum will be used.
:returns: List of gaps and overlaps of the form:
``[(type, start, end)]``.
:raises KeyError: If a tier is non existent.
:raises IndexError: If no annotations are available in the tiers.
"""
if tier_name is None:
tier_name = '%s_%s_ftos' % (tier1, tier2)
self.remove_tier(tier_name)
self.add_tier(tier_name)
ftos = self.get_gaps_and_overlaps_duration(tier1, tier2, maxlen)
for fto in ftos:
self.insert_annotation(tier_name, fto[1], fto[2], fto[0])
return ftos
def get_gaps_and_overlaps_duration(self, tier1, tier2, maxlen=-1,
progressbar=False):
"""Give gaps and overlaps. The return types are shown in the table
below. The string will be of the format: ``id_tiername_tiername``.
For example when a gap occurs between tier1 and tier2 and they are
called ``speakerA`` and ``speakerB`` the annotation value of that gap
will be ``G12_speakerA_speakerB``.
| The gaps and overlaps are calculated using Heldner and Edlunds
method found in:
| *Heldner, M., & Edlund, J. (2010). Pauses, gaps and overlaps in
conversations. Journal of Phonetics, 38(4), 555–568.
doi:10.1016/j.wocn.2010.08.002*
+-----+--------------------------------------------+
| id | Description |
+=====+============================================+
| O12 | Overlap from tier1 to tier2 |
+-----+--------------------------------------------+
| O21 | Overlap from tier2 to tier1 |
+-----+--------------------------------------------+
| G12 | Gap from tier1 to tier2 |
+-----+--------------------------------------------+
| G21 | Gap from tier2 to tier1 |
+-----+--------------------------------------------+
| P1 | Pause for tier1 |
+-----+--------------------------------------------+
| P2 | Pause for tier2 |
+-----+--------------------------------------------+
| B12 | Within speaker overlap from tier1 to tier2 |
+-----+--------------------------------------------+
| B21 | Within speaker overlap from tier2 to tier1 |
+-----+--------------------------------------------+
:param str tier1: Name of the first tier.
:param str tier2: Name of the second tier.
:param int maxlen: Maximum length of gaps (skip longer ones), if ``-1``
no maximum will be used.
:param bool progressbar: Flag for debugging purposes that shows the
progress during the process.
:returns: List of gaps and overlaps of the form:
``[(type, start, end)]``.
:raises KeyError: If a tier is non existent.
:raises IndexError: If no annotations are available in the tiers.
"""
spkr1anns = sorted((self.timeslots[a[0]], self.timeslots[a[1]])
for a in self.tiers[tier1][0].values())
spkr2anns = sorted((self.timeslots[a[0]], self.timeslots[a[1]])
for a in self.tiers[tier2][0].values())
line1 = []
isin = lambda x, lst: False if\
len([i for i in lst if i[0] <= x and i[1] >= x]) == 0 else True
minmax = (min(spkr1anns[0][0], spkr2anns[0][0]),
max(spkr1anns[-1][1], spkr2anns[-1][1]))
last = (1, minmax[0])
lastP = 0
for ts in xrange(*minmax):
in1, in2 = isin(ts, spkr1anns), isin(ts, spkr2anns)
if in1 and in2: # Both speaking
if last[0] == 'B':
continue
ty = 'B'
elif in1: # Only 1 speaking
if last[0] == '1':
continue
ty = '1'
elif in2: # Only 2 speaking
if last[0] == '2':
continue
ty = '2'
else: # None speaking
if last[0] == 'N':
continue
ty = 'N'
line1.append((last[0], last[1], ts))
last = (ty, ts)
if progressbar and int((ts*1.0/minmax[1])*100) > lastP:
lastP = int((ts*1.0/minmax[1])*100)
print '%d%%' % lastP
line1.append((last[0], last[1], minmax[1]))
ftos = []
for i in xrange(len(line1)):
if line1[i][0] == 'N':
if i != 0 and i < len(line1) - 1 and\
line1[i-1][0] != line1[i+1][0]:
ftos.append(('G12_%s_%s' % (tier1, tier2)
if line1[i-1][0] == '1' else 'G21_%s_%s' %
(tier2, tier1), line1[i][1], line1[i][2]))
else:
ftos.append(('P_%s' %
(tier1 if line1[i-1][0] == '1' else tier2),
line1[i][1], line1[i][2]))
elif line1[i][0] == 'B':
if i != 0 and i < len(line1) - 1 and\
line1[i-1][0] != line1[i+1][0]:
ftos.append(('O12_%s_%s' % ((tier1, tier2)
if line1[i-1][0] else 'O21_%s_%s' %
(tier2, tier1)), line1[i][1], line1[i][2]))
else:
ftos.append(('B_%s_%s' % ((tier1, tier2)
if line1[i-1][0] == '1' else
(tier2, tier1)), line1[i][1], line1[i][2]))
return [f for f in ftos if maxlen == -1 or abs(f[2] - f[1]) < maxlen]
def create_controlled_vocabulary(self, cv_id, descriptions, entries,
ext_ref=None):
"""Create a controlled vocabulary.
.. warning:: This is a very raw implementation and you should check the
Eaf file format specification for the entries.
:param str cv_id: Name of the controlled vocabulary.
:param list descriptions: List of descriptions.
:param dict entries: Entries dictionary.
:param str ext_ref: External reference.
"""
self.controlledvocabularies[cv_id] = (descriptions, entries, ext_ref)
def get_tier_ids_for_linguistic_type(self, ling_type, parent=None):
"""Give a list of all tiers matching a linguistic type.
:param str ling_type: Name of the linguistic type.
:param str parent: Only match tiers from this parent, when ``None``
this option will be ignored.
:returns: List of tiernames.
:raises KeyError: If a tier or linguistic type is non existent.
"""
return [t for t in self.tiers if
self.tiers[t][2]['LINGUISTIC_TYPE_REF'] == ling_type and
(parent is None or self.tiers[t][2]['PARENT_REF'] == parent)]
def remove_linguistic_type(self, ling_type):
"""Remove a linguistic type.
:param str ling_type: Name of the linguistic type.
"""
del(self.linguistic_types[ling_type])
def add_linguistic_type(self, lingtype, constraints=None,
timealignable=True, graphicreferences=False,
extref=None):
"""Add a linguistic type.
:param str lingtype: Name of the linguistic type.
:param list constraints: Constraint names.
:param bool timealignable: Flag for time alignable.
:param bool graphicreferences: Flag for graphic references.
:param str extref: External reference.
"""
self.linguistic_types[lingtype] = {
'LINGUISTIC_TYPE_ID': lingtype,
'TIME_ALIGNABLE': str(timealignable).lower(),
'GRAPHIC_REFERENCES': str(graphicreferences).lower(),
'CONSTRAINTS': constraints}
if extref is not None:
self.linguistic_types[lingtype]['EXT_REF'] = extref
def get_linguistic_types(self):
"""Give a list of available linguistic types.
:returns: List of linguistic type names.
"""
return self.linguistic_types.keys()
| acuriel/Nixtla | nixtla/core/tools/pympi/Elan.py | Python | gpl-2.0 | 33,330 |
<div class="form-horizontal">
<h3>Create a new Data</h3>
<div class="form-group">
<div class="col-md-offset-2 col-sm-2">
<a id="Create" name="Create" class="btn btn-primary"
href="#/DataConfig/new"><span
class="glyphicon glyphicon-plus-sign"></span> Create</a>
</div>
</div>
</div>
<hr />
<div>
<h3>Search for Data</h3>
<form id="DataConfigSearch" class="form-horizontal">
<div class="form-group">
<label for="project" class="col-sm-2 control-label">Project</label>
<div class="col-sm-10">
<input id="project" name="project" class="form-control" type="text"
ng-model="search.baseConfig.id.project"
placeholder="Enter the Project Name"></input>
</div>
</div>
<div class="form-group">
<label for="buildVersion" class="col-sm-2 control-label">Build
Version</label>
<div class="col-sm-10">
<input id="buildVersion" name="buildVersion" class="form-control"
type="text" ng-model="search.baseConfig.id.buildVersion"
placeholder="Enter the Build Version"></input>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-sm-10">
<a id="Search" name="Search" class="btn btn-primary"
ng-click="performSearch()"><span
class="glyphicon glyphicon-search"></span> Search</a>
</div>
</div>
</form>
</div>
<div id="search-results">
<div class="table-responsive">
<table
class="table table-responsive table-bordered table-striped clearfix">
<thead>
<tr>
<th>Name</th>
<th>Browser</th>
<th>Status</th>
<th>Description</th>
</tr>
</thead>
<tbody id="search-results-body">
<tr
ng-repeat="result in searchResults | searchFilter:searchResults | startFrom:currentPage*pageSize | limitTo:pageSize">
<td><a href="#/DataConfig/edit/{{result.id}}">{{result.scriptName}}</a></td>
<td><a href="#/DataConfig/edit/{{result.id}}">{{result.browser}}</a></td>
<td><a href="#/DataConfig/edit/{{result.id}}">{{result.status}}</a></td>
<td><a href="#/DataConfig/edit/{{result.id}}">{{result.description}}</a></td>
</tr>
</tbody>
</table>
</div>
<ul class="pagination pagination-centered">
<li ng-class="{disabled:currentPage == 0}"><a id="prev" href
ng-click="previous()">«</a></li>
<li ng-repeat="n in pageRange" ng-class="{active:currentPage == n}"
ng-click="setPage(n)"><a href ng-bind="n + 1">1</a></li>
<li ng-class="{disabled: currentPage == (numberOfPages() - 1)}">
<a id="next" href ng-click="next()">»</a>
</li>
</ul>
</div>
| AnilVunnava/Automation | qa-webapp/src/main/webapp/admin/views/DataConfig/search.html | HTML | gpl-2.0 | 2,522 |
% custom packages
\usepackage{config/textpos}
\setlength{\TPHorizModule}{1cm}
\setlength{\TPVertModule}{1cm}
\newcommand\crule[1][black]{\textcolor{#1}{\rule{2cm}{2cm}}}
\newcommand{\hugetextsc}[1]{
{
\begin{spacing}{\linespaceone}
\textsc{\fontsize{\fontsizeone}{\fontsizeone}{\notosansfont #1}}
\end{spacing}
}
}
\newcommand{\btVFill}{\vskip0pt plus 1filll}
\newcommand{\frameanimation}[4]{
{
\usebackgroundtemplate{%
\setbeamercolor{background canvas}{bg=black}
\tikz[overlay,remember picture] \node[opacity=1, at=(current page.center)] {
\animategraphics[loop,width=\paperwidth,autoplay]{#4}{#1}{#2}{#3}
};
}
\begin{frame}[plain]
\end{frame}
}
}
\usepackage{animate}
\usepackage{graphicx}
\usepackage{multimedia}
\usepackage{media9}[2013/11/04]
% Partial derivatives
\newcommand*{\pd}[3][]{\ensuremath{\frac{\partial^{#1} #2}{\partial #3}}}
% Letters
\newcommand{\R}{\mathbb{R}}
% Algorithms
\usepackage{algorithm}
\usepackage[noend]{algpseudocode} | agarciamontoro/TFG | Documentation/Presentation/config/custom-command.tex | TeX | gpl-2.0 | 994 |
/* -*- c++ -*-
Kvalobs - Free Quality Control Software for Meteorological Observations
$Id: decodermgr.h,v 1.1.2.2 2007/09/27 09:02:27 paule Exp $
Copyright (C) 2007 met.no
Contact information:
Norwegian Meteorological Institute
Box 43 Blindern
0313 OSLO
NORWAY
email: [email protected]
This file is part of KVALOBS
KVALOBS is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
KVALOBS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with KVALOBS; if not, write to the Free Software Foundation Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef __dnmi_decoder_DecoderMgr_h__
#define __dnmi_decoder_DecoderMgr_h__
#include <list>
#include <string>
#include <kvdb/kvdb.h>
#include <fileutil/dso.h>
#include <decoderbase/decoder.h>
#include <kvalobs/kvTypes.h>
#include <boost/noncopyable.hpp>
#include <miconfparser/miconfparser.h>
/**
* \addtogroup kvdecoder
*
* @{
*/
extern "C" {
typedef kvalobs::decoder::DecoderBase*
(*decoderFactory)(dnmi::db::Connection &con_, const ParamList ¶ms,
const std::list<kvalobs::kvTypes> &typeList, int decoderId_,
const std::string &observationType_,
const std::string &observation_);
typedef void (*releaseDecoderFunc)(kvalobs::decoder::DecoderBase* decoder);
typedef std::list<std::string> (*getObsTypes)();
typedef std::list<std::string> (*getObsTypesExt)(
miutil::conf::ConfSection *theKvConf);
typedef void (*setKvConf)(kvalobs::decoder::DecoderBase* decoder,
miutil::conf::ConfSection *theKvConf);
}
namespace kvalobs {
namespace decoder {
/**
* \brief DecoderMgr is responsible for loading of decoders.
*/
class DecoderMgr {
struct DecoderItem : public boost::noncopyable {
decoderFactory factory;
releaseDecoderFunc releaseFunc;
setKvConf setConf;
dnmi::file::DSO *dso;
time_t modTime;
int decoderCount;
int decoderId;
std::list<std::string> obsTypes;
DecoderItem(decoderFactory factory_, releaseDecoderFunc releaseFunc_,
setKvConf setKvConf_, dnmi::file::DSO *dso_, time_t mTime)
: factory(factory_),
releaseFunc(releaseFunc_),
setConf(setKvConf_),
dso(dso_),
modTime(mTime),
decoderCount(0),
decoderId(-1) {
}
~DecoderItem() {
delete dso;
}
};
typedef std::list<DecoderItem*> DecoderList;
typedef std::list<DecoderItem*>::iterator IDecoderList;
typedef std::list<DecoderItem*>::const_iterator CIDecoderList;
DecoderList decoders;
std::string decoderPath;
std::string soVersion;
miutil::conf::ConfSection *theKvConf;
public:
DecoderMgr(const std::string &decoderPath_,
miutil::conf::ConfSection *theKvConf);
DecoderMgr()
: theKvConf(0) {
}
;
~DecoderMgr();
std::string fixDecoderName(const std::string &driver);
void setTheKvConf(miutil::conf::ConfSection *theKvConf);
void setDecoderPath(const std::string &decoderPath_);
/**
* returns true when all decoder has a decoderCount of 0.
*/
bool readyForUpdate();
void updateDecoders(miutil::conf::ConfSection *theKvConf);
void updateDecoders();
DecoderBase *findDecoder(dnmi::db::Connection &connection,
const ParamList ¶ms,
const std::list<kvalobs::kvTypes> &typeList,
const std::string &obsType, const std::string &obs,
std::string &errorMsg);
void releaseDecoder(DecoderBase *dec);
int numberOfDecoders() const {
return decoders.size();
}
void obsTypes(std::list<std::string> &list);
private:
void clearDecoders();
};
/** @} */
}
}
#endif
| metno/kvalobs | src/lib/decoder/decoderbase/decodermgr.h | C | gpl-2.0 | 4,157 |
// <copyright file="Collision.cs" company="LeagueSharp">
// Copyright (c) 2015 LeagueSharp.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/
// </copyright>
namespace LeagueSharp.SDK
{
using System;
using System.Collections.Generic;
using System.Linq;
using LeagueSharp.Data.Enumerations;
using LeagueSharp.SDK.Polygons;
using LeagueSharp.SDK.Utils;
using SharpDX;
/// <summary>
/// Collision class, calculates collision for moving objects.
/// </summary>
public static class Collision
{
#region Static Fields
private static MissileClient yasuoWallLeft, yasuoWallRight;
private static RectanglePoly yasuoWallPoly;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes static members of the <see cref="Collision" /> class.
/// Static Constructor
/// </summary>
static Collision()
{
GameObject.OnCreate += (sender, args) =>
{
var missile = sender as MissileClient;
var spellCaster = missile?.SpellCaster as Obj_AI_Hero;
if (spellCaster == null || spellCaster.ChampionName != "Yasuo"
|| spellCaster.Team == GameObjects.Player.Team)
{
return;
}
switch (missile.SData.Name)
{
case "YasuoWMovingWallMisL":
yasuoWallLeft = missile;
break;
case "YasuoWMovingWallMisR":
yasuoWallRight = missile;
break;
case "YasuoWMovingWallMisVis":
yasuoWallRight = missile;
break;
}
};
GameObject.OnDelete += (sender, args) =>
{
var missile = sender as MissileClient;
if (missile == null)
{
return;
}
if (missile.Compare(yasuoWallLeft))
{
yasuoWallLeft = null;
}
else if (missile.Compare(yasuoWallRight))
{
yasuoWallRight = null;
}
};
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Returns the list of the units that the skill-shot will hit before reaching the set positions.
/// </summary>
/// <param name="positions">
/// The positions.
/// </param>
/// <param name="input">
/// The input.
/// </param>
/// <returns>
/// A list of <c>Obj_AI_Base</c>s which the input collides with.
/// </returns>
public static List<Obj_AI_Base> GetCollision(List<Vector3> positions, PredictionInput input)
{
var result = new List<Obj_AI_Base>();
foreach (var position in positions)
{
if (input.CollisionObjects.HasFlag(CollisionableObjects.Minions))
{
result.AddRange(
GameObjects.EnemyMinions.Where(i => i.IsMinion() || i.IsPet())
.Concat(GameObjects.Jungle)
.Where(
minion =>
minion.IsValidTarget(
Math.Min(input.Range + input.Radius + 100, 2000),
true,
input.RangeCheckFrom) && IsHitCollision(minion, input, position, 20)));
}
if (input.CollisionObjects.HasFlag(CollisionableObjects.Heroes))
{
result.AddRange(
GameObjects.EnemyHeroes.Where(
hero =>
hero.IsValidTarget(
Math.Min(input.Range + input.Radius + 100, 2000),
true,
input.RangeCheckFrom) && IsHitCollision(hero, input, position, 50)));
}
if (input.CollisionObjects.HasFlag(CollisionableObjects.Walls))
{
var step = position.Distance(input.From) / 20;
for (var i = 0; i < 20; i++)
{
if (input.From.ToVector2().Extend(position, step * i).IsWall())
{
result.Add(GameObjects.Player);
}
}
}
if (input.CollisionObjects.HasFlag(CollisionableObjects.YasuoWall))
{
if (yasuoWallLeft == null || yasuoWallRight == null)
{
continue;
}
yasuoWallPoly = new RectanglePoly(yasuoWallLeft.Position, yasuoWallRight.Position, 75);
var intersections = new List<Vector2>();
for (var i = 0; i < yasuoWallPoly.Points.Count; i++)
{
var inter =
yasuoWallPoly.Points[i].Intersection(
yasuoWallPoly.Points[i != yasuoWallPoly.Points.Count - 1 ? i + 1 : 0],
input.From.ToVector2(),
position.ToVector2());
if (inter.Intersects)
{
intersections.Add(inter.Point);
}
}
if (intersections.Count > 0)
{
result.Add(GameObjects.Player);
}
}
}
return result.Distinct().ToList();
}
#endregion
#region Methods
private static bool IsHitCollision(Obj_AI_Base collision, PredictionInput input, Vector3 pos, float extraRadius)
{
var inputSub = input.Clone() as PredictionInput;
if (inputSub == null)
{
return false;
}
inputSub.Unit = collision;
var predPos = Movement.GetPrediction(inputSub, false, false).UnitPosition.ToVector2();
return predPos.Distance(input.From) < input.Radius + input.Unit.BoundingRadius / 2
|| predPos.Distance(pos) < input.Radius + input.Unit.BoundingRadius / 2
|| predPos.DistanceSquared(input.From.ToVector2(), pos.ToVector2(), true)
<= Math.Pow(input.Radius + input.Unit.BoundingRadius + extraRadius, 2);
}
#endregion
}
}
| CjShuMoon/TwLS.SDK | Core/Math/Collision.cs | C# | gpl-2.0 | 7,683 |
/*
* Copyright (c) 1990,1993 Regents of The University of Michigan.
* All Rights Reserved. See COPYRIGHT.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/uio.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <errno.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <atalk/logger.h>
#include <atalk/adouble.h>
#include <atalk/compat.h>
#include <atalk/dsi.h>
#include <atalk/afp.h>
#include <atalk/paths.h>
#include <atalk/util.h>
#include <atalk/server_child.h>
#include <atalk/server_ipc.h>
#include <atalk/errchk.h>
#include <atalk/globals.h>
#include <atalk/netatalk_conf.h>
#include "afp_config.h"
#include "status.h"
#include "fork.h"
#include "uam_auth.h"
#include "afp_zeroconf.h"
#define AFP_LISTENERS 32
#define FDSET_SAFETY 5
unsigned char nologin = 0;
static AFPObj obj;
static server_child *server_children;
static sig_atomic_t reloadconfig = 0;
static sig_atomic_t gotsigchld = 0;
/* Two pointers to dynamic allocated arrays which store pollfds and associated data */
static struct pollfd *fdset;
static struct polldata *polldata;
static int fdset_size; /* current allocated size */
static int fdset_used; /* number of used elements */
static int disasociated_ipc_fd; /* disasociated sessions uses this fd for IPC */
static afp_child_t *dsi_start(AFPObj *obj, DSI *dsi, server_child *server_children);
static void afp_exit(int ret)
{
exit(ret);
}
/* ------------------
initialize fd set we are waiting for.
*/
static void fd_set_listening_sockets(const AFPObj *config)
{
DSI *dsi;
for (dsi = config->dsi; dsi; dsi = dsi->next) {
fdset_add_fd(config->options.connections + AFP_LISTENERS + FDSET_SAFETY,
&fdset,
&polldata,
&fdset_used,
&fdset_size,
dsi->serversock,
LISTEN_FD,
dsi);
}
if (config->options.flags & OPTION_KEEPSESSIONS)
fdset_add_fd(config->options.connections + AFP_LISTENERS + FDSET_SAFETY,
&fdset,
&polldata,
&fdset_used,
&fdset_size,
disasociated_ipc_fd,
DISASOCIATED_IPC_FD,
NULL);
}
static void fd_reset_listening_sockets(const AFPObj *config)
{
const DSI *dsi;
for (dsi = config->dsi; dsi; dsi = dsi->next) {
fdset_del_fd(&fdset, &polldata, &fdset_used, &fdset_size, dsi->serversock);
}
if (config->options.flags & OPTION_KEEPSESSIONS)
fdset_del_fd(&fdset, &polldata, &fdset_used, &fdset_size, disasociated_ipc_fd);
}
/* ------------------ */
static void afp_goaway(int sig)
{
switch( sig ) {
case SIGTERM:
case SIGQUIT:
switch (sig) {
case SIGTERM:
LOG(log_note, logtype_afpd, "AFP Server shutting down on SIGTERM");
break;
case SIGQUIT:
if (obj.options.flags & OPTION_KEEPSESSIONS) {
LOG(log_note, logtype_afpd, "AFP Server shutting down on SIGQUIT, NOT disconnecting clients");
} else {
LOG(log_note, logtype_afpd, "AFP Server shutting down on SIGQUIT");
sig = SIGTERM;
}
break;
}
if (server_children)
server_child_kill(server_children, CHILD_DSIFORK, sig);
_exit(0);
break;
case SIGUSR1 :
nologin++;
auth_unload();
LOG(log_info, logtype_afpd, "disallowing logins");
if (server_children)
server_child_kill(server_children, CHILD_DSIFORK, sig);
break;
case SIGHUP :
/* w/ a configuration file, we can force a re-read if we want */
reloadconfig = 1;
break;
case SIGCHLD:
/* w/ a configuration file, we can force a re-read if we want */
gotsigchld = 1;
break;
default :
LOG(log_error, logtype_afpd, "afp_goaway: bad signal" );
}
return;
}
static void child_handler(void)
{
int fd;
int status, i;
pid_t pid;
#ifndef WAIT_ANY
#define WAIT_ANY (-1)
#endif /* ! WAIT_ANY */
while ((pid = waitpid(WAIT_ANY, &status, WNOHANG)) > 0) {
for (i = 0; i < server_children->nforks; i++) {
if ((fd = server_child_remove(server_children, i, pid)) != -1) {
fdset_del_fd(&fdset, &polldata, &fdset_used, &fdset_size, fd);
break;
}
}
if (WIFEXITED(status)) {
if (WEXITSTATUS(status))
LOG(log_info, logtype_afpd, "child[%d]: exited %d", pid, WEXITSTATUS(status));
else
LOG(log_info, logtype_afpd, "child[%d]: done", pid);
} else {
if (WIFSIGNALED(status))
LOG(log_info, logtype_afpd, "child[%d]: killed by signal %d", pid, WTERMSIG(status));
else
LOG(log_info, logtype_afpd, "child[%d]: died", pid);
}
}
}
static int setlimits(void)
{
struct rlimit rlim;
if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
LOG(log_warning, logtype_afpd, "setlimits: reading current limits failed: %s", strerror(errno));
return -1;
}
if (rlim.rlim_cur != RLIM_INFINITY && rlim.rlim_cur < 65535) {
rlim.rlim_cur = 65535;
if (rlim.rlim_max != RLIM_INFINITY && rlim.rlim_max < 65535)
rlim.rlim_max = 65535;
if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
LOG(log_warning, logtype_afpd, "setlimits: increasing limits failed: %s", strerror(errno));
return -1;
}
}
return 0;
}
int main(int ac, char **av)
{
fd_set rfds;
void *ipc;
struct sigaction sv;
sigset_t sigs;
int ret;
/* Parse argv args and initialize default options */
afp_options_parse_cmdline(&obj, ac, av);
if (!(obj.cmdlineflags & OPTION_DEBUG) && (daemonize(0, 0) != 0))
exit(EXITERR_SYS);
/* Log SIGBUS/SIGSEGV SBT */
fault_setup(NULL);
if (afp_config_parse(&obj, "afpd") != 0)
afp_exit(EXITERR_CONF);
/* Save the user's current umask */
obj.options.save_mask = umask(obj.options.umask);
/* install child handler for asp and dsi. we do this before afp_goaway
* as afp_goaway references stuff from here.
* XXX: this should really be setup after the initial connections. */
if (!(server_children = server_child_alloc(obj.options.connections, CHILD_NFORKS))) {
LOG(log_error, logtype_afpd, "main: server_child alloc: %s", strerror(errno) );
afp_exit(EXITERR_SYS);
}
sigemptyset(&sigs);
pthread_sigmask(SIG_SETMASK, &sigs, NULL);
memset(&sv, 0, sizeof(sv));
/* linux at least up to 2.4.22 send a SIGXFZ for vfat fs,
even if the file is open with O_LARGEFILE ! */
#ifdef SIGXFSZ
sv.sa_handler = SIG_IGN;
sigemptyset( &sv.sa_mask );
if (sigaction(SIGXFSZ, &sv, NULL ) < 0 ) {
LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
afp_exit(EXITERR_SYS);
}
#endif
sv.sa_handler = afp_goaway; /* handler for all sigs */
sigemptyset( &sv.sa_mask );
sigaddset(&sv.sa_mask, SIGALRM);
sigaddset(&sv.sa_mask, SIGHUP);
sigaddset(&sv.sa_mask, SIGTERM);
sigaddset(&sv.sa_mask, SIGUSR1);
sigaddset(&sv.sa_mask, SIGQUIT);
sv.sa_flags = SA_RESTART;
if ( sigaction( SIGCHLD, &sv, NULL ) < 0 ) {
LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
afp_exit(EXITERR_SYS);
}
sigemptyset( &sv.sa_mask );
sigaddset(&sv.sa_mask, SIGALRM);
sigaddset(&sv.sa_mask, SIGTERM);
sigaddset(&sv.sa_mask, SIGHUP);
sigaddset(&sv.sa_mask, SIGCHLD);
sigaddset(&sv.sa_mask, SIGQUIT);
sv.sa_flags = SA_RESTART;
if ( sigaction( SIGUSR1, &sv, NULL ) < 0 ) {
LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
afp_exit(EXITERR_SYS);
}
sigemptyset( &sv.sa_mask );
sigaddset(&sv.sa_mask, SIGALRM);
sigaddset(&sv.sa_mask, SIGTERM);
sigaddset(&sv.sa_mask, SIGUSR1);
sigaddset(&sv.sa_mask, SIGCHLD);
sigaddset(&sv.sa_mask, SIGQUIT);
sv.sa_flags = SA_RESTART;
if ( sigaction( SIGHUP, &sv, NULL ) < 0 ) {
LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
afp_exit(EXITERR_SYS);
}
sigemptyset( &sv.sa_mask );
sigaddset(&sv.sa_mask, SIGALRM);
sigaddset(&sv.sa_mask, SIGHUP);
sigaddset(&sv.sa_mask, SIGUSR1);
sigaddset(&sv.sa_mask, SIGCHLD);
sigaddset(&sv.sa_mask, SIGQUIT);
sv.sa_flags = SA_RESTART;
if ( sigaction( SIGTERM, &sv, NULL ) < 0 ) {
LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
afp_exit(EXITERR_SYS);
}
sigemptyset( &sv.sa_mask );
sigaddset(&sv.sa_mask, SIGALRM);
sigaddset(&sv.sa_mask, SIGHUP);
sigaddset(&sv.sa_mask, SIGUSR1);
sigaddset(&sv.sa_mask, SIGCHLD);
sigaddset(&sv.sa_mask, SIGTERM);
sv.sa_flags = SA_RESTART;
if (sigaction(SIGQUIT, &sv, NULL ) < 0 ) {
LOG(log_error, logtype_afpd, "main: sigaction: %s", strerror(errno) );
afp_exit(EXITERR_SYS);
}
/* afp.conf: not in config file: lockfile, configfile
* preference: command-line provides defaults.
* config file over-writes defaults.
*
* we also need to make sure that killing afpd during startup
* won't leave any lingering registered names around.
*/
sigemptyset(&sigs);
sigaddset(&sigs, SIGALRM);
sigaddset(&sigs, SIGHUP);
sigaddset(&sigs, SIGUSR1);
#if 0
/* don't block SIGTERM */
sigaddset(&sigs, SIGTERM);
#endif
sigaddset(&sigs, SIGCHLD);
pthread_sigmask(SIG_BLOCK, &sigs, NULL);
if (configinit(&obj) != 0) {
LOG(log_error, logtype_afpd, "main: no servers configured");
afp_exit(EXITERR_CONF);
}
pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
/* Initialize */
cnid_init();
/* watch atp, dsi sockets and ipc parent/child file descriptor. */
if (obj.options.flags & OPTION_KEEPSESSIONS) {
LOG(log_note, logtype_afpd, "Activating continous service");
disasociated_ipc_fd = ipc_server_uds(_PATH_AFP_IPC);
}
fd_set_listening_sockets(&obj);
/* set limits */
(void)setlimits();
afp_child_t *child;
int recon_ipc_fd;
pid_t pid;
int saveerrno;
/* wait for an appleshare connection. parent remains in the loop
* while the children get handled by afp_over_{asp,dsi}. this is
* currently vulnerable to a denial-of-service attack if a
* connection is made without an actual login attempt being made
* afterwards. establishing timeouts for logins is a possible
* solution. */
while (1) {
LOG(log_maxdebug, logtype_afpd, "main: polling %i fds", fdset_used);
pthread_sigmask(SIG_UNBLOCK, &sigs, NULL);
ret = poll(fdset, fdset_used, -1);
pthread_sigmask(SIG_BLOCK, &sigs, NULL);
saveerrno = errno;
if (gotsigchld) {
gotsigchld = 0;
child_handler();
continue;
}
if (reloadconfig) {
nologin++;
auth_unload();
fd_reset_listening_sockets(&obj);
LOG(log_info, logtype_afpd, "re-reading configuration file");
configfree(&obj, NULL);
if (configinit(&obj) != 0) {
LOG(log_error, logtype_afpd, "config re-read: no servers configured");
afp_exit(EXITERR_CONF);
}
fd_set_listening_sockets(&obj);
nologin = 0;
reloadconfig = 0;
errno = saveerrno;
continue;
}
if (ret == 0)
continue;
if (ret < 0) {
if (errno == EINTR)
continue;
LOG(log_error, logtype_afpd, "main: can't wait for input: %s", strerror(errno));
break;
}
for (int i = 0; i < fdset_used; i++) {
if (fdset[i].revents & (POLLIN | POLLERR | POLLHUP | POLLNVAL)) {
switch (polldata[i].fdtype) {
case LISTEN_FD:
if (child = dsi_start(&obj, (DSI *)polldata[i].data, server_children)) {
/* Add IPC fd to select fd set */
fdset_add_fd(obj.options.connections + AFP_LISTENERS + FDSET_SAFETY,
&fdset,
&polldata,
&fdset_used,
&fdset_size,
child->ipc_fd,
IPC_FD,
child);
}
break;
case IPC_FD:
child = (afp_child_t *)polldata[i].data;
LOG(log_debug, logtype_afpd, "main: IPC request from child[%u]", child->pid);
if (ipc_server_read(server_children, child->ipc_fd) != 0) {
fdset_del_fd(&fdset, &polldata, &fdset_used, &fdset_size, child->ipc_fd);
close(child->ipc_fd);
child->ipc_fd = -1;
if ((obj.options.flags & OPTION_KEEPSESSIONS) && child->disasociated) {
LOG(log_note, logtype_afpd, "main: removing reattached child[%u]", child->pid);
server_child_remove(server_children, CHILD_DSIFORK, child->pid);
}
}
break;
case DISASOCIATED_IPC_FD:
LOG(log_debug, logtype_afpd, "main: IPC reconnect request");
if ((recon_ipc_fd = accept(disasociated_ipc_fd, NULL, NULL)) == -1) {
LOG(log_error, logtype_afpd, "main: accept: %s", strerror(errno));
break;
}
if (readt(recon_ipc_fd, &pid, sizeof(pid_t), 0, 1) != sizeof(pid_t)) {
LOG(log_error, logtype_afpd, "main: readt: %s", strerror(errno));
close(recon_ipc_fd);
break;
}
LOG(log_note, logtype_afpd, "main: IPC reconnect from pid [%u]", pid);
if ((child = server_child_add(server_children, CHILD_DSIFORK, pid, recon_ipc_fd)) == NULL) {
LOG(log_error, logtype_afpd, "main: server_child_add");
close(recon_ipc_fd);
break;
}
child->disasociated = 1;
fdset_add_fd(obj.options.connections + AFP_LISTENERS + FDSET_SAFETY,
&fdset,
&polldata,
&fdset_used,
&fdset_size,
recon_ipc_fd,
IPC_FD,
child);
break;
default:
LOG(log_debug, logtype_afpd, "main: IPC request for unknown type");
break;
} /* switch */
} /* if */
} /* for (i)*/
} /* while (1) */
return 0;
}
static afp_child_t *dsi_start(AFPObj *obj, DSI *dsi, server_child *server_children)
{
afp_child_t *child = NULL;
if (dsi_getsession(dsi, server_children, obj->options.tickleval, &child) != 0) {
LOG(log_error, logtype_afpd, "dsi_start: session error: %s", strerror(errno));
return NULL;
}
/* we've forked. */
if (child == NULL) {
configfree(obj, dsi);
afp_over_dsi(obj); /* start a session */
exit (0);
}
return child;
}
| igorbernstein/netatalk-debian | etc/afpd/main.c | C | gpl-2.0 | 16,185 |
var express = require('express');
var path = require('path');
var tilestrata = require('tilestrata');
var disk = require('tilestrata-disk');
var mapnik = require('tilestrata-mapnik');
var dependency = require('tilestrata-dependency');
var strata = tilestrata();
var app = express();
// define layers
strata.layer('hillshade')
.route('shade.png')
.use(disk.cache({dir: './tiles/shade/'}))
.use(mapnik({
pathname: './styles/hillshade.xml',
tileSize: 256,
scale: 1
}));
strata.layer('dem')
.route('dem.png')
.use(disk.cache({dir: './tiles/dem/'}))
.use(mapnik({
pathname: './styles/dem.xml',
tileSize: 256,
scale: 1
}));
strata.layer('sim1')
.route('sim1.png')
.use(disk.cache({dir: './tiles/sim1/'}))
.use(mapnik({
pathname: './styles/sim1.xml',
tileSize: 256,
scale: 1
}));
strata.layer('sim2')
.route('sim2.png')
.use(disk.cache({dir: './tiles/sim2/'}))
.use(mapnik({
pathname: './styles/sim2.xml',
tileSize: 256,
scale: 1
}));
strata.layer('sim3')
.route('sim3.png')
.use(disk.cache({dir: './tiles/sim3/'}))
.use(mapnik({
pathname: './styles/sim3.xml',
tileSize: 256,
scale: 1
}));
strata.layer('slope')
.route('slope.png')
.use(disk.cache({dir: './tiles/slope/'}))
.use(mapnik({
pathname: './styles/slope.xml',
tileSize: 256,
scale: 1
}));
var staticPath = path.resolve(__dirname, './public/');
app.use(express.static(staticPath));
app.use(tilestrata.middleware({
server: strata,
prefix: ''
}));
app.listen(8080, function() {
console.log('Express server running on port 8080.');
});
| nronnei/srtm-server | app.js | JavaScript | gpl-2.0 | 1,877 |
/*
* synergy -- mouse and keyboard sharing utility
* Copyright (C) 2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/OSXUchrKeyResource.h"
#include <Carbon/Carbon.h>
//
// OSXUchrKeyResource
//
OSXUchrKeyResource::OSXUchrKeyResource(const void* resource,
UInt32 keyboardType) :
m_m(NULL),
m_cti(NULL),
m_sdi(NULL),
m_sri(NULL),
m_st(NULL)
{
m_resource = reinterpret_cast<const UCKeyboardLayout*>(resource);
if (m_resource == NULL) {
return;
}
// find the keyboard info for the current keyboard type
const UCKeyboardTypeHeader* th = NULL;
const UCKeyboardLayout* r = m_resource;
for (ItemCount i = 0; i < r->keyboardTypeCount; ++i) {
if (keyboardType >= r->keyboardTypeList[i].keyboardTypeFirst &&
keyboardType <= r->keyboardTypeList[i].keyboardTypeLast) {
th = r->keyboardTypeList + i;
break;
}
if (r->keyboardTypeList[i].keyboardTypeFirst == 0) {
// found the default. use it unless we find a match.
th = r->keyboardTypeList + i;
}
}
if (th == NULL) {
// cannot find a suitable keyboard type
return;
}
// get tables for keyboard type
const UInt8* base = reinterpret_cast<const UInt8*>(m_resource);
m_m = reinterpret_cast<const UCKeyModifiersToTableNum*>(base +
th->keyModifiersToTableNumOffset);
m_cti = reinterpret_cast<const UCKeyToCharTableIndex*>(base +
th->keyToCharTableIndexOffset);
m_sdi = reinterpret_cast<const UCKeySequenceDataIndex*>(base +
th->keySequenceDataIndexOffset);
if (th->keyStateRecordsIndexOffset != 0) {
m_sri = reinterpret_cast<const UCKeyStateRecordsIndex*>(base +
th->keyStateRecordsIndexOffset);
}
if (th->keyStateTerminatorsOffset != 0) {
m_st = reinterpret_cast<const UCKeyStateTerminators*>(base +
th->keyStateTerminatorsOffset);
}
// find the space key, but only if it can combine with dead keys.
// a dead key followed by a space yields the non-dead version of
// the dead key.
m_spaceOutput = 0xffffu;
UInt32 table = getTableForModifier(0);
for (UInt32 button = 0, n = getNumButtons(); button < n; ++button) {
KeyID id = getKey(table, button);
if (id == 0x20) {
UCKeyOutput c =
reinterpret_cast<const UCKeyOutput*>(base +
m_cti->keyToCharTableOffsets[table])[button];
if ((c & kUCKeyOutputTestForIndexMask) ==
kUCKeyOutputStateIndexMask) {
m_spaceOutput = (c & kUCKeyOutputGetIndexMask);
break;
}
}
}
}
bool
OSXUchrKeyResource::isValid() const
{
return (m_m != NULL);
}
UInt32
OSXUchrKeyResource::getNumModifierCombinations() const
{
// only 32 (not 256) because the righthanded modifier bits are ignored
return 32;
}
UInt32
OSXUchrKeyResource::getNumTables() const
{
return m_cti->keyToCharTableCount;
}
UInt32
OSXUchrKeyResource::getNumButtons() const
{
return m_cti->keyToCharTableSize;
}
UInt32
OSXUchrKeyResource::getTableForModifier(UInt32 mask) const
{
if (mask >= m_m->modifiersCount) {
return m_m->defaultTableNum;
}
else {
return m_m->tableNum[mask];
}
}
KeyID
OSXUchrKeyResource::getKey(UInt32 table, UInt32 button) const
{
assert(table < getNumTables());
assert(button < getNumButtons());
const UInt8* base = reinterpret_cast<const UInt8*>(m_resource);
const UCKeyOutput* cPtr = reinterpret_cast<const UCKeyOutput*>(base +
m_cti->keyToCharTableOffsets[table]);
const UCKeyOutput c = cPtr[button];
KeySequence keys;
switch (c & kUCKeyOutputTestForIndexMask) {
case kUCKeyOutputStateIndexMask:
if (!getDeadKey(keys, c & kUCKeyOutputGetIndexMask)) {
return kKeyNone;
}
break;
case kUCKeyOutputSequenceIndexMask:
default:
if (!addSequence(keys, c)) {
return kKeyNone;
}
break;
}
// XXX -- no support for multiple characters
if (keys.size() != 1) {
return kKeyNone;
}
return keys.front();
}
bool
OSXUchrKeyResource::getDeadKey(
KeySequence& keys, UInt16 index) const
{
if (m_sri == NULL || index >= m_sri->keyStateRecordCount) {
// XXX -- should we be using some other fallback?
return false;
}
UInt16 state = 0;
if (!getKeyRecord(keys, index, state)) {
return false;
}
if (state == 0) {
// not a dead key
return true;
}
// no dead keys if we couldn't find the space key
if (m_spaceOutput == 0xffffu) {
return false;
}
// the dead key should not have put anything in the key list
if (!keys.empty()) {
return false;
}
// get the character generated by pressing the space key after the
// dead key. if we're still in a compose state afterwards then we're
// confused so we bail.
if (!getKeyRecord(keys, m_spaceOutput, state) || state != 0) {
return false;
}
// convert keys to their dead counterparts
for (KeySequence::iterator i = keys.begin(); i != keys.end(); ++i) {
*i = synergy::KeyMap::getDeadKey(*i);
}
return true;
}
bool
OSXUchrKeyResource::getKeyRecord(
KeySequence& keys, UInt16 index, UInt16& state) const
{
const UInt8* base = reinterpret_cast<const UInt8*>(m_resource);
const UCKeyStateRecord* sr =
reinterpret_cast<const UCKeyStateRecord*>(base +
m_sri->keyStateRecordOffsets[index]);
const UCKeyStateEntryTerminal* kset =
reinterpret_cast<const UCKeyStateEntryTerminal*>(sr->stateEntryData);
UInt16 nextState = 0;
bool found = false;
if (state == 0) {
found = true;
nextState = sr->stateZeroNextState;
if (!addSequence(keys, sr->stateZeroCharData)) {
return false;
}
}
else {
// we have a next entry
switch (sr->stateEntryFormat) {
case kUCKeyStateEntryTerminalFormat:
for (UInt16 j = 0; j < sr->stateEntryCount; ++j) {
if (kset[j].curState == state) {
if (!addSequence(keys, kset[j].charData)) {
return false;
}
nextState = 0;
found = true;
break;
}
}
break;
case kUCKeyStateEntryRangeFormat:
// XXX -- not supported yet
break;
default:
// XXX -- unknown format
return false;
}
}
if (!found) {
// use a terminator
if (m_st != NULL && state < m_st->keyStateTerminatorCount) {
if (!addSequence(keys, m_st->keyStateTerminators[state - 1])) {
return false;
}
}
nextState = sr->stateZeroNextState;
if (!addSequence(keys, sr->stateZeroCharData)) {
return false;
}
}
// next
state = nextState;
return true;
}
bool
OSXUchrKeyResource::addSequence(
KeySequence& keys, UCKeyCharSeq c) const
{
if ((c & kUCKeyOutputTestForIndexMask) == kUCKeyOutputSequenceIndexMask) {
UInt16 index = (c & kUCKeyOutputGetIndexMask);
if (index < m_sdi->charSequenceCount &&
m_sdi->charSequenceOffsets[index] !=
m_sdi->charSequenceOffsets[index + 1]) {
// XXX -- sequences not supported yet
return false;
}
}
if (c != 0xfffe && c != 0xffff) {
KeyID id = unicharToKeyID(c);
if (id != kKeyNone) {
keys.push_back(id);
}
}
return true;
}
| hunterua/synergy | src/lib/platform/OSXUchrKeyResource.cpp | C++ | gpl-2.0 | 7,325 |
<?php
include_once "srcPHP/View/View.php";
include_once "srcPHP/Model/ResearchModel.php";
class Mosaic implements View{
var $model = NULL;
var $array = NULL;
function Mosaic(){
$this->model = new ResearchModel("dbserver", "xjouveno", "xjouveno", "pdp");
$this->array = $this->model->getAllVideo();
}
function linkCSS(){ echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"css/mosaic.css\">"; }
function linkJS(){ }
function onLoadJS(){ }
function draw(){
echo "<section>";
echo "<ul class=\"patients\">";
echo $tmp = NULL;
for($i=0; $i<count($this->array); $i++){
// Patient suivant
if($tmp != $this->array[$i]["IdPatient"]){
$tmp = $this->array[$i]["IdPatient"];
if($i != 0){
echo "</ul>";
echo "</li>";
}
echo "<li>";
echo "<h3>".$this->array[$i]["Name"]." - ".$this->array[$i]["IdPatient"]."</h3>";
echo "<ul>";
}
//Video Suivante
echo "<li>";
echo "<span>";
// echo "<a href=\"index.php?play=".$this->array[$i]["IdVideo"]."\" ><img src=\"modules/jQuery-File-Upload/server/php/files/video_thumbnails/video.png\" /></a>";
echo "<a href=\"index.php?play=".$this->array[$i]["IdVideo"]."\" ><img src=\"modules/jQuery-File-Upload/server/php/files/video_thumbnails/".$this->array[$i]["IdVideo"].".jpg\" /></a>";
echo "<label>".$this->array[$i]["Title"]."</label>";
echo "</span>";
echo "</li>";
}
echo "</ul>";
echo "</section>";
}
}
?>
| s4e-tom/navideo | Trunk/srcPHP/View/Section/GuestSection/Mosaic.php | PHP | gpl-2.0 | 1,462 |
<?php
/**
* Description of Resume
*
* @author greg
* @package
*/
class Wpjb_Form_Abstract_Resume extends Daq_Form_ObjectAbstract
{
protected $_custom = "wpjb_form_resume";
protected $_key = "resume";
protected $_model = "Wpjb_Model_Resume";
public function _exclude()
{
if($this->_object->getId()) {
return array("id" => $this->_object->getId());
} else {
return array();
}
}
public function init()
{
$this->_upload = array(
"path" => wpjb_upload_dir("{object}", "{field}", "{id}", "basedir"),
"object" => "resume",
"field" => null,
"id" => wpjb_upload_id($this->getId())
);
$this->addGroup("_internal", "");
$this->addGroup("default", __("Account Information", "wpjobboard"));
$this->addGroup("location", __("Address", "wpjobboard"));
$this->addGroup("resume", __("Resume", "wpjobboard"));
$this->addGroup("experience", __("Experience", "wpjobboard"));
$this->addGroup("education", __("Education", "wpjobboard"));
$this->_group["experience"]->setAlwaysVisible(true);
$this->_group["education"]->setAlwaysVisible(true);
$user = new WP_User($this->getObject()->user_id);
$e = $this->create("first_name");
$e->setLabel(__("First Name", "wpjobboard"));
$e->setRequired(true);
$e->setValue($user->first_name);
$this->addElement($e, "default");
$e = $this->create("last_name");
$e->setLabel(__("Last Name", "wpjobboard"));
$e->setRequired(true);
$e->setValue($user->last_name);
$this->addElement($e, "default");
$def = wpjb_locale();
$e = $this->create("candidate_country", "select");
$e->setLabel(__("Country", "wpjobboard"));
$e->setValue(($this->_object->candidate_country) ? $this->_object->candidate_country : $def);
$e->addOptions(wpjb_form_get_countries());
$e->addClass("wpjb-location-country");
$this->addElement($e, "location");
$e = $this->create("candidate_state");
$e->setLabel(__("State", "wpjobboard"));
$e->setValue($this->_object->candidate_state);
$e->addClass("wpjb-location-state");
$this->addElement($e, "location");
$e = $this->create("candidate_zip_code");
$e->setLabel(__("Zip-Code", "wpjobboard"));
$e->addValidator(new Daq_Validate_StringLength(null, 20));
$e->setValue($this->_object->candidate_zip_code);
$this->addElement($e, "location");
$e = $this->create("candidate_location");
$e->setValue($this->_object->candidate_location);
$e->setRequired(true);
$e->setLabel(__("City", "wpjobboard"));
$e->setHint(__('For example: "Chicago", "London", "Anywhere" or "Telecommute".', "wpjobboard"));
$e->addValidator(new Daq_Validate_StringLength(null, 120));
$e->addClass("wpjb-location-city");
$this->addElement($e, "location");
$e = $this->create("user_email");
$e->setRequired(true);
$e->setLabel(__("Email Address", "wpjobboard"));
$e->setHint(__('This field will be shown only to registered employers.', "wpjobboard"));
$e->addValidator(new Daq_Validate_Email(array("exclude"=>$user->ID)));
$e->setValue($user->user_email);
$this->addElement($e, "default");
$e = $this->create("phone");
$e->setLabel(__("Phone Number", "wpjobboard"));
$e->setHint(__('This field will be shown only to registered employers.', "wpjobboard"));
$e->setValue($this->_object->phone);
$this->addElement($e, "default");
$e = $this->create("user_url");
$e->setLabel(__("Website", "wpjobboard"));
$e->setHint(__('This field will be shown only to registered employers.', "wpjobboard"));
$e->addFilter(new Daq_Filter_WP_Url());
$e->addValidator(new Daq_Validate_Url());
$e->setValue($user->user_url);
$this->addElement($e, "default");
$e = $this->create("is_public", "checkbox");
$e->setLabel(__("Privacy", "wpjobboard"));
$e->addOption(1, 1, __("Show my resume in search results.", "wpjobboard"));
$e->setValue($this->_object->is_public);
$e->addFilter(new Daq_Filter_Int());
$this->addElement($e, "default");
$e = $this->create("is_active", "checkbox");
$e->setValue($this->_object->is_active);
$e->setLabel(__("Status", "wpjobboard"));
$e->addOption(1, 1, __("Resume is approved.", "wpjobboard"));
$this->addElement($e, "_internal");
$e = $this->create("modified_at", "text_date");
$e->setDateFormat(wpjb_date_format());
$e->setValue($this->ifNew(date("Y-m-d"), $this->_object->modified_at));
$this->addElement($e, "_internal");
$e = $this->create("created_at", "text_date");
$e->setDateFormat(wpjb_date_format());
$e->setValue($this->ifNew(date("Y-m-d"), $this->_object->created_at));
$this->addElement($e, "_internal");
$e = $this->create("image", "file");
$e->setLabel(__("Your Photo", "wpjobboard"));;
$e->addValidator(new Daq_Validate_File_Default());
$e->addValidator(new Daq_Validate_File_Ext("jpg,jpeg,gif,png"));
$e->addValidator(new Daq_Validate_File_Size(300000));
$e->setUploadPath($this->_upload);
$e->setRenderer("wpjb_form_field_upload");
$this->addElement($e, "default");
$e = $this->create("category", "select");
$e->setLabel(__("Category", "wpjobboard"));
$e->setValue($this->_object->getTagIds("category"));
$e->addOptions(wpjb_form_get_categories());
$this->addElement($e, "resume");
$this->addTag($e);
$e = $this->create("headline");
$e->setLabel(__("Professional Headline", "wpjobboard"));
$e->setHint(__("Describe yourself in few words, for example: Experienced Web Developer", "wpjobboard"));
$e->addValidator(new Daq_Validate_StringLength(1, 120));
$e->setValue($this->_object->headline);
$this->addElement($e, "resume");
$e = $this->create("description", "textarea");
$e->setLabel(__("Profile Summary", "wpjobboard"));
$e->setHint(__("Use this field to list your skills, specialities, experience or goals", "wpjobboard"));
$e->setValue($this->_object->description);
$e->setEditor(Daq_Form_Element_Textarea::EDITOR_TINY);
$this->addElement($e, "resume");
}
public function save($append = array())
{
parent::save($append);
$user = $this->getObject()->getUser(true);
$names = array_merge($user->getFieldNames(), array("first_name", "last_name"));
$userdata = array("ID"=>$user->ID);
$user = new WP_User($this->getObject(true)->ID);
$update = false;
foreach($names as $key) {
if($this->hasElement($key) && !in_array($key, array("user_login", "user_pass"))) {
$userdata[$key] = $this->value($key);
$update = true;
}
}
if($update) {
wp_update_user($userdata);
}
$temp = wpjb_upload_dir("resume", "", null, "basedir");
$finl = dirname($temp)."/".$this->getId();
wpjb_rename_dir($temp, $finl);
}
public function dump()
{
$dump = parent::dump();
$count = count($dump);
for($i=0; $i<$count; $i++) {
if(in_array($dump[$i]->name, array("experience", "education"))) {
$dump[$i]->editable = false;
}
}
return $dump;
}
}
?> | Sparxoo/chime | wp-content/plugins/wpjobboard/application/libraries/Form/Abstract/Resume.php | PHP | gpl-2.0 | 7,924 |
/*
* This file is part of PowerDNS or dnsdist.
* Copyright -- PowerDNS.COM B.V. and its contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* In addition, for the avoidance of any doubt, permission is granted to
* link this program with OpenSSL and to (re)distribute the binaries
* produced as the result of such linking.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "utility.hh"
#include "packetcache.hh"
#include "logger.hh"
#include "arguments.hh"
#include "statbag.hh"
#include <map>
#include <boost/algorithm/string.hpp>
extern StatBag S;
PacketCache::PacketCache()
{
d_ops=0;
d_maps.resize(1024);
for(auto& mc : d_maps) {
pthread_rwlock_init(&mc.d_mut, 0);
}
d_ttl=-1;
d_recursivettl=-1;
S.declare("packetcache-hit");
S.declare("packetcache-miss");
S.declare("packetcache-size");
d_statnumhit=S.getPointer("packetcache-hit");
d_statnummiss=S.getPointer("packetcache-miss");
d_statnumentries=S.getPointer("packetcache-size");
d_doRecursion=false;
}
PacketCache::~PacketCache()
{
// WriteLock l(&d_mut);
vector<WriteLock*> locks;
for(auto& mc : d_maps) {
locks.push_back(new WriteLock(&mc.d_mut));
}
for(auto wl : locks) {
delete wl;
}
}
int PacketCache::get(DNSPacket *p, DNSPacket *cached, bool recursive)
{
extern StatBag S;
if(d_ttl<0)
getTTLS();
cleanupIfNeeded();
if(d_doRecursion && p->d.rd) { // wants recursion
if(!d_recursivettl) {
(*d_statnummiss)++;
return 0;
}
}
else { // does not
if(!d_ttl) {
(*d_statnummiss)++;
return 0;
}
}
if(ntohs(p->d.qdcount)!=1) // we get confused by packets with more than one question
return 0;
unsigned int age=0;
string value;
bool haveSomething;
{
auto& mc=getMap(p->qdomain);
TryReadLock l(&mc.d_mut); // take a readlock here
if(!l.gotIt()) {
S.inc("deferred-cache-lookup");
return 0;
}
uint16_t maxReplyLen = p->d_tcp ? 0xffff : p->getMaxReplyLen();
haveSomething=getEntryLocked(p->qdomain, p->qtype, PacketCache::PACKETCACHE, value, -1, recursive, maxReplyLen, p->d_dnssecOk, p->hasEDNS(), &age);
}
if(haveSomething) {
(*d_statnumhit)++;
if (recursive)
ageDNSPacket(value, age);
if(cached->noparse(value.c_str(), value.size()) < 0)
return 0;
cached->spoofQuestion(p); // for correct case
cached->qdomain=p->qdomain;
cached->qtype=p->qtype;
return 1;
}
// cerr<<"Packet cache miss for '"<<p->qdomain<<"', merits: "<<packetMeritsRecursion<<endl;
(*d_statnummiss)++;
return 0; // bummer
}
void PacketCache::getTTLS()
{
d_ttl=::arg().asNum("cache-ttl");
d_recursivettl=::arg().asNum("recursive-cache-ttl");
d_doRecursion=::arg().mustDo("recursor");
}
void PacketCache::insert(DNSPacket *q, DNSPacket *r, bool recursive, unsigned int maxttl)
{
if(d_ttl < 0)
getTTLS();
if(ntohs(q->d.qdcount)!=1) {
return; // do not try to cache packets with multiple questions
}
if(q->qclass != QClass::IN) // we only cache the INternet
return;
uint16_t maxReplyLen = q->d_tcp ? 0xffff : q->getMaxReplyLen();
unsigned int ourttl = recursive ? d_recursivettl : d_ttl;
if(!recursive) {
if(maxttl<ourttl)
ourttl=maxttl;
} else {
unsigned int minttl = r->getMinTTL();
if(minttl<ourttl)
ourttl=minttl;
}
insert(q->qdomain, q->qtype, PacketCache::PACKETCACHE, r->getString(), ourttl, -1, recursive,
maxReplyLen, q->d_dnssecOk, q->hasEDNS());
}
// universal key appears to be: qname, qtype, kind (packet, query cache), optionally zoneid, meritsRecursion
void PacketCache::insert(const DNSName &qname, const QType& qtype, CacheEntryType cet, const string& value, unsigned int ttl, int zoneID,
bool meritsRecursion, unsigned int maxReplyLen, bool dnssecOk, bool EDNS)
{
cleanupIfNeeded();
if(!ttl)
return;
//cerr<<"Inserting qname '"<<qname<<"', cet: "<<(int)cet<<", qtype: "<<qtype.getName()<<", ttl: "<<ttl<<", maxreplylen: "<<maxReplyLen<<", hasEDNS: "<<EDNS<<endl;
CacheEntry val;
val.created=time(0);
val.ttd=val.created+ttl;
val.qname=qname;
val.qtype=qtype.getCode();
val.value=value;
val.ctype=cet;
val.meritsRecursion=meritsRecursion;
val.maxReplyLen = maxReplyLen;
val.dnssecOk = dnssecOk;
val.zoneID = zoneID;
val.hasEDNS = EDNS;
auto& mc = getMap(val.qname);
TryWriteLock l(&mc.d_mut);
if(l.gotIt()) {
bool success;
cmap_t::iterator place;
tie(place, success)=mc.d_map.insert(val);
if(!success)
mc.d_map.replace(place, val);
}
else
S.inc("deferred-cache-inserts");
}
void PacketCache::insert(const DNSName &qname, const QType& qtype, CacheEntryType cet, const vector<DNSZoneRecord>& value, unsigned int ttl, int zoneID)
{
cleanupIfNeeded();
if(!ttl)
return;
//cerr<<"Inserting qname '"<<qname<<"', cet: "<<(int)cet<<", qtype: "<<qtype.getName()<<", ttl: "<<ttl<<", maxreplylen: "<<maxReplyLen<<", hasEDNS: "<<EDNS<<endl;
CacheEntry val;
val.created=time(0);
val.ttd=val.created+ttl;
val.qname=qname;
val.qtype=qtype.getCode();
val.drs=value;
val.ctype=cet;
val.meritsRecursion=false;
val.maxReplyLen = 0;
val.dnssecOk = false;
val.zoneID = zoneID;
val.hasEDNS = false;
auto& mc = getMap(val.qname);
TryWriteLock l(&mc.d_mut);
if(l.gotIt()) {
bool success;
cmap_t::iterator place;
tie(place, success)=mc.d_map.insert(val);
if(!success)
mc.d_map.replace(place, val);
}
else
S.inc("deferred-cache-inserts");
}
/* clears the entire packetcache. */
int PacketCache::purge()
{
int delcount=0;
for(auto& mc : d_maps) {
WriteLock l(&mc.d_mut);
delcount+=mc.d_map.size();
mc.d_map.clear();
}
d_statnumentries->store(0);
return delcount;
}
int PacketCache::purgeExact(const DNSName& qname)
{
int delcount=0;
auto& mc = getMap(qname);
WriteLock l(&mc.d_mut);
auto range = mc.d_map.equal_range(tie(qname));
if(range.first != range.second) {
delcount+=distance(range.first, range.second);
mc.d_map.erase(range.first, range.second);
}
*d_statnumentries-=delcount; // XXX FIXME NEEDS TO BE ADJUSTED (for packetcache shards)
return delcount;
}
/* purges entries from the packetcache. If match ends on a $, it is treated as a suffix */
int PacketCache::purge(const string &match)
{
if(ends_with(match, "$")) {
int delcount=0;
string prefix(match);
prefix.resize(prefix.size()-1);
DNSName dprefix(prefix);
for(auto& mc : d_maps) {
WriteLock l(&mc.d_mut);
cmap_t::const_iterator iter = mc.d_map.lower_bound(tie(dprefix));
auto start=iter;
for(; iter != mc.d_map.end(); ++iter) {
if(!iter->qname.isPartOf(dprefix)) {
break;
}
delcount++;
}
mc.d_map.erase(start, iter);
}
*d_statnumentries-=delcount; // XXX FIXME NEEDS TO BE ADJUSTED (for packetcache shards)
return delcount;
}
else {
return purgeExact(DNSName(match));
}
}
// called from ueberbackend
bool PacketCache::getEntry(const DNSName &qname, const QType& qtype, CacheEntryType cet, vector<DNSZoneRecord>& value, int zoneID)
{
if(d_ttl<0)
getTTLS();
cleanupIfNeeded();
auto& mc=getMap(qname);
TryReadLock l(&mc.d_mut); // take a readlock here
if(!l.gotIt()) {
S.inc( "deferred-cache-lookup");
return false;
}
return getEntryLocked(qname, qtype, cet, value, zoneID);
}
bool PacketCache::getEntryLocked(const DNSName &qname, const QType& qtype, CacheEntryType cet, string& value, int zoneID, bool meritsRecursion,
unsigned int maxReplyLen, bool dnssecOK, bool hasEDNS, unsigned int *age)
{
uint16_t qt = qtype.getCode();
//cerr<<"Lookup for maxReplyLen: "<<maxReplyLen<<endl;
auto& mc=getMap(qname);
// cmap_t::const_iterator i=mc.d_map.find(tie(qname, qt, cet, zoneID, meritsRecursion, maxReplyLen, dnssecOK, hasEDNS, *age));
auto& idx = boost::multi_index::get<UnorderedNameTag>(mc.d_map);
auto range=idx.equal_range(tie(qname, qt, cet, zoneID));
if(range.first == range.second)
return false;
time_t now=time(0);
for(auto iter = range.first ; iter != range.second; ++iter) {
if(meritsRecursion == iter->meritsRecursion && maxReplyLen == iter->maxReplyLen && dnssecOK == iter->dnssecOk && hasEDNS == iter->hasEDNS ) {
if(iter->ttd > now) {
if (age)
*age = now - iter->created;
value = iter->value;
return true;
}
}
}
return false;
}
bool PacketCache::getEntryLocked(const DNSName &qname, const QType& qtype, CacheEntryType cet, vector<DNSZoneRecord>& value, int zoneID)
{
uint16_t qt = qtype.getCode();
//cerr<<"Lookup for maxReplyLen: "<<maxReplyLen<<endl;
auto& mc=getMap(qname);
auto& idx = boost::multi_index::get<UnorderedNameTag>(mc.d_map);
auto i=idx.find(tie(qname, qt, cet, zoneID));
if(i==idx.end())
return false;
time_t now=time(0);
if(i->ttd > now) {
value = i->drs;
return true;
}
return false;
}
map<char,int> PacketCache::getCounts()
{
int recursivePackets=0, nonRecursivePackets=0, queryCacheEntries=0, negQueryCacheEntries=0;
for(auto& mc : d_maps) {
ReadLock l(&mc.d_mut);
for(cmap_t::const_iterator iter = mc.d_map.begin() ; iter != mc.d_map.end(); ++iter) {
if(iter->ctype == PACKETCACHE)
if(iter->meritsRecursion)
recursivePackets++;
else
nonRecursivePackets++;
else if(iter->ctype == QUERYCACHE) {
if(iter->value.empty())
negQueryCacheEntries++;
else
queryCacheEntries++;
}
}
}
map<char,int> ret;
ret['!']=negQueryCacheEntries;
ret['Q']=queryCacheEntries;
ret['n']=nonRecursivePackets;
ret['r']=recursivePackets;
return ret;
}
int PacketCache::size()
{
uint64_t ret=0;
for(auto& mc : d_maps) {
ReadLock l(&mc.d_mut);
ret+=mc.d_map.size();
}
return ret;
}
/** readlock for figuring out which iterators to delete, upgrade to writelock when actually cleaning */
void PacketCache::cleanup()
{
d_statnumentries->store(0);
for(auto& mc : d_maps) {
ReadLock l(&mc.d_mut);
*d_statnumentries+=mc.d_map.size();
}
unsigned int maxCached=::arg().asNum("max-cache-entries");
unsigned int toTrim=0;
unsigned long cacheSize=*d_statnumentries;
if(maxCached && cacheSize > maxCached) {
toTrim = cacheSize - maxCached;
}
unsigned int lookAt=0;
// two modes - if toTrim is 0, just look through 10% of the cache and nuke everything that is expired
// otherwise, scan first 5*toTrim records, and stop once we've nuked enough
if(toTrim)
lookAt=5*toTrim;
else
lookAt=cacheSize/10;
// cerr<<"cacheSize: "<<cacheSize<<", lookAt: "<<lookAt<<", toTrim: "<<toTrim<<endl;
time_t now=time(0);
DLOG(L<<"Starting cache clean"<<endl);
//unsigned int totErased=0;
for(auto& mc : d_maps) {
WriteLock wl(&mc.d_mut);
typedef cmap_t::nth_index<1>::type sequence_t;
sequence_t& sidx=mc.d_map.get<1>();
unsigned int erased=0, lookedAt=0;
for(sequence_t::iterator i=sidx.begin(); i != sidx.end(); lookedAt++) {
if(i->ttd < now) {
sidx.erase(i++);
erased++;
}
else {
++i;
}
if(toTrim && erased > toTrim / d_maps.size())
break;
if(lookedAt > lookAt / d_maps.size())
break;
}
//totErased += erased;
}
// if(totErased)
// cerr<<"erased: "<<totErased<<endl;
d_statnumentries->store(0);
for(auto& mc : d_maps) {
ReadLock l(&mc.d_mut);
*d_statnumentries+=mc.d_map.size();
}
DLOG(L<<"Done with cache clean"<<endl);
}
| grahamhayes/pdns | pdns/packetcache.cc | C++ | gpl-2.0 | 12,146 |
<?php
/**
* BackPress Styles Procedural API
*
* @since 2.6.0
*
* @package WordPress
* @subpackage BackPress
*/
/**
* Initialize $wp_styles if it has not been set.
*
* @global WP_Styles $wp_styles
*
* @since 4.2.0
*
* @return WP_Styles WP_Styles instance.
*/
function wp_styles() {
global $wp_styles;
if ( ! ( $wp_styles instanceof WP_Styles ) ) {
$wp_styles = new WP_Styles();
}
return $wp_styles;
}
/**
* Display styles that are in the $handles queue.
*
* Passing an empty array to $handles prints the queue,
* passing an array with one string prints that style,
* and passing an array of strings prints those styles.
*
* @global WP_Styles $wp_styles The WP_Styles object for printing styles.
*
* @since 2.6.0
*
* @param string|bool|array $handles Styles to be printed. Default 'false'.
* @return array On success, a processed array of WP_Dependencies items; otherwise, an empty array.
*/
function wp_print_styles( $handles = false ) {
if ( '' === $handles ) { // for wp_head
$handles = false;
}
/**
* Fires before styles in the $handles queue are printed.
*
* @since 2.6.0
*/
if ( ! $handles ) {
do_action( 'wp_print_styles' );
}
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
global $wp_styles;
if ( ! ( $wp_styles instanceof WP_Styles ) ) {
if ( ! $handles ) {
return array(); // No need to instantiate if nothing is there.
}
}
return wp_styles()->do_items( $handles );
}
/**
* Add extra CSS styles to a registered stylesheet.
*
* Styles will only be added if the stylesheet in already in the queue.
* Accepts a string $data containing the CSS. If two or more CSS code blocks
* are added to the same stylesheet $handle, they will be printed in the order
* they were added, i.e. the latter added styles can redeclare the previous.
*
* @see WP_Styles::add_inline_style()
*
* @since 3.3.0
*
* @param string $handle Name of the stylesheet to add the extra styles to. Must be lowercase.
* @param string $data String containing the CSS styles to be added.
* @return bool True on success, false on failure.
*/
function wp_add_inline_style( $handle, $data ) {
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
if ( false !== stripos( $data, '</style>' ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Do not pass style tags to wp_add_inline_style().' ), '3.7' );
$data = trim( preg_replace( '#<style[^>]*>(.*)</style>#is', '$1', $data ) );
}
return wp_styles()->add_inline_style( $handle, $data );
}
/**
* Register a CSS stylesheet.
*
* @see WP_Dependencies::add()
* @link http://www.w3.org/TR/CSS2/media.html#media-types List of CSS media types.
*
* @since 2.6.0
* @since 4.3.0 A return value was added.
*
* @param string $handle Name of the stylesheet.
* @param string|bool $src Path to the stylesheet from the WordPress root directory. Example: '/css/mystyle.css'.
* @param array $deps An array of registered style handles this stylesheet depends on. Default empty array.
* @param string|bool $ver String specifying the stylesheet version number. Used to ensure that the correct version
* is sent to the client regardless of caching. Default 'false'. Accepts 'false', 'null', or 'string'.
* @param string $media Optional. The media for which this stylesheet has been defined.
* Default 'all'. Accepts 'all', 'aural', 'braille', 'handheld', 'projection', 'print',
* 'screen', 'tty', or 'tv'.
* @return bool Whether the style has been registered. True on success, false on failure.
*/
function wp_register_style( $handle, $src, $deps = array(), $ver = false, $media = 'all' ) {
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
return wp_styles()->add( $handle, $src, $deps, $ver, $media );
}
/**
* Remove a registered stylesheet.
*
* @see WP_Dependencies::remove()
*
* @since 2.1.0
*
* @param string $handle Name of the stylesheet to be removed.
*/
function wp_deregister_style( $handle ) {
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
wp_styles()->remove( $handle );
}
/**
* Enqueue a CSS stylesheet.
*
* Registers the style if source provided (does NOT overwrite) and enqueues.
*
* @see WP_Dependencies::add(), WP_Dependencies::enqueue()
* @link http://www.w3.org/TR/CSS2/media.html#media-types List of CSS media types.
*
* @since 2.6.0
*
* @param string $handle Name of the stylesheet.
* @param string|bool $src Path to the stylesheet from the root directory of WordPress. Example: '/css/mystyle.css'.
* @param array $deps An array of registered style handles this stylesheet depends on. Default empty array.
* @param string|bool $ver String specifying the stylesheet version number, if it has one. This parameter is used
* to ensure that the correct version is sent to the client regardless of caching, and so
* should be included if a version number is available and makes sense for the stylesheet.
* @param string $media Optional. The media for which this stylesheet has been defined.
* Default 'all'. Accepts 'all', 'aural', 'braille', 'handheld', 'projection', 'print',
* 'screen', 'tty', or 'tv'.
*/
function wp_enqueue_style( $handle, $src = false, $deps = array(), $ver = false, $media = 'all' ) {
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
$wp_styles = wp_styles();
if ( $src ) {
$_handle = explode('?', $handle);
$wp_styles->add( $_handle[0], $src, $deps, $ver, $media );
}
$wp_styles->enqueue( $handle );
}
/**
* Remove a previously enqueued CSS stylesheet.
*
* @see WP_Dependencies::dequeue()
*
* @since 3.1.0
*
* @param string $handle Name of the stylesheet to be removed.
*/
function wp_dequeue_style( $handle ) {
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
wp_styles()->dequeue( $handle );
}
/**
* Check whether a CSS stylesheet has been added to the queue.
*
* @since 2.8.0
*
* @param string $handle Name of the stylesheet.
* @param string $list Optional. Status of the stylesheet to check. Default 'enqueued'.
* Accepts 'enqueued', 'registered', 'queue', 'to_do', and 'done'.
* @return bool Whether style is queued.
*/
function wp_style_is( $handle, $list = 'enqueued' ) {
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
return (bool) wp_styles()->query( $handle, $list );
}
/**
* Add metadata to a CSS stylesheet.
*
* Works only if the stylesheet has already been added.
*
* Possible values for $key and $value:
* 'conditional' string Comments for IE 6, lte IE 7 etc.
* 'rtl' bool|string To declare an RTL stylesheet.
* 'suffix' string Optional suffix, used in combination with RTL.
* 'alt' bool For rel="alternate stylesheet".
* 'title' string For preferred/alternate stylesheets.
*
* @see WP_Dependency::add_data()
*
* @since 3.6.0
*
* @param string $handle Name of the stylesheet.
* @param string $key Name of data point for which we're storing a value.
* Accepts 'conditional', 'rtl' and 'suffix', 'alt' and 'title'.
* @param mixed $value String containing the CSS data to be added.
* @return bool True on success, false on failure.
*/
function wp_style_add_data( $handle, $key, $value ) {
return wp_styles()->add_data( $handle, $key, $value );
}
| SKLCC/website | wp-includes/functions.wp-styles.php | PHP | gpl-2.0 | 7,435 |
cmd_drivers/mmc/core/built-in.o := /home/ar/android/aosp/prebuilt/linux-x86/toolchain/arm-eabi-4.4.3/bin/arm-eabi-ld -EL -r -o drivers/mmc/core/built-in.o drivers/mmc/core/mmc_core.o
| kannu1994/crespo_kernel | drivers/mmc/core/.built-in.o.cmd | Batchfile | gpl-2.0 | 188 |
// TransformPatternDlg.cpp : implementation file
#include <psycle/host/detail/project.private.hpp>
#include "TransformPatternDlg.hpp"
#include "Song.hpp"
#include "ChildView.hpp"
#include "MainFrm.hpp"
namespace psycle { namespace host {
static const char notes[12][3]={"C-","C#","D-","D#","E-","F-","F#","G-","G#","A-","A#","B-"};
static const char *empty ="Empty";
static const char *nonempty="Nonempty";
static const char *all="All";
static const char *same="Same";
static const char *off="off";
static const char *twk="twk";
static const char *tws="tws";
static const char *mcm="mcm";
// CTransformPatternDlg dialog
IMPLEMENT_DYNAMIC(CTransformPatternDlg, CDialog)
CTransformPatternDlg::CTransformPatternDlg(Song& _pSong, CChildView& _cview, CWnd* pParent /*=NULL*/)
: CDialog(CTransformPatternDlg::IDD, pParent)
, song(_pSong), cview(_cview), m_applyto(0)
{
}
CTransformPatternDlg::~CTransformPatternDlg()
{
}
void CTransformPatternDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_SEARCHNOTECOMB, m_searchnote);
DDX_Control(pDX, IDC_SEARCHINSTCOMB, m_searchinst);
DDX_Control(pDX, IDC_SEARCHMACHCOMB, m_searchmach);
DDX_Control(pDX, IDC_REPLNOTECOMB, m_replacenote);
DDX_Control(pDX, IDC_REPLINSTCOMB, m_replaceinst);
DDX_Control(pDX, IDC_REPLMACHCOMB, m_replacemach);
DDX_Control(pDX, IDC_REPLTWEAKCHECK, m_replacetweak);
DDX_Radio(pDX,IDC_APPLYTOSONG, m_applyto);
DDX_Control(pDX, IDC_CH_INCLUDEPAT, m_includePatNotInSeq);
}
BEGIN_MESSAGE_MAP(CTransformPatternDlg, CDialog)
ON_BN_CLICKED(IDD_SEARCH, &CTransformPatternDlg::OnBnClickedSearch)
ON_BN_CLICKED(IDD_REPLACE, &CTransformPatternDlg::OnBnClickedReplace)
END_MESSAGE_MAP()
BOOL CTransformPatternDlg::OnInitDialog()
{
CDialog::OnInitDialog();
//Note (search and replace)
m_searchnote.AddString(all); m_searchnote.SetItemData(0,1003);
m_searchnote.AddString(empty); m_searchnote.SetItemData(1,1001);
m_searchnote.AddString(nonempty); m_searchnote.SetItemData(2,1002);
m_replacenote.AddString(same); m_replacenote.SetItemData(0,1002);
m_replacenote.AddString(empty); m_replacenote.SetItemData(1,1001);
bool is440 = PsycleGlobal::conf().patView().showA440;
for (int i=notecommands::c0; i <= notecommands::b9;i++) {
std::ostringstream os;
os << notes[i%12];
if (is440) os << (i/12)-1;
else os << (i/12);
m_searchnote.AddString(os.str().c_str()); m_searchnote.SetItemData(3+i,i);
m_replacenote.AddString(os.str().c_str()); m_replacenote.SetItemData(2+i,i);
}
m_searchnote.AddString(off); m_searchnote.SetItemData(123,notecommands::release);
m_searchnote.AddString(twk); m_searchnote.SetItemData(124,notecommands::tweak);
m_searchnote.AddString(tws); m_searchnote.SetItemData(125,notecommands::tweakslide);
m_searchnote.AddString(mcm); m_searchnote.SetItemData(126,notecommands::midicc);
m_replacenote.AddString(off); m_replacenote.SetItemData(122,notecommands::release);
m_replacenote.AddString(twk); m_replacenote.SetItemData(123,notecommands::tweak);
m_replacenote.AddString(tws); m_replacenote.SetItemData(124,notecommands::tweakslide);
m_replacenote.AddString(mcm); m_replacenote.SetItemData(125,notecommands::midicc);
m_searchnote.SetCurSel(0);
m_replacenote.SetCurSel(0);
//Inst (search and replace)
m_searchinst.AddString(all); m_searchinst.SetItemData(0,1003);
m_searchinst.AddString(empty); m_searchinst.SetItemData(1,1001);
m_searchinst.AddString(nonempty); m_searchinst.SetItemData(2,1002);
m_replaceinst.AddString(same); m_replaceinst.SetItemData(0,1002);
m_replaceinst.AddString(empty); m_replaceinst.SetItemData(1,1001);
for (int i=0; i < 0xFF; i++) {
std::ostringstream os;
if (i < 16) os << "0";
os << std::uppercase << std::hex << i;
m_searchinst.AddString(os.str().c_str()); m_searchinst.SetItemData(3+i,i);
m_replaceinst.AddString(os.str().c_str()); m_replaceinst.SetItemData(2+i,i);
}
m_searchinst.SetCurSel(0);
m_replaceinst.SetCurSel(0);
//Mach (search and replace)
m_searchmach.AddString(all); m_searchmach.SetItemData(0,1003);
m_searchmach.AddString(empty); m_searchmach.SetItemData(1,1001);
m_searchmach.AddString(nonempty); m_searchmach.SetItemData(2,1002);
m_replacemach.AddString(same); m_replacemach.SetItemData(0,1002);
m_replacemach.AddString(empty); m_replacemach.SetItemData(1,1001);
for (int i=0; i < 0xFF; i++) {
std::ostringstream os;
if (i < 16) os << "0";
os << std::uppercase << std::hex << i;
m_searchmach.AddString(os.str().c_str()); m_searchmach.SetItemData(3+i,i);
m_replacemach.AddString(os.str().c_str()); m_replacemach.SetItemData(2+i,i);
}
m_searchmach.SetCurSel(0);
m_replacemach.SetCurSel(0);
if (cview.blockSelected) m_applyto = 2;
UpdateData(FALSE);
return true; // return true unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return false
}
// CTransformPatternDlg message handlers
void CTransformPatternDlg::OnBnClickedSearch()
{
CSearchReplaceMode mode = cview.SetupSearchReplaceMode(
m_searchnote.GetItemData(m_searchnote.GetCurSel()),
m_searchinst.GetItemData(m_searchinst.GetCurSel()),
m_searchmach.GetItemData(m_searchmach.GetCurSel()));
CCursor cursor;
cursor.line = -1;
int pattern = -1;
UpdateData (TRUE);
if (m_applyto == 0) {
bool includeOther = m_includePatNotInSeq.GetCheck() > 0;
int lastPatternUsed = (includeOther )? song.GetHighestPatternIndexInSequence() : MAX_PATTERNS;
for (int currentPattern = 0; currentPattern <= lastPatternUsed; currentPattern++)
{
if (song.IsPatternUsed(currentPattern, !includeOther))
{
CSelection sel;
sel.start.line = 0; sel.start.track = 0;
sel.end.line = song.patternLines[currentPattern];
sel.end.track = MAX_TRACKS;
cursor = cview.SearchInPattern(currentPattern, sel , mode);
if (cursor.line != -1) {
pattern=currentPattern;
break;
}
}
}
}
else if (m_applyto == 1) {
CSelection sel;
sel.start.line = 0; sel.start.track = 0;
sel.end.line = song.patternLines[cview._ps()];
sel.end.track = MAX_TRACKS;
cursor = cview.SearchInPattern(cview._ps(), sel , mode);
pattern = cview._ps();
}
else if (m_applyto == 2 && cview.blockSelected) {
cursor = cview.SearchInPattern(cview._ps(), cview.blockSel , mode);
pattern = cview._ps();
}
else {
MessageBox("No block selected for action","Search and replace",MB_ICONWARNING);
return;
}
if (cursor.line == -1) {
MessageBox("Nothing found that matches the selected options","Search and replace",MB_ICONINFORMATION);
}
else {
cview.editcur = cursor;
if (cview._ps() != pattern) {
int pos = -1;
for (int i=0; i < MAX_SONG_POSITIONS; i++) {
if (song.playOrder[i] == pattern) {
pos = i;
break;
}
}
if (pos == -1){
pos = song.playLength;
++song.playLength;
song.playOrder[pos]=pattern;
((CMainFrame*)cview.pParentFrame)->UpdateSequencer();
}
cview.editPosition = pos;
memset(song.playOrderSel,0,MAX_SONG_POSITIONS*sizeof(bool));
song.playOrderSel[cview.editPosition]=true;
((CMainFrame*)cview.pParentFrame)->UpdatePlayOrder(true);
cview.Repaint(draw_modes::pattern);
}
else {
cview.Repaint(draw_modes::cursor);
}
}
}
void CTransformPatternDlg::OnBnClickedReplace()
{
CSearchReplaceMode mode = cview.SetupSearchReplaceMode(
m_searchnote.GetItemData(m_searchnote.GetCurSel()),
m_searchinst.GetItemData(m_searchinst.GetCurSel()),
m_searchmach.GetItemData(m_searchmach.GetCurSel()),
m_replacenote.GetItemData(m_replacenote.GetCurSel()),
m_replaceinst.GetItemData(m_replaceinst.GetCurSel()),
m_replacemach.GetItemData(m_replacemach.GetCurSel()),
m_replacetweak.GetCheck());
bool replaced=false;
UpdateData (TRUE);
if (m_applyto == 0) {
bool includeOther = m_includePatNotInSeq.GetCheck() > 0;
int lastPatternUsed = (includeOther )? song.GetHighestPatternIndexInSequence() : MAX_PATTERNS;
for (int currentPattern = 0; currentPattern <= lastPatternUsed; currentPattern++)
{
if (song.IsPatternUsed(currentPattern, !includeOther))
{
CSelection sel;
sel.start.line = 0; sel.start.track = 0;
sel.end.line = song.patternLines[currentPattern];
sel.end.track = MAX_TRACKS;
replaced=cview.SearchReplace(currentPattern, sel , mode);
}
}
}
else if (m_applyto == 1) {
CSelection sel;
sel.start.line = 0; sel.start.track = 0;
sel.end.line = song.patternLines[cview._ps()];
sel.end.track = MAX_TRACKS;
replaced=cview.SearchReplace(cview._ps(), sel, mode);
}
else if (m_applyto == 2 && cview.blockSelected) {
replaced=cview.SearchReplace(cview._ps(), cview.blockSel , mode);
}
else {
MessageBox("No block selected for action","Search and replace",MB_ICONWARNING);
return;
}
if (replaced) {
cview.Repaint(draw_modes::pattern);
}
else {
MessageBox("Nothing found that matches the selected options","Search and replace",MB_ICONINFORMATION);
}
}
} // namespace
} // namespace
| eriser/psycle | psycle/src/psycle/host/TransformPatternDlg.cpp | C++ | gpl-2.0 | 9,403 |
/* ========================================================================
* Bootstrap: alert.js v3.0.3
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
+function($) {
"use strict";
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function(element, options) {
this.type =
this.options =
this.enabled =
this.timeout =
this.hoverState =
this.$element = null
this.init('tooltip', element, options)
}
Tooltip.DEFAULTS = {
animation: true
, placement: 'top'
, selector: false
, template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
, trigger: 'hover focus'
, title: ''
, delay: 0
, html: false
, container: false
}
Tooltip.prototype.init = function(type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--; ) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focus'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, {trigger: 'manual', selector: ''})) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function() {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function(options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay
, hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function() {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function(key, value) {
if (defaults[key] != value)
options[key] = value
})
return options
}
Tooltip.prototype.enter = function(obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show)
return self.show()
self.timeout = setTimeout(function() {
if (self.hoverState == 'in')
self.show()
}, self.options.delay.show)
}
Tooltip.prototype.leave = function(obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide)
return self.hide()
self.timeout = setTimeout(function() {
if (self.hoverState == 'out')
self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function() {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
if (e.isDefaultPrevented())
return
var $tip = this.tip()
this.setContent()
if (this.options.animation)
$tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace)
placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({top: 0, left: 0, display: 'block'})
.addClass(placement)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var $parent = this.$element.parent()
var orgPlacement = placement
var docScroll = document.documentElement.scrollTop || document.body.scrollTop
var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth()
var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight()
var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left
placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' :
placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' :
placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' :
placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
this.$element.trigger('shown.bs.' + this.type)
}
}
Tooltip.prototype.applyPlacement = function(offset, placement) {
var replace
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop))
marginTop = 0
if (isNaN(marginLeft))
marginLeft = 0
offset.top = offset.top + marginTop
offset.left = offset.left + marginLeft
$tip
.offset(offset)
.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
replace = true
offset.top = offset.top + height - actualHeight
}
if (/bottom|top/.test(placement)) {
var delta = 0
if (offset.left < 0) {
delta = offset.left * -2
offset.left = 0
$tip.offset(offset)
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
}
this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
} else {
this.replaceArrow(actualHeight - height, actualHeight, 'top')
}
if (replace)
$tip.offset(offset)
}
Tooltip.prototype.replaceArrow = function(delta, dimension, position) {
this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + "%") : '')
}
Tooltip.prototype.setContent = function() {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function() {
var that = this
var $tip = this.tip()
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in')
$tip.detach()
}
this.$element.trigger(e)
if (e.isDefaultPrevented())
return
$tip.removeClass('in')
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one($.support.transition.end, complete)
.emulateTransitionEnd(150) :
complete()
this.$element.trigger('hidden.bs.' + this.type)
return this
}
Tooltip.prototype.fixTitle = function() {
var $e = this.$element
if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function() {
return this.getTitle()
}
Tooltip.prototype.getPosition = function() {
var el = this.$element[0]
return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
width: el.offsetWidth
, height: el.offsetHeight
}, this.$element.offset())
}
Tooltip.prototype.getCalculatedOffset = function(placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2} :
placement == 'top' ? {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2} :
placement == 'left' ? {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth} :
/* placement == 'right' */ {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}
}
Tooltip.prototype.getTitle = function() {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.tip = function() {
return this.$tip = this.$tip || $(this.options.template)
}
Tooltip.prototype.arrow = function() {
return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')
}
Tooltip.prototype.validate = function() {
if (!this.$element[0].parentNode) {
this.hide()
this.$element = null
this.options = null
}
}
Tooltip.prototype.enable = function() {
this.enabled = true
}
Tooltip.prototype.disable = function() {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function() {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function(e) {
var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
Tooltip.prototype.destroy = function() {
this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
}
// TOOLTIP PLUGIN DEFINITION
// =========================
var old = $.fn.tooltip
$.fn.tooltip = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data)
$this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function() {
$.fn.tooltip = old
return this
}
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function(el) {
$(el).on('click', dismiss, this.close)
}
Alert.prototype.close = function(e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e)
e.preventDefault()
if (!$parent.length) {
$parent = $this.hasClass('alert') ? $this : $this.parent()
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented())
return
$parent.removeClass('in')
function removeElement() {
$parent.trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one($.support.transition.end, removeElement)
.emulateTransitionEnd(150) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
var old = $.fn.alert
$.fn.alert = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data)
$this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string')
data[option].call($this)
})
}
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function() {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.0.3
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
+function($) {
"use strict";
// TAB CLASS DEFINITION
// ====================
var Tab = function(element) {
this.element = $(element)
}
Tab.prototype.show = function() {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
if ($this.parent('li').hasClass('active'))
return
var previous = $ul.find('.active:last a')[0]
var e = $.Event('show.bs.tab', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented())
return
var $target = $(selector)
this.activate($this.parent('li'), $ul)
this.activate($target, $target.parent(), function() {
$this.trigger({
type: 'shown.bs.tab'
, relatedTarget: previous
})
})
}
Tab.prototype.activate = function(element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& $active.hasClass('fade')
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
transition ?
$active
.one($.support.transition.end, next)
.emulateTransitionEnd(150) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
var old = $.fn.tab
$.fn.tab = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data)
$this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function() {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
$(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function(e) {
e.preventDefault()
$(this).tab('show')
})
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.0.3
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
+function($) {
"use strict";
// AFFIX CLASS DEFINITION
// ======================
var Affix = function(element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$window = $(window)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed =
this.unpin = null
this.checkPosition()
}
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0
}
Affix.prototype.checkPositionWithEventLoop = function() {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function() {
if (!this.$element.is(':visible'))
return
var scrollHeight = $(document).height()
var scrollTop = this.$window.scrollTop()
var position = this.$element.offset()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
if (typeof offset != 'object')
offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function')
offsetTop = offset.top()
if (typeof offsetBottom == 'function')
offsetBottom = offset.bottom()
var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false :
offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' :
offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false
if (this.affixed === affix)
return
if (this.unpin)
this.$element.css('top', '')
this.affixed = affix
this.unpin = affix == 'bottom' ? position.top - scrollTop : null
this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : ''))
if (affix == 'bottom') {
this.$element.offset({top: document.body.offsetHeight - offsetBottom - this.$element.height()})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
var old = $.fn.affix
$.fn.affix = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data)
$this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function() {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function() {
$('[data-spy="affix"]').each(function() {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom)
data.offset.bottom = data.offsetBottom
if (data.offsetTop)
data.offset.top = data.offsetTop
$spy.affix(data)
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.0.3
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
+function($) {
"use strict";
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function(element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.transitioning = null
if (this.options.parent)
this.$parent = $(this.options.parent)
if (this.options.toggle)
this.toggle()
}
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function() {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function() {
if (this.transitioning || this.$element.hasClass('in'))
return
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented())
return
var actives = this.$parent && this.$parent.find('> .panel > .in')
if (actives && actives.length) {
var hasData = actives.data('bs.collapse')
if (hasData && hasData.transitioning)
return
actives.collapse('hide')
hasData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')
[dimension](0)
this.transitioning = 1
var complete = function() {
this.$element
.removeClass('collapsing')
.addClass('in')
[dimension]('auto')
this.transitioning = 0
this.$element.trigger('shown.bs.collapse')
}
if (!$.support.transition)
return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one($.support.transition.end, $.proxy(complete, this))
.emulateTransitionEnd(350)
[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function() {
if (this.transitioning || !this.$element.hasClass('in'))
return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented())
return
var dimension = this.dimension()
this.$element
[dimension](this.$element[dimension]())
[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse')
.removeClass('in')
this.transitioning = 1
var complete = function() {
this.transitioning = 0
this.$element
.trigger('hidden.bs.collapse')
.removeClass('collapsing')
.addClass('collapse')
}
if (!$.support.transition)
return complete.call(this)
this.$element
[dimension](0)
.one($.support.transition.end, $.proxy(complete, this))
.emulateTransitionEnd(350)
}
Collapse.prototype.toggle = function() {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
var old = $.fn.collapse
$.fn.collapse = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data)
$this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function() {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function(e) {
var $this = $(this), href
var target = $this.attr('data-target')
|| e.preventDefault()
|| (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
var $target = $(target)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
var parent = $this.attr('data-parent')
var $parent = parent && $(parent)
if (!data || !data.transitioning) {
if ($parent)
$parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed')
$this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
}
$target.collapse(option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.0.3
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
+function($) {
"use strict";
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
var href
var process = $.proxy(this.process, this)
this.$element = $(element).is('body') ? $(window) : $(element)
this.$body = $('body')
this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target
|| ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
|| '') + ' .nav li > a'
this.offsets = $([])
this.targets = $([])
this.activeTarget = null
this.refresh()
this.process()
}
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.refresh = function() {
var offsetMethod = this.$element[0] == window ? 'offset' : 'position'
this.offsets = $([])
this.targets = $([])
var self = this
var $targets = this.$body
.find(this.selector)
.map(function() {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#\w/.test(href) && $(href)
return ($href
&& $href.length
&& [[$href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href]]) || null
})
.sort(function(a, b) {
return a[0] - b[0]
})
.each(function() {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function() {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
var maxScroll = scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets.last()[0]) && this.activate(i)
}
for (i = offsets.length; i--; ) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function(target) {
this.activeTarget = target
$(this.selector)
.parents('.active')
.removeClass('active')
var selector = this.selector
+ '[data-target="' + target + '"],'
+ this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
var old = $.fn.scrollspy
$.fn.scrollspy = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data)
$this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function() {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load', function() {
$('[data-spy="scroll"]').each(function() {
var $spy = $(this)
$spy.scrollspy($spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.0.3
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
+function($) {
"use strict";
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd'
, 'MozTransition': 'transitionend'
, 'OTransition': 'oTransitionEnd otransitionend'
, 'transition': 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return {end: transEndEventNames[name]}
}
}
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function(duration) {
var called = false, $el = this
$(this).one($.support.transition.end, function() {
called = true
})
var callback = function() {
if (!called)
$($el).trigger($.support.transition.end)
}
setTimeout(callback, duration)
return this
}
$(function() {
$.support.transition = transitionEnd()
})
}(jQuery);
| nick144/Tournaments | js/bootstrap.js | JavaScript | gpl-2.0 | 36,381 |
/**
* Copyright (C) 2008-2014, Marvell International Ltd.
*
* This software file (the "File") is distributed by Marvell International
* Ltd. under the terms of the GNU General Public License Version 2, June 1991
* (the "License"). You may use, redistribute and/or modify this File in
* accordance with the terms and conditions of the License, a copy of which
* is available by writing to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA or on the
* worldwide web at http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* THE FILE IS DISTRIBUTED AS-IS, WITHOUT WARRANTY OF ANY KIND, AND THE
* IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
* ARE EXPRESSLY DISCLAIMED. The License provides additional details about
* this warranty disclaimer.
*
*/
/******************** (c) Marvell Semiconductor, Inc., 2001 *******************
*
* Purpose:
* This file contains the definitions of the fragment module
*
*****************************************************************************/
#ifndef __FRAGMENT_H__
#define __FRAGMENT_H__
#include "StaDb.h"
//=============================================================================
// INCLUDE FILES
//=============================================================================
//=============================================================================
// DEFINITIONS
//=============================================================================
//=============================================================================
// PUBLIC TYPE DEFINITIONS
//=============================================================================
//=============================================================================
// PUBLIC PROCEDURES (ANSI Prototypes)
//=============================================================================
extern struct sk_buff *DeFragPck(struct net_device *dev,struct sk_buff *skb, extStaDb_StaInfo_t **pStaInfo);
#endif/* __FRAGMENT_H__ */
| TheDgtl/mrvl_wlan_v7drv | wlan-v7/core/incl/Fragment.h | C | gpl-2.0 | 2,157 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_67) on Thu Apr 09 10:31:52 MDT 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.lucene.analysis.custom.CustomAnalyzer (Lucene 5.1.0 API)</title>
<meta name="date" content="2015-04-09">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.lucene.analysis.custom.CustomAnalyzer (Lucene 5.1.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/lucene/analysis/custom/CustomAnalyzer.html" title="class in org.apache.lucene.analysis.custom">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/lucene/analysis/custom/class-use/CustomAnalyzer.html" target="_top">Frames</a></li>
<li><a href="CustomAnalyzer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.lucene.analysis.custom.CustomAnalyzer" class="title">Uses of Class<br>org.apache.lucene.analysis.custom.CustomAnalyzer</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/apache/lucene/analysis/custom/CustomAnalyzer.html" title="class in org.apache.lucene.analysis.custom">CustomAnalyzer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.lucene.analysis.custom">org.apache.lucene.analysis.custom</a></td>
<td class="colLast">
<div class="block">A general-purpose Analyzer that can be created with a builder-style API.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.lucene.analysis.custom">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/apache/lucene/analysis/custom/CustomAnalyzer.html" title="class in org.apache.lucene.analysis.custom">CustomAnalyzer</a> in <a href="../../../../../../org/apache/lucene/analysis/custom/package-summary.html">org.apache.lucene.analysis.custom</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/apache/lucene/analysis/custom/package-summary.html">org.apache.lucene.analysis.custom</a> that return <a href="../../../../../../org/apache/lucene/analysis/custom/CustomAnalyzer.html" title="class in org.apache.lucene.analysis.custom">CustomAnalyzer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/apache/lucene/analysis/custom/CustomAnalyzer.html" title="class in org.apache.lucene.analysis.custom">CustomAnalyzer</a></code></td>
<td class="colLast"><span class="strong">CustomAnalyzer.Builder.</span><code><strong><a href="../../../../../../org/apache/lucene/analysis/custom/CustomAnalyzer.Builder.html#build()">build</a></strong>()</code>
<div class="block">Builds the analyzer.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/lucene/analysis/custom/CustomAnalyzer.html" title="class in org.apache.lucene.analysis.custom">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/lucene/analysis/custom/class-use/CustomAnalyzer.html" target="_top">Frames</a></li>
<li><a href="CustomAnalyzer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2015 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| marcialhernandez/TecnologiasWeb | lucene-5.1.0/docs/analyzers-common/org/apache/lucene/analysis/custom/class-use/CustomAnalyzer.html | HTML | gpl-2.0 | 7,208 |
var express = require('express'),
Weapon = require('../models/Weapon'),
router = express.Router();
// HOMEPAGE
router.get('/', function(req, res) {
res.render('index', {
title:'Weapons Guide | Fire Emblem | Awakening',
credit: 'Matt.Dodson.Digital',
msg: 'Hello Word!'
});
});
// WEAPON
router.get('/weapon', function(req, res) {
var schema = {};
Weapon.schema.eachPath(function (pathname, schemaType) {
schema[pathname] = schemaType.instance;
});
res.render('weapon', {
title:'Weapons Guide | Fire Emblem | Awakening',
credit: 'Matt.Dodson.Digital',
msg: 'This is a form.',
schema: schema
});
});
module.exports = router;
| dodsonm/fire-emblem-awakening | routes/index.js | JavaScript | gpl-2.0 | 717 |
/*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2013 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. Redistributions
in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution. Neither the name of
the Intel Corporation nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
END_LEGAL */
#include <stdio.h>
#pragma data_seg("dsec")
static char greeting[] = "Hello";
#pragma code_seg("asection")
void report()
{
printf("%s, world\n", greeting);
}
#pragma code_seg(".text")
int main ()
{
report();
return 0;
}
| cyjseagull/SHMA | zsim-nvmain/pin_kit/source/tools/ToolUnitTests/secname_app.cpp | C++ | gpl-2.0 | 1,776 |
function isCompatible(){if(navigator.appVersion.indexOf('MSIE')!==-1&&parseFloat(navigator.appVersion.split('MSIE')[1])<6){return false;}return true;}var startUp=function(){mw.config=new mw.Map(true);mw.loader.addSource({"local":{"loadScript":"//bits.wikimedia.org/he.wikipedia.org/load.php","apiScript":"/w/api.php"}});mw.loader.register([["site","1349976191",[],"site"],["noscript","1347062400",[],"noscript"],["startup","1351588618",[],"startup"],["filepage","1347062400"],["user.groups","1347062400",[],"user"],["user","1347062400",[],"user"],["user.cssprefs","1347062400",["mediawiki.user"],"private"],["user.options","1347062400",[],"private"],["user.tokens","1347062400",[],"private"],["mediawiki.language.data","1351588618",["mediawiki.language.init"]],["skins.chick","1350311539"],["skins.cologneblue","1350311539"],["skins.modern","1350311539"],["skins.monobook","1350311539"],["skins.nostalgia","1350311539"],["skins.simple","1350311539"],["skins.standard","1350311539"],["skins.vector",
"1350311539"],["jquery","1350311539"],["jquery.appear","1350311539"],["jquery.arrowSteps","1350311539"],["jquery.async","1350311539"],["jquery.autoEllipsis","1350334340",["jquery.highlightText"]],["jquery.badge","1350311539"],["jquery.byteLength","1350311539"],["jquery.byteLimit","1350311539",["jquery.byteLength"]],["jquery.checkboxShiftClick","1350311539"],["jquery.client","1350311539"],["jquery.collapsibleTabs","1350311539"],["jquery.color","1350311539",["jquery.colorUtil"]],["jquery.colorUtil","1350311539"],["jquery.cookie","1350311539"],["jquery.delayedBind","1350311539"],["jquery.expandableField","1350311539",["jquery.delayedBind"]],["jquery.farbtastic","1350311539",["jquery.colorUtil"]],["jquery.footHovzer","1350311539"],["jquery.form","1350311539"],["jquery.getAttrs","1350311539"],["jquery.hidpi","1350311539"],["jquery.highlightText","1350334340",["jquery.mwExtension"]],["jquery.hoverIntent","1350311539"],["jquery.json","1350311539"],["jquery.localize","1350311539"],[
"jquery.makeCollapsible","1351565405"],["jquery.mockjax","1350311539"],["jquery.mw-jump","1350311539"],["jquery.mwExtension","1350311539"],["jquery.placeholder","1350311539"],["jquery.qunit","1350311539"],["jquery.qunit.completenessTest","1350311539",["jquery.qunit"]],["jquery.spinner","1350311539"],["jquery.jStorage","1350311539",["jquery.json"]],["jquery.suggestions","1350311539",["jquery.autoEllipsis"]],["jquery.tabIndex","1350311539"],["jquery.tablesorter","1351565484",["jquery.mwExtension"]],["jquery.textSelection","1350311539",["jquery.client"]],["jquery.validate","1350311539"],["jquery.xmldom","1350311539"],["jquery.tipsy","1350311539"],["jquery.ui.core","1350311539",["jquery"],"jquery.ui"],["jquery.ui.widget","1350311539",[],"jquery.ui"],["jquery.ui.mouse","1350311539",["jquery.ui.widget"],"jquery.ui"],["jquery.ui.position","1350311539",[],"jquery.ui"],["jquery.ui.draggable","1350311539",["jquery.ui.core","jquery.ui.mouse","jquery.ui.widget"],"jquery.ui"],["jquery.ui.droppable"
,"1350311539",["jquery.ui.core","jquery.ui.mouse","jquery.ui.widget","jquery.ui.draggable"],"jquery.ui"],["jquery.ui.resizable","1350311539",["jquery.ui.core","jquery.ui.widget","jquery.ui.mouse"],"jquery.ui"],["jquery.ui.selectable","1350311539",["jquery.ui.core","jquery.ui.widget","jquery.ui.mouse"],"jquery.ui"],["jquery.ui.sortable","1350311539",["jquery.ui.core","jquery.ui.widget","jquery.ui.mouse"],"jquery.ui"],["jquery.ui.accordion","1350311539",["jquery.ui.core","jquery.ui.widget"],"jquery.ui"],["jquery.ui.autocomplete","1350311539",["jquery.ui.core","jquery.ui.widget","jquery.ui.position"],"jquery.ui"],["jquery.ui.button","1350311539",["jquery.ui.core","jquery.ui.widget"],"jquery.ui"],["jquery.ui.datepicker","1350311539",["jquery.ui.core"],"jquery.ui"],["jquery.ui.dialog","1350311539",["jquery.ui.core","jquery.ui.widget","jquery.ui.button","jquery.ui.draggable","jquery.ui.mouse","jquery.ui.position","jquery.ui.resizable"],"jquery.ui"],["jquery.ui.progressbar","1350311539",[
"jquery.ui.core","jquery.ui.widget"],"jquery.ui"],["jquery.ui.slider","1350311539",["jquery.ui.core","jquery.ui.widget","jquery.ui.mouse"],"jquery.ui"],["jquery.ui.tabs","1350311539",["jquery.ui.core","jquery.ui.widget"],"jquery.ui"],["jquery.effects.core","1350311539",["jquery"],"jquery.ui"],["jquery.effects.blind","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.bounce","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.clip","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.drop","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.explode","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.fade","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.fold","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.highlight","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.pulsate","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.scale",
"1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.shake","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.slide","1350311539",["jquery.effects.core"],"jquery.ui"],["jquery.effects.transfer","1350311539",["jquery.effects.core"],"jquery.ui"],["mediawiki","1350311539"],["mediawiki.api","1350311539",["mediawiki.util"]],["mediawiki.api.category","1350311539",["mediawiki.api","mediawiki.Title"]],["mediawiki.api.edit","1350311539",["mediawiki.api","mediawiki.Title"]],["mediawiki.api.parse","1350311539",["mediawiki.api"]],["mediawiki.api.titleblacklist","1350311539",["mediawiki.api","mediawiki.Title"]],["mediawiki.api.watch","1350311539",["mediawiki.api","user.tokens"]],["mediawiki.debug","1350311539",["jquery.footHovzer"]],["mediawiki.debug.init","1350311539",["mediawiki.debug"]],["mediawiki.feedback","1350311539",["mediawiki.api.edit","mediawiki.Title","mediawiki.jqueryMsg","jquery.ui.dialog"]],["mediawiki.hidpi","1350311539",["jquery.hidpi"]],[
"mediawiki.htmlform","1350311539"],["mediawiki.notification","1350311539",["mediawiki.page.startup"]],["mediawiki.notify","1350311539"],["mediawiki.searchSuggest","1351565405",["jquery.autoEllipsis","jquery.client","jquery.placeholder","jquery.suggestions"]],["mediawiki.Title","1350311539",["mediawiki.util"]],["mediawiki.Uri","1350311539"],["mediawiki.user","1350311539",["jquery.cookie","mediawiki.api","user.options","user.tokens"]],["mediawiki.util","1351565428",["jquery.client","jquery.cookie","jquery.mwExtension","mediawiki.notify"]],["mediawiki.action.edit","1350311539",["jquery.textSelection","jquery.byteLimit"]],["mediawiki.action.edit.preview","1350311539",["jquery.form","jquery.spinner"]],["mediawiki.action.history","1350311539",[],"mediawiki.action.history"],["mediawiki.action.history.diff","1350311539",[],"mediawiki.action.history"],["mediawiki.action.view.dblClickEdit","1350311539",["mediawiki.util","mediawiki.page.startup"]],["mediawiki.action.view.metadata","1351565405"],[
"mediawiki.action.view.rightClickEdit","1350311539"],["mediawiki.action.watch.ajax","1347062400",["mediawiki.page.watch.ajax"]],["mediawiki.language","1350311539",["mediawiki.language.data","mediawiki.cldr"]],["mediawiki.cldr","1350311539",["mediawiki.libs.pluralruleparser"]],["mediawiki.libs.pluralruleparser","1350311539"],["mediawiki.language.init","1350311539"],["mediawiki.jqueryMsg","1350311539",["mediawiki.util","mediawiki.language"]],["mediawiki.libs.jpegmeta","1350311539"],["mediawiki.page.ready","1350311539",["jquery.checkboxShiftClick","jquery.makeCollapsible","jquery.placeholder","jquery.mw-jump","mediawiki.util"]],["mediawiki.page.startup","1350311539",["jquery.client","mediawiki.util"]],["mediawiki.page.watch.ajax","1351565428",["mediawiki.page.startup","mediawiki.api.watch","mediawiki.util","mediawiki.notify","jquery.mwExtension"]],["mediawiki.special","1350311539"],["mediawiki.special.block","1350311539",["mediawiki.util"]],["mediawiki.special.changeemail","1350311539",[
"mediawiki.util"]],["mediawiki.special.changeslist","1350311539",["jquery.makeCollapsible"]],["mediawiki.special.movePage","1350311539",["jquery.byteLimit"]],["mediawiki.special.preferences","1350311539"],["mediawiki.special.recentchanges","1350311539",["mediawiki.special"]],["mediawiki.special.search","1351565552"],["mediawiki.special.undelete","1350311539"],["mediawiki.special.upload","1351573522",["mediawiki.libs.jpegmeta","mediawiki.util"]],["mediawiki.special.javaScriptTest","1350311539",["jquery.qunit"]],["mediawiki.tests.qunit.testrunner","1350311539",["jquery.qunit","jquery.qunit.completenessTest","mediawiki.page.startup","mediawiki.page.ready"]],["mediawiki.legacy.ajax","1350311539",["mediawiki.util","mediawiki.legacy.wikibits"]],["mediawiki.legacy.commonPrint","1350311539"],["mediawiki.legacy.config","1350311539",["mediawiki.legacy.wikibits"]],["mediawiki.legacy.IEFixes","1350311539",["mediawiki.legacy.wikibits"]],["mediawiki.legacy.protect","1350311539",[
"mediawiki.legacy.wikibits","jquery.byteLimit"]],["mediawiki.legacy.shared","1350311539"],["mediawiki.legacy.oldshared","1350311539"],["mediawiki.legacy.upload","1350311539",["mediawiki.legacy.wikibits","mediawiki.util"]],["mediawiki.legacy.wikibits","1350311539",["mediawiki.util"]],["mediawiki.legacy.wikiprintable","1350311539"],["ext.gadget.Checkty","1349240575",["jquery.ui.button","jquery.ui.dialog"]],["ext.gadget.SubsetMenu","1347062400",["mediawiki.api"]],["ext.gadget.OrphanCheck","1347062400"],["ext.gadget.Revert","1347062400"],["ext.gadget.autocomplete","1347062400",["jquery.ui.widget","jquery.ui.autocomplete","jquery.textSelection"]],["ext.gadget.TemplateParamWizard","1349813783",["jquery.ui.widget","jquery.tipsy","jquery.textSelection","jquery.ui.autocomplete","jquery.ui.dialog"]],["ext.gadget.TemplatesExternalLinks","1351381284",["jquery.ui.dialog","jquery.textSelection"]],["ext.gadget.Summarieslist","1347062400"],["ext.gadget.ReferencesWarn","1347062400"],[
"ext.gadget.CustomSideBarLinks","1347062400"],["ext.gadget.Dwim","1351288385",["jquery.suggestions","mediawiki.user"]],["ext.gadget.mySandbox","1347062400",["mediawiki.util"]],["ext.gadget.alignEditsectionToRight","1347062400"],["ext.gadget.FixedMenu","1347062400"],["ext.gadget.FixedSidebar","1347062400"],["ext.gadget.refStyle","1347062400"],["ext.gadget.CiteTooltip","1350413007",["jquery.tipsy","mediawiki.user"]],["ext.gadget.ExternalLinkIcon","1347062400"],["ext.gadget.updateMarker","1348209888"],["ext.gadget.watchlistMark","1347062400"],["ext.gadget.DeleteRequest","1347062400",["mediawiki.util"]],["ext.gadget.rollBackSummary","1347062400"],["ext.gadget.ajaxRC","1347062400"],["ext.gadget.patrolAlarm","1347062400"],["ext.gadget.disableFeedback","1347062400"],["ext.gadget.microblog","1347062400"],["ext.gadget.mychat","1347062400"],["ext.gadget.MoveToCommons","1351028833"],["mobile.device.default","1350311691"],["mobile.device.webkit","1351099404"],["mobile.device.android","1351099404"]
,["mobile.device.iphone","1351099404"],["mobile.device.iphone2","1351099404"],["mobile.device.palm_pre","1350311691"],["mobile.device.kindle","1350311691"],["mobile.device.blackberry","1351099404"],["mobile.device.simple","1350311691"],["mobile.device.psp","1350311691"],["mobile.device.wii","1350311691"],["mobile.device.operamini","1350311691"],["mobile.device.operamobile","1350311691"],["mobile.device.nokia","1350311691"],["ext.wikihiero","1350311861"],["ext.wikihiero.Special","1350311861",["jquery.spinner"]],["ext.cite","1350311592",["jquery.tooltip"]],["jquery.tooltip","1350311592"],["ext.specialcite","1350311592"],["ext.geshi.local","1347062400"],["ext.categoryTree","1351565722"],["ext.categoryTree.css","1350311573"],["ext.nuke","1350311699"],["ext.centralauth","1351583215"],["ext.centralauth.noflash","1350311583"],["ext.centralauth.globalusers","1350311583"],["ext.centralauth.globalgrouppermissions","1350311583"],["ext.centralNotice.interface","1350311586",["jquery.ui.datepicker"]
],["ext.centralNotice.bannerStats","1350311586"],["ext.centralNotice.bannerController","1351218499"],["ext.collection.jquery.jstorage","1350311605",["jquery.json"]],["ext.collection.suggest","1350311605",["ext.collection.bookcreator"]],["ext.collection","1350311605",["ext.collection.bookcreator","jquery.ui.sortable"]],["ext.collection.bookcreator","1350311605",["ext.collection.jquery.jstorage"]],["ext.collection.checkLoadFromLocalStorage","1350311605",["ext.collection.jquery.jstorage"]],["ext.abuseFilter","1350311550"],["ext.abuseFilter.edit","1351260433",["mediawiki.util","jquery.textSelection","jquery.spinner"]],["ext.abuseFilter.tools","1351261611",["mediawiki.util","jquery.spinner"]],["ext.abuseFilter.examine","1351261611",["mediawiki.util"]],["ext.vector.collapsibleNav","1351565552",["mediawiki.util","jquery.client","jquery.cookie","jquery.tabIndex"],"ext.vector"],["ext.vector.collapsibleTabs","1350311790",["jquery.collapsibleTabs","jquery.delayedBind"],"ext.vector"],[
"ext.vector.editWarning","1351565552",[],"ext.vector"],["ext.vector.expandableSearch","1350311790",["jquery.client","jquery.expandableField","jquery.delayedBind"],"ext.vector"],["ext.vector.footerCleanup","1351196615",["mediawiki.jqueryMsg","jquery.cookie"],"ext.vector"],["ext.vector.sectionEditLinks","1350311790",["jquery.cookie","jquery.clickTracking"],"ext.vector"],["contentCollector","1350311833",[],"ext.wikiEditor"],["jquery.wikiEditor","1351565399",["jquery.client","jquery.textSelection","jquery.delayedBind"],"ext.wikiEditor"],["jquery.wikiEditor.iframe","1350311833",["jquery.wikiEditor","contentCollector"],"ext.wikiEditor"],["jquery.wikiEditor.dialogs","1350311833",["jquery.wikiEditor","jquery.wikiEditor.toolbar","jquery.ui.dialog","jquery.ui.button","jquery.ui.draggable","jquery.ui.resizable","jquery.tabIndex"],"ext.wikiEditor"],["jquery.wikiEditor.dialogs.config","1351565399",["jquery.wikiEditor","jquery.wikiEditor.dialogs","jquery.wikiEditor.toolbar.i18n","jquery.suggestions"
,"mediawiki.Title"],"ext.wikiEditor"],["jquery.wikiEditor.highlight","1350311833",["jquery.wikiEditor","jquery.wikiEditor.iframe"],"ext.wikiEditor"],["jquery.wikiEditor.preview","1350311833",["jquery.wikiEditor"],"ext.wikiEditor"],["jquery.wikiEditor.previewDialog","1350311833",["jquery.wikiEditor","jquery.wikiEditor.dialogs"],"ext.wikiEditor"],["jquery.wikiEditor.publish","1350311833",["jquery.wikiEditor","jquery.wikiEditor.dialogs"],"ext.wikiEditor"],["jquery.wikiEditor.templateEditor","1350311833",["jquery.wikiEditor","jquery.wikiEditor.iframe","jquery.wikiEditor.dialogs"],"ext.wikiEditor"],["jquery.wikiEditor.templates","1350311833",["jquery.wikiEditor","jquery.wikiEditor.iframe"],"ext.wikiEditor"],["jquery.wikiEditor.toc","1350311833",["jquery.wikiEditor","jquery.wikiEditor.iframe","jquery.ui.draggable","jquery.ui.resizable","jquery.autoEllipsis","jquery.color"],"ext.wikiEditor"],["jquery.wikiEditor.toolbar","1350311833",["jquery.wikiEditor","jquery.wikiEditor.toolbar.i18n"],
"ext.wikiEditor"],["jquery.wikiEditor.toolbar.config","1350311833",["jquery.wikiEditor","jquery.wikiEditor.toolbar.i18n","jquery.wikiEditor.toolbar","jquery.cookie","jquery.async"],"ext.wikiEditor"],["jquery.wikiEditor.toolbar.i18n","1347062400",[],"ext.wikiEditor"],["ext.wikiEditor","1350311833",["jquery.wikiEditor"],"ext.wikiEditor"],["ext.wikiEditor.dialogs","1350311833",["ext.wikiEditor","ext.wikiEditor.toolbar","jquery.wikiEditor.dialogs","jquery.wikiEditor.dialogs.config"],"ext.wikiEditor"],["ext.wikiEditor.highlight","1350311833",["ext.wikiEditor","jquery.wikiEditor.highlight"],"ext.wikiEditor"],["ext.wikiEditor.preview","1350311833",["ext.wikiEditor","jquery.wikiEditor.preview"],"ext.wikiEditor"],["ext.wikiEditor.previewDialog","1350311833",["ext.wikiEditor","jquery.wikiEditor.previewDialog"],"ext.wikiEditor"],["ext.wikiEditor.publish","1350311833",["ext.wikiEditor","jquery.wikiEditor.publish"],"ext.wikiEditor"],["ext.wikiEditor.templateEditor","1350311833",["ext.wikiEditor",
"ext.wikiEditor.highlight","jquery.wikiEditor.templateEditor"],"ext.wikiEditor"],["ext.wikiEditor.templates","1350311833",["ext.wikiEditor","ext.wikiEditor.highlight","jquery.wikiEditor.templates"],"ext.wikiEditor"],["ext.wikiEditor.toc","1350311833",["ext.wikiEditor","ext.wikiEditor.highlight","jquery.wikiEditor.toc"],"ext.wikiEditor"],["ext.wikiEditor.tests.toolbar","1350311833",["ext.wikiEditor.toolbar"],"ext.wikiEditor"],["ext.wikiEditor.toolbar","1350311833",["ext.wikiEditor","jquery.wikiEditor.toolbar","jquery.wikiEditor.toolbar.config"],"ext.wikiEditor"],["ext.wikiEditor.toolbar.hideSig","1350311833",[],"ext.wikiEditor"],["ext.wikiLove.icon","1350311835"],["ext.wikiLove.defaultOptions","1351566772"],["ext.wikiLove.startup","1351566772",["ext.wikiLove.defaultOptions","jquery.ui.dialog","jquery.ui.button","jquery.localize","jquery.elastic"]],["ext.wikiLove.local","1351571152"],["ext.wikiLove.init","1350311835",["ext.wikiLove.startup"]],["jquery.elastic","1350311835"],[
"mobile.head","1351099404"],["mobile","1351190119"],["mobile.beta.jquery","1351187517"],["mobile.beta.jquery.eventlog","1351099404"],["mobile.production-only","1351190119"],["mobile.beta","1351190119"],["mobile.filePage","1351037747"],["mobile.references","1351187517"],["mobile.site","1347062400",[],"site"],["mobile.desktop","1351037747",["jquery.cookie"]],["ext.math.mathjax","1350311683",[],"ext.math.mathjax"],["ext.math.mathjax.enabler","1350311683"],["ext.babel","1350311571"],["ext.apiSandbox","1350311555",["mediawiki.util","jquery.ui.button"]],["ext.interwiki.specialpage","1350311669",["jquery.makeCollapsible"]],["ext.postEdit","1351565462",["jquery.cookie"]],["ext.checkUser","1350311590",["mediawiki.util"]]]);mw.config.set({"wgLoadScript":"//bits.wikimedia.org/he.wikipedia.org/load.php","debug":false,"skin":"vector","stylepath":"//bits.wikimedia.org/static-1.21wmf2/skins","wgUrlProtocols":
"http\\:\\/\\/|https\\:\\/\\/|ftp\\:\\/\\/|irc\\:\\/\\/|ircs\\:\\/\\/|gopher\\:\\/\\/|telnet\\:\\/\\/|nntp\\:\\/\\/|worldwind\\:\\/\\/|mailto\\:|news\\:|svn\\:\\/\\/|git\\:\\/\\/|mms\\:\\/\\/|\\/\\/","wgArticlePath":"/wiki/$1","wgScriptPath":"/w","wgScriptExtension":".php","wgScript":"/w/index.php","wgVariantArticlePath":false,"wgActionPaths":{},"wgServer":"//he.wikipedia.org","wgUserLanguage":"he","wgContentLanguage":"he","wgVersion":"1.21wmf2","wgEnableAPI":true,"wgEnableWriteAPI":true,"wgMainPageTitle":"עמוד ראשי","wgFormattedNamespaces":{"-2":"מדיה","-1":"מיוחד","0":"","1":"שיחה","2":"משתמש","3":"שיחת משתמש","4":"ויקיפדיה","5":"שיחת ויקיפדיה","6":"קובץ","7":"שיחת קובץ","8":"מדיה ויקי","9":"שיחת מדיה ויקי","10":"תבנית","11":"שיחת תבנית","12":"עזרה","13":"שיחת עזרה","14":"קטגוריה","15":"שיחת קטגוריה","100":"פורטל","101":"שיחת פורטל","108":
"ספר","109":"שיחת ספר"},"wgNamespaceIds":{"מדיה":-2,"מיוחד":-1,"":0,"שיחה":1,"משתמש":2,"שיחת_משתמש":3,"ויקיפדיה":4,"שיחת_ויקיפדיה":5,"קובץ":6,"שיחת_קובץ":7,"מדיה_ויקי":8,"שיחת_מדיה_ויקי":9,"תבנית":10,"שיחת_תבנית":11,"עזרה":12,"שיחת_עזרה":13,"קטגוריה":14,"שיחת_קטגוריה":15,"פורטל":100,"שיחת_פורטל":101,"ספר":108,"שיחת_ספר":109,"תמונה":6,"שיחת_תמונה":7,"משתמשת":2,"שיחת_משתמשת":3,"image":6,"image_talk":7,"media":-2,"special":-1,"talk":1,"user":2,"user_talk":3,"project":4,"project_talk":5,"file":6,"file_talk":7,"mediawiki":8,"mediawiki_talk":9,"template":10,"template_talk":11,"help":12,"help_talk":13,"category":14,"category_talk":15},"wgSiteName":"ויקיפדיה","wgFileExtensions":["png","gif","jpg","jpeg","xcf","pdf","mid","ogg","ogv","svg","djvu","tiff","tif","oga"],"wgDBname":"hewiki","wgFileCanRotate"
:true,"wgAvailableSkins":{"chick":"Chick","cologneblue":"CologneBlue","modern":"Modern","monobook":"MonoBook","myskin":"MySkin","nostalgia":"Nostalgia","simple":"Simple","standard":"Standard","vector":"Vector"},"wgExtensionAssetsPath":"//bits.wikimedia.org/static-1.21wmf2/extensions","wgCookiePrefix":"hewiki","wgResourceLoaderMaxQueryLength":-1,"wgCaseSensitiveNamespaces":[],"wgCollectionVersion":"1.6.1","wgCollapsibleNavBucketTest":false,"wgCollapsibleNavForceNewVersion":false,"wgWikiEditorToolbarClickTracking":false,"wgWikiEditorMagicWords":{"redirect":"#הפניה","img_right":"ימין","img_left":"שמאל","img_none":"ללא","img_center":"מרכז","img_thumbnail":"ממוזער","img_framed":"ממוסגר","img_frameless":"לא ממוסגר"},"wgNoticeFundraisingUrl":"https://donate.wikimedia.org/wiki/Special:LandingCheck","wgCentralPagePath":"//meta.wikimedia.org/w/index.php","wgNoticeBannerListLoader":"מיוחד:BannerListLoader","wgCentralBannerDispatcher":
"//meta.wikimedia.org/wiki/Special:BannerLoader","wgCookiePath":"/","wgMFStopRedirectCookieHost":".wikipedia.org"});};if(isCompatible()){document.write("\x3cscript src=\"//bits.wikimedia.org/he.wikipedia.org/load.php?debug=false\x26amp;lang=he\x26amp;modules=jquery%2Cmediawiki\x26amp;only=scripts\x26amp;skin=vector\x26amp;version=20121015T143219Z\"\x3e\x3c/script\x3e");}delete isCompatible;
/* cache key: hewiki:resourceloader:filter:minify-js:7:60f4df8e133ee65d1c188b18b6f0e1b4 */ | dimasalomatine/SDI_BATool | advinfo/מודל בלק ושולס – ויקיפדיה_files/load.php | PHP | gpl-2.0 | 21,282 |
{- hpodder component
Copyright (C) 2006 John Goerzen <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : FeedParser
Copyright : Copyright (C) 2006 John Goerzen
License : GNU GPL, version 2 or above
Maintainer : John Goerzen <[email protected]>
Stability : provisional
Portability: portable
Written by John Goerzen, jgoerzen\@complete.org
-}
module FeedParser where
import Types
import Text.XML.HaXml
import Text.XML.HaXml.Parse
import Text.XML.HaXml.Posn
import Utils
import Data.Maybe.Utils
import Data.Char
import Data.Either.Utils
import Data.List
import System.IO
data Item = Item {itemtitle :: String,
itemguid :: Maybe String,
enclosureurl :: String,
enclosuretype :: String,
enclosurelength :: String
}
deriving (Eq, Show, Read)
data Feed = Feed {channeltitle :: String,
items :: [Item]}
deriving (Eq, Show, Read)
item2ep pc item =
Episode {podcast = pc, epid = 0,
eptitle = sanitize_basic (itemtitle item),
epurl = sanitize_basic (enclosureurl item),
epguid = fmap sanitize_basic (itemguid item),
eptype = sanitize_basic (enclosuretype item), epstatus = Pending,
eplength = case reads . sanitize_basic . enclosurelength $ item of
[] -> 0
[(x, [])] -> x
_ -> 0,
epfirstattempt = Nothing,
eplastattempt = Nothing,
epfailedattempts = 0}
parse :: FilePath -> String -> IO (Either String Feed)
parse fp name =
do h <- openBinaryFile fp ReadMode
c <- hGetContents h
case xmlParse' name (unifrob c) of
Left x -> return (Left x)
Right y ->
do let doc = getContent y
let title = getTitle doc
let feeditems = getEnclosures doc
return $ Right $
(Feed {channeltitle = title, items = feeditems})
where getContent (Document _ _ e _) = CElem e noPos
unifrob ('\xfeff':x) = x -- Strip off unicode BOM
unifrob x = x
unesc = xmlUnEscape stdXmlEscaper
getTitle doc = forceEither $ strofm "title" (channel doc)
getEnclosures doc =
concat . map procitem $ item doc
where procitem i = map (procenclosure title guid) enclosure
where title = case strofm "title" [i] of
Left x -> "Untitled"
Right x -> x
guid = case strofm "guid" [i] of
Left _ -> Nothing
Right x -> Just x
enclosure = tag "enclosure" `o` children $ i
procenclosure title guid e =
Item {itemtitle = title,
itemguid = guid,
enclosureurl = head0 $ forceMaybe $ stratt "url" e,
enclosuretype = head0 $ case stratt "type" e of
Nothing -> ["application/octet-stream"]
Just x -> x,
enclosurelength = head $ case stratt "length" e of
Nothing -> ["0"]
Just [] -> ["0"]
Just x -> x
}
head0 [] = ""
head0 (x:xs) = x
item = tag "item" `o` children `o` channel
channel =
tag "channel" `o` children `o` tag "rss"
--------------------------------------------------
-- Utilities
--------------------------------------------------
attrofelem :: String -> Content Posn -> Maybe AttValue
attrofelem attrname (CElem inelem _) =
case unesc inelem of
Elem name al _ -> lookup attrname al
attrofelem _ _ =
error "attrofelem: called on something other than a CElem"
stratt :: String -> Content Posn -> Maybe [String]
stratt attrname content =
case attrofelem attrname content of
Just (AttValue x) -> Just (concat . map mapfunc $ x)
Nothing -> Nothing
where mapfunc (Left x) = [x]
mapfunc (Right _) = []
-- Finds the literal children of the named tag, and returns it/them
tagof :: String -> CFilter Posn
tagof x = keep /> tag x -- /> txt
-- Retruns the literal string that tagof would find
strof :: String -> Content Posn -> String
strof x y = forceEither $ strof_either x y
strof_either :: String -> Content Posn -> Either String String
strof_either x y =
case tagof x $ y of
[CElem elem pos] -> Right $ verbatim $ tag x /> txt
$ CElem (unesc elem) pos
z -> Left $ "strof: expecting CElem in " ++ x ++ ", got "
++ verbatim z ++ " at " ++ verbatim y
strofm x y =
if length errors /= 0
then Left errors
else Right (concat plainlist)
where mapped = map (strof_either x) $ y
(errors, plainlist) = conveithers mapped
isright (Left _) = False
isright (Right _) = True
conveithers :: [Either a b] -> ([a], [b])
conveithers inp = worker inp ([], [])
where worker [] y = y
worker (Left x:xs) (lefts, rights) =
worker xs (x:lefts, rights)
worker (Right x:xs) (lefts, rights) =
worker xs (lefts, x:rights)
| jgoerzen/hpodder | FeedParser.hs | Haskell | gpl-2.0 | 6,088 |
/*
* Copyright (c) 1997 Enterprise Systems Management Corp.
*
* This file is part of UName*It.
*
* UName*It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2, or (at your option) any later
* version.
*
* UName*It is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License
* along with UName*It; see the file COPYING. If not, write to the Free
* Software Foundation, 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
/* $Id: transaction.h,v 1.13 1997/05/28 23:19:52 viktor Exp $ */
#ifndef _TRANSACTION_H
#define _TRANSACTION_H
#include <dbi.h>
#include <tcl.h>
typedef enum {NORESTORE, RESTOREDATA, RESTORESCHEMA} RestoreMode;
/*
* item_class NON-NULL iff template is for a 'unameit_item'
*/
extern DB_OBJECT *Udb_Finish_Object(
DB_OBJECT *item_class,
DB_OTMPL *template,
int item_deleted
);
extern RestoreMode Udb_Restore_Mode(RestoreMode *new);
extern Tcl_CmdProc Udb_Syscall;
extern Tcl_CmdProc Udb_Transaction;
extern Tcl_CmdProc Udb_Version;
extern Tcl_CmdProc Udb_Rollback;
extern Tcl_CmdProc Udb_Commit;
extern void Udb_OpenLog(const char *logPrefix);
extern void Udb_CloseLog(void);
extern void Udb_Force_Rollback(Tcl_Interp *interp);
extern int Udb_Do_Rollback(Tcl_Interp *interp);
extern int Udb_Do_Commit(Tcl_Interp *interp, const char *logEntry);
#endif
| oxdeadbeef/unameit | libudb/transaction.h | C | gpl-2.0 | 1,683 |
<?php
/* Icinga Web 2 | (c) 2013-2015 Icinga Development Team | GPLv2+ */
namespace Icinga\Module\Monitoring\DataView;
class Contactgroup extends DataView
{
/**
* {@inheritdoc}
*/
public function isValidFilterTarget($column)
{
if ($column[0] === '_' && preg_match('/^_(?:host|service)_/', $column)) {
return true;
}
return parent::isValidFilterTarget($column);
}
/**
* {@inheritdoc}
*/
public function getColumns()
{
return array(
'contactgroup_name',
'contactgroup_alias',
'contact_object_id',
'contact_id',
'contact_name',
'contact_alias',
'contact_email',
'contact_pager',
'contact_has_host_notfications',
'contact_has_service_notfications',
'contact_can_submit_commands',
'contact_notify_service_recovery',
'contact_notify_service_warning',
'contact_notify_service_critical',
'contact_notify_service_unknown',
'contact_notify_service_flapping',
'contact_notify_service_downtime',
'contact_notify_host_recovery',
'contact_notify_host_down',
'contact_notify_host_unreachable',
'contact_notify_host_flapping',
'contact_notify_host_downtime',
'contact_notify_host_timeperiod',
'contact_notify_service_timeperiod'
);
}
/**
* {@inheritdoc}
*/
public function getSortRules()
{
return array(
'contactgroup_name' => array(
'order' => self::SORT_ASC
),
'contactgroup_alias' => array(
'order' => self::SORT_ASC
)
);
}
/**
* {@inheritdoc}
*/
public function getFilterColumns()
{
return array(
'contactgroup', 'contact',
'host', 'host_name', 'host_display_name', 'host_alias',
'hostgroup', 'hostgroup_alias', 'hostgroup_name',
'service', 'service_description', 'service_display_name',
'servicegroup', 'servicegroup_alias', 'servicegroup_name'
);
}
/**
* {@inheritdoc}
*/
public function getSearchColumns()
{
return array('contactgroup_alias');
}
}
| yodaaut/icingaweb2 | modules/monitoring/library/Monitoring/DataView/Contactgroup.php | PHP | gpl-2.0 | 2,396 |
import configparser
CONFIG_PATH = 'accounting.conf'
class MyConfigParser():
def __init__(self, config_path=CONFIG_PATH):
self.config = configparser.ConfigParser(allow_no_value=True)
self.config.read(config_path)
def config_section_map(self, section):
""" returns all configuration options in 'section' in a dict with
key: config_option and value: the read value in the file"""
dict1 = {}
options = self.config.options(section)
for option in options:
try:
dict1[option] = self.config.get(section, option)
if dict1[option] == -1:
DebugPrint("skip: %s" % option)
except:
dict1[option] = None
return dict1
# getint(section, option)
# getboolean(section, option)
| Stiliyan92/accounting-system | common/config_parser.py | Python | gpl-2.0 | 828 |
/////////////////////////////////////////////////////////////////////////////
// Name: imagpnm.h
// Purpose: wxImage PNM handler
// Author: Sylvain Bougnoux
// RCS-ID: $Id: imagpnm.h,v 1.1 1999/12/15 22:37:51 VS Exp $
// Copyright: (c) Sylvain Bougnoux
// Licence: wxWindows licence
// Modified by: Chris M. Christoudias
// read/write pnm image
/////////////////////////////////////////////////////////////////////////////
#ifndef _BG_IMAGPNM_H_
#define _BG_IMAGPNM_H_
#ifdef __GNUG__
#pragma interface "BgImagPNM.h"
#endif
#include <wx/image.h>
//-----------------------------------------------------------------------------
// bgPGMHandler
//-----------------------------------------------------------------------------
class bgPNMHandler : public wxImageHandler
{
DECLARE_DYNAMIC_CLASS(bgPNMHandler)
public:
inline bgPNMHandler()
{
m_name = "PNM file";
m_extension = "pnm";
m_type = wxBITMAP_TYPE_PNM;
m_mime = "image/pnm";
};
virtual bool LoadFile( wxImage *image, wxInputStream& stream, bool verbose=TRUE, int index=0 );
virtual bool SaveFile( wxImage *image, wxOutputStream& stream, bool verbose=TRUE );
virtual bool DoCanRead( wxInputStream& stream );
void Skip_Comment(wxInputStream &stream);
};
#endif
| gr4viton/vutbr_mpov_terrain | examples/Edison_Mean_Shift/GUI/BgImagPNM.h | C | gpl-2.0 | 1,299 |
# codingInPython
Github space for my experiments with programming, learning Python and git alongside.
Much of what I have in here are some code examples of exercies I have been trying to complete.
As of 4/6, most of the effort has been on data manipulation or rather list manipulation.
4/7 : Updated files :
| quixoticmonk/codingInPython | README.md | Markdown | gpl-2.0 | 310 |
<h2><?php print $node->title; ?></h2>
<h3><?php print content_format('field_subtitle', $field_subtitle[0]); ?></h3>
<? print l('Back', 'node/'.$node->field_case_project[0]['nid'], array('html'=>TRUE, 'attributes'=>array('class'=>'back-link'))); ?>
<? print content_format('field_case_intro_title', $field_case_intro_title[0]); ?>
<? print content_format('field_case_intro_body', $field_case_intro_body[0]); ?>
<? print content_format('field_case_video', $field_case_video[0]); ?>
<?
$distribution_body = strip_tags($field_case_distribution_body[0]['value']);
if (!empty($distribution_body))
print content_format('field_case_distribution_body', $field_case_distribution_body[0]);
?>
<? if (!empty($field_case_distribution_image[0]['filename'])) print content_format('field_case_distribution_image', $field_case_distribution_image[0], 'image_plain'); ?>
<?
$finance_body = strip_tags($field_case_finance_body[0]['value']);
if (!empty($finance_body))
print content_format('field_case_finance_body', $field_case_finance_body[0]);
?>
<? if (!empty($field_case_finance_image[0]['filename'])) print content_format('field_case_finance_image', $field_case_finance_image[0], 'image_plain'); ?>
<?
$multiplatform_body = strip_tags($field_case_multiplatform_body[0]['value']);
if (!empty($multiplatform_body))
print content_format('field_case_multiplatform_body', $field_case_multiplatform_body[0]);
?>
<? if (!empty($field_case_multiplatform_image[0]['filename'])) print content_format('field_case_multiplatform_image', $field_case_multiplatform_image[0], 'image_plain'); ?>
<?
$ad_body = strip_tags($field_case_ad_body[0]['value']);
if (!empty($ad_body))
print content_format('field_case_ad_body', $field_case_ad_body[0]);
?>
<? if (!empty($field_case_ad_image[0]['filename'])) print content_format('field_case_ad_image', $field_case_ad_image[0], 'image_plain'); ?>
<?
$international_body = strip_tags($field_case_international_body[0]['value']);
if (!empty($international_body))
print content_format('field_case_international_body', $field_case_international_body[0]);
?>
<? if (!empty($field_case_international_image[0]['filename'])) print content_format('field_case_international_image', $field_case_international_image[0], 'image_plain'); ?>
<?
$format_body = strip_tags($field_case_format_body[0]['value']);
if (!empty($format_body))
print content_format('field_case_format_body', $field_case_format_body[0]);
?>
<? if (!empty($field_case_format_image[0]['filename'])) print content_format('field_case_format_image', $field_case_format_image[0], 'image_plain'); ?>
<? print content_format('field_case_whitepaper', $field_case_whitepaper[0]); ?>
<div class="sponsor-logos">
<? print views_embed_view('sponsor_logos', 'block_1', $field_case_project[0]['nid']); ?>
</div> | iTTemple/html | 2012/themes/garland/node-case_study.tpl.php | PHP | gpl-2.0 | 2,796 |
package ms.aurora.browser.wrapper;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.tidy.Tidy;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* A parser / access layer for HTML pages
* @author Rick
*/
public final class HTML {
private static Logger logger = Logger.getLogger(HTML.class);
private Document dom;
public HTML(Document dom) {
this.dom = dom;
}
public Document getDOM() {
return dom;
}
public List<Node> searchXPath(String expression) {
List<Node> matchingElements = new ArrayList<Node>();
try {
XPathExpression expressionObj = getExpression(expression);
NodeList resultingNodeList = (NodeList) expressionObj.evaluate(dom,
XPathConstants.NODESET);
for (int index = 0; index < resultingNodeList.getLength(); index++) {
matchingElements.add(resultingNodeList.item(index));
}
} catch (XPathExpressionException e) {
logger.error("Incorrect XPath expression", e);
}
return matchingElements;
}
public List<Node> searchXPath(Node base, String expression) {
List<Node> matchingElements = new ArrayList<Node>();
try {
XPathExpression expressionObj = getExpression(expression);
NodeList resultingNodeList = (NodeList) expressionObj.evaluate(base,
XPathConstants.NODESET);
for (int index = 0; index < resultingNodeList.getLength(); index++) {
matchingElements.add(resultingNodeList.item(index));
}
} catch (XPathExpressionException e) {
logger.error("Incorrect XPath expression", e);
}
return matchingElements;
}
private XPathExpression getExpression(String expression) throws XPathExpressionException {
XPath xpath = XPathFactory.newInstance().newXPath();
return xpath.compile(expression);
}
public static HTML fromStream(InputStream stream) {
try {
/*
* UGLY ASS W3C API IS UGLY
*/
Tidy tidy = new Tidy();
tidy.setXHTML(true);
Document dom = tidy.parseDOM(stream, null);
dom.getDocumentElement().normalize();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Source xmlSource = new DOMSource(dom);
Result outputTarget = new StreamResult(outputStream);
TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
return new HTML(db.parse(is));
} catch (Exception e) {
logger.error("Failed to parse HTML properly", e);
}
return null;
}
}
| rvbiljouw/aurorabot | src/main/java/ms/aurora/browser/wrapper/HTML.java | Java | gpl-2.0 | 3,499 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_43) on Tue Dec 15 22:07:49 NZDT 2015 -->
<TITLE>
weka.core.stemmers
</TITLE>
<META NAME="date" CONTENT="2015-12-15">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="weka.core.stemmers";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="http://www.cs.waikato.ac.nz/ml/weka/" target="_blank"><FONT CLASS="NavBarFont1"><B>Weka's home</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../weka/core/pmml/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../weka/core/tokenizers/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?weka/core/stemmers/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<H2>
Package weka.core.stemmers
</H2>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Interface Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../weka/core/stemmers/Stemmer.html" title="interface in weka.core.stemmers">Stemmer</A></B></TD>
<TD>Interface for all stemming algorithms.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Class Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../weka/core/stemmers/IteratedLovinsStemmer.html" title="class in weka.core.stemmers">IteratedLovinsStemmer</A></B></TD>
<TD>An iterated version of the Lovins stemmer.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../weka/core/stemmers/LovinsStemmer.html" title="class in weka.core.stemmers">LovinsStemmer</A></B></TD>
<TD>A stemmer based on the Lovins stemmer, described here:<br/>
<br/>
Julie Beth Lovins (1968).</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../weka/core/stemmers/NullStemmer.html" title="class in weka.core.stemmers">NullStemmer</A></B></TD>
<TD>A dummy stemmer that performs no stemming at all.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../weka/core/stemmers/SnowballStemmer.html" title="class in weka.core.stemmers">SnowballStemmer</A></B></TD>
<TD>A wrapper class for the Snowball stemmers.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD WIDTH="15%"><B><A HREF="../../../weka/core/stemmers/Stemming.html" title="class in weka.core.stemmers">Stemming</A></B></TD>
<TD>A helper class for using the stemmers.</TD>
</TR>
</TABLE>
<P>
<DL>
</DL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="http://www.cs.waikato.ac.nz/ml/weka/" target="_blank"><FONT CLASS="NavBarFont1"><B>Weka's home</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../weka/core/pmml/package-summary.html"><B>PREV PACKAGE</B></A>
<A HREF="../../../weka/core/tokenizers/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?weka/core/stemmers/package-summary.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| powdream/manage_movie_files | external-libs/weka-stable-3.6/doc/weka/core/stemmers/package-summary.html | HTML | gpl-2.0 | 7,701 |
<html>
<head>
<title>Transverse Ray Aberration Diagram</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="generator" content="HelpNDoc Personal Edition 4.3.1.364">
<link type="text/css" rel="stylesheet" media="all" href="css/reset.css" />
<link type="text/css" rel="stylesheet" media="all" href="css/base.css" />
<link type="text/css" rel="stylesheet" media="all" href="css/hnd.css" />
<!--[if lte IE 8]>
<link type="text/css" rel="stylesheet" media="all" href="css/ielte8.css" />
<![endif]-->
<style type="text/css">
#topic_header
{
background-color: #EFEFEF;
}
</style>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/hnd.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
if (top.frames.length == 0)
{
var sTopicUrl = top.location.href.substring(top.location.href.lastIndexOf("/") + 1, top.location.href.length);
top.location.href = "Programming and Algorithms Reference MATLAB Based Optical Analysis Toolbox V 3.0.html?" + sTopicUrl;
}
else if (top && top.FrameTOC && top.FrameTOC.SelectTocItem)
{
top.FrameTOC.SelectTocItem("TransverseRayAberrationDiagram");
}
});
</script>
</head>
<body>
<div id="topic_header">
<div id="topic_header_content">
<h1 id="topic_header_text">Transverse Ray Aberration Diagram</h1>
<div id="topic_breadcrumb">
<a href="ExamplesofExtendingtheToolbox.html">Examples of Extending the Toolbox</a> ›› <a href="Method1Aspartofthetoolbox.html">Method 1: As part of the toolbox</a> ›› </div>
</div>
<div id="topic_header_nav">
<a href="Method1Aspartofthetoolbox.html"><img src="img/arrow_up.png" alt="Parent"/></a>
<a href="Method1Aspartofthetoolbox.html"><img src="img/arrow_left.png" alt="Previous"/></a>
<a href="Procedures.html"><img src="img/arrow_right.png" alt="Next"/></a>
</div>
<div class="clear"></div>
</div>
<div id="topic_content">
<p></p>
<h1 class="rvps11"><span class="rvts0"><span class="rvts59">Toolbox Extension Example: Transverse Ray Aberration Diagram</span></span></h1>
<p class="rvps10"><span class="rvts37">Purpose:</span></p>
<p class="rvps10"><span class="rvts38">To add an analysis window to the toolbox which shows ray aberrations as a function of pupil coordinate. </span></p>
<p class="rvps10"><span class="rvts38"><br/></span></p>
<p></p>
<p class="rvps6"><span class="rvts20">Created with the Personal Edition of HelpNDoc: </span><a class="rvts21" href="http://www.helpndoc.com/help-authoring-tool">Create HTML Help, DOC, PDF and print manuals from 1 single source</a></p>
</div>
<div id="topic_footer">
<div id="topic_footer_content">
Copyright © <2014> by <Norman G. Worku ([email protected]), Optical System Design Research Group, FSU, Jena>. All Rights Reserved.</div>
</div>
</body>
</html>
| IAPJena/ProjectOne | 7.Documentation_Package/Programming_and_Algorithms_Reference/Build html documentation/TransverseRayAberrationDiagram.html | HTML | gpl-2.0 | 2,989 |
/*
* Read-Copy Update mechanism for mutual exclusion
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Copyright IBM Corporation, 2001
*
* Author: Dipankar Sarma <[email protected]>
*
* Based on the original work by Paul McKenney <[email protected]>
* and inputs from Rusty Russell, Andrea Arcangeli and Andi Kleen.
* Papers:
* http://www.rdrop.com/users/paulmck/paper/rclockpdcsproof.pdf
* http://lse.sourceforge.net/locking/rclock_OLS.2001.05.01c.sc.pdf (OLS2001)
*
* For detailed explanation of Read-Copy Update mechanism see -
* http://lse.sourceforge.net/locking/rcupdate.html
*
*/
#ifndef __LINUX_RCUPDATE_H
#define __LINUX_RCUPDATE_H
#include <linux/cache.h>
#include <linux/spinlock.h>
#include <linux/threads.h>
#include <linux/cpumask.h>
#include <linux/seqlock.h>
#include <linux/lockdep.h>
#include <linux/completion.h>
/**
* struct rcu_head - callback structure for use with RCU
* @next: next update requests in a list
* @func: actual update function to call after the grace period.
*/
struct rcu_head {
struct rcu_head *next;
void (*func)(struct rcu_head *head);
};
/* Exported common interfaces */
#ifdef CONFIG_TREE_PREEMPT_RCU
extern void synchronize_rcu(void);
#else /* #ifdef CONFIG_TREE_PREEMPT_RCU */
#define synchronize_rcu synchronize_sched
#endif /* #else #ifdef CONFIG_TREE_PREEMPT_RCU */
extern void synchronize_rcu_bh(void);
extern void synchronize_sched(void);
extern void rcu_barrier(void);
extern void rcu_barrier_bh(void);
extern void rcu_barrier_sched(void);
extern void synchronize_sched_expedited(void);
extern int sched_expedited_torture_stats(char *page);
/* Internal to kernel */
extern void rcu_init(void);
extern void rcu_scheduler_starting(void);
#ifndef CONFIG_TINY_RCU
extern int rcu_needs_cpu(int cpu);
#else
static inline int rcu_needs_cpu(int cpu) { return 0; }
#endif
extern int rcu_scheduler_active;
#include "rcutiny.h" /* Figure out why later. */
// #if defined(CONFIG_TREE_RCU) || defined(CONFIG_TREE_PREEMPT_RCU)
// #include <linux/rcutree.h>
#ifdef CONFIG_TINY_RCU
#include <linux/rcutiny.h>
#else
#error "Unknown RCU implementation specified to kernel configuration"
#endif
#define RCU_HEAD_INIT { .next = NULL, .func = NULL }
#define RCU_HEAD(head) struct rcu_head head = RCU_HEAD_INIT
#define INIT_RCU_HEAD(ptr) do { \
(ptr)->next = NULL; (ptr)->func = NULL; \
} while (0)
#ifdef CONFIG_DEBUG_LOCK_ALLOC
extern struct lockdep_map rcu_lock_map;
# define rcu_read_acquire() \
lock_acquire(&rcu_lock_map, 0, 0, 2, 1, NULL, _THIS_IP_)
# define rcu_read_release() lock_release(&rcu_lock_map, 1, _THIS_IP_)
#else
# define rcu_read_acquire() do { } while (0)
# define rcu_read_release() do { } while (0)
#endif
/**
* rcu_read_lock - mark the beginning of an RCU read-side critical section.
*
* When synchronize_rcu() is invoked on one CPU while other CPUs
* are within RCU read-side critical sections, then the
* synchronize_rcu() is guaranteed to block until after all the other
* CPUs exit their critical sections. Similarly, if call_rcu() is invoked
* on one CPU while other CPUs are within RCU read-side critical
* sections, invocation of the corresponding RCU callback is deferred
* until after the all the other CPUs exit their critical sections.
*
* Note, however, that RCU callbacks are permitted to run concurrently
* with RCU read-side critical sections. One way that this can happen
* is via the following sequence of events: (1) CPU 0 enters an RCU
* read-side critical section, (2) CPU 1 invokes call_rcu() to register
* an RCU callback, (3) CPU 0 exits the RCU read-side critical section,
* (4) CPU 2 enters a RCU read-side critical section, (5) the RCU
* callback is invoked. This is legal, because the RCU read-side critical
* section that was running concurrently with the call_rcu() (and which
* therefore might be referencing something that the corresponding RCU
* callback would free up) has completed before the corresponding
* RCU callback is invoked.
*
* RCU read-side critical sections may be nested. Any deferred actions
* will be deferred until the outermost RCU read-side critical section
* completes.
*
* It is illegal to block while in an RCU read-side critical section.
*/
static inline void rcu_read_lock(void)
{
__rcu_read_lock();
__acquire(RCU);
rcu_read_acquire();
}
/*
* So where is rcu_write_lock()? It does not exist, as there is no
* way for writers to lock out RCU readers. This is a feature, not
* a bug -- this property is what provides RCU's performance benefits.
* Of course, writers must coordinate with each other. The normal
* spinlock primitives work well for this, but any other technique may be
* used as well. RCU does not care how the writers keep out of each
* others' way, as long as they do so.
*/
/**
* rcu_read_unlock - marks the end of an RCU read-side critical section.
*
* See rcu_read_lock() for more information.
*/
static inline void rcu_read_unlock(void)
{
rcu_read_release();
__release(RCU);
__rcu_read_unlock();
}
/**
* rcu_read_lock_bh - mark the beginning of a softirq-only RCU critical section
*
* This is equivalent of rcu_read_lock(), but to be used when updates
* are being done using call_rcu_bh(). Since call_rcu_bh() callbacks
* consider completion of a softirq handler to be a quiescent state,
* a process in RCU read-side critical section must be protected by
* disabling softirqs. Read-side critical sections in interrupt context
* can use just rcu_read_lock().
*
*/
static inline void rcu_read_lock_bh(void)
{
__rcu_read_lock_bh();
__acquire(RCU_BH);
rcu_read_acquire();
}
/*
* rcu_read_unlock_bh - marks the end of a softirq-only RCU critical section
*
* See rcu_read_lock_bh() for more information.
*/
static inline void rcu_read_unlock_bh(void)
{
rcu_read_release();
__release(RCU_BH);
__rcu_read_unlock_bh();
}
/**
* rcu_read_lock_sched - mark the beginning of a RCU-classic critical section
*
* Should be used with either
* - synchronize_sched()
* or
* - call_rcu_sched() and rcu_barrier_sched()
* on the write-side to insure proper synchronization.
*/
static inline void rcu_read_lock_sched(void)
{
preempt_disable();
__acquire(RCU_SCHED);
rcu_read_acquire();
}
/* Used by lockdep and tracing: cannot be traced, cannot call lockdep. */
static inline notrace void rcu_read_lock_sched_notrace(void)
{
preempt_disable_notrace();
__acquire(RCU_SCHED);
}
/*
* rcu_read_unlock_sched - marks the end of a RCU-classic critical section
*
* See rcu_read_lock_sched for more information.
*/
static inline void rcu_read_unlock_sched(void)
{
rcu_read_release();
__release(RCU_SCHED);
preempt_enable();
}
/* Used by lockdep and tracing: cannot be traced, cannot call lockdep. */
static inline notrace void rcu_read_unlock_sched_notrace(void)
{
__release(RCU_SCHED);
preempt_enable_notrace();
}
/**
* rcu_dereference - fetch an RCU-protected pointer in an
* RCU read-side critical section. This pointer may later
* be safely dereferenced.
*
* Inserts memory barriers on architectures that require them
* (currently only the Alpha), and, more importantly, documents
* exactly which pointers are protected by RCU.
*/
#define rcu_dereference(p) ({ \
typeof(p) _________p1 = ACCESS_ONCE(p); \
smp_read_barrier_depends(); \
(_________p1); \
})
/**
* rcu_assign_pointer - assign (publicize) a pointer to a newly
* initialized structure that will be dereferenced by RCU read-side
* critical sections. Returns the value assigned.
*
* Inserts memory barriers on architectures that require them
* (pretty much all of them other than x86), and also prevents
* the compiler from reordering the code that initializes the
* structure after the pointer assignment. More importantly, this
* call documents which pointers will be dereferenced by RCU read-side
* code.
*/
#define rcu_assign_pointer(p, v) \
({ \
if (!__builtin_constant_p(v) || \
((v) != NULL)) \
smp_wmb(); \
(p) = (v); \
})
/* Infrastructure to implement the synchronize_() primitives. */
struct rcu_synchronize {
struct rcu_head head;
struct completion completion;
};
extern void wakeme_after_rcu(struct rcu_head *head);
/**
* call_rcu - Queue an RCU callback for invocation after a grace period.
* @head: structure to be used for queueing the RCU updates.
* @func: actual update function to be invoked after the grace period
*
* The update function will be invoked some time after a full grace
* period elapses, in other words after all currently executing RCU
* read-side critical sections have completed. RCU read-side critical
* sections are delimited by rcu_read_lock() and rcu_read_unlock(),
* and may be nested.
*/
extern void call_rcu(struct rcu_head *head,
void (*func)(struct rcu_head *head));
/**
* call_rcu_bh - Queue an RCU for invocation after a quicker grace period.
* @head: structure to be used for queueing the RCU updates.
* @func: actual update function to be invoked after the grace period
*
* The update function will be invoked some time after a full grace
* period elapses, in other words after all currently executing RCU
* read-side critical sections have completed. call_rcu_bh() assumes
* that the read-side critical sections end on completion of a softirq
* handler. This means that read-side critical sections in process
* context must not be interrupted by softirqs. This interface is to be
* used when most of the read-side critical sections are in softirq context.
* RCU read-side critical sections are delimited by :
* - rcu_read_lock() and rcu_read_unlock(), if in interrupt context.
* OR
* - rcu_read_lock_bh() and rcu_read_unlock_bh(), if in process context.
* These may be nested.
*/
extern void call_rcu_bh(struct rcu_head *head,
void (*func)(struct rcu_head *head));
#endif /* __LINUX_RCUPDATE_H */
| k0nane/Twilight_Zone_kernel | include/linux/rcupdate.h | C | gpl-2.0 | 10,542 |
<?php
/**
* Plugin Name: Custom Register Form Plugin
* Plugin URI: http://tamanhquyen.com/register-form-for-wordpress.html
* Description: Create Custom Register Form Frontend Page
* Version: 1.0
* Author: TA MANH QUYEN
* Author URI: http://tamanhquyen.com
*/
global $wp_version;
if(version_compare($wp_version,'3.6.1','<'))
{
exit('This is plugin requice Wordpress Version 3.6 on highter. Please update now!');
}
register_activation_hook(__FILE__,'mq_register_setting');
register_deactivation_hook(__FILE__,'mq_delete_setting');
function enque_register()
{
wp_register_script('mq_register_ajax',plugins_url('inc/js/init.js',__FILE__),array('jquery'),true);
wp_localize_script('mq_register_ajax','mq_register_ajax',array('mq_ajax_url' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script('mq_register_ajax');
}
add_action('wp_enqueue_scripts','enque_register');
function mq_registerform_menu()
{
add_menu_page('Register Form Setting','Register Form','update_plugins','register-form-setting','mq_registerform_set','',1);
}
add_action('admin_menu','mq_registerform_menu');
function mq_register_setting()
{
add_option('mq_register_form_title','','255','yes');
add_option('mq_register_form_setting','','255','yes');
add_option('mq_register_form_css','','255','yes');
add_option('mq_register_form_intro','','255','yes');
add_option('mq_register_facelink','','255','yes');
}
function mq_delete_setting()
{
delete_option('mq_register_form_setting');
delete_option('mq_register_form_title');
delete_option('mq_register_form_css');
delete_option('mq_register_facelink');
delete_option('mq_register_form_intro');
remove_shortcode('mq_register');
}
include_once('inc/mq_shortcode.php');
include_once('inc/mq_ajax.php');
include_once('inc/form_setting.php');
include_once('inc/form_create.php');
include_once('inc/script/register_action.php'); | Nguyenkain/hanghieusales | wp-content/plugins/tamanhquyen_register/plugin_funtion.php | PHP | gpl-2.0 | 1,849 |
<?php
class grid_assignments_progress{
private $db = false;
private $user;
private $edit_color = '#FFFFFF';
public function __construct(){
$this->db = Connection::getDB();
$this->user = new administrator();
if($this->user->role=='pupil' || $this->user->role=='parent'){
$this->edit_color = '#AAAAAA';
}
$this->db->query("START TRANSACTION");
error_reporting(E_ALL ^ E_NOTICE);
switch ($_POST['action']) {
case 'editresult':
$this->editResult($_POST['id'],$_POST['value'],$_POST['pass']);
break;
case 'editgrade':
$this->editGrade($_POST['id'],$_POST['value'],$_POST['pass']);
break;
case 'editassessment':
$this->editAssessment($_POST['id'],$_POST['assessment']);
break;
case 'deactive':
$this->deactivePerformance($_POST['id']);
break;
case 'reactive':
$this->reactivePerformance($_POST['id']);
break;
case 'editstatus':
$this->editStutus($_POST['assid'],$_POST['pid'],$_POST['value']);
break;
case 'makeassubmitted':
$this->makeAsSubmitted($_POST['assid'],$_POST['pid']);
break;
case 'makeasnotsubmitted':
$this->makeAsNotSubmitted($_POST['assid'],$_POST['pid']);
break;
case 'activate':
$this->activate($_POST['assid'],$_POST['pid'],$_POST['type']);
break;
case 'remove':
$this->remove($_POST['assid'],$_POST['pid'],$_POST['type']);
break;
case 'deactivate':
$this->deactivate($_POST['assid'],$_POST['pid'],$_POST['type']);
break;
default:
$this->getAssignmentsGrid();
break;
}
$this->db->query("COMMIT");
}
private function editStutus($id,$pid,$val){
$result = $this->db->query("UPDATE pupli_submission_slot SET status='$val' WHERE assignment_id=$id AND pupil_id=$pid");
}
private function makeAsSubmitted($id,$pid){
$result = $this->db->query("UPDATE pupli_submission_slot SET status='1', submission_date = NOW() WHERE assignment_id=$id AND pupil_id=$pid");
}
private function makeAsNotSubmitted($id,$pid){
$ns = dlang("grids_not_subm_text","Not subm.");
$result = $this->db->query("UPDATE pupli_submission_slot SET status='$ns' WHERE assignment_id=$id AND pupil_id=$pid");
}
private function editResult($id,$val,$pass){
@session_start();
$_SESSION['submissions_update']=$this->user->id;
session_write_close();
$this->db->query("UPDATE pupil_submission_result SET result='$val', pass='$pass' WHERE pupil_submission_result_id=$id");
if($val=='A' || $val=='B'|| $val=='C'||$val=='D'||$val=='E'||$val=='F'||$val=='Fx'||$val==dlang("passvalue","Pass")||$val==dlang("npassvalue","NPass")){
$result = $this->db->query("UPDATE pupil_submission_result SET assessment='$val' WHERE pupil_submission_result_id=$id");
}
$this->db->query("UPDATE pupli_submission_slot,pupil_submission_result SET pupli_submission_slot.status='1' WHERE pupli_submission_slot.submission_slot_id = pupil_submission_result.submission_slot_id
AND pupil_submission_result.pupil_submission_result_id = $id");
echo 1;
}
private function editGrade($id,$val,$pass){
$result = $this->db->query("UPDATE pupil_submission_result SET assessment='$assess', pass=$val WHERE pupil_submission_result_id=$id");
}
private function editAssessment($id, $assess){
$result = $this->db->query("UPDATE pupil_performance_assessment SET assessment='$assess' WHERE pupil_performance_assessment_id=$id");
}
private function remove($id,$pid,$type){
if($type=="performance"){
$result = $this->db->query("DELETE FROM pupil_performance_assessment WHERE pupil_id=$pid AND performance_id=$id");
}else{
$result = $this->db->query("DELETE FROM pupli_submission_slot WHERE pupil_id=$pid AND assignment_id=$id");
}
}
private function activate($id,$pid,$type){
if($type=="performance"){
$this->db->query("UPDATE pupil_performance_assessment SET active=1, activation_date=NOW() WHERE pupil_id=$pid AND performance_id=$id");
}else{
$this->db->query("UPDATE pupli_submission_slot SET active=1, activation_date=NOW() WHERE pupil_id=$pid AND assignment_id=$id");
}
}
private function deactivate($id,$pid,$type){
if($type=="performance"){
$this->db->query("UPDATE pupil_performance_assessment SET active=0 WHERE pupil_id=$pid AND performance_id=$id");
}else{
$this->db->query("UPDATE pupli_submission_slot SET active=0 WHERE pupil_id=$pid AND assignment_id=$id");
}
}
private function getPerformanceArray($result,$rows){
//$rows = array();
while($row = mysql_fetch_assoc($result)){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][12] = $row['performance_id'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][1] = $row['perf_title'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][7] = $row['sid'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][8] = $row['s_id'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][11] = $row['active']?"1":"0.5";
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][13] = $row['active'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][10] = $row['active']?"#FFFFFF":"#F5F5F5";
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][0] = $row['pid'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][3]= $row['ass'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][13] = $row['active'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][10] = $row['active']?"#FFFFFF":"#F5F5F5";
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][11] = $row['active']?"1":"0.5";
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][4][] = $row['obj_title'];
if($row['ass'] == "" || $row['ass'] == "na"){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][5] = $this->edit_color;
}elseif($row['ass'] == "F" || $row['ass'] == "Fx"){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][5] = "#ff8888";
}else{
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][5] = "#88ff88";
}
}
//print_r($rows);
return $rows;
}
private function getAssignmentsGrid(){
header("Content-type:text/xml");
print('<?xml version="1.0" encoding="UTF-8"?>');
$id = $_GET['id'];
$and = "";
if(isset($_GET['stg']) && $_GET['stg']!=""){
$and = "AND studygroups.studygroup_id = ".$_GET['stg'];
}
$result = $this->db->query("
SELECT course_rooms_assignments.number as numb, course_rooms_assignments.title_en as title_assignment,
course_rooms_assignments.assignment_id as aid,
DATEDIFF(course_rooms_assignments.deadline_date, CURDATE()) as dl_date,
DATEDIFF(course_rooms_assignments.deadline_date, pupli_submission_slot.submission_date) as submission_date,
course_rooms_assignments.deadline_date as deadline_date2,
pupli_submission_slot.submission_date as submission_date2,
course_objectives.title_en as title_course_obj,
course_rooms_assignments.deadline as deadline,
course_rooms_assignments.deadline_passed as dp,
pupli_submission_slot.content_en as pcont,
pupli_submission_slot.status as status,
pupli_submission_slot.active as active,
resultsets.result_max as max_rs,
resultsets.result_pass as pass_rs,
resultsets.studygroup_ids as studygroup_ids,
result_units.result_unit_en as unit_rs,
pupil_submission_result.result as subm_result,
pupil_submission_result.assessment as assessment,
pupil_submission_result.pupil_submission_result_id as psr,
studygroups.title_en as sid,
studygroups.studygroup_id as s_id,
result_units.result_unit_id as result_unit_id,
academic_years.title_en as acyear,
subjects.title_en as subject,
academic_years.academic_year_id as acyear_id,
subjects.subject_id as subject_id,
resultsets.castom_name as castom_name
FROM course_rooms,pupli_submission_slot, course_rooms_assignments, resultsets,
studygroups, course_objectives, result_units, pupil_submission_result, resultset_to_course_objectives, academic_years, subjects
WHERE pupli_submission_slot.assignment_id = course_rooms_assignments.assignment_id
AND course_rooms_assignments.course_room_id = course_rooms.course_room_id
AND course_rooms.course_room_id = studygroups.course_room_id
AND resultsets.assignment_id = pupli_submission_slot.assignment_id
AND resultset_to_course_objectives.resultset_id = resultsets.resultset_id
AND course_objectives.objective_id = resultset_to_course_objectives.objective_id
AND result_units.result_unit_id = resultsets.result_unit_id
AND pupil_submission_result.result_set_id = resultsets.resultset_id
AND pupil_submission_result.submission_slot_id = pupli_submission_slot.submission_slot_id
AND pupli_submission_slot.pupil_id=$id
AND studygroups.subject_id=subjects.subject_id
AND subjects.academic_year_id = academic_years.academic_year_id
AND resultset_to_course_objectives.type = 'assignment'
{$and}
");
$result_perf = $this->db->query("
SELECT performance.title_en as perf_title, pupil_performance_assessment.pupil_performance_assessment_id as pid,
course_objectives.title_en as obj_title,pupil_performance_assessment.assessment as ass,
pupil_performance_assessment.passed as passed,
pupil_performance_assessment.active as active,
studygroups.title_en as sid, studygroups.studygroup_id as s_id,
pupil_performance_assessment.performance_id as performance_id,
resultsets.resultset_id as resultset_id,
academic_years.title_en as acyear,
subjects.title_en as subject,
academic_years.academic_year_id as acyear_id,
subjects.subject_id as subject_id
FROM course_rooms, pupil_performance_assessment, performance, studygroups,resultsets,course_objectives,resultset_to_course_objectives, academic_years, subjects
WHERE pupil_performance_assessment.performance_id = performance.performance_id
AND performance.course_room_id = course_rooms.course_room_id
AND course_rooms.course_room_id = studygroups.course_room_id
AND resultsets.resultset_id = pupil_performance_assessment.resultset_id
AND resultset_to_course_objectives.resultset_id = resultsets.resultset_id
AND course_objectives.objective_id = resultset_to_course_objectives.objective_id
AND pupil_performance_assessment.pupil_id = $id
AND studygroups.subject_id=subjects.subject_id
AND subjects.academic_year_id = academic_years.academic_year_id
AND resultset_to_course_objectives.type = 'performance'
");
echo '<rows>';
$assarr = $this->getAssignmentsArray($result);
$perfarr = $this->getPerformanceArray($result_perf,$assarr);
//$perform = $this->outPerformanceArray($this->getPerformanceArray($result_perf));
$this->outAssignmentsArray($perfarr);
echo '</rows>';
}
private function outPerformanceArray($value2){
$perf_xml = '
<row id="performance_'.$value2[12].'">
<cell bgColor="'.$value2[10].'" style="opacity: '.$value2[11].';" sid="performance_'.$value2[12].'" image="assessment.png">'.$value2[1].'</cell>
<cell bgColor="'.$value2[10].'" style="opacity: '.$value2[11].';"/><cell style="opacity: '.$value2[11].';" bgColor="'.$value2[10].'"/>
<cell style="opacity: '.$value2[11].';" bgColor="'.$value2[10].'"/><cell style="opacity: '.$value2[11].';" bgColor="'.$value2[10].'"/>
<cell style="opacity: '.$value2[11].';" bgColor="'.$value2[10].'"/><cell bgColor="'.$value2[10].'"/>';
foreach ($value2[14] as $value3) {
$perf_xml.= '
<row id="p_'.$value3[0].'" style="opacity: '.$value3[11].';">
<cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$value3[11].';" image="objective.png" >'.$value2[7].': '.implode(', ',$value3[4]).'</cell>
<cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';"></cell>
<cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';"></cell>
<cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';"></cell>
<cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';"></cell>
<cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';">'.$value3[6].'</cell>
<cell style="opacity: '.$value3[11].';" xmlcontent="1" bgColor="'.$value3[5].'">'.$value3[3].'<option value="A">'."A".'</option>
<option value="B">'."B".'</option>
<option value="C">'."C".'</option>
<option value="D">'."D".'</option>
<option value="E">'."E".'</option>
<option value="F">'."F".'</option>
<option value="Fx">'."Fx".'</option>
<option value="">'."".'</option>
</cell>
</row>
';
}
$perf_xml.= '<userdata name="activate">'.$value2[13].'</userdata></row>';
return $perf_xml;
}
private function getAssignmentsArray($result){
$rows = array();
$graeds = array('A','B','C','D','E','F');
while($row = mysql_fetch_assoc($result)){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']][0] = $row['sid'];
$rows[$row['acyear_id']][0] = $row['acyear'];
$rows[$row['acyear_id']][$row['subject_id']][0] = $row['subject'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][0] = $row['aid'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][2] = $row['title_assignment'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][3] = $row['dp'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][4] = $row['pcont'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][5] = $row['dl_date'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][20] = $row['deadline_date2'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][21] = $row['submission_date2'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][16] = $row['deadline'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][6] = $row['status'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][7] = $row['title_course'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][9] = $row['sid'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][10] = $row['active']?"#FFFFFF":"#F5F5F5";
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][11] = $row['active']?"1":"0.5";
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][12] = $row['active'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][15] = $row['submission_date'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][0] = $row['psr'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][1] = $row['castom_name'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][2] = $row['max_rs'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][3] = $row['pass_rs'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][4] = $row['subm_result'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][6] = $row['dl_date'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][7] = $row['sid'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][8] = $row['s_id'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][9] = $row['assessment'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][12] = $row['result_unit_id'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][14] = $row['studygroup_ids'];
if($row['assessment']=="p"){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][9] = dlang("passvalue","Pass");
}
if($row['assessment']=="np"){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][9] = dlang("npassvalue","NPass");
}
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][10] = $row['title_course'];
$pass = $row['pass_rs'];
$res = $row['subm_result'];
switch ($row['result_unit_id']) {
case '1':
if((int)$pass <= (int)$res){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88";
}else{
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888";
}
break;
case '2':
if((int)$pass <= (int)$res){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88";
}else{
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888";
}
break;
case '3':
if(array_search($pass,$graeds)>=array_search($res,$graeds)){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88";
}else{
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888";
}
break;
case '4':
if(strtolower($res)==dlang("passvalue","Pass")){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88";
}else{
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888";
}
break;
}
if($res==""){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = $this->edit_color;
}
if($row['assessment']!=""){
if($row['assessment']=='F' || $row['assessment']=="Fx" || $row['assessment']==dlang("npassvalue","NPass")){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888";
}else{
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88";
}
}
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][5][] = $row['title_course_obj'];
}
// print_r($rows);
return $rows;
}
private function outStgsArray($stg){
foreach ($stg as $key => $group){
if($key=="0")
continue;
echo '
<row id="stg_'.$key.'">
<cell style="color:rgb(73, 74, 75);" sid="stg_'.$key.'" image="studygroup.png">'.$group[0].'</cell>';
foreach ($group as $key2 => $assignment){
if($key2=="0"){
continue;
}
$tkey2 = explode('_',$key2);
if($tkey2[0] == 'performancep'){
echo $this->outPerformanceArray($assignment);
continue;
}
echo '<row style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';" bgColor="'.$assignment[10].'" id="assignment_'.$assignment[0].'"><cell bgColor="'.$assignment[10].'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';" image="submission.png">'.$assignment[2].'</cell>';
if($assignment[6]!="1" && $assignment[6]!=dlang("grids_not_subm_text","Not subm.") && $assignment[6]!="Not subm."){
echo '<cell bgColor="'.$this->edit_color.'" style="color:#006699; opacity: '.$assignment[11].';">'.$assignment[6].'</cell>';
}else{
if($assignment[5]>=0 && ($assignment[6]==dlang("grids_not_subm_text","Not subm.") || $assignment[6]=="Not subm.") ){
echo '<cell bgColor="'.$this->edit_color.'" style="color:#6495ED; opacity: '.$assignment[11].';">'.dlang("grids_not_subm_text","Not subm.").'</cell>';
}elseif($assignment[5]<0 && ($assignment[6]==dlang("grids_not_subm_text","Not subm."))){
echo '<cell bgColor="'.$this->edit_color.'" style="color:#EE6A50; opacity: '.$assignment[11].';">'.dlang("grids_not_subm_text","Not subm.").'</cell>';
}else{
if($assignment[16]=='No deadline'){
echo '<cell bgColor="'.$this->edit_color.'" style="color:green; opacity: '.$assignment[9].';">'.dlang("grids_subm_text","Subm.").'</cell>';
}else{
if($assignment[15]>=0){
if($assignment[21]<=$assignment[20]){
echo '<cell bgColor="'.$this->edit_color.'" style="color:green; opacity: '.$assignment[13].';">'.abs($assignment[15]).' '.dlang("grids_not_subm_daye","day early").'</cell>';
}else{
echo '<cell bgColor="'.$this->edit_color.'" style="color:red; opacity: '.$assignment[13].';">'.abs($assignment[15]).' '.dlang("grids_not_subm_dayl","day late").'</cell>';
}
}else{
echo '<cell bgColor="'.$this->edit_color.'" style="color:red; opacity: '.$assignment[13].';">'.abs($assignment[15]).' '.dlang("grids_not_subm_dayl","day late").'</cell>';
}
}
}
}
echo '<cell bgColor="'.$assignment[10].'"/><cell bgColor="'.$assignment[10].'"/><cell bgColor="'.$assignment[10].'"/><cell bgColor="'.$assignment[10].'"/><cell bgColor="'.$assignment[10].'"/>';
foreach ($assignment[8] as $key3 => $rset) {
$sql = "SELECT title_en FROM studygroups WHERE studygroup_id IN (".$rset[14].")";
$result = $this->db->query($sql);
$sgids = null;
while($row = mysql_fetch_assoc($result)){
$sgids[] = $row['title_en'];
}
echo '
<row id="a_'.$rset[0].'" style="opacity: '.$assignment[11].';">
<cell image="objective.png" bgColor="#FFFFFF" style="opacity: '.$assignment[11].'; color:rgb(73, 74, 75);">'.implode(', ', $sgids).': '.implode(', ',$rset[5]).'</cell>
<cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';"></cell>
<cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[1].'</cell>
<cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[2].'</cell>
<cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[3].'</cell>
';
switch ($rset[12]) {
case '1':
echo '<cell type="ed" bgColor="'.$this->edit_color.'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[4].'</cell>';
break;
case '2':
echo '<cell type="ed" bgColor="'.$this->edit_color.'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[4].'</cell>';
break;
case '3':
echo '<cell type="co" xmlcontent="1" bgColor="'.$this->edit_color.'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[4].'<option value="'."A".'">'."A".'</option>
<option value="B">'."B".'</option>
<option value="C">'."C".'</option>
<option value="D">'."D".'</option>
<option value="E">'."E".'</option>
<option value="F">'."F".'</option>
<option value="Fx">'."Fx".'</option>
</cell>
';
break;
case '4':
echo '<cell type="co" xmlcontent="1" bgColor="'.$this->edit_color.'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.dlang($rset[4]).'<option value="'.dlang("passvalue","Pass").'">'.dlang("passvalue","Pass").'</option>
<option value="'.dlang("npassvalue","NPass").'">'.dlang("npassvalue","NPass").'</option>
<option value="">'."".'</option>
</cell>';
break;
default:
break;
}
if($rset[12]=='4'){
echo '<cell xmlcontent="1" bgColor="'.$rset[11].'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[9].'<option value="'.dlang("passvalue","Pass").'">'.dlang("passvalue","Pass").'</option>
<option value="'.dlang("npassvalue","NPass").'">'.dlang("npassvalue","NPass").'</option>
<option value="">'."".'</option>
</cell><userdata name="unit">'.$rset[12].'</userdata></row>';
}else{
echo '<cell xmlcontent="1" bgColor="'.$rset[11].'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[9].'<option value="'."A".'">'."A".'</option>
<option value="B">'."B".'</option>
<option value="C">'."C".'</option>
<option value="D">'."D".'</option>
<option value="E">'."E".'</option>
<option value="F">'."F".'</option>
<option value="Fx">'."Fx".'</option>
<option value="">'."".'</option>
</cell><userdata name="unit">'.$rset[12].'</userdata></row>';
}
}
echo "<userdata name='submitted'>".($assignment[6]=="1"?1:0)."</userdata>";
echo "<userdata name='activate'>".$assignment[12]."</userdata>";
echo '</row>';
}
echo '</row>';
}
}
private function outAssignmentsArray($acyears){
foreach($acyears as $yid => $year){
if($yid=="0")
continue;
echo '<row id="year_'.$yid.'">
<cell style="color:rgb(73, 74, 75);" sid="year_'.$yid.'" image="folder_closed.png">'.$year[0].'</cell>';
foreach($year as $subid => $subject){
if($subid=="0" || !$subject[0])
continue;
echo '<row id="subject_'.$subid.'">
<cell style="color:rgb(73, 74, 75);" sid="subject_'.$subid.'" image="folder_closed.png">'.$subject[0].'</cell>';
$this->outStgsArray($subject);
echo '</row>';
}
echo '</row>';
}
}
}
?> | ya6adu6adu/schoolmule | connectors/grid_assignments_progress.php | PHP | gpl-2.0 | 30,338 |
.admanage-img p img{
width: 300px;
height:100px;
display: block;
float: left;
} | simaxuaner/Xinxin | sites/all/modules/custom/admanage/admanage.css | CSS | gpl-2.0 | 95 |
/*
* ircd-hybrid: an advanced Internet Relay Chat Daemon(ircd).
* s_misc.c: Yet another miscellaneous functions file.
*
* Copyright (C) 2002 by the past and present ircd coders, and others.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* $Id: s_misc.c 33 2005-10-02 20:50:00Z knight $
*/
#include "stdinc.h"
#include "s_misc.h"
#include "client.h"
#include "common.h"
#include "irc_string.h"
#include "sprintf_irc.h"
#include "ircd.h"
#include "numeric.h"
#include "irc_res.h"
#include "fdlist.h"
#include "s_bsd.h"
#include "s_conf.h"
#include "s_serv.h"
#include "send.h"
#include "memory.h"
static const char *months[] =
{
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November","December"
};
static const char *weekdays[] =
{
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};
char *
date(time_t lclock)
{
static char buf[80], plus;
struct tm *lt, *gm;
struct tm gmbuf;
int minswest;
if (!lclock)
lclock = CurrentTime;
gm = gmtime(&lclock);
memcpy(&gmbuf, gm, sizeof(gmbuf));
gm = &gmbuf;
lt = localtime(&lclock);
/*
* There is unfortunately no clean portable way to extract time zone
* offset information, so do ugly things.
*/
minswest = (gm->tm_hour - lt->tm_hour) * 60 + (gm->tm_min - lt->tm_min);
if (lt->tm_yday != gm->tm_yday)
{
if ((lt->tm_yday > gm->tm_yday && lt->tm_year == gm->tm_year) ||
(lt->tm_yday < gm->tm_yday && lt->tm_year != gm->tm_year))
minswest -= 24 * 60;
else
minswest += 24 * 60;
}
plus = (minswest > 0) ? '-' : '+';
if (minswest < 0)
minswest = -minswest;
ircsprintf(buf, "%s %s %d %d -- %02u:%02u:%02u %c%02u:%02u",
weekdays[lt->tm_wday], months[lt->tm_mon],lt->tm_mday,
lt->tm_year + 1900, lt->tm_hour, lt->tm_min, lt->tm_sec,
plus, minswest/60, minswest%60);
return buf;
}
const char *
smalldate(time_t lclock)
{
static char buf[MAX_DATE_STRING];
struct tm *lt, *gm;
struct tm gmbuf;
if (!lclock)
lclock = CurrentTime;
gm = gmtime(&lclock);
memcpy(&gmbuf, gm, sizeof(gmbuf));
gm = &gmbuf;
lt = localtime(&lclock);
ircsprintf(buf, "%d/%d/%d %02d.%02d",
lt->tm_year + 1900, lt->tm_mon + 1, lt->tm_mday,
lt->tm_hour, lt->tm_min);
return buf;
}
/* small_file_date()
* Make a small YYYYMMDD formatted string suitable for a
* dated file stamp.
*/
char *
small_file_date(time_t lclock)
{
static char timebuffer[MAX_DATE_STRING];
struct tm *tmptr;
if (!lclock)
time(&lclock);
tmptr = localtime(&lclock);
strftime(timebuffer, MAX_DATE_STRING, "%Y%m%d", tmptr);
return timebuffer;
}
#ifdef HAVE_LIBCRYPTO
char *
ssl_get_cipher(SSL *ssl)
{
static char buffer[128];
const char *name = NULL;
int bits;
switch (ssl->session->ssl_version)
{
case SSL2_VERSION:
name = "SSLv2";
break;
case SSL3_VERSION:
name = "SSLv3";
break;
case TLS1_VERSION:
name = "TLSv1";
break;
default:
name = "UNKNOWN";
}
SSL_CIPHER_get_bits(SSL_get_current_cipher(ssl), &bits);
snprintf(buffer, sizeof(buffer), "%s %s-%d",
name, SSL_get_cipher(ssl), bits);
return buffer;
}
#endif
| codemstr/eircd-hybrid | src/s_misc.c | C | gpl-2.0 | 3,996 |
/*
* Copyright (C) 2004
* Swiss Federal Institute of Technology, Lausanne. All rights reserved.
*
* Developed at the Autonomous Systems Lab.
* Visit our homepage at http://asl.epfl.ch/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#ifndef NPM_TRAJECTORYDRAWING_HPP
#define NPM_TRAJECTORYDRAWING_HPP
#include <npm/gfx/Drawing.hpp>
namespace npm {
class RobotServer;
class TrajectoryDrawing
: public Drawing
{
public:
TrajectoryDrawing(const RobotServer * owner);
virtual void Draw();
private:
const RobotServer * m_owner;
};
}
#endif // NPM_TRAJECTORYDRAWING_HPP
| poftwaresatent/sfl2 | npm/gfx/TrajectoryDrawing.hpp | C++ | gpl-2.0 | 1,294 |
/*
sort.c
Ruby/GSL: Ruby extension library for GSL (GNU Scientific Library)
(C) Copyright 2001-2006 by Yoshiki Tsunesada
Ruby/GSL is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY.
*/
#include <extconf.h>
#include "rb_gsl_array.h"
#include <gsl/gsl_heapsort.h>
#include <gsl/gsl_sort.h>
EXTERN ID RBGSL_ID_call;
EXTERN VALUE cgsl_complex;
int rb_gsl_comparison_double(const void *aa, const void *bb);
int rb_gsl_comparison_complex(const void *aa, const void *bb);
int rb_gsl_comparison_double(const void *aa, const void *bb)
{
double *a = NULL, *b = NULL;
a = (double *) aa;
b = (double *) bb;
return FIX2INT(rb_funcall(RB_GSL_MAKE_PROC, RBGSL_ID_call, 2, rb_float_new(*a), rb_float_new(*b)));
}
int rb_gsl_comparison_complex(const void *aa, const void *bb)
{
gsl_complex *a = NULL, *b = NULL;
a = (gsl_complex *) aa;
b = (gsl_complex *) bb;
return FIX2INT(rb_funcall(RB_GSL_MAKE_PROC, RBGSL_ID_call, 2,
Data_Wrap_Struct(cgsl_complex, 0, NULL, a),
Data_Wrap_Struct(cgsl_complex, 0, NULL, b)));
}
static VALUE rb_gsl_heapsort_vector(VALUE obj)
{
gsl_vector *v = NULL;
if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given");
Data_Get_Struct(obj, gsl_vector, v);
gsl_heapsort(v->data, v->size, sizeof(double), rb_gsl_comparison_double);
return obj;
}
static VALUE rb_gsl_heapsort_vector2(VALUE obj)
{
gsl_vector *v = NULL, *vnew = NULL;
if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given");
Data_Get_Struct(obj, gsl_vector, v);
vnew = gsl_vector_alloc(v->size);
gsl_vector_memcpy(vnew, v);
gsl_heapsort(vnew->data, vnew->size, sizeof(double), rb_gsl_comparison_double);
return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, vnew);
}
static VALUE rb_gsl_heapsort_index_vector(VALUE obj)
{
gsl_vector *v = NULL;
gsl_permutation *p = NULL;
if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given");
Data_Get_Struct(obj, gsl_vector, v);
p = gsl_permutation_alloc(v->size);
gsl_heapsort_index(p->data, v->data, v->size, sizeof(double), rb_gsl_comparison_double);
return Data_Wrap_Struct(cgsl_permutation, 0, gsl_permutation_free, p);
}
static VALUE rb_gsl_heapsort_vector_complex(VALUE obj)
{
gsl_vector_complex *v = NULL;
if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given");
Data_Get_Struct(obj, gsl_vector_complex, v);
gsl_heapsort(v->data, v->size, sizeof(gsl_complex), rb_gsl_comparison_complex);
return obj;
}
static VALUE rb_gsl_heapsort_vector_complex2(VALUE obj)
{
gsl_vector_complex *v = NULL, *vnew = NULL;
if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given");
Data_Get_Struct(obj, gsl_vector_complex, v);
vnew = gsl_vector_complex_alloc(v->size);
gsl_vector_complex_memcpy(vnew, v);
gsl_heapsort(vnew->data, vnew->size, sizeof(gsl_complex), rb_gsl_comparison_complex);
return Data_Wrap_Struct(cgsl_vector_complex, 0, gsl_vector_complex_free, vnew);
}
static VALUE rb_gsl_heapsort_index_vector_complex(VALUE obj)
{
gsl_vector_complex *v = NULL;
gsl_permutation *p = NULL;
if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given");
Data_Get_Struct(obj, gsl_vector_complex, v);
p = gsl_permutation_alloc(v->size);
gsl_heapsort_index(p->data, v->data, v->size, sizeof(gsl_complex), rb_gsl_comparison_complex);
return Data_Wrap_Struct(cgsl_permutation, 0, gsl_permutation_free, p);
}
/* singleton */
static VALUE rb_gsl_heapsort(VALUE obj, VALUE vv)
{
if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given");
if (rb_obj_is_kind_of(vv, cgsl_vector_complex)) {
return rb_gsl_heapsort_vector_complex(vv);
} else if (rb_obj_is_kind_of(vv, cgsl_vector)) {
return rb_gsl_heapsort_vector(vv);
} else {
rb_raise(rb_eTypeError, "wrong argument type %s (Vector or Vector::Complex expected)", rb_class2name(CLASS_OF(vv)));
}
return vv;
}
static VALUE rb_gsl_heapsort2(VALUE obj, VALUE vv)
{
if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given");
if (rb_obj_is_kind_of(vv, cgsl_vector_complex)) {
return rb_gsl_heapsort_vector_complex2(vv);
} else if (rb_obj_is_kind_of(vv, cgsl_vector)) {
return rb_gsl_heapsort_vector2(vv);
} else {
rb_raise(rb_eTypeError, "wrong argument type %s (Vector or Vector::Complex expected)", rb_class2name(CLASS_OF(vv)));
}
return vv;
}
static VALUE rb_gsl_heapsort_index(VALUE obj, VALUE vv)
{
if (!rb_block_given_p()) rb_raise(rb_eRuntimeError, "Proc is not given");
if (rb_obj_is_kind_of(vv, cgsl_vector_complex)) {
return rb_gsl_heapsort_index_vector_complex(vv);
} else if (rb_obj_is_kind_of(vv, cgsl_vector)) {
return rb_gsl_heapsort_index_vector(vv);
} else {
rb_raise(rb_eTypeError, "wrong argument type %s (Vector or Vector::Complex expected)", rb_class2name(CLASS_OF(vv)));
}
return vv;
}
/*****/
#ifdef HAVE_NARRAY_H
#include "narray.h"
static VALUE rb_gsl_sort_narray(VALUE obj)
{
struct NARRAY *na;
size_t size, stride;
double *ptr1, *ptr2;
VALUE ary;
GetNArray(obj, na);
ptr1 = (double*) na->ptr;
size = na->total;
stride = 1;
ary = na_make_object(NA_DFLOAT, na->rank, na->shape, CLASS_OF(obj));
ptr2 = NA_PTR_TYPE(ary, double*);
memcpy(ptr2, ptr1, sizeof(double)*size);
gsl_sort(ptr2, stride, size);
return ary;
}
static VALUE rb_gsl_sort_narray_bang(VALUE obj)
{
struct NARRAY *na;
size_t size, stride;
double *ptr1;
GetNArray(obj, na);
ptr1 = (double*) na->ptr;
size = na->total;
stride = 1;
gsl_sort(ptr1, stride, size);
return obj;
}
static VALUE rb_gsl_sort_index_narray(VALUE obj)
{
struct NARRAY *na;
size_t size, stride;
double *ptr1;
gsl_permutation *p;
GetNArray(obj, na);
ptr1 = (double*) na->ptr;
size = na->total;
stride = 1;
p = gsl_permutation_alloc(size);
gsl_sort_index(p->data, ptr1, stride, size);
return Data_Wrap_Struct(cgsl_permutation, 0, gsl_permutation_free, p);
}
#endif
void Init_gsl_sort(VALUE module)
{
rb_define_singleton_method(module, "heapsort!", rb_gsl_heapsort, 1);
rb_define_singleton_method(module, "heapsort", rb_gsl_heapsort2, 1);
rb_define_singleton_method(module, "heapsort_index", rb_gsl_heapsort_index, 1);
rb_define_method(cgsl_vector, "heapsort!", rb_gsl_heapsort_vector, 0);
rb_define_method(cgsl_vector, "heapsort", rb_gsl_heapsort_vector2, 0);
rb_define_method(cgsl_vector, "heapsort_index", rb_gsl_heapsort_index_vector, 0);
rb_define_method(cgsl_vector_complex, "heapsort!", rb_gsl_heapsort_vector_complex, 0);
rb_define_method(cgsl_vector_complex, "heapsort", rb_gsl_heapsort_vector_complex2, 0);
rb_define_method(cgsl_vector_complex, "heapsort_index", rb_gsl_heapsort_index_vector_complex, 0);
#ifdef HAVE_NARRAY_H
rb_define_method(cNArray, "gsl_sort", rb_gsl_sort_narray, 0);
rb_define_method(cNArray, "gsl_sort!", rb_gsl_sort_narray_bang, 0);
rb_define_method(cNArray, "gsl_sort_index", rb_gsl_sort_index_narray, 0);
#endif
}
| iliya-gr/rb-gsl | ext/gsl/sort.c | C | gpl-2.0 | 7,112 |
/*
* This file is part of Soprano Project.
*
* Copyright (C) 2007-2010 Sebastian Trueg <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "servercore.h"
#include "servercore_p.h"
#include "soprano-server-config.h"
#include "serverconnection.h"
#ifdef BUILD_DBUS_SUPPORT
#include "dbus/dbuscontroller.h"
#endif
#include "modelpool.h"
#include "localserver.h"
#include "tcpserver.h"
#include "backend.h"
#include "storagemodel.h"
#include "global.h"
#include "asyncmodel.h"
#include <QtCore/QHash>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QTcpSocket>
#include <QtDBus/QtDBus>
const quint16 Soprano::Server::ServerCore::DEFAULT_PORT = 5000;
void Soprano::Server::ServerCorePrivate::addConnection( ServerConnection* conn )
{
connections.append( conn );
QObject::connect( conn, SIGNAL(destroyed(QObject*)), q, SLOT(serverConnectionFinished(QObject*)) );
conn->start();
qDebug() << Q_FUNC_INFO << "New connection. New count:" << connections.count();
}
Soprano::Server::ServerCore::ServerCore( QObject* parent )
: QObject( parent ),
d( new ServerCorePrivate() )
{
d->q = this;
// default backend
d->backend = Soprano::usedBackend();
d->modelPool = new ModelPool( this );
}
Soprano::Server::ServerCore::~ServerCore()
{
#ifdef BUILD_DBUS_SUPPORT
delete d->dbusController;
#endif
// We avoid using qDeleteAll because d->connections is modified by each delete operation
foreach(const Soprano::Server::ServerConnection* con, d->connections) {
delete con;
}
qDeleteAll( d->models );
delete d->modelPool;
delete d;
}
void Soprano::Server::ServerCore::setBackend( const Backend* backend )
{
d->backend = backend;
}
const Soprano::Backend* Soprano::Server::ServerCore::backend() const
{
return d->backend;
}
void Soprano::Server::ServerCore::setBackendSettings( const QList<BackendSetting>& settings )
{
d->settings = settings;
}
QList<Soprano::BackendSetting> Soprano::Server::ServerCore::backendSettings() const
{
return d->settings;
}
void Soprano::Server::ServerCore::setMaximumConnectionCount( int max )
{
d->maxConnectionCount = max;
}
int Soprano::Server::ServerCore::maximumConnectionCount() const
{
return d->maxConnectionCount;
}
Soprano::Model* Soprano::Server::ServerCore::model( const QString& name )
{
QHash<QString, Model*>::const_iterator it = d->models.constFind( name );
if ( it == d->models.constEnd() ) {
BackendSettings settings = d->createBackendSettings( name );
if ( isOptionInSettings( settings, BackendOptionStorageDir ) ) {
QDir().mkpath( valueInSettings( settings, BackendOptionStorageDir ).toString() );
}
Model* model = createModel( settings );
d->models.insert( name, model );
return model;
}
else {
return *it;
}
}
void Soprano::Server::ServerCore::removeModel( const QString& name )
{
clearError();
QHash<QString, Model*>::iterator it = d->models.find( name );
if ( it == d->models.end() ) {
setError( QString( "Could not find model with name %1" ).arg( name ) );
}
else {
Model* model = *it;
d->models.erase( it );
// delete the model, removing any cached data
delete model;
if ( isOptionInSettings( d->settings, BackendOptionStorageDir ) ) {
// remove the data on disk
backend()->deleteModelData( d->createBackendSettings( name ) );
// remove the dir which should now be empty
QDir( valueInSettings( d->settings, BackendOptionStorageDir ).toString() ).rmdir( name );
}
}
}
bool Soprano::Server::ServerCore::listen( quint16 port )
{
clearError();
if ( !d->tcpServer ) {
d->tcpServer = new TcpServer( d, this );
}
if ( !d->tcpServer->listen( QHostAddress::Any, port ) ) {
setError( QString( "Failed to start listening at port %1 on localhost." ).arg( port ) );
qDebug() << "Failed to start listening at port " << port;
return false;
}
else {
qDebug() << "Listening on port " << port;
return true;
}
}
void Soprano::Server::ServerCore::stop()
{
qDebug() << "Stopping and deleting";
// We avoid using qDeleteAll because d->connections is modified by each delete operation
foreach(const Soprano::Server::ServerConnection* con, d->connections) {
delete con;
}
qDeleteAll( d->models );
delete d->tcpServer;
d->tcpServer = 0;
delete d->socketServer;
d->socketServer = 0;
#ifdef BUILD_DBUS_SUPPORT
delete d->dbusController;
d->dbusController = 0;
#endif
}
quint16 Soprano::Server::ServerCore::serverPort() const
{
if ( d->tcpServer ) {
return d->tcpServer->serverPort();
}
else {
return 0;
}
}
bool Soprano::Server::ServerCore::start( const QString& name )
{
clearError();
if ( !d->socketServer ) {
d->socketServer = new LocalServer( d, this );
}
QString path( name );
if ( path.isEmpty() ) {
path = QDir::homePath() + QLatin1String( "/.soprano/socket" );
}
if ( !d->socketServer->listen( path ) ) {
setError( QString( "Failed to start listening at %1." ).arg( path ) );
return false;
}
else {
return true;
}
}
void Soprano::Server::ServerCore::registerAsDBusObject( const QString& objectPath )
{
#ifdef BUILD_DBUS_SUPPORT
if ( !d->dbusController ) {
QString path( objectPath );
if ( path.isEmpty() ) {
path = "/org/soprano/Server";
}
d->dbusController = new Soprano::Server::DBusController( this, path );
}
#else
qFatal("Soprano has been built without D-Bus support!" );
#endif
}
void Soprano::Server::ServerCore::serverConnectionFinished(QObject* obj)
{
qDebug() << Q_FUNC_INFO << d->connections.count();
// We use static_cast cause qobject_case will fail since the object has been destroyed
ServerConnection* conn = static_cast<ServerConnection*>( obj );
d->connections.removeAll( conn );
qDebug() << Q_FUNC_INFO << "Connection removed. Current count:" << d->connections.count();
}
Soprano::Model* Soprano::Server::ServerCore::createModel( const QList<BackendSetting>& settings )
{
Model* m = backend()->createModel( settings );
if ( m ) {
clearError();
}
else if ( backend()->lastError() ) {
setError( backend()->lastError() );
}
else {
setError( "Could not create new Model for unknown reason" );
}
return m;
}
QStringList Soprano::Server::ServerCore::allModels() const
{
return d->models.keys();
}
| KDE/soprano | server/servercore.cpp | C++ | gpl-2.0 | 7,513 |
package es.uniovi.asw.gui.util.form.validator.specific;
import es.uniovi.asw.gui.util.form.validator.composite.CheckAllValidator;
import es.uniovi.asw.gui.util.form.validator.simple.LengthValidator;
import es.uniovi.asw.gui.util.form.validator.simple.NumberValidator;
public class TelephoneValidator extends CheckAllValidator {
public TelephoneValidator() {
super(new NumberValidator(), new LengthValidator(9));
}
@Override
public String help() {
return "S�lo n�meros, 9 caracteres.";
}
}
| Arquisoft/Trivial5a | game/src/main/java/es/uniovi/asw/gui/util/form/validator/specific/TelephoneValidator.java | Java | gpl-2.0 | 507 |
Package.describe({
summary: "Next bike list package"
});
Package.on_use(function (api) {
api.use(['nb','underscore', 'templating', 'nb-autocomplete', 'nb-markers', 'nb-infowindow', 'nb-directions', 'nb-geocoder', 'nb-markerlabel', 'nb-citypicker'], ['client']);
api.add_files(['list.html', 'list.js'], ['client']);
});
| wolasss/nextbike-poland | packages/nb-list/package.js | JavaScript | gpl-2.0 | 326 |
<?php
/**
*
* @package phpBB Extension - Senky Post Links
* @copyright (c) 2014 Jakub Senko
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2
* Swedish translation by/
* Svensk översättning av: Tage Strandell, Webmaster vulcanriders-sweden.org
*
*/
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
$lang = array_merge($lang, array(
'ACP_POST_LINKS' => 'Post links',
'PL_ENABLE' => 'Tillåt inläggslänkar',
'PL_ENABLE_EXPLAIN' => 'Om tillåtna, varje länk kommer att innehålla kopierbara av de typer som tillåts nedan.',
'PL_LINK_ENABLE' => 'Tillåt normallänk',
'PL_BBCODE_ENABLE' => 'Tillåt BB-kodlänk',
'PL_HTML_ENABLE' => 'Tillåt HTML-länk',
));
| Senky/phpbb-ext-postlinks | language/sv/acp.php | PHP | gpl-2.0 | 755 |
/**
* \ingroup devices
* \defgroup TapBridgeModel Tap Bridge Model
*
* \section TapBridgeModelOverview TapBridge Model Overview
*
* The Tap Bridge is designed to integrate "real" internet hosts (or more
* precisely, hosts that support Tun/Tap devices) into ns-3 simulations. The
* goal is to make it appear to a "real" host node in that it has an ns-3 net
* device as a local device. The concept of a "real host" is a bit slippery
* since the "real host" may actually be virtualized using readily avialable
* technologies such as VMware or OpenVZ.
*
* Since we are, in essence, connecting the inputs and outputs of an ns-3 net
* device to the inputs and outputs of a Linux Tap net device, we call this
* arrangement a Tap Bridge.
*
* There are two basic operating modes of this device available to users.
* Basic functionality is essentially identical, but the two modes are
* different in details regarding how the arrangement is configured. In the
* first mode, the configuration is ns-3 configuration-centric. Configuration
* information is taken from the ns-3 simulation and a tap device matching
* the ns-3 attributes is created for you. In this mode, which we call
* LocalDevice mode, an ns-3 net device is made to appear to be directly
* connected to a real host.
*
* This is illustrated below
*
* \verbatim
* +--------+
* | Linux |
* | host | +----------+
* | ------ | | ghost |
* | apps | | node |
* | ------ | | -------- |
* | stack | | IP | +----------+
* | ------ | | stack | | node |
* | TAP | |==========| | -------- |
* | device | <-- IPC Bridge --> | tap | | IP |
* +--------+ | bridge | | stack |
* | -------- | | -------- |
* | ns-3 | | ns-3 |
* | net | | net |
* | device | | device |
* +----------+ +----------+
* || ||
* +---------------------------+
* | ns-3 channel |
* +---------------------------+
*\endverbatim
*
* In this case, the ns-3 net device in the ghost node appears as if it were
* actually replacing the TAP device in the Linux host. The ns-3 process
* creates the TAP device configures the IP address and MAC address of the
* TAP device to match the values assigned to the ns-3 net device. The IPC
* link is via the network tap mechanism in the underlying OS and acts as a
* conventional bridge; but a bridge between devices that happen to have the
* same shared MAC address.
*
* The LocalDevice mode is the default operating mode of the Tap Bridge.
*
* The second mode, BridgedDevice mode, is more oriented toward allowing existing
* host configurations. This allows ns-3 net devices to appear as part of a host
* operating system bridge (in Linux, we make the ns-3 device part of a "brctl"
* bridge. This mode is especially useful in the case of virtualization where
* the configuration of the virtual hosts may be dictated by another system and
* not be changable to suit ns-3. For example, a particular VM scheme may create
* virtual "vethx" or "vmnetx" devices that appear local to virtual hosts. In
* order to connect to such systems, one would need to manually create TAP devices
* on the host system and brigde these TAP devices to the existing (VM) virtual
* devices. The job of the Tap Bridge in this case is to extend the bridge to
* join the ns-3 net device.
*
* This is illustrated below:
*
* \verbatim
* +---------+
* | Linux |
* | VM | +----------+
* | ------- | | ghost |
* | apps | | node |
* | ------- | | -------- |
* | stack | | IP | +----------+
* | ------- | +--------+ | stack | | node |
* | Virtual | | TAP | |==========| | -------- |
* | Device | | Device | <-- IPC Bridge-> | tap | | IP |
* +---------+ +--------+ | bridge | | stack |
* || || | -------- | | -------- |
* +--------------------+ | ns-3 | | ns-3 |
* | OS (brctl) Bridge | | net | | net |
* +--------------------+ | device | | device |
* +----------+ +----------+
* || ||
* +---------------------------+
* | ns-3 channel |
* +---------------------------+
*\endverbatim
*
* In this case, a collection of virtual machines with associated Virtual
* Devices is created in the virtualization environment (for exampe, OpenVZ
* or VMware). A TAP device (with a specific name) is then manually created
* for each Virtual Device that will be bridged into the ns-3 simulation.
* These created TAP devices are then bridged together with the Virtual Devices
* using a native OS bridge mechanism shown as "OS (brctl) Bridge" in the
* illustration above.
*
* In the ns-3 simulation, a Tap Bridge is created to match each TAP Device.
* The name of the TAP Device is assigned to the Tap Bridge using the
* "DeviceName" attribute. The Tap Bridge then opens a network tap to the TAP
* Device and logically extends the bridge to encompass the ns-3 net device.
* This makes it appear as if an ns-3 simulated net device is a member of the
* "OS (brctl) Bridge" and allows the Virtual Machines to communicate with the
* ns-3 simulation..
*
* \subsection TapBridgeLocalDeviceMode TapBridge LocalDevice Mode
*
* In LocalDevice mode, the TapBridge and therefore its associated ns-3 net
* device appears to the Linux host computer as a network device just like any
* arbitrary "eth0" or "ath0" might appear. The creation and configuration
* of the TAP device is done by the ns-3 simulation and no manual configuration
* is required by the user. The IP addresses, MAC addresses, gateways, etc.,
* for created TAP devices are extracted from the simulation itself by querying
* the configuration of the ns-3 device and the TapBridge Attributes.
*
* The TapBridge appears to an ns-3 simulation as a channel-less net device.
* This device must not have an IP address associated with it, but the bridged
* (ns-3) net device must have an IP adress. Be aware that this is the inverse
* of an ns-3 BridgeNetDevice (or a conventional bridge in general) which
* demands that its bridge ports not have IP addresses, but allows the bridge
* device itself to have an IP address.
*
* The host computer will appear in a simulation as a "ghost" node that contains
* one TapBridge for each NetDevice that is being bridged. From the perspective
* of a simulation, the only difference between a ghost node and any other node
* will be the presence of the TapBridge devices. Note however, that the
* presence of the TapBridge does affect the connectivity of the net device to
* the IP stack of the ghost node.
*
* Configuration of address information and the ns-3 devices is not changed in
* any way if a TapBridge is present. A TapBridge will pick up the addressing
* information from the ns-3 net device to which it is connected (its "bridged"
* net device) and use that information to create and configure the TAP device
* on the real host.
*
* The end result of this is a situation where one can, for example, use the
* standard ping utility on a real host to ping a simulated ns-3 node. If
* correct routes are added to the internet host (this is expected to be done
* automatically in future ns-3 releases), the routing systems in ns-3 will
* enable correct routing of the packets across simulated ns-3 networks.
* For an example of this, see the example program, tap-wifi-dumbbell.cc in
* the ns-3 distribution.
*
* \subsection TapBridgeLocalDeviceModeOperation TapBridge LocalDevice Mode Operation
*
* The Tap Bridge lives in a kind of a gray world somewhere between a Linux host
* and an ns-3 bridge device. From the Linux perspective, this code appears as
* the user mode handler for a TAP net device. In LocalDevice mode, this TAP
* device is automatically created by the ns-3 simulation. When the Linux host
* writes to one of these automatically created /dev/tap devices, the write is
* redirected into the TapBridge that lives in the ns-3 world; and from this
* perspective, the packet write on Linux becomes a packet read in the Tap Bridge.
* In other words, a Linux process writes a packet to a tap device and this packet
* is redirected by the network tap mechanism toan ns-3 process where it is
* received by the TapBridge as a result of a read operation there. The TapBridge
* then writes the packet to the ns-3 net device to which it is bridged; and
* therefore it appears as if the Linux host sent a packet directly through an
* ns-3 net device onto an ns-3 network.
*
* In the other direction, a packet received by the ns-3 net device connected to
* the Tap Bridge is sent via promiscuous callback to the TapBridge. The
* TapBridge then takes that packet and writes it back to the host using the
* network tap mechanism. This write to the device will appear to the Linux
* host as if a packet has arrived on its device; and therefore as if a packet
* received by the ns-3 net device has appeared on a Linux net device.
*
* The upshot is that the Tap Bridge appears to bridge a tap device on a
* Linux host in the "real world" to an ns-3 net device in the simulation.
* Because the TAP device and the bridged ns-3 net device have the same MAC
* address and the network tap IPC link is not exernalized, this particular
* kind of bridge makes ti appear that a ns-3 net device is actually installed
* in the Linux host.
*
* In order to implement this on the ns-3 side, we need a "ghost node" in the
* simulation to hold the bridged ns-3 net device and the TapBridge. This node
* should not actually do anything else in the simulation since its job is
* simply to make the net device appear in Linux. This is not just arbitrary
* policy, it is because:
*
* - Bits sent to the Tap Bridge from higher layers in the ghost node (using
* the TapBridge Send method) are completely ignored. The Tap Bridge is
* not, itself, connected to any network, neither in Linux nor in ns-3. You
* can never send nor receive data over a Tap Bridge from the ghost node.
*
* - The bridged ns-3 net device has its receive callback disconnected
* from the ns-3 node and reconnected to the Tap Bridge. All data received
* by a bridged device will then be sent to the Linux host and will not be
* received by the node. From the perspective of the ghost node, you can
* send over this device but you cannot ever receive.
*
* Of course, if you understand all of the issues you can take control of
* your own destiny and do whatever you want -- we do not actively
* prevent you from using the ghost node for anything you decide. You
* will be able to perform typical ns-3 operations on the ghost node if
* you so desire. The internet stack, for example, must be there and
* functional on that node in order to participate in IP address
* assignment and global routing. However, as mentioned above,
* interfaces talking any Tap Bridge or associated bridged net devices
* will not work completely. If you understand exactly what you are
* doing, you can set up other interfaces and devices on the ghost node
* and use them; or take advantage of the operational send side of the
* bridged devices to create traffic generators. We generally recommend
* that you treat this node as a ghost of the Linux host and leave it to
* itself, though.
*
* \subsection TapBridgeBridgedDeviceMode TapBridge BridgedDevice Mode
*
* In BridgedDevice mode, the TapBridge and its associated ns-3 net device are
* arranged in a fundamentally similar was as in LocalDevice mode. The TAP
* device is bridged to the ns-3 net device in the same way. The description
* of LocalDevice mode applies except as noted below.
*
* The most user-visible difference in modes is how the creation and
* configuration of the underlying TAP device is done. In LocalDevice mode,
* both creation and configuration of the underlying TAP device are handled
* completely by ns-3. In BridgedDevice mode, creation and configuration is
* delegated (due to requirements) to the user. No configuration is done in
* ns-3 other than settting the operating mode of the TapBridge to
* "BridgedDevice" and specifying the name of a pre-configured TAP device
* using ns-3 Attributes of the TapBridge.
*
* The primary conceptual difference between modes is due to the fact that in
* BridgedDevice mode the MAC addresses of the user-created TAPs will be pre-
* configured and will therefore be different than those in the bridged device.
* As in LocalDevice mode, the Tap Bridge functions as IPC bridge between the
* TAP device and the ns-3 net device, but in BridgedDevice configurations the
* two devices will have different MAC addresses and the bridging functionality
* will be fundamentally the same as in any bridge. Since this implies MAC
* address spoofing, the only ns-3 devices which may paritcipate in a bridge
* in BridgedDevice mode must support SendFrom (i.e., a call to the method
* SupportsSendFrom in the bridged net device must return true).
*
* \subsection TapBridgeBridgedDeviceModeOperation TapBridge BridgedDevice Mode Operation
*
* As described in the LocalDevice mode section, when the Linux host writes to
* one of the /dev/tap devices, the write is redirected into the TapBridge
* that lives in the ns-3 world. In the case of the BridgedDevice mode, these
* packets will need to be sent out on the ns-3 network as if they were sent on
* the Linux network. This means calling the SendFrom method on the bridged
* device and providing the source and destination MAC addresses found in the
* packet.
*
* In the other direction, a packet received by an ns-3 net device is hooked
* via callback to the TapBridge. This must be done in promiscuous mode since
* the goal is to bridge the ns-3 net device onto the OS (brctl) bridge of
* which the TAP device is a part.
*
* There is no functional difference between modes at this level, even though
* the configuration and conceptual models regarding what is going on are quite
* different -- the Tap Bridge is just acting like a bridge. In the LocalDevice
* mode, the bridge is between devices having the same MAC address and in the
* BridgedDevice model the bridge is between devices having different MAC
* addresses.
*
* \subsection TapBridgeSingleSourceModeOperation TapBridge SingleSource Mode Operation
*
* As described in above, the Tap Bridge acts like a bridge. Just like every
* other bridge, there is a requirement that participating devices must have
* the ability to receive promiscuously and to spoof the source MAC addresses
* of packets.
*
* We do, however, have a specific requirement to be able to bridge Virtual
* Machines onto wireless STA nodes. Unfortunately, the 802.11 spec doesn't
* provide a good way to implement SendFrom. So we have to work around this.
*
* To this end, we provice the SingleSource mode of the Tap Bridge. This
* mode allows you to create a bridge as described in BridgedDevice mode, but
* only allows one source of packets on the Linux side of the bridge. The
* address on the Linux side is remembered in the Tap Bridge, and all packets
* coming from the Linux side are repeated out the ns-3 side using the ns-3 device
* MAC source address. All packets coming in from the ns-3 side are repeated
* out the Linux side using the remembered MAC address. This allows us to use
* SendFrom on the ns-3 device side which is available on all ns-3 net devices.
*
* \section TapBridgeChannelModel Tap Bridge Channel Model
*
* There is no channel model associated with the Tap Bridge. In fact, the
* intention is make it appear that the real internet host is connected to
* the channel of the bridged net device.
*
* \section TapBridgeTracingModel Tap Bridge Tracing Model
*
* Unlike most ns-3 devices, the TapBridge does not provide any standard trace
* sources. This is because the bridge is an intermediary that is essentially
* one function call away from the bridged device. We expect that the trace
* hooks in the bridged device will be sufficient for most users,
*
* \section TapBridgeUsage Using the Tap Bridge
*
* We expect that most users will interact with the TapBridge device through
* the TapBridgeHelper. Users of other helper classes, such as CSMA or Wifi,
* should be comfortable with the idioms used.
*/
| AliZafar120/NetworkStimulatorSPl3 | src/devices/tap-bridge/tap.h | C | gpl-2.0 | 17,622 |
package com.greenpineyu.fel.function.operator;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.greenpineyu.fel.Expression;
import com.greenpineyu.fel.common.ArrayUtils;
import com.greenpineyu.fel.common.Null;
import com.greenpineyu.fel.common.ReflectUtil;
import com.greenpineyu.fel.compile.FelMethod;
import com.greenpineyu.fel.compile.SourceBuilder;
import com.greenpineyu.fel.context.FelContext;
import com.greenpineyu.fel.function.CommonFunction;
import com.greenpineyu.fel.function.Function;
import com.greenpineyu.fel.parser.FelNode;
import com.greenpineyu.fel.security.SecurityMgr;
public class Dot implements Function {
private static final Logger logger = LoggerFactory.getLogger(Dot.class);
private SecurityMgr securityMgr;
public SecurityMgr getSecurityMgr() {
return securityMgr;
}
public void setSecurityMgr(SecurityMgr securityMgr) {
this.securityMgr = securityMgr;
}
static final Map<Class<?>, Class<?>> PRIMITIVE_TYPES;
static {
PRIMITIVE_TYPES = new HashMap<Class<?>, Class<?>>();
PRIMITIVE_TYPES.put(Boolean.class, Boolean.TYPE);
PRIMITIVE_TYPES.put(Byte.class, Byte.TYPE);
PRIMITIVE_TYPES.put(Character.class, Character.TYPE);
PRIMITIVE_TYPES.put(Double.class, Double.TYPE);
PRIMITIVE_TYPES.put(Float.class, Float.TYPE);
PRIMITIVE_TYPES.put(Integer.class, Integer.TYPE);
PRIMITIVE_TYPES.put(Long.class, Long.TYPE);
PRIMITIVE_TYPES.put(Short.class, Short.TYPE);
}
public static final String DOT = ".";
@Override
public String getName() {
return DOT;
}
@Override
public Object call(FelNode node, FelContext context) {
List<FelNode> children = node.getChildren();
Object left = children.get(0);
if (left instanceof Expression) {
Expression exp = (Expression) left;
left = exp.eval(context);
}
FelNode right = children.get(1);
FelNode exp = right;
Class<?>[] argsType = new Class<?>[0];
Object[] args = CommonFunction.evalArgs(right, context);
if (!ArrayUtils.isEmpty(args)) {
argsType = new Class[args.length];
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
argsType[i] = Null.class;
continue;
}
argsType[i] = args[i].getClass();
}
}
Method method = null;
Class<?> cls = left instanceof Class<?> ? (Class<?>) left : left.getClass();
String methodName = right.getText();
method = findMethod(cls, methodName, argsType);
if (method == null) {
String getMethod = "get";
method = findMethod(cls, getMethod, new Class<?>[] { String.class });
args = new Object[] { exp.getText() };
}
if (method != null) return invoke(left, method, args);
return null;
}
private Method findMethod(Class<?> cls, String methodName, Class<?>[] argsType) {
Method method = ReflectUtil.findMethod(cls, methodName, argsType);
return getCallableMethod(method);
}
private Method getMethod(Class<?> cls, String methodName, Class<?>[] argsType) {
Method method = ReflectUtil.getMethod(cls, methodName, argsType);
return getCallableMethod(method);
}
private Method getCallableMethod(Method m) {
if (m == null || securityMgr.isCallable(m)) return m;
throw new SecurityException("安全管理器[" + securityMgr.getClass().getSimpleName() + "]禁止调用方法[" + m.toString() + "]");
}
/**
* 调用方法
*
* @param obj
* @param method
* @param args
* @return
*/
public static Object invoke(Object obj, Method method, Object[] args) {
try {
return method.invoke(obj, args);
} catch (IllegalArgumentException | IllegalAccessException e) {
logger.error("", e);
} catch (InvocationTargetException e) {
logger.error("", e.getTargetException());
}
return null;
}
@Override
public FelMethod toMethod(FelNode node, FelContext context) {
StringBuilder sb = new StringBuilder();
List<FelNode> children = node.getChildren();
FelNode l = children.get(0);
SourceBuilder leftMethod = l.toMethod(context);
Class<?> cls = leftMethod.returnType(context, l);
String leftSrc = leftMethod.source(context, l);
if (cls.isPrimitive()) {
Class<?> wrapperClass = ReflectUtil.toWrapperClass(cls);
// 如果左边返回的值的基本类型,要转成包装类型[eg:((Integer)1).doubleValue()]
sb.append("((").append(wrapperClass.getSimpleName()).append(")").append(leftSrc).append(")");
} else {
sb.append(leftSrc);
}
sb.append(".");
Method method = null;
FelNode rightNode = children.get(1);
List<FelNode> params = rightNode.getChildren();
List<SourceBuilder> paramMethods = new ArrayList<SourceBuilder>();
Class<?>[] paramValueTypes = null;
boolean hasParam = params != null && !params.isEmpty();
String rightMethod = rightNode.getText();
String rightMethodParam = "";
if (hasParam) {
// 有参数
paramValueTypes = new Class<?>[params.size()];
for (int i = 0; i < params.size(); i++) {
FelNode p = params.get(i);
SourceBuilder paramMethod = p.toMethod(context);
paramMethods.add(paramMethod);
paramValueTypes[i] = paramMethod.returnType(context, p);
}
// 根据参数查找方法
method = findMethod(cls, rightNode.getText(), paramValueTypes);
if (method != null) {
Class<?>[] paramTypes = method.getParameterTypes();
for (int i = 0; i < paramTypes.length; i++) {
Class<?> paramType = paramTypes[i];
FelNode p = params.get(i);
String paramCode = getParamCode(paramType, p, context);
rightMethodParam += paramCode + ",";
}
rightMethod = method.getName();
}
} else {
method = findMethod(cls, rightNode.getText(), new Class<?>[0]);
if (method == null) {
// 当没有找到方法 ,直接使用get方法来获取属性
method = getMethod(cls, "get", new Class<?>[] { String.class });
if (method != null) {
rightMethod = "get";
rightMethodParam = "\"" + rightNode.getText() + "\"";
}
} else {
rightMethod = method.getName();
}
}
if (method != null) {}
if (rightMethodParam.endsWith(",")) {
rightMethodParam = rightMethodParam.substring(0, rightMethodParam.length() - 1);
}
rightMethod += "(" + rightMethodParam + ")";
sb.append(rightMethod);
FelMethod returnMe = new FelMethod(method == null ? null : method.getReturnType(), sb.toString());
return returnMe;
}
/**
* 获取参数代码
*
* @param paramType
* 方法声明的参数类型
* @param paramValueType
* 参数值的类型
* @param paramMethod
* @return
*/
public static String getParamCode(Class<?> paramType, FelNode node, FelContext ctx) {
// 如果类型相等(包装类型与基本类型(int和Integer)也认为是相等 ),直接添加参数。
String paramCode = "";
SourceBuilder paramMethod = node.toMethod(ctx);
Class<?> paramValueType = paramMethod.returnType(ctx, node);
if (ReflectUtil.isTypeMatch(paramType, paramValueType)) {
paramCode = paramMethod.source(ctx, node);
} else {
// 如果类型不匹配,使用强制转型
String className = null;
Class<?> wrapperClass = ReflectUtil.toWrapperClass(paramType);
if (wrapperClass != null) {
className = wrapperClass.getName();
} else {
className = paramType.getName();
}
paramCode = "(" + className + ")" + paramMethod.source(ctx, node);
}
return paramCode;
}
}
| zbutfly/albacore | expr-fel-import/src/main/java/com/greenpineyu/fel/function/operator/Dot.java | Java | gpl-2.0 | 7,449 |
--リトマスの死儀式
function c8955148.initial_effect(c)
aux.AddRitualProcGreaterCode(c,72566043)
--to deck
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TODECK+CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_GRAVE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1,8955148)
e1:SetTarget(c8955148.tdtg)
e1:SetOperation(c8955148.tdop)
c:RegisterEffect(e1)
end
function c8955148.tdfilter(c)
return c:IsCode(72566043) and c:IsAbleToDeck()
end
function c8955148.tdtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c8955148.tdfilter(chkc) and chkc~=e:GetHandler() end
if chk==0 then return e:GetHandler():IsAbleToDeck()
and Duel.IsExistingTarget(c8955148.tdfilter,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,e:GetHandler()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,c8955148.tdfilter,tp,LOCATION_GRAVE,LOCATION_GRAVE,1,1,e:GetHandler())
g:AddCard(e:GetHandler())
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,2,0,0)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c8955148.tdop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) then
local g=Group.FromCards(c,tc)
if Duel.SendtoDeck(g,nil,2,REASON_EFFECT)==0 then return end
Duel.ShuffleDeck(tp)
Duel.BreakEffect()
Duel.Draw(tp,1,REASON_EFFECT)
end
end
| destdev/ygopro-scripts | c8955148.lua | Lua | gpl-2.0 | 1,460 |
/* *****************************************************************************
* The method lives() is based on Xitari's code, from Google Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* *****************************************************************************
* A.L.E (Arcade Learning Environment)
* Copyright (c) 2009-2013 by Yavar Naddaf, Joel Veness, Marc G. Bellemare and
* the Reinforcement Learning and Artificial Intelligence Laboratory
* Released under the GNU General Public License; see License.txt for details.
*
* Based on: Stella -- "An Atari 2600 VCS Emulator"
* Copyright (c) 1995-2007 by Bradford W. Mott and the Stella team
*
* *****************************************************************************
*/
#include "games/supported/ChopperCommand.hpp"
#include "games/RomUtils.hpp"
namespace ale {
using namespace stella;
ChopperCommandSettings::ChopperCommandSettings() { reset(); }
/* create a new instance of the rom */
RomSettings* ChopperCommandSettings::clone() const {
return new ChopperCommandSettings(*this);
}
/* process the latest information from ALE */
void ChopperCommandSettings::step(const System& system) {
// update the reward
reward_t score = getDecimalScore(0xEE, 0xEC, &system);
score *= 100;
m_reward = score - m_score;
m_score = score;
// update terminal status
m_lives = readRam(&system, 0xE4) & 0xF;
m_terminal = (m_lives == 0);
/*
* Memory address 0xC2 indicates whether the Chopper is pointed
* left or right on the screen.
* - If the value is 0x00 we're looking left.
* - If the value ix 0x01 we are looking right.
* At the beginning of the game when we're selecting the game mode
* we are always facing left, therefore, 0xC2 == 0x00.
* When the game starts the chopper is initialized facing
* right, i.e., 0xC2 == 0x01. We know if the game has started
* if at any point 0xC2 == 0x01 so we can just OR the LSB of 0xC2
* to keep track of whether the game has started or not.
*
* */
m_is_started |= readRam(&system, 0xC2) & 0x1;
}
/* is end of game */
bool ChopperCommandSettings::isTerminal() const {
return (m_is_started && m_terminal);
};
/* get the most recently observed reward */
reward_t ChopperCommandSettings::getReward() const { return m_reward; }
/* is an action part of the minimal set? */
bool ChopperCommandSettings::isMinimal(const Action& a) const {
switch (a) {
case PLAYER_A_NOOP:
case PLAYER_A_FIRE:
case PLAYER_A_UP:
case PLAYER_A_RIGHT:
case PLAYER_A_LEFT:
case PLAYER_A_DOWN:
case PLAYER_A_UPRIGHT:
case PLAYER_A_UPLEFT:
case PLAYER_A_DOWNRIGHT:
case PLAYER_A_DOWNLEFT:
case PLAYER_A_UPFIRE:
case PLAYER_A_RIGHTFIRE:
case PLAYER_A_LEFTFIRE:
case PLAYER_A_DOWNFIRE:
case PLAYER_A_UPRIGHTFIRE:
case PLAYER_A_UPLEFTFIRE:
case PLAYER_A_DOWNRIGHTFIRE:
case PLAYER_A_DOWNLEFTFIRE:
return true;
default:
return false;
}
}
/* reset the state of the game */
void ChopperCommandSettings::reset() {
m_reward = 0;
m_score = 0;
m_terminal = false;
m_lives = 3;
m_is_started = false;
}
/* saves the state of the rom settings */
void ChopperCommandSettings::saveState(Serializer& ser) {
ser.putInt(m_reward);
ser.putInt(m_score);
ser.putBool(m_terminal);
ser.putInt(m_lives);
}
// loads the state of the rom settings
void ChopperCommandSettings::loadState(Deserializer& ser) {
m_reward = ser.getInt();
m_score = ser.getInt();
m_terminal = ser.getBool();
m_lives = ser.getInt();
}
// returns a list of mode that the game can be played in
ModeVect ChopperCommandSettings::getAvailableModes() {
return {0, 2};
}
// set the mode of the game
// the given mode must be one returned by the previous function
void ChopperCommandSettings::setMode(
game_mode_t m, System& system,
std::unique_ptr<StellaEnvironmentWrapper> environment) {
if (m == 0 || m == 2) {
// read the mode we are currently in
unsigned char mode = readRam(&system, 0xE0);
// press select until the correct mode is reached
while (mode != m) {
environment->pressSelect(2);
mode = readRam(&system, 0xE0);
}
//reset the environment to apply changes.
environment->softReset();
} else {
throw std::runtime_error("This mode doesn't currently exist for this game");
}
}
DifficultyVect ChopperCommandSettings::getAvailableDifficulties() {
return {0, 1};
}
} // namespace ale
| mgbellemare/Arcade-Learning-Environment | src/games/supported/ChopperCommand.cpp | C++ | gpl-2.0 | 5,077 |
package gui;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import logic.DB.MongoUserManager;
import logic.model.Statistics;
import logic.model.User;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Toolkit;
public class ListPlayers extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JScrollPane spUsers;
private JTable tabUsers;
private MongoUserManager mongo = new MongoUserManager();
private List<User> users;
private JButton btnClose;
private JLabel lbListUsers;
/**
* Launch the application.
*/
/*public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ListPlayers frame = new ListPlayers();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}*/
/**
* Create the frame.
*/
public ListPlayers() {
setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\Raquel\\Desktop\\ASWProject\\Trivial_i1b\\Game\\src\\main\\resources\\Images\\icono.png"));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 532, 340);
contentPane = new JPanel();
contentPane.setBackground(new Color(0,0,139));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.add(getSpUsers());
contentPane.add(getBtnClose());
contentPane.setBackground(InitialWindow.pnFondo.getBackground());
JButton btnSeeStatistics = new JButton("See statistics");
btnSeeStatistics.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
users = mongo.getAllUsers();
StatisticsWindow statistics = new StatisticsWindow();
statistics.setVisible(true);
statistics.txPlayer.setText((String) tabUsers.getValueAt(tabUsers.getSelectedRow(), 0));
int row = tabUsers.getSelectedRow();
int newRow = 0;
for (User u : users){
if (u.getEmail().equals(tabUsers.getValueAt(row, 1))){
Statistics s = u.getStatistics();
statistics.tabStatistics.setValueAt(s.getQuestionsMatched(), newRow, 0);
statistics.tabStatistics.setValueAt(s.getQuestionsAnswered(), newRow, 1);
statistics.tabStatistics.setValueAt(s.getTimesPlayed(), newRow, 2);
newRow++;
}
}
}
});
btnSeeStatistics.setBounds(357, 42, 123, 23);
contentPane.add(btnSeeStatistics);
contentPane.add(getLbListUsers());
}
private JScrollPane getSpUsers() {
if (spUsers == null) {
spUsers = new JScrollPane();
spUsers.setBounds(42, 103, 306, 128);
spUsers.setViewportView(getTabUsers());
spUsers.setBackground(InitialWindow.pnFondo.getBackground());
}
return spUsers;
}
private JTable getTabUsers() {
if (tabUsers == null) {
tabUsers = new JTable();
tabUsers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tabUsers.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Username", "Email"
}
));
}
DefaultTableModel model = (DefaultTableModel)tabUsers.getModel();
listUsers(model);
return tabUsers;
}
private JButton getBtnClose() {
if (btnClose == null) {
btnClose = new JButton("Close");
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
btnClose.setBounds(378, 230, 76, 23);
}
return btnClose;
}
private void listUsers(DefaultTableModel model) {
users = mongo.getAllUsers();
Object[] row = new Object[2];
for (int i = 0; i < users.size(); i++) {
row[0] = users.get(i).getUsername();
row[1] = users.get(i).getEmail();
model.addRow(row);
}
}
private JLabel getLbListUsers() {
if (lbListUsers == null) {
lbListUsers = new JLabel("List of users:");
lbListUsers.setFont(new Font("Arial", Font.PLAIN, 25));
lbListUsers.setBounds(142, 32, 195, 32);
}
return lbListUsers;
}
}
| Arquisoft/Trivial_i1b | Game/src/main/java/gui/ListPlayers.java | Java | gpl-2.0 | 4,299 |
package sabstracta;
/**
* Represents an or operation in the syntax tree.
*
*/
public class Or extends ExpresionBinariaLogica {
public Or(Expresion _izq, Expresion _dch) {
super(_izq, _dch);
}
/**
* Returns the instruction code.
*/
@Override
protected String getInst() {
return "or";
}
}
| igofunke/LPM | src/sabstracta/Or.java | Java | gpl-2.0 | 325 |
<?php
/**
* @package JFBConnect
* @copyright (c) 2009-2015 by SourceCoast - All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
* @version Release v7.1.1
* @build-date 2016/11/18
*/
defined('JPATH_PLATFORM') or die;
jimport('joomla.form.helper');
class JFormFieldProviderloginbutton extends JFormField
{
protected function getInput()
{
$html = array();
$provider = $this->element['provider'] ? (string)$this->element['provider'] : null;
$style = $this->element['style'] ? (string)$this->element['style'] . '"' : '';
// Initialize some field attributes.
$class = !empty($this->class) ? ' class="radio ' . $this->class . '"' : ' class="radio"';
$required = $this->required ? ' required aria-required="true"' : '';
$autofocus = $this->autofocus ? ' autofocus' : '';
$disabled = $this->disabled ? ' disabled' : '';
$readonly = $this->readonly;
$style = 'style="float:left;' . $style . '"';
$html[] = '<div style="clear: both"> </div>';
// Start the radio field output.
$html[] = '<fieldset id="' . $this->id . '"' . $class . $required . $autofocus . $disabled . $style . ' >';
// Get the field options.
$options = $this->getOptions();
$p = JFBCFactory::provider($provider);
// Build the radio field output.
$html[] = '<label class="providername">' . $p->name . '</label>';
foreach ($options as $i => $option)
{
// Initialize some option attributes.
$checked = ((string)$option->value == (string)$this->value) ? ' checked="checked"' : '';
$class = !empty($option->class) ? ' class="' . $option->class . '"' : '';
$disabled = !empty($option->disable) || ($readonly && !$checked);
$disabled = $disabled ? ' disabled' : '';
$html[] = '<input type="radio" id="' . $this->id . $i . '" name="' . $this->name . '" value="'
. htmlspecialchars($option->value, ENT_COMPAT, 'UTF-8') . '"' . $checked . $class . $required . $disabled . ' />';
$html[] = '<label for="' . $this->id . $i . '"' . $class . ' >' .
'<img src="' . JUri::root() . 'media/sourcecoast/images/provider/' . $provider . '/' . $option->value . '" />' .
#. JText::alt($option->text, preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname)) . '</label>'
'</label>' .
$required = '';
}
// End the radio field output.
$html[] = '</fieldset>';
$html[] = '<div style="clear: both"> </div>';
return implode($html);
}
protected function getOptions()
{
// Scan the /media/sourcecoast/images/provider directory for this provider's buttons
// Merge in any custom images from ??
$provider = $this->element['provider'] ? (string)$this->element['provider'] : null;
$options = array();
$buttons = $this->getButtons('/media/sourcecoast/images/provider/' . $provider);
if ($buttons)
{
foreach ($buttons as $button)
{
$options[] = JHtml::_('select.option', $button, $button, 'value', 'text', false);
}
}
reset($options);
return $options;
}
private function getButtons($folder)
{
$folder = JPATH_SITE . $folder;
$buttons = array();
if (JFolder::exists($folder))
{
$buttons = JFolder::files($folder, '^' . '.*(\.png|\.jpg|\.gif)$');
}
return $buttons;
}
}
| Creativetech-Solutions/joomla-easysocial-network | administrator/components/com_jfbconnect/models/fields/providerloginbutton.php | PHP | gpl-2.0 | 3,688 |
\documentclass{report}
\usepackage{hyperref}
% WARNING: THIS SHOULD BE MODIFIED DEPENDING ON THE LETTER/A4 SIZE
\oddsidemargin 0cm
\evensidemargin 0cm
\marginparsep 0cm
\marginparwidth 0cm
\parindent 0cm
\textwidth 16.5cm
\ifpdf
\usepackage[pdftex]{graphicx}
\else
\usepackage[dvips]{graphicx}
\fi
\begin{document}
% special variable used for calculating some widths.
\newlength{\tmplength}
\chapter{Unit ok{\_}interface{\_}implicit}
\section{Overview}
\begin{description}
\item[\texttt{\begin{ttfamily}IMyInterface\end{ttfamily} Interface}]
\item[\texttt{\begin{ttfamily}TMyRecord\end{ttfamily} Record}]
\item[\texttt{\begin{ttfamily}TMyPackedRecord\end{ttfamily} Packed Record}]
\item[\texttt{\begin{ttfamily}TMyClass\end{ttfamily} Class}]
\end{description}
\section{Classes, Interfaces, Objects and Records}
\subsection*{IMyInterface Interface}
\subsubsection*{\large{\textbf{Hierarchy}}\normalsize\hspace{1ex}\hfill}
IMyInterface {$>$} IInterface
%%%%Description
\subsubsection*{\large{\textbf{Methods}}\normalsize\hspace{1ex}\hfill}
\paragraph*{PublicMethod}\hspace*{\fill}
\begin{list}{}{
\settowidth{\tmplength}{\textbf{Description}}
\setlength{\itemindent}{0cm}
\setlength{\listparindent}{0cm}
\setlength{\leftmargin}{\evensidemargin}
\addtolength{\leftmargin}{\tmplength}
\settowidth{\labelsep}{X}
\addtolength{\leftmargin}{\labelsep}
\setlength{\labelwidth}{\tmplength}
}
\begin{flushleft}
\item[\textbf{Declaration}\hfill]
\begin{ttfamily}
public procedure PublicMethod;\end{ttfamily}
\end{flushleft}
\end{list}
\subsection*{TMyRecord Record}
%%%%Description
\subsubsection*{\large{\textbf{Fields}}\normalsize\hspace{1ex}\hfill}
\paragraph*{PublicField}\hspace*{\fill}
\begin{list}{}{
\settowidth{\tmplength}{\textbf{Description}}
\setlength{\itemindent}{0cm}
\setlength{\listparindent}{0cm}
\setlength{\leftmargin}{\evensidemargin}
\addtolength{\leftmargin}{\tmplength}
\settowidth{\labelsep}{X}
\addtolength{\leftmargin}{\labelsep}
\setlength{\labelwidth}{\tmplength}
}
\begin{flushleft}
\item[\textbf{Declaration}\hfill]
\begin{ttfamily}
public PublicField: Integer;\end{ttfamily}
\end{flushleft}
\end{list}
\subsection*{TMyPackedRecord Packed Record}
%%%%Description
\subsubsection*{\large{\textbf{Fields}}\normalsize\hspace{1ex}\hfill}
\paragraph*{PublicField}\hspace*{\fill}
\begin{list}{}{
\settowidth{\tmplength}{\textbf{Description}}
\setlength{\itemindent}{0cm}
\setlength{\listparindent}{0cm}
\setlength{\leftmargin}{\evensidemargin}
\addtolength{\leftmargin}{\tmplength}
\settowidth{\labelsep}{X}
\addtolength{\leftmargin}{\labelsep}
\setlength{\labelwidth}{\tmplength}
}
\begin{flushleft}
\item[\textbf{Declaration}\hfill]
\begin{ttfamily}
public PublicField: Integer;\end{ttfamily}
\end{flushleft}
\end{list}
\subsection*{TMyClass Class}
\subsubsection*{\large{\textbf{Hierarchy}}\normalsize\hspace{1ex}\hfill}
TMyClass {$>$} TObject
%%%%Description
\subsubsection*{\large{\textbf{Fields}}\normalsize\hspace{1ex}\hfill}
\paragraph*{PublicField}\hspace*{\fill}
\begin{list}{}{
\settowidth{\tmplength}{\textbf{Description}}
\setlength{\itemindent}{0cm}
\setlength{\listparindent}{0cm}
\setlength{\leftmargin}{\evensidemargin}
\addtolength{\leftmargin}{\tmplength}
\settowidth{\labelsep}{X}
\addtolength{\leftmargin}{\labelsep}
\setlength{\labelwidth}{\tmplength}
}
\begin{flushleft}
\item[\textbf{Declaration}\hfill]
\begin{ttfamily}
public PublicField: Integer;\end{ttfamily}
\end{flushleft}
\end{list}
\end{document}
| michaliskambi/pasdoc | tests/testcases_output/latex2rtf/ok_interface_implicit/docs.tex | TeX | gpl-2.0 | 3,460 |
package org.oguz.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class XMLServlet extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName = request.getParameter("username");
String fullName = request.getParameter("fullname");
String profession = request.getParameter("profession");
// HttpSession session =request.getSession();
ServletContext context = request.getServletContext();
if (userName != "" && userName != null)
{
// session.setAttribute("savedUser",userName);
context.setAttribute("savedUser", userName);
out.println("<p>Hello context parameter " + (String)context.getAttribute("savedUser") +
" from GET method</p>");
}
else
{
out.println("<p>Hello default user " +
this.getServletConfig().getInitParameter("username") + " from GET method</p>");
}
if (fullName != "" && fullName != null)
{
// session.setAttribute("savedFull", fullName);
context.setAttribute("savedFull", fullName);
out.println("<p> your full name is: " + (String)context.getAttribute("savedFull") +
"</p>");
}
else
{
out.println("<p>Hello default fullname " +
this.getServletConfig().getInitParameter("fullname") + " from GET method</p>");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName = request.getParameter("username");
String fullName = request.getParameter("fullname");
String profession = request.getParameter("profession");
// String location = request.getParameter("location");
String[] location = request.getParameterValues("location");
out.println("<p>Hello " + userName + " from POST method in XMLSERVLET response</p>");
out.println("<p> your full name is: " + fullName + "</p>");
out.println("<p>your profession is: " + profession + "</p>");
for (int i = 0; i < location.length; i++)
{
out.println("<p>your location is: " + location[i].toUpperCase() + "</p>");
}
}
}
| ogz00/Servlet-SimpleServletProject | src/org/oguz/servlet/XMLServlet.java | Java | gpl-2.0 | 2,759 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
<head>
<meta name="description" content="Dubstep indie music">
<meta name="keywords" content="dubstep, superman, indie, hollywood, maryland, soundtrack, a boy named su, a boy named sue, heart">
<meta name="author" content="Mike Su">
<script class="cssdeck" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<title>A Boy Named Su ♥ the SoundCloud</title>
<link type="text/css" media="screen" rel="stylesheet" href="../../slabText/css/slabtext.css">
<link rel="stylesheet" href="../css/sc-player-artwork.css" type="text/css">
<link rel="stylesheet" href="../../css/style.css" type="text/css">
<style>
@font-face
{
font-family: 'LeagueGothicRegular';
src: url('../../fonts/League_Gothic-webfont.eot');
src: url('../../fonts/League_Gothic-webfont.eot?#iefix') format('embedded-opentype'),
url('../../fonts/League_Gothic-webfont.woff') format('woff'),
url('../../fonts/League_Gothic-webfont.ttf') format('truetype'),
url('../../fonts/League_Gothic-webfont.svg#LeagueGothicRegular') format('svg');
font-weight: normal;
font-style: normal;
}
html,
body
{
background:#000;
color:#444;
}
body
{
font: 16px/1.8 "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
width:80%;
padding:20px 0;
max-width:960px;
margin:0 auto;
}
hr
{
border: 0;
height: 1px;
background-image: -webkit-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0));
background-image: -moz-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0));
background-image: -ms-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0));
background-image: -o-linear-gradient(left, rgba(0,0,0,0), rgba(0,0,0,0.75), rgba(0,0,0,0));
}
.col-1
{
width:47.5%;
margin:0 2.5% 0 0;
float:left;
}
.col-2
{
width:47.5%;
margin:0 0 0 2.5%;
float:left;
}
.col-1 p,
.col-2 p
{
color:#888;
font-size:80%;
text-align:center;
}
a
{
color:#111;
}
h1 a
{
text-decoration:none;
}
p
{
margin:0 0 1.5em 0;
line-height:1.5em;
}
dt
{
font-family:monospace;
}
pre
{
line-height:1.2;
}
footer
{
border-top:3px double #aaa;
padding-top:1em;
}
footer section
{
border-bottom:3px double #aaa;
padding-bottom:1em;
margin-bottom:1em;
}
sup a
{
text-decoration:none;
}
#h4
{
clear:both;
}
.amp
{
font-family:Baskerville,'Goudy Old Style',Palatino,'Book Antiqua',serif;
font-style:italic;
font-weight:lighter;
}
/* Set font-sizes for the headings to be given the slabText treatment */
h1
{
text-align:left;
font-family:'LeagueGothicRegular', "Impact", Charcoal, Arial Black, Gadget, Sans serif;
text-transform: uppercase;
line-height:1;
color:#222;
font-size:300%;
/* Remember to set the correct font weight if using fontface */
font-weight:normal;
}
/* Smaller font-size for the side-by-side demo */
.col-1 h1,
.col-2 h1
{
font-size: 32px;
}
h2
{
font-size: 25px;
}
/* Adjust the line-height for all headlines that have been given the
slabtext treatment. Use a unitless line-height to stop sillyness */
.slabtexted h1
{
line-height:.9;
}
/* Target specific lines in the preset Studio One demo */
.slabtexted #studio-one span:nth-child(2)
{
line-height:.8;
}
.slabtexted #studio-one span:nth-child(3)
{
line-height:1.1;
}
/* Fun with media queries - resize your browser to view changes. */
@media screen and (max-width: 960px)
{
body
{
padding:10px 0;
min-width:20em;
}
.col-1,
.col-2
{
float:none;
margin:0;
width:100%;
}
h1
{
font-size:36px;
}
h2
{
font-size:22px;
}
}
@media screen and (max-width: 460px)
{
h1
{
font-size:26px;
}
h2
{
font-size:18px;
}
}
</style> <div class="menu">
<div id="logo"><a href="/">♥</a></div>
</div>
</head>
<body>
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="menu">
<div id="logo"><a href="../../">♥</a></div>
<a href="../../album">/Album</a>
<a href="http://t.qkme.me/3st1se.jpg">ArchNemesis!</a>
<a href="http://listen.boynamedsumusic.com/">BandCamp</a>
<a href="../../covers">/Covers</a>
<a href="../../lekryptonite">/LeKryptonite</a>
<a href="../../lightshow/14hearts/155bpm"><span class="red155">/Lightshow/14♥</span></a>
<a href="http://sudocoda.com">RillyThickGlasses</a>
<a href="../../soundcloud/heart" class="active">/SoundCloud/♥</a>
<a href="../../album/heart/exit-music-for-a-hollywood-movie"><h1 style="padding:3px;">Exit</h1></a>
</div>
<div class="social">
<div class="footer-social"><a href="http://facebook.com/boynamedsumusic" target="_blank"><img src="../../images/footer_facebook.png" alt=""></a></div>
<div class="footer-social"><a href="http://twitter.com/boynamedsumusic" target="_blank"><img src="../../images/footer_twitter.png" alt=""></a></div>
<div class="footer-social"><a href="http://plus.google.com/u/3/109615451595602898651/" target="_blank"><img src="../../images/footer_google.png" alt=""></a></div>
</div>
<div class="fb-like" data-href="http://boynamedsumusic.com/soundcloud/heart" data-send="true" data-width="450" data-show-faces="true" data-font="lucida grande" data-colorscheme="dark"></div>
<a href="https://twitter.com/share" class="twitter-share-button" data-via="boynamedsumusic">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script>
<h1>I ♥ the SoundCloud. It was twue WubWubWub at first listen!</h1>
<div class="post">
<div class="sc-player">
<a href="http://soundcloud.com/aboynamedsu/sets/heart" class="sc-player">Heart</a>
</div>
</div>
<script type="text/javascript">
$(function(){
var menu = $('.menu'),
a = menu.find('a');
a.wrapInner($('<span />'));
a.each(function(){
var t = $(this), span = t.find('span');
for (i=0;i<2;i++){
span.clone().appendTo(t);
}
});
a.hover(function(){
var t = $(this), s = t.siblings('a');
t.toggleClass('shadow');
s.toggleClass('blur');
});
$(a[0]).delay(500).queue(function(n) {
$(this).mouseenter();
n();
});
$(a[0]).delay(500).queue(function(n) {
$(this).mouseleave();
n();
});
});
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="../js/soundcloud.player.api.js"></script>
<script type="text/javascript" src="../js/sc-player.js"></script>
</body>
</html> | sudocoda/boynamedsumusic.com | soundcloud/heart/index.html | HTML | gpl-2.0 | 9,572 |
// **********************************************************************
//
// Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************
#ifndef ICEGRID_ADMINSESSIONI_H
#define ICEGRID_ADMINSESSIONI_H
#include <IceGrid/SessionI.h>
#include <IceGrid/Topics.h>
#include <IceGrid/ReapThread.h>
#include <IceGrid/Internal.h>
namespace IceGrid
{
class RegistryI;
typedef IceUtil::Handle<RegistryI> RegistryIPtr;
class FileIteratorI;
typedef IceUtil::Handle<FileIteratorI> FileIteratorIPtr;
class AdminSessionI : public BaseSessionI, public AdminSession
{
public:
AdminSessionI(const std::string&, const DatabasePtr&, int, const RegistryIPtr&);
virtual ~AdminSessionI();
Ice::ObjectPrx _register(const SessionServantManagerPtr&, const Ice::ConnectionPtr&);
virtual void keepAlive(const Ice::Current& current) { BaseSessionI::keepAlive(current); }
virtual AdminPrx getAdmin(const Ice::Current&) const;
virtual Ice::ObjectPrx getAdminCallbackTemplate(const Ice::Current&) const;
virtual void setObservers(const RegistryObserverPrx&, const NodeObserverPrx&, const ApplicationObserverPrx&,
const AdapterObserverPrx&, const ObjectObserverPrx&, const Ice::Current&);
virtual void setObserversByIdentity(const Ice::Identity&, const Ice::Identity&, const Ice::Identity&,
const Ice::Identity&, const Ice::Identity&, const Ice::Current&);
virtual int startUpdate(const Ice::Current&);
virtual void finishUpdate(const Ice::Current&);
virtual std::string getReplicaName(const Ice::Current&) const;
virtual FileIteratorPrx openServerLog(const std::string&, const std::string&, int, const Ice::Current&);
virtual FileIteratorPrx openServerStdOut(const std::string&, int, const Ice::Current&);
virtual FileIteratorPrx openServerStdErr(const std::string&, int, const Ice::Current&);
virtual FileIteratorPrx openNodeStdOut(const std::string&, int, const Ice::Current&);
virtual FileIteratorPrx openNodeStdErr(const std::string&, int, const Ice::Current&);
virtual FileIteratorPrx openRegistryStdOut(const std::string&, int, const Ice::Current&);
virtual FileIteratorPrx openRegistryStdErr(const std::string&, int, const Ice::Current&);
virtual void destroy(const Ice::Current&);
void removeFileIterator(const Ice::Identity&, const Ice::Current&);
private:
void setupObserverSubscription(TopicName, const Ice::ObjectPrx&, bool = false);
Ice::ObjectPrx addForwarder(const Ice::Identity&, const Ice::Current&);
Ice::ObjectPrx addForwarder(const Ice::ObjectPrx&);
FileIteratorPrx addFileIterator(const FileReaderPrx&, const std::string&, int, const Ice::Current&);
virtual void destroyImpl(bool);
const int _timeout;
const std::string _replicaName;
AdminPrx _admin;
std::map<TopicName, std::pair<Ice::ObjectPrx, bool> > _observers;
RegistryIPtr _registry;
Ice::ObjectPrx _adminCallbackTemplate;
};
typedef IceUtil::Handle<AdminSessionI> AdminSessionIPtr;
class AdminSessionFactory : public virtual IceUtil::Shared
{
public:
AdminSessionFactory(const SessionServantManagerPtr&, const DatabasePtr&, const ReapThreadPtr&, const RegistryIPtr&);
Glacier2::SessionPrx createGlacier2Session(const std::string&, const Glacier2::SessionControlPrx&);
AdminSessionIPtr createSessionServant(const std::string&);
const TraceLevelsPtr& getTraceLevels() const;
private:
const SessionServantManagerPtr _servantManager;
const DatabasePtr _database;
const int _timeout;
const ReapThreadPtr _reaper;
const RegistryIPtr _registry;
const bool _filters;
};
typedef IceUtil::Handle<AdminSessionFactory> AdminSessionFactoryPtr;
class AdminSessionManagerI : public virtual Glacier2::SessionManager
{
public:
AdminSessionManagerI(const AdminSessionFactoryPtr&);
virtual Glacier2::SessionPrx create(const std::string&, const Glacier2::SessionControlPrx&, const Ice::Current&);
private:
const AdminSessionFactoryPtr _factory;
};
class AdminSSLSessionManagerI : public virtual Glacier2::SSLSessionManager
{
public:
AdminSSLSessionManagerI(const AdminSessionFactoryPtr&);
virtual Glacier2::SessionPrx create(const Glacier2::SSLInfo&, const Glacier2::SessionControlPrx&,
const Ice::Current&);
private:
const AdminSessionFactoryPtr _factory;
};
class FileIteratorI : public FileIterator
{
public:
FileIteratorI(const AdminSessionIPtr&, const FileReaderPrx&, const std::string&, Ice::Long, int);
virtual bool read(int, Ice::StringSeq&, const Ice::Current&);
virtual void destroy(const Ice::Current&);
private:
const AdminSessionIPtr _session;
const FileReaderPrx _reader;
const std::string _filename;
Ice::Long _offset;
const int _messageSizeMax;
};
};
#endif
| ljx0305/ice | cpp/src/IceGrid/AdminSessionI.h | C | gpl-2.0 | 5,095 |
---
layout: default
---
 <div class="container blog-container"><h3 class="less-space-top">The Sinfonia Solutions Blog</h3><div class="jumbotron people"><p><em>{{ page.date | date_to_string }}</em></p><h1>{{page.title}}</h1></div><div class="row"><div class="col-sm-8 post-content">{{ content }}</div><div class="col-sm-4"><h3>Recent Posts</h3>{% for post in site.posts limit:8 %}<div class="top-thick-border"><p>{{post.date | date_to_long_string}}</p><h4 class="less-space-top">{{ post.title }}</h4><p>{{ post.description }}</p><a href="{{ post.url }}">Read More</a><div class="spacer-s"></div></div>{% endfor %}</div></div></div> | sinfoniasolutions/sinfoniasolutions.github.io | _layouts/post.html | HTML | gpl-2.0 | 634 |
package fr.npellegrin.xebia.mower.parser.model;
/**
* Parsed position.
*/
public class PositionDefinition {
private int x;
private int y;
private OrientationDefinition orientation;
public int getX() {
return x;
}
public void setX(final int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(final int y) {
this.y = y;
}
public OrientationDefinition getOrientation() {
return orientation;
}
public void setOrientation(final OrientationDefinition orientation) {
this.orientation = orientation;
}
}
| npellegrin/MowItNow | src/main/java/fr/npellegrin/xebia/mower/parser/model/PositionDefinition.java | Java | gpl-2.0 | 550 |
#============================================================= -*-Perl-*-
#
# Pod::POM::Constants
#
# DESCRIPTION
# Constants used by Pod::POM.
#
# AUTHOR
# Andy Wardley <[email protected]>
# Andrew Ford <[email protected]>
#
# COPYRIGHT
# Copyright (C) 2000, 2001 Andy Wardley. All Rights Reserved.
# Copyright (C) 2009 Andrew Ford. All Rights Reserved.
#
# This module is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#
# REVISION
# $Id: Constants.pm 89 2013-05-30 07:41:52Z ford $
#
#========================================================================
package Pod::POM::Constants;
$Pod::POM::Constants::VERSION = '2.00';
require 5.006;
use strict;
use warnings;
use parent qw( Exporter );
our @SEQUENCE = qw( CMD LPAREN RPAREN FILE LINE CONTENT );
our @STATUS = qw( IGNORE REDUCE REJECT );
our @EXPORT_OK = ( @SEQUENCE, @STATUS );
our %EXPORT_TAGS = (
status => [ @STATUS ],
seq => [ @SEQUENCE ],
all => [ @STATUS, @SEQUENCE ],
);
# sequence items
use constant CMD => 0;
use constant LPAREN => 1;
use constant RPAREN => 2;
use constant FILE => 3;
use constant LINE => 4;
use constant CONTENT => 5;
# node add return values
use constant IGNORE => 0;
use constant REDUCE => 1;
use constant REJECT => 2;
1;
=head1 NAME
Pod::POM::Constants
=head1 DESCRIPTION
Constants used by Pod::POM.
=head1 AUTHOR
Andy Wardley E<lt>[email protected]<gt>
Andrew Ford E<lt>[email protected]<gt>
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2000, 2001 Andy Wardley. All Rights Reserved.
Copyright (C) 2009 Andrew Ford. All Rights Reserved.
This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=cut
| mishin/dwimperl-windows | strawberry-perl-5.20.0.1-32bit-portable/perl/site/lib/Pod/POM/Constants.pm | Perl | gpl-2.0 | 1,772 |
#!/usr/bin/env python3
import sys
import numpy as np
from spc import SPC
import matplotlib.pyplot as plt
def plot(files, fac=1.0):
for f in files:
if f.split('.')[-1] == 'xy':
td = np.loadtxt(f)
plt.plot(td[:, 0], np.log(1. / td[:, 1]) * fac, label=f)
elif f.split('.')[-1] == 'spc':
td = SPC(f)
plt.plot(td.xdata, np.log(1. / np.array(td.ydata)), label=f)
plt.legend()
plt.show()
if __name__ == '__main__':
files = sys.argv[2:]
fac = float(sys.argv[1])
plot(files, fac)
| JHeimdal/HalIR | Test/plotf.py | Python | gpl-2.0 | 564 |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\CanonVRD;
use PHPExiftool\Driver\AbstractTag;
class LandscapeRawContrast extends AbstractTag
{
protected $Id = 33;
protected $Name = 'LandscapeRawContrast';
protected $FullName = 'CanonVRD::Ver2';
protected $GroupName = 'CanonVRD';
protected $g0 = 'CanonVRD';
protected $g1 = 'CanonVRD';
protected $g2 = 'Image';
protected $Type = 'int16s';
protected $Writable = true;
protected $Description = 'Landscape Raw Contrast';
}
| Droces/casabio | vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/CanonVRD/LandscapeRawContrast.php | PHP | gpl-2.0 | 739 |
/****************************************************************************
**
** This file is part of the Qtopia Opensource Edition Package.
**
** Copyright (C) 2008 Trolltech ASA.
**
** Contact: Qt Extended Information ([email protected])
**
** This file may be used under the terms of the GNU General Public License
** versions 2.0 as published by the Free Software Foundation and appearing
** in the file LICENSE.GPL included in the packaging of this file.
**
** Please review the following information to ensure GNU General Public
** Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html.
**
**
****************************************************************************/
#include <qtopia/private/qmimetypedata_p.h>
#include <qtopia/private/drmcontent_p.h>
#include <QApplication>
#include <QtDebug>
Q_GLOBAL_STATIC_WITH_ARGS(QIcon,unknownDocumentIcon,(QLatin1String(":image/qpe/UnknownDocument")));
Q_GLOBAL_STATIC_WITH_ARGS(QIcon,validDrmUnknownDocumentIcon,(DrmContentPrivate::createIcon(
*unknownDocumentIcon(),
qApp->style()->pixelMetric( QStyle::PM_ListViewIconSize ),
qApp->style()->pixelMetric( QStyle::PM_LargeIconSize ),
true )));
Q_GLOBAL_STATIC_WITH_ARGS(QIcon,invalidDrmUnknownDocumentIcon,(DrmContentPrivate::createIcon(
*unknownDocumentIcon(),
qApp->style()->pixelMetric( QStyle::PM_ListViewIconSize ),
qApp->style()->pixelMetric( QStyle::PM_LargeIconSize ),
false )));
class QMimeTypeDataPrivate : public QSharedData
{
public:
struct AppData
{
QContent application;
QString iconFile;
QIcon icon;
QIcon validDrmIcon;
QIcon invalidDrmIcon;
QDrmRights::Permission permission;
bool iconLoaded;
bool validDrmIconLoaded;
bool invalidDrmIconLoaded;
};
QMimeTypeDataPrivate()
{
}
~QMimeTypeDataPrivate()
{
qDeleteAll( applicationData.values() );
}
QString id;
QContentList applications;
QContent defaultApplication;
QMap< QContentId, AppData * > applicationData;
void loadIcon( AppData *data ) const;
void loadValidDrmIcon( AppData *data ) const;
void loadInvalidDrmIcon( AppData *data ) const;
};
void QMimeTypeDataPrivate::loadIcon( AppData *data ) const
{
if( !data->iconFile.isEmpty() )
data->icon = QIcon( QLatin1String( ":icon/" ) + data->iconFile );
data->iconLoaded = true;
}
void QMimeTypeDataPrivate::loadValidDrmIcon( AppData *data ) const
{
if( !data->icon.isNull() )
data->validDrmIcon = DrmContentPrivate::createIcon(
data->icon,
qApp->style()->pixelMetric( QStyle::PM_ListViewIconSize ),
qApp->style()->pixelMetric( QStyle::PM_LargeIconSize ),
true );
data->validDrmIconLoaded = true;
}
void QMimeTypeDataPrivate::loadInvalidDrmIcon( AppData *data ) const
{
if( !data->icon.isNull() )
data->invalidDrmIcon = DrmContentPrivate::createIcon(
data->icon,
qApp->style()->pixelMetric( QStyle::PM_ListViewIconSize ),
qApp->style()->pixelMetric( QStyle::PM_LargeIconSize ),
false );
data->invalidDrmIconLoaded = true;
}
Q_GLOBAL_STATIC_WITH_ARGS(QSharedDataPointer<QMimeTypeDataPrivate>,nullQMimeTypeDataPrivate,(new QMimeTypeDataPrivate));
QMimeTypeData::QMimeTypeData()
{
d = *nullQMimeTypeDataPrivate();
}
QMimeTypeData::QMimeTypeData( const QString &id )
{
if( !id.isEmpty() )
{
d = new QMimeTypeDataPrivate;
d->id = id;
}
else
d = *nullQMimeTypeDataPrivate();
}
QMimeTypeData::QMimeTypeData( const QMimeTypeData &other )
: d( other.d )
{
}
QMimeTypeData::~QMimeTypeData()
{
}
QMimeTypeData &QMimeTypeData::operator =( const QMimeTypeData &other )
{
d = other.d;
return *this;
}
bool QMimeTypeData::operator ==( const QMimeTypeData &other )
{
return d->id == other.d->id;
}
QString QMimeTypeData::id() const
{
return d->id;
}
QContentList QMimeTypeData::applications() const
{
return d->applications;
}
QContent QMimeTypeData::defaultApplication() const
{
return d->defaultApplication;
}
QIcon QMimeTypeData::icon( const QContent &application ) const
{
if( d->applicationData.contains( application.id() ) )
{
const QMimeTypeDataPrivate::AppData *data = d->applicationData.value( application.id() );
if( !data->iconLoaded )
d->loadIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) );
return !data->icon.isNull() ? data->icon : data->application.icon();
}
else
return *unknownDocumentIcon();
}
QIcon QMimeTypeData::validDrmIcon( const QContent &application ) const
{
if( d->applicationData.contains( application.id() ) )
{
const QMimeTypeDataPrivate::AppData *data = d->applicationData.value( application.id() );
if( !data->iconLoaded )
d->loadIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) );
if( !data->validDrmIconLoaded )
d->loadValidDrmIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) );
return !data->validDrmIcon.isNull() ? data->validDrmIcon : data->application.icon();
}
else
return *validDrmUnknownDocumentIcon();
}
QIcon QMimeTypeData::invalidDrmIcon( const QContent &application ) const
{
if( d->applicationData.contains( application.id() ) )
{
const QMimeTypeDataPrivate::AppData *data = d->applicationData.value( application.id() );
if( !data->iconLoaded )
d->loadIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) );
if( !data->invalidDrmIconLoaded )
d->loadInvalidDrmIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) );
return !data->invalidDrmIcon.isNull() ? data->invalidDrmIcon : data->application.icon();
}
else
return *invalidDrmUnknownDocumentIcon();
}
QDrmRights::Permission QMimeTypeData::permission( const QContent &application ) const
{
if( d->applicationData.contains( application.id() ) )
{
const QMimeTypeDataPrivate::AppData *data = d->applicationData.value( application.id() );
return data->permission;
}
else
return QDrmRights::Unrestricted;
}
void QMimeTypeData::addApplication( const QContent &application, const QString &iconFile, QDrmRights::Permission permission )
{
if( application.id() != QContent::InvalidId && !d->applicationData.contains( application.id() ) )
{
QMimeTypeDataPrivate::AppData *data = new QMimeTypeDataPrivate::AppData;
data->application = application;
data->iconFile = iconFile;
data->permission = permission;
data->iconLoaded = false;
data->validDrmIconLoaded = false;
data->invalidDrmIconLoaded = false;
d->applicationData.insert( application.id(), data );
d->applications.append( application );
if(d->defaultApplication.id() == QContent::InvalidId)
setDefaultApplication(application);
}
}
void QMimeTypeData::removeApplication( const QContent &application )
{
if(d->applicationData.contains( application.id() ))
{
delete d->applicationData.take(application.id());
d->applications.removeAll(application);
}
}
void QMimeTypeData::setDefaultApplication( const QContent &application )
{
if(application.id() != QContent::InvalidId)
d->defaultApplication = application;
}
template <typename Stream> void QMimeTypeData::serialize(Stream &stream) const
{
stream << d->id;
stream << d->defaultApplication.id();
stream << d->applicationData.count();
QList< QContentId > keys = d->applicationData.keys();
foreach( QContentId contentId, keys )
{
QMimeTypeDataPrivate::AppData *data = d->applicationData.value( contentId );
stream << contentId;
stream << data->iconFile;
stream << data->permission;
}
}
template <typename Stream> void QMimeTypeData::deserialize(Stream &stream)
{
qDeleteAll( d->applicationData.values() );
d->applicationData.clear();
stream >> d->id;
{
QContentId contentId;
stream >> contentId;
d->defaultApplication = QContent( contentId );
}
int count;
stream >> count;
for( int i = 0; i < count; i++ )
{
QContentId contentId;
QString iconFile;
QDrmRights::Permission permission;
stream >> contentId;
stream >> iconFile;
stream >> permission;
addApplication( QContent( contentId ), iconFile, permission );
}
}
Q_IMPLEMENT_USER_METATYPE(QMimeTypeData);
| muromec/qtopia-ezx | src/libraries/qtopia/qmimetypedata.cpp | C++ | gpl-2.0 | 8,816 |
/* frame_data.c
* Routines for packet disassembly
*
* $Id$
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
#include <glib.h>
#include <wiretap/wtap.h>
#include <epan/frame_data.h>
#include <epan/packet.h>
#include <epan/emem.h>
#include <epan/timestamp.h>
/* Protocol-specific data attached to a frame_data structure - protocol
index and opaque pointer. */
typedef struct _frame_proto_data {
int proto;
void *proto_data;
} frame_proto_data;
/* XXX - I declared this static, because it only seems to be used by
* p_get_proto_data and p_add_proto_data
*/
static gint
p_compare(gconstpointer a, gconstpointer b)
{
const frame_proto_data *ap = (const frame_proto_data *)a;
const frame_proto_data *bp = (const frame_proto_data *)b;
if (ap -> proto > bp -> proto)
return 1;
else if (ap -> proto == bp -> proto)
return 0;
else
return -1;
}
void
p_add_proto_data(frame_data *fd, int proto, void *proto_data)
{
frame_proto_data *p1 = se_alloc(sizeof(frame_proto_data));
p1->proto = proto;
p1->proto_data = proto_data;
/* Add it to the GSLIST */
fd -> pfd = g_slist_insert_sorted(fd -> pfd,
(gpointer *)p1,
p_compare);
}
void *
p_get_proto_data(frame_data *fd, int proto)
{
frame_proto_data temp, *p1;
GSList *item;
temp.proto = proto;
temp.proto_data = NULL;
item = g_slist_find_custom(fd->pfd, (gpointer *)&temp, p_compare);
if (item) {
p1 = (frame_proto_data *)item->data;
return p1->proto_data;
}
return NULL;
}
void
p_remove_proto_data(frame_data *fd, int proto)
{
frame_proto_data temp;
GSList *item;
temp.proto = proto;
temp.proto_data = NULL;
item = g_slist_find_custom(fd->pfd, (gpointer *)&temp, p_compare);
if (item) {
fd->pfd = g_slist_remove(fd->pfd, item->data);
}
}
#define COMPARE_FRAME_NUM() ((fdata1->num < fdata2->num) ? -1 : \
(fdata1->num > fdata2->num) ? 1 : \
0)
#define COMPARE_NUM(f) ((fdata1->f < fdata2->f) ? -1 : \
(fdata1->f > fdata2->f) ? 1 : \
COMPARE_FRAME_NUM())
/* Compare time stamps.
A packet whose time is a reference time is considered to have
a lower time stamp than any frame with a non-reference time;
if both packets' times are reference times, we compare the
times of the packets. */
#define COMPARE_TS_REAL(time1, time2) \
((fdata1->flags.ref_time && !fdata2->flags.ref_time) ? -1 : \
(!fdata1->flags.ref_time && fdata2->flags.ref_time) ? 1 : \
((time1).secs < (time2).secs) ? -1 : \
((time1).secs > (time2).secs) ? 1 : \
((time1).nsecs < (time2).nsecs) ? -1 :\
((time1).nsecs > (time2).nsecs) ? 1 : \
COMPARE_FRAME_NUM())
#define COMPARE_TS(ts) COMPARE_TS_REAL(fdata1->ts, fdata2->ts)
void
frame_delta_abs_time(const frame_data *fdata, const frame_data *prev, nstime_t *delta)
{
if (prev) {
nstime_delta(delta, &fdata->abs_ts, &prev->abs_ts);
} else {
/* If we don't have the time stamp of the previous packet,
it's because we have no displayed/captured packets prior to this.
Set the delta time to zero. */
nstime_set_zero(delta);
}
}
static gint
frame_data_time_delta_compare(const frame_data *fdata1, const frame_data *fdata2)
{
nstime_t del_cap_ts1, del_cap_ts2;
frame_delta_abs_time(fdata1, fdata1->prev_cap, &del_cap_ts1);
frame_delta_abs_time(fdata2, fdata2->prev_cap, &del_cap_ts2);
return COMPARE_TS_REAL(del_cap_ts1, del_cap_ts2);
}
static gint
frame_data_time_delta_dis_compare(const frame_data *fdata1, const frame_data *fdata2)
{
nstime_t del_dis_ts1, del_dis_ts2;
frame_delta_abs_time(fdata1, fdata1->prev_dis, &del_dis_ts1);
frame_delta_abs_time(fdata2, fdata2->prev_dis, &del_dis_ts2);
return COMPARE_TS_REAL(del_dis_ts1, del_dis_ts2);
}
gint
frame_data_compare(const frame_data *fdata1, const frame_data *fdata2, int field)
{
switch (field) {
case COL_NUMBER:
return COMPARE_FRAME_NUM();
case COL_CLS_TIME:
switch (timestamp_get_type()) {
case TS_ABSOLUTE:
case TS_ABSOLUTE_WITH_DATE:
case TS_UTC:
case TS_UTC_WITH_DATE:
case TS_EPOCH:
return COMPARE_TS(abs_ts);
case TS_RELATIVE:
return COMPARE_TS(rel_ts);
case TS_DELTA:
return frame_data_time_delta_compare(fdata1, fdata2);
case TS_DELTA_DIS:
return frame_data_time_delta_dis_compare(fdata1, fdata2);
case TS_NOT_SET:
return 0;
}
return 0;
case COL_ABS_TIME:
case COL_ABS_DATE_TIME:
case COL_UTC_TIME:
case COL_UTC_DATE_TIME:
return COMPARE_TS(abs_ts);
case COL_REL_TIME:
return COMPARE_TS(rel_ts);
case COL_DELTA_TIME:
return frame_data_time_delta_compare(fdata1, fdata2);
case COL_DELTA_TIME_DIS:
return frame_data_time_delta_dis_compare(fdata1, fdata2);
case COL_PACKET_LENGTH:
return COMPARE_NUM(pkt_len);
case COL_CUMULATIVE_BYTES:
return COMPARE_NUM(cum_bytes);
}
g_return_val_if_reached(0);
}
void
frame_data_init(frame_data *fdata, guint32 num,
const struct wtap_pkthdr *phdr, gint64 offset,
guint32 cum_bytes)
{
fdata->pfd = NULL;
fdata->num = num;
fdata->interface_id = phdr->interface_id;
fdata->pkt_len = phdr->len;
fdata->cum_bytes = cum_bytes + phdr->len;
fdata->cap_len = phdr->caplen;
fdata->file_off = offset;
fdata->subnum = 0;
/* To save some memory, we coerce it into a gint16 */
g_assert(phdr->pkt_encap <= G_MAXINT16);
fdata->lnk_t = (gint16) phdr->pkt_encap;
fdata->flags.passed_dfilter = 0;
fdata->flags.dependent_of_displayed = 0;
fdata->flags.encoding = PACKET_CHAR_ENC_CHAR_ASCII;
fdata->flags.visited = 0;
fdata->flags.marked = 0;
fdata->flags.ref_time = 0;
fdata->flags.ignored = 0;
fdata->flags.has_ts = (phdr->presence_flags & WTAP_HAS_TS) ? 1 : 0;
fdata->flags.has_if_id = (phdr->presence_flags & WTAP_HAS_INTERFACE_ID) ? 1 : 0;
fdata->color_filter = NULL;
fdata->abs_ts.secs = phdr->ts.secs;
fdata->abs_ts.nsecs = phdr->ts.nsecs;
fdata->shift_offset.secs = 0;
fdata->shift_offset.nsecs = 0;
fdata->rel_ts.secs = 0;
fdata->rel_ts.nsecs = 0;
fdata->prev_dis = NULL;
fdata->prev_cap = NULL;
fdata->opt_comment = phdr->opt_comment;
}
void
frame_data_set_before_dissect(frame_data *fdata,
nstime_t *elapsed_time,
nstime_t *first_ts,
const frame_data *prev_dis,
const frame_data *prev_cap)
{
/* If we don't have the time stamp of the first packet in the
capture, it's because this is the first packet. Save the time
stamp of this packet as the time stamp of the first packet. */
if (nstime_is_unset(first_ts))
*first_ts = fdata->abs_ts;
/* if this frames is marked as a reference time frame, reset
firstsec and firstusec to this frame */
if(fdata->flags.ref_time)
*first_ts = fdata->abs_ts;
/* Get the time elapsed between the first packet and this packet. */
nstime_delta(&fdata->rel_ts, &fdata->abs_ts, first_ts);
/* If it's greater than the current elapsed time, set the elapsed time
to it (we check for "greater than" so as not to be confused by
time moving backwards). */
if ((gint32)elapsed_time->secs < fdata->rel_ts.secs
|| ((gint32)elapsed_time->secs == fdata->rel_ts.secs && (gint32)elapsed_time->nsecs < fdata->rel_ts.nsecs)) {
*elapsed_time = fdata->rel_ts;
}
fdata->prev_dis = prev_dis;
fdata->prev_cap = prev_cap;
}
void
frame_data_set_after_dissect(frame_data *fdata,
guint32 *cum_bytes)
{
/* This frame either passed the display filter list or is marked as
a time reference frame. All time reference frames are displayed
even if they dont pass the display filter */
if(fdata->flags.ref_time){
/* if this was a TIME REF frame we should reset the cul bytes field */
*cum_bytes = fdata->pkt_len;
fdata->cum_bytes = *cum_bytes;
} else {
/* increase cum_bytes with this packets length */
*cum_bytes += fdata->pkt_len;
fdata->cum_bytes = *cum_bytes;
}
}
void
frame_data_cleanup(frame_data *fdata)
{
if (fdata->pfd) {
g_slist_free(fdata->pfd);
fdata->pfd = NULL;
}
/* XXX, frame_data_cleanup() is called when redissecting (rescan_packets()),
* which might be triggered by lot of things, like: preferences change,
* setting manual address resolve, etc.. (grep by redissect_packets)
* fdata->opt_comment can be set by user, which we must not discard when redissecting.
*/
#if 0
if (fdata->opt_comment) {
g_free(fdata->opt_comment);
fdata->opt_comment = NULL;
}
#endif
}
| sstjohn/wireshark | epan/frame_data.c | C | gpl-2.0 | 9,594 |
package org.iproduct.iptpi.domain.movement;
import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.Math.atan;
import static java.lang.Math.cbrt;
import static java.lang.Math.cos;
import static java.lang.Math.hypot;
import static java.lang.Math.min;
import static java.lang.Math.pow;
import static java.lang.Math.signum;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.iproduct.iptpi.demo.robot.RobotParametrs.MAIN_AXE_LENGTH;
import static org.iproduct.iptpi.demo.robot.RobotParametrs.MAX_ROBOT_ANGULAR_ACCELERATION;
import static org.iproduct.iptpi.demo.robot.RobotParametrs.MAX_ROBOT_LINEAR_ACCELERATION;
import static org.iproduct.iptpi.demo.robot.RobotParametrs.MAX_ROBOT_LINEAR_VELOCITY;
import static org.iproduct.iptpi.demo.robot.RobotParametrs.ROBOT_STOPPING_DECCELERATION;
import static org.iproduct.iptpi.demo.robot.RobotParametrs.WHEEL_RADIUS;
import static org.iproduct.iptpi.domain.CommandName.STOP;
import static org.iproduct.iptpi.domain.CommandName.VOID;
import org.iproduct.iptpi.domain.Command;
import org.iproduct.iptpi.domain.arduino.LineReadings;
import org.iproduct.iptpi.domain.audio.AudioPlayer;
import org.iproduct.iptpi.domain.position.Position;
import org.iproduct.iptpi.domain.position.PositionsFlux;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import com.pi4j.wiringpi.Gpio;
import reactor.core.publisher.EmitterProcessor;
import reactor.core.publisher.Flux;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuple3;
import reactor.util.function.Tuple4;
import reactor.util.function.Tuples;
public class MovementCommandSubscriber implements Subscriber<Command> {
public static final int MAX_SPEED = 1024;
public static final int CLOCK_DIVISOR = 2;
public static final double LANDING_CURVE_PARAMETER = 0.000000005;
public static final MotorsCommand STOP_COMMAND = new MotorsCommand(0, 0, 0, 0, 0);
private Subscription subscription;
private PositionsFlux positions;
private Flux<LineReadings> lineReadings;
// private SchedulerGroup eventLoops = SchedulerGroup.async();
//Create movement command broadcaster
private EmitterProcessor<Command> commandFlux = EmitterProcessor.create();
public MovementCommandSubscriber(PositionsFlux positions, Flux<LineReadings> lineReadings) {
this.positions = positions;
this.lineReadings = lineReadings;
}
@Override
public void onNext(Command command) {
setupGpioForMovement();
switch (command.getName()) {
case MOVE_FORWARD : moveForward(command); break;
case FOLLOW_LINE : followLine(command); break;
case MOVE_RELATIVE : moveRelative(command); break;
case STOP :
System.out.println("STOPPING THE ROBOT");
runMotors(STOP_COMMAND);
break;
default:
break;
}
}
protected void moveRelative(Command command) {
RelativeMovement relMove = (RelativeMovement) command.getData();
// start moving - and think later as it comes :)
int directionL, directionR;
if(relMove.getVelocity() < 0) {
directionL = directionR = -1;
} else {
directionL = directionR = 1;
}
double targetVelocity = abs(relMove.getVelocity());
int velocity = (int)(MAX_SPEED * targetVelocity / MAX_ROBOT_LINEAR_VELOCITY); // 50 mm/s max
MotorsCommand initialCommand = new MotorsCommand(directionL, directionR, velocity, velocity, Long.MAX_VALUE); //distance still unknown
System.out.println(initialCommand);
runMotors(initialCommand);
Position startPos = positions.elementAt(1).block();
double targetDeltaX = relMove.getDeltaX();
double targetDeltaY = relMove.getDeltaY();
double targetX = startPos.getX() + targetDeltaX;
double targetY = startPos.getY() + targetDeltaY;
double distance = hypot(targetDeltaX, targetDeltaY);
System.out.println("$$$$$$$$$$$$$$ TargetX=" + targetX );
System.out.println("$$$$$$$$$$$$$$ TargetY=" + targetY );
System.out.println("$$$$$$$$$$$$$$ Target Distance=" + distance);
double targetHeading, targetDeltaHeading, targetCurvature, h = 0;
if(relMove.getDeltaHeading() == 0 ) {
targetCurvature = targetDeltaHeading = 0;
targetHeading = startPos.getHeading();
} else {
targetDeltaHeading = relMove.getDeltaHeading();
targetHeading = startPos.getHeading() + targetDeltaHeading ;
targetCurvature = (2 * sin(targetDeltaHeading / 2) ) / distance ;
h = sqrt( 1/(targetCurvature * targetCurvature) - 0.25 * distance * distance );
}
double xC, yC; //circle center coordinates
double r = hypot(distance/2, h);
if(targetCurvature != 0) {
double q = hypot( targetX - startPos.getX(), targetY - startPos.getY() ),
x3 = (targetX + startPos.getX()) /2,
y3 = (targetY + startPos.getY()) /2;
if(targetCurvature > 0) {
xC = x3 + sqrt(r*r - (q*q/4)) * (startPos.getY() - targetY)/q;
yC = y3 + sqrt(r*r - (q*q/4)) * (targetX - startPos.getX() )/q;
} else {
xC = x3 - sqrt(r*r - (q*q/4)) * (startPos.getY() - targetY)/q;
yC = y3 - sqrt(r*r - (q*q/4)) * (targetX - startPos.getX() )/q;
}
} else {
xC = (targetX + startPos.getX()) /2;
yC = (targetY + startPos.getY()) /2;
}
System.out.println("$$$$$$$$$$$$$$ TargetHeading=" + targetHeading );
System.out.println("$$$$$$$$$$$$$$ TargetCurvature=" + targetCurvature );
double targetAngularVelocity;
if (targetDeltaHeading != 0 && relMove.getAngularVelocity() == 0)
targetAngularVelocity = targetVelocity * targetCurvature;
else
targetAngularVelocity = relMove.getAngularVelocity();
double startH = startPos.getHeading();
System.out.println("START POSITION: " + startPos);
Flux<Position> skip1 = positions.skip(1);
Flux.zip(positions, skip1)
.scan(initialCommand, (last, tupple) -> {
Position prevPos = ((Position)tupple.getT1());
Position currPos = ((Position)tupple.getT2());
float prevX = prevPos.getX();
float prevY = prevPos.getY();
double prevH = prevPos.getHeading();
float currX = currPos.getX();
float currY = currPos.getY();
double currH = currPos.getHeading();
System.out.println(currPos + " - " + prevPos);
double dt = (currPos.getTimestamp() - prevPos.getTimestamp()) / 1000.0; //delta time in seconds between position redings
if(dt <= 0) return last; // if invalid sequence do nothing
double time = (currPos.getTimestamp() - startPos.getTimestamp()) /1000.0;
// calculating the ideal trajectory position
double tarX, tarY, tarH, remainingPathLength;
if(targetCurvature == 0) {
tarX = startPos.getX() + targetVelocity * time * cos(targetHeading);
tarY = startPos.getY() + targetVelocity * time * sin(targetHeading);
remainingPathLength = hypot(targetX - currX, targetY - currY) ;
tarH = targetHeading;
} else {
double deltaHeading = targetAngularVelocity * time;
double startAng = atan((startPos.getY() - yC) / (startPos.getX() - xC));
double angle = startAng + deltaHeading;
if(signum(angle) != (startPos.getY() - yC))
angle -= PI;
tarX = cos(angle) * r + xC;
tarY = sin(angle) * r + yC;
tarH = startPos.getHeading() + deltaHeading;
remainingPathLength = (targetDeltaHeading - deltaHeading ) / targetCurvature;
// System.out.println(" -----> tarX=" + tarX + ", tarY=" + tarY + ", tarH=" + tarH + ", deltaHeading=" + deltaHeading + ", startAng=" + startAng + ", angle=" + angle);
// System.out.println(" -----> r=" + r + ", xC=" + xC + ", yC=" + yC );
}
//calculating current trajectory parameters
float dX = currX - prevX;
float dY = currY - prevY;
double currDist = hypot(dX, dY);
double currV = currDist / dt; // current velocity [mm/s]
double currAngV = (currH - prevH) / dt;
//calculating errors
double errX = (tarX - currX) * cos(tarH) + (tarY - currY) + sin(tarH);
double errY = (tarX - currX) * sin(tarH) + (tarY - currY) + cos(tarH);
double errH = tarH - currH;
//calculating landing curve
double Cx = LANDING_CURVE_PARAMETER;
double dlandY = 3 * Cx * pow(cbrt(abs(errY) / Cx), 2) * signum(errY);
double landH = tarH + atan(dlandY);
double dErrY = -targetAngularVelocity * errX + currV * sin (errH);
double landAngV = targetAngularVelocity + (2 * (1 / cbrt(abs(errY) / Cx)) * dErrY) /
(1 + tan(landH - tarH) * tan(landH - tarH));
//calculating the corrected trajectory control parameters
double switchAngV = landAngV - currAngV +
sqrt(2 * MAX_ROBOT_ANGULAR_ACCELERATION * abs(landH - currH))
* signum(landH - currH) * 0.2;
double switchAngA = min(abs(switchAngV / dt), MAX_ROBOT_ANGULAR_ACCELERATION) * signum(switchAngV);
double newAngV = currAngV + switchAngA * dt;
//calculating new velocity
double dErrX = targetVelocity - currV * cos(errH) + targetAngularVelocity * errY;
double switchV = dErrX + sqrt( 2 * MAX_ROBOT_LINEAR_ACCELERATION * abs(errX)) * signum(errX);
double switchA = min(abs(switchV / dt), MAX_ROBOT_LINEAR_ACCELERATION) * signum(switchV);
//calculating delta motor speed control values
double k = 0.1;
double newDeltaLR = k* MAX_SPEED * MAIN_AXE_LENGTH * dt * switchAngA / (2 * WHEEL_RADIUS);
//calculating new motor speed control values
int newVL = (int) (last.getVelocityL() + switchA * dt / WHEEL_RADIUS - newDeltaLR * last.getDirL());
int newVR = (int) (last.getVelocityR() + switchA * dt / WHEEL_RADIUS + newDeltaLR * last.getDirL());
System.out.println("--> errH=" + errH + ", targetHeading=" + targetHeading + ", currH=" + currH + ", dist=" + currDist
);
// System.out.println("!!! landH=" + landH + ", dErrY=" + dErrY
// + ", currAngV=" + currAngV + ", landAngV=" + landAngV + ", switchAngV=" + switchAngV
// + ", switchAngA=" + switchAngA + ", newAngV=" + newAngV );
// System.out.println("!!! remainingPathLength=" + remainingPathLength + ", dErrX=" + dErrX + ", switchV=" + switchV + ", switchA=" + switchA );
// System.out.println("!!! newDeltaV=" + switchA * dt / WHEEL_RADIUS + ", newDelatLR=" + newDeltaLR + ", newVL=" + newVL + ", newVR=" + newVR);
double remainingDeltaHeading = targetHeading - currH;
if(remainingPathLength < last.getRemainingPath()
&& remainingPathLength > currV * currV / ROBOT_STOPPING_DECCELERATION
|| targetDeltaHeading > 0.01
&& abs(remainingDeltaHeading) > 0.05 && remainingDeltaHeading * targetDeltaHeading > 0 ) { //drive until minimum distance to target
return new MotorsCommand(last.getDirL(), last.getDirR(), newVL, newVR, (float) remainingPathLength);
} else {
System.out.println("FINAL POSITION: " + currPos);
return STOP_COMMAND;
}
}).map((MotorsCommand motorsCommand) -> {
runMotors(motorsCommand);
return motorsCommand;
})
.takeUntil((MotorsCommand motorsCommand) -> motorsCommand.equals(STOP_COMMAND) )
.subscribe( (MotorsCommand motorsCommand) -> {
System.out.println(motorsCommand);
});
}
protected void followLine(Command command) {
{
ForwardMovement forwardMove = (ForwardMovement) command.getData();
// start moving - and think later as it comes :)
int directionL, directionR;
if(forwardMove.getVelocity() < 0) {
directionL = directionR = -1;
} else {
directionL = directionR = 1;
}
double targetVelocity = abs(forwardMove.getVelocity());
int velocity = (int)(MAX_SPEED * targetVelocity / MAX_ROBOT_LINEAR_VELOCITY); // 50 mm/s max
MotorsCommand initialCommand = new MotorsCommand(directionL, directionR, velocity, velocity, Long.MAX_VALUE); //distance still unknown
System.out.println(initialCommand);
runMotors(initialCommand);
Position startPos = positions.elementAt(1).block();
double distance = forwardMove.getDistance();
double targetHeading = startPos.getHeading();
double targetDeltaX = distance * cos(targetHeading);
double targetDeltaY = distance * sin(targetHeading);
double targetX = startPos.getX() + targetDeltaX;
double targetY = startPos.getY() + targetDeltaY;
System.out.println("$$$$$$$$$$$$$$ TargetX=" + targetX );
System.out.println("$$$$$$$$$$$$$$ TargetY=" + targetY );
System.out.println("$$$$$$$$$$$$$$ Target Distance=" + distance);
System.out.println("$$$$$$$$$$$$$$ TargetHeading=" + targetHeading );
double startH = startPos.getHeading();
System.out.println("START POSITION: " + startPos);
Flux<Position> skip1 = positions.skip(1);
Flux<Tuple2<Position, Position>> lastTwoPositionsFlux = Flux.zip(positions, skip1);
Flux<Tuple4<Position, Position, LineReadings, Command>> flux =
Flux.combineLatest(
lastTwoPositionsFlux,
lineReadings,
commandFlux.startWith(new Command(VOID, null)),
(Object[] args) ->
Tuples.of(((Tuple2<Position, Position>)args[0]).getT1(),
((Tuple2<Position, Position>)args[0]).getT2(),
(LineReadings)args[1],
(Command)args[2])
);
flux.scan(initialCommand, (last, tuple4) -> {
System.out.println("########## NEW EVENT !!!!!!!!!!!");
Position prevPos = tuple4.getT1();
Position currPos = tuple4.getT2();
LineReadings lastReadings = tuple4.getT3();
Command lastCommand = tuple4.getT4();
float prevX = prevPos.getX();
float prevY = prevPos.getY();
double prevH = prevPos.getHeading();
float currX = currPos.getX();
float currY = currPos.getY();
double currH = currPos.getHeading();
System.out.println(currPos + " - " + prevPos);
double dt = (currPos.getTimestamp() - prevPos.getTimestamp()) / 1000.0; //delta time in seconds between position redings
if(dt <= 0) return last; // if invalid sequence do nothing
double time = (currPos.getTimestamp() - startPos.getTimestamp()) /1000.0;
// calculating the ideal trajectory position
double tarX, tarY, tarH, remainingPathLength;
tarX = startPos.getX() + targetVelocity * time * cos(targetHeading);
tarY = startPos.getY() + targetVelocity * time * sin(targetHeading);
remainingPathLength = hypot(targetX - currX, targetY - currY) ;
tarH = targetHeading;
//calculating current trajectory parameters
float dX = currX - prevX;
float dY = currY - prevY;
double currDist = hypot(dX, dY);
double currV = currDist / dt; // current velocity [mm/s]
double currAngV = (currH - prevH) / dt;
//calculating errors
double errX = (tarX - currX) * cos(tarH) + (tarY - currY) + sin(tarH);
double errY = (tarX - currX) * sin(tarH) + (tarY - currY) + cos(tarH);
double errH = tarH - currH;
//calculating landing curve
double Cx = LANDING_CURVE_PARAMETER;
double dlandY = 3 * Cx * pow(cbrt(abs(errY) / Cx), 2) * signum(errY);
double landH = tarH + atan(dlandY);
double dErrY = currV * sin (errH);
double landAngV = (2 * (1 / cbrt(abs(errY) / Cx)) * dErrY) /
(1 + tan(landH - tarH) * tan(landH - tarH));
//calculating the corrected trajectory control parameters
double switchAngV = landAngV - currAngV +
sqrt(2 * MAX_ROBOT_ANGULAR_ACCELERATION * abs(landH - currH))
* signum(landH - currH) * 0.2;
double switchAngA = min(abs(switchAngV / dt), MAX_ROBOT_ANGULAR_ACCELERATION) * signum(switchAngV);
double newAngV = currAngV + switchAngA * dt;
//calculating new velocity
double dErrX = targetVelocity - currV * cos(errH);
double switchV = dErrX + sqrt( 2 * MAX_ROBOT_LINEAR_ACCELERATION * abs(errX)) * signum(errX);
double switchA = min(abs(switchV / dt), MAX_ROBOT_LINEAR_ACCELERATION) * signum(switchV);
// double newV = currV + switchA * dt;
//calculating delta motor speed control values
double k = 0.1;
double newDeltaLR = k* MAX_SPEED * MAIN_AXE_LENGTH * dt * switchAngA / (2 * WHEEL_RADIUS);
//calculating new motor speed control values
int newVL = (int) (last.getVelocityL() + switchA * dt / WHEEL_RADIUS - newDeltaLR * last.getDirL());
int newVR = (int) (last.getVelocityR() + switchA * dt / WHEEL_RADIUS + newDeltaLR * last.getDirL());
System.out.println("!!! time=" + time + ", dt=" + dt + ", tarX=" + tarX + ", tarY=" + tarY
+ ", startH=" + startH + ", errH=" + errH + ", targetX=" + targetX + ", targetY=" + targetY + ", targetHeading=" + targetHeading
+ ", errX=" + errX + ", errY=" + errY + ", dlandY=" + dlandY + ", currV=" + currV + ", dist=" + currDist
+ ", switchAngV/dt=" + switchAngV / dt );
System.out.println("!!! remainingPathLength=" + remainingPathLength + ", dErrX=" + dErrX + ", switchV=" + switchV + ", switchA=" + switchA );
if(lastCommand.getName() != STOP && remainingPathLength < last.getRemainingPath()
&& remainingPathLength > currV * currV / ROBOT_STOPPING_DECCELERATION ) { //drive until minimum distance to target
return new MotorsCommand(last.getDirL(), last.getDirR(), newVL, newVR, (float) remainingPathLength);
} else {
System.out.println("FINAL POSITION: " + currPos);
return STOP_COMMAND;
}
}).map((MotorsCommand motorsCommand) -> {
runMotors(motorsCommand);
return motorsCommand;
})
.takeUntil((MotorsCommand motorsCommand) -> motorsCommand.equals(STOP_COMMAND) )
.subscribe( (MotorsCommand motorsCommand) -> {
System.out.println(motorsCommand);
});
}
}
protected void moveForward(Command command) {
{
ForwardMovement forwardMove = (ForwardMovement) command.getData();
// start moving - and think later as it comes :)
int directionL, directionR;
if(forwardMove.getVelocity() < 0) {
directionL = directionR = -1;
} else {
directionL = directionR = 1;
}
double targetVelocity = abs(forwardMove.getVelocity());
int velocity = (int)(MAX_SPEED * targetVelocity / MAX_ROBOT_LINEAR_VELOCITY); // 50 mm/s max
MotorsCommand initialCommand = new MotorsCommand(directionL, directionR, velocity, velocity, Long.MAX_VALUE); //distance still unknown
System.out.println(initialCommand);
runMotors(initialCommand);
Position startPos = positions.elementAt(1).block();
double distance = forwardMove.getDistance();
double targetHeading = startPos.getHeading();
double targetDeltaX = distance * cos(targetHeading);
double targetDeltaY = distance * sin(targetHeading);
double targetX = startPos.getX() + targetDeltaX;
double targetY = startPos.getY() + targetDeltaY;
System.out.println("$$$$$$$$$$$$$$ TargetX=" + targetX );
System.out.println("$$$$$$$$$$$$$$ TargetY=" + targetY );
System.out.println("$$$$$$$$$$$$$$ Target Distance=" + distance);
System.out.println("$$$$$$$$$$$$$$ TargetHeading=" + targetHeading );
double startH = startPos.getHeading();
System.out.println("START POSITION: " + startPos);
Flux<Position> skip1 = positions.skip(1);
Flux<Tuple2<Position, Position>> lastTwoPositionsFlux = Flux.zip(positions, skip1);
Flux<Tuple3<Position, Position, Command>> flux =
Flux.combineLatest(
lastTwoPositionsFlux,
commandFlux.startWith(new Command(VOID, null)),
(tuple2, lastCommand) -> Tuples.of(tuple2.getT1(), tuple2.getT2(), lastCommand)
);
flux.scan(initialCommand, (last, tuple3) -> {
System.out.println("########## NEW EVENT !!!!!!!!!!!");
Position prevPos = tuple3.getT1();
Position currPos = tuple3.getT2();
Command lastCommand = tuple3.getT3();
float prevX = prevPos.getX();
float prevY = prevPos.getY();
double prevH = prevPos.getHeading();
float currX = currPos.getX();
float currY = currPos.getY();
double currH = currPos.getHeading();
System.out.println(currPos + " - " + prevPos);
double dt = (currPos.getTimestamp() - prevPos.getTimestamp()) / 1000.0; //delta time in seconds between position redings
if(dt <= 0) return last; // if invalid sequence do nothing
double time = (currPos.getTimestamp() - startPos.getTimestamp()) /1000.0;
// calculating the ideal trajectory position
double tarX, tarY, tarH, remainingPathLength;
tarX = startPos.getX() + targetVelocity * time * cos(targetHeading);
tarY = startPos.getY() + targetVelocity * time * sin(targetHeading);
remainingPathLength = hypot(targetX - currX, targetY - currY) ;
tarH = targetHeading;
//calculating current trajectory parameters
float dX = currX - prevX;
float dY = currY - prevY;
double currDist = hypot(dX, dY);
double currV = currDist / dt; // current velocity [mm/s]
double currAngV = (currH - prevH) / dt;
//calculating errors
double errX = (tarX - currX) * cos(tarH) + (tarY - currY) + sin(tarH);
double errY = (tarX - currX) * sin(tarH) + (tarY - currY) + cos(tarH);
double errH = tarH - currH;
//calculating landing curve
double Cx = LANDING_CURVE_PARAMETER;
double dlandY = 3 * Cx * pow(cbrt(abs(errY) / Cx), 2) * signum(errY);
double landH = tarH + atan(dlandY);
double dErrY = currV * sin (errH);
double landAngV = (2 * (1 / cbrt(abs(errY) / Cx)) * dErrY) /
(1 + tan(landH - tarH) * tan(landH - tarH));
//calculating the corrected trajectory control parameters
double switchAngV = landAngV - currAngV +
sqrt(2 * MAX_ROBOT_ANGULAR_ACCELERATION * abs(landH - currH))
* signum(landH - currH) * 0.2;
double switchAngA = min(abs(switchAngV / dt), MAX_ROBOT_ANGULAR_ACCELERATION) * signum(switchAngV);
double newAngV = currAngV + switchAngA * dt;
//calculating new velocity
double dErrX = targetVelocity - currV * cos(errH);
double switchV = dErrX + sqrt( 2 * MAX_ROBOT_LINEAR_ACCELERATION * abs(errX)) * signum(errX);
double switchA = min(abs(switchV / dt), MAX_ROBOT_LINEAR_ACCELERATION) * signum(switchV);
// double newV = currV + switchA * dt;
//calculating delta motor speed control values
double k = 0.1;
double newDeltaLR = k* MAX_SPEED * MAIN_AXE_LENGTH * dt * switchAngA / (2 * WHEEL_RADIUS);
//calculating new motor speed control values
int newVL = (int) (last.getVelocityL() + switchA * dt / WHEEL_RADIUS - newDeltaLR * last.getDirL());
int newVR = (int) (last.getVelocityR() + switchA * dt / WHEEL_RADIUS + newDeltaLR * last.getDirL());
System.out.println("!!! time=" + time + ", dt=" + dt + ", tarX=" + tarX + ", tarY=" + tarY
+ ", startH=" + startH + ", errH=" + errH + ", targetX=" + targetX + ", targetY=" + targetY + ", targetHeading=" + targetHeading
+ ", errX=" + errX + ", errY=" + errY + ", dlandY=" + dlandY + ", currV=" + currV + ", dist=" + currDist
+ ", switchAngV/dt=" + switchAngV / dt );
System.out.println("!!! remainingPathLength=" + remainingPathLength + ", dErrX=" + dErrX + ", switchV=" + switchV + ", switchA=" + switchA );
if(lastCommand.getName() != STOP && remainingPathLength < last.getRemainingPath()
&& remainingPathLength > currV * currV / ROBOT_STOPPING_DECCELERATION ) { //drive until minimum distance to target
return new MotorsCommand(last.getDirL(), last.getDirR(), newVL, newVR, (float) remainingPathLength);
} else {
System.out.println("FINAL POSITION: " + currPos);
return STOP_COMMAND;
}
}).map((MotorsCommand motorsCommand) -> {
runMotors(motorsCommand);
return motorsCommand;
})
.takeUntil((MotorsCommand motorsCommand) -> motorsCommand.equals(STOP_COMMAND) )
.subscribe( (MotorsCommand motorsCommand) -> {
System.out.println(motorsCommand);
});
}
}
protected void setupGpioForMovement() {
// Motor direction pins
Gpio.pinMode(5, Gpio.OUTPUT);
Gpio.pinMode(6, Gpio.OUTPUT);
Gpio.pinMode(12, Gpio.PWM_OUTPUT);
Gpio.pinMode(13, Gpio.PWM_OUTPUT);
Gpio.pwmSetMode(Gpio.PWM_MODE_MS);
Gpio.pwmSetRange(MAX_SPEED);
Gpio.pwmSetClock(CLOCK_DIVISOR);
}
private void runMotors(MotorsCommand mc) {
//setting motor directions
Gpio.digitalWrite(5, mc.getDirR() > 0 ? 1 : 0);
Gpio.digitalWrite(6, mc.getDirL() > 0 ? 1 : 0);
//setting speed
if(mc.getVelocityR() >= 0 && mc.getVelocityR() <= MAX_SPEED)
Gpio.pwmWrite(12, mc.getVelocityR()); // speed up to MAX_SPEED
if(mc.getVelocityL() >= 0 && mc.getVelocityL() <= MAX_SPEED)
Gpio.pwmWrite(13, mc.getVelocityL());
}
@Override
public void onSubscribe(Subscription s) {
subscription = s;
subscription.request(Long.MAX_VALUE);
}
@Override
public void onError(Throwable t) {
// TODO Auto-generated method stub
}
@Override
public void onComplete() {
// TODO Auto-generated method stub
}
}
| iproduct/course-social-robotics | iptpi-demo/src/main/java/org/iproduct/iptpi/domain/movement/MovementCommandSubscriber.java | Java | gpl-2.0 | 25,456 |
package cn.ac.iscas.cloudeploy.v2.puppet.transform.ast;
import java.util.List;
public class ASTCollExpr extends ASTBase{
private Object test1;
private Object test2;
private String oper;
private List<Object> children;
private String form;
private String type;
public Object getTest1() {
return test1;
}
public void setTest1(Object test1) {
this.test1 = test1;
}
public Object getTest2() {
return test2;
}
public void setTest2(Object test2) {
this.test2 = test2;
}
public String getOper() {
return oper;
}
public void setOper(String oper) {
this.oper = oper;
}
public List<Object> getChildren() {
return children;
}
public void setChildren(List<Object> children) {
this.children = children;
}
public String getForm() {
return form;
}
public void setForm(String form) {
this.form = form;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| xpxstar/Cloudeploy | script-service/src/main/java/cn/ac/iscas/cloudeploy/v2/puppet/transform/ast/ASTCollExpr.java | Java | gpl-2.0 | 941 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.FocusFinder;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import com.android.launcher.R;
public class Cling extends FrameLayout {
static final String WORKSPACE_CLING_DISMISSED_KEY = "cling.workspace.dismissed";
static final String ALLAPPS_CLING_DISMISSED_KEY = "cling.allapps.dismissed";
static final String FOLDER_CLING_DISMISSED_KEY = "cling.folder.dismissed";
private static String WORKSPACE_PORTRAIT = "workspace_portrait";
private static String WORKSPACE_LANDSCAPE = "workspace_landscape";
private static String WORKSPACE_LARGE = "workspace_large";
private static String WORKSPACE_CUSTOM = "workspace_custom";
private static String ALLAPPS_PORTRAIT = "all_apps_portrait";
private static String ALLAPPS_LANDSCAPE = "all_apps_landscape";
private static String ALLAPPS_LARGE = "all_apps_large";
private static String FOLDER_PORTRAIT = "folder_portrait";
private static String FOLDER_LANDSCAPE = "folder_landscape";
private static String FOLDER_LARGE = "folder_large";
private Launcher mLauncher;
private boolean mIsInitialized;
private String mDrawIdentifier;
private Drawable mBackground;
private Drawable mPunchThroughGraphic;
private Drawable mHandTouchGraphic;
private int mPunchThroughGraphicCenterRadius;
private int mAppIconSize;
private int mButtonBarHeight;
private float mRevealRadius;
private int[] mPositionData;
private Paint mErasePaint;
public Cling(Context context) {
this(context, null, 0);
}
public Cling(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public Cling(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Cling, defStyle, 0);
mDrawIdentifier = a.getString(R.styleable.Cling_drawIdentifier);
a.recycle();
setClickable(true);
}
void init(Launcher l, int[] positionData) {
if (!mIsInitialized) {
mLauncher = l;
mPositionData = positionData;
Resources r = getContext().getResources();
mPunchThroughGraphic = r.getDrawable(R.drawable.cling);
mPunchThroughGraphicCenterRadius =
r.getDimensionPixelSize(R.dimen.clingPunchThroughGraphicCenterRadius);
mAppIconSize = r.getDimensionPixelSize(R.dimen.app_icon_size);
mRevealRadius = r.getDimensionPixelSize(R.dimen.reveal_radius) * 1f;
mButtonBarHeight = r.getDimensionPixelSize(R.dimen.button_bar_height);
mErasePaint = new Paint();
mErasePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
mErasePaint.setColor(0xFFFFFF);
mErasePaint.setAlpha(0);
mIsInitialized = true;
}
}
void cleanup() {
mBackground = null;
mPunchThroughGraphic = null;
mHandTouchGraphic = null;
mIsInitialized = false;
}
public String getDrawIdentifier() {
return mDrawIdentifier;
}
private int[] getPunchThroughPositions() {
if (mDrawIdentifier.equals(WORKSPACE_PORTRAIT)) {
return new int[]{getMeasuredWidth() / 2, getMeasuredHeight() - (mButtonBarHeight / 2)};
} else if (mDrawIdentifier.equals(WORKSPACE_LANDSCAPE)) {
return new int[]{getMeasuredWidth() - (mButtonBarHeight / 2), getMeasuredHeight() / 2};
} else if (mDrawIdentifier.equals(WORKSPACE_LARGE)) {
final float scale = LauncherApplication.getScreenDensity();
final int cornerXOffset = (int) (scale * 15);
final int cornerYOffset = (int) (scale * 10);
return new int[]{getMeasuredWidth() - cornerXOffset, cornerYOffset};
} else if (mDrawIdentifier.equals(ALLAPPS_PORTRAIT) ||
mDrawIdentifier.equals(ALLAPPS_LANDSCAPE) ||
mDrawIdentifier.equals(ALLAPPS_LARGE)) {
return mPositionData;
}
return new int[]{-1, -1};
}
@Override
public View focusSearch(int direction) {
return this.focusSearch(this, direction);
}
@Override
public View focusSearch(View focused, int direction) {
return FocusFinder.getInstance().findNextFocus(this, focused, direction);
}
@Override
public boolean onHoverEvent(MotionEvent event) {
return (mDrawIdentifier.equals(WORKSPACE_PORTRAIT)
|| mDrawIdentifier.equals(WORKSPACE_LANDSCAPE)
|| mDrawIdentifier.equals(WORKSPACE_LARGE)
|| mDrawIdentifier.equals(ALLAPPS_PORTRAIT)
|| mDrawIdentifier.equals(ALLAPPS_LANDSCAPE)
|| mDrawIdentifier.equals(ALLAPPS_LARGE)
|| mDrawIdentifier.equals(WORKSPACE_CUSTOM));
}
@Override
public boolean onTouchEvent(android.view.MotionEvent event) {
if (mDrawIdentifier.equals(WORKSPACE_PORTRAIT) ||
mDrawIdentifier.equals(WORKSPACE_LANDSCAPE) ||
mDrawIdentifier.equals(WORKSPACE_LARGE) ||
mDrawIdentifier.equals(ALLAPPS_PORTRAIT) ||
mDrawIdentifier.equals(ALLAPPS_LANDSCAPE) ||
mDrawIdentifier.equals(ALLAPPS_LARGE)) {
int[] positions = getPunchThroughPositions();
for (int i = 0; i < positions.length; i += 2) {
double diff = Math.sqrt(Math.pow(event.getX() - positions[i], 2) +
Math.pow(event.getY() - positions[i + 1], 2));
if (diff < mRevealRadius) {
return false;
}
}
} else if (mDrawIdentifier.equals(FOLDER_PORTRAIT) ||
mDrawIdentifier.equals(FOLDER_LANDSCAPE) ||
mDrawIdentifier.equals(FOLDER_LARGE)) {
Folder f = mLauncher.getWorkspace().getOpenFolder();
if (f != null) {
Rect r = new Rect();
f.getHitRect(r);
if (r.contains((int) event.getX(), (int) event.getY())) {
return false;
}
}
}
return true;
};
@Override
protected void dispatchDraw(Canvas canvas) {
if (mIsInitialized) {
DisplayMetrics metrics = new DisplayMetrics();
mLauncher.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// Initialize the draw buffer (to allow punching through)
Bitmap b = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
// Draw the background
if (mBackground == null) {
if (mDrawIdentifier.equals(WORKSPACE_PORTRAIT) ||
mDrawIdentifier.equals(WORKSPACE_LANDSCAPE) ||
mDrawIdentifier.equals(WORKSPACE_LARGE)) {
mBackground = getResources().getDrawable(R.drawable.bg_cling1);
} else if (mDrawIdentifier.equals(ALLAPPS_PORTRAIT) ||
mDrawIdentifier.equals(ALLAPPS_LANDSCAPE) ||
mDrawIdentifier.equals(ALLAPPS_LARGE)) {
mBackground = getResources().getDrawable(R.drawable.bg_cling2);
} else if (mDrawIdentifier.equals(FOLDER_PORTRAIT) ||
mDrawIdentifier.equals(FOLDER_LANDSCAPE)) {
mBackground = getResources().getDrawable(R.drawable.bg_cling3);
} else if (mDrawIdentifier.equals(FOLDER_LARGE)) {
mBackground = getResources().getDrawable(R.drawable.bg_cling4);
} else if (mDrawIdentifier.equals(WORKSPACE_CUSTOM)) {
mBackground = getResources().getDrawable(R.drawable.bg_cling5);
}
}
if (mBackground != null) {
mBackground.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
mBackground.draw(c);
} else {
c.drawColor(0x99000000);
}
int cx = -1;
int cy = -1;
float scale = mRevealRadius / mPunchThroughGraphicCenterRadius;
int dw = (int) (scale * mPunchThroughGraphic.getIntrinsicWidth());
int dh = (int) (scale * mPunchThroughGraphic.getIntrinsicHeight());
// Determine where to draw the punch through graphic
int[] positions = getPunchThroughPositions();
for (int i = 0; i < positions.length; i += 2) {
cx = positions[i];
cy = positions[i + 1];
if (cx > -1 && cy > -1) {
c.drawCircle(cx, cy, mRevealRadius, mErasePaint);
mPunchThroughGraphic.setBounds(cx - dw / 2, cy - dh / 2, cx + dw / 2, cy + dh / 2);
mPunchThroughGraphic.draw(c);
}
}
// Draw the hand graphic in All Apps
if (mDrawIdentifier.equals(ALLAPPS_PORTRAIT) ||
mDrawIdentifier.equals(ALLAPPS_LANDSCAPE) ||
mDrawIdentifier.equals(ALLAPPS_LARGE)) {
if (mHandTouchGraphic == null) {
mHandTouchGraphic = getResources().getDrawable(R.drawable.hand);
}
int offset = mAppIconSize / 4;
mHandTouchGraphic.setBounds(cx + offset, cy + offset,
cx + mHandTouchGraphic.getIntrinsicWidth() + offset,
cy + mHandTouchGraphic.getIntrinsicHeight() + offset);
mHandTouchGraphic.draw(c);
}
canvas.drawBitmap(b, 0, 0, null);
c.setBitmap(null);
b = null;
}
// Draw the rest of the cling
super.dispatchDraw(canvas);
};
}
| rex-xxx/mt6572_x201 | packages/apps/Launcher2/src/com/android/launcher2/Cling.java | Java | gpl-2.0 | 11,008 |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<!-- template designed by Marco Von Ballmoos -->
<title>Docs for page default.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 toggleNodeVisibility(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">/components/com_content/views/featured/tmpl/default.php</h2>
<a name="sec-description"></a>
<div class="info-box">
<div class="info-box-title">Description</div>
<div class="nav-bar">
</div>
<div class="info-box-body">
<!-- ========== Info from phpDoc block ========= -->
<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-Site_com_content_componentscom_contentviewsfeaturedtmpldefault.php.html">Source Code for this file</a></li>
<li><span class="field">license:</span> GNU</li>
</ul>
</div>
</div>
<p class="notes" id="credit">
Documentation generated on Tue, 19 Nov 2013 14:58:39 +0100 by <a href="http://www.phpdoc.org" target="_blank">phpDocumentor 1.4.3</a>
</p>
</div></body>
</html> | asika32764/Joomla-CMS-API-Document | Joomla-Site/com_content/_components---com_content---views---featured---tmpl---default.php.html | HTML | gpl-2.0 | 3,794 |
package rb;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.persistence.TypedQuery;
import rb.helpers.ClassificationResult;
import rb.helpers.DBHandler;
import rb.helpers.StemmerHelper;
import rb.persistentobjects.Statement;
import rb.persistentobjects.Word;
import ca.uwo.csd.ai.nlp.common.SparseVector;
import ca.uwo.csd.ai.nlp.kernel.KernelManager;
import ca.uwo.csd.ai.nlp.kernel.LinearKernel;
import ca.uwo.csd.ai.nlp.libsvm.svm_model;
import ca.uwo.csd.ai.nlp.libsvm.ex.Instance;
import ca.uwo.csd.ai.nlp.libsvm.ex.SVMPredictor;
import com.cd.reddit.Reddit;
import com.cd.reddit.RedditException;
import com.cd.reddit.json.jackson.RedditJsonParser;
import com.cd.reddit.json.mapping.RedditComment;
import com.cd.reddit.json.mapping.RedditLink;
import com.cd.reddit.json.util.RedditComments;
import de.daslaboratorium.machinelearning.classifier.BayesClassifier;
import de.daslaboratorium.machinelearning.classifier.Classification;
public class Poster {
private static Random randomGenerator;
static Reddit reddit = new Reddit("machinelearningbot/0.1 by elggem");
static String subreddit = "";
static BayesClassifier<String, String> bayes = null;
static svm_model model = null;
static List<Statement> statements = null;
static List<Word> words = null;
static int max_reply_length = 25;
static int classifier = 0;
static ArrayList<String> alreadyPostedComments = new ArrayList<String>();
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Reddit BOT Final stage. Armed and ready to go!");
randomGenerator = new Random();
if (args.length < 4) {
System.out.println(" usage: java -Xmx4g -jar JAR SUBREDDIT CLASSIFIER USER PASS\n" +
" with: SUBREDDIT = the subreddit to post to\n" +
" CLASSIFIER = 1:BN, 2:SVM 3:Random\n" +
" USER/PASS = username and password\n");
System.exit(1);
}
subreddit = args[0];
classifier = Integer.valueOf(args[1]);
try {
reddit.login(args[2], args[3]);
} catch (RedditException e) {
e.printStackTrace();
}
DBHandler.initializeHandler(args[0]);
if (statements == null) {
TypedQuery<Statement> query=DBHandler.em.createQuery("Select o from Statement o where o.text != \"[deleted]\" and o.parentStatement!= null and o.length>0 and o.length < " + max_reply_length,Statement.class);
statements = query.getResultList();
}
if (words == null) {
TypedQuery<Word> queryW=DBHandler.em.createQuery("Select o from Word o",Word.class);
words = queryW.getResultList();
}
//TIMER CODE
Timer timer = new Timer();
long thirty_minutes = 30*60*1000;
long one_hour = thirty_minutes*2;
long waiting_time = (long) (one_hour+(Math.random()*one_hour));
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("-> Awake from Hibernation");
RedditComment commentToReplyTo = findInterestingCommentPopularity(subreddit);
System.out.println("-> Generating Reply for " + commentToReplyTo.getBody());
String generatedReply = generateCommentFor(commentToReplyTo, classifier);
System.out.println("-> Generated " + generatedReply);
System.out.println("-> Posting..");
postCommentAsReplyTo(generatedReply, commentToReplyTo);
System.out.println("-> Going Back to Sleep...");
}
}, waiting_time, waiting_time);
//-------------
System.out.println("-> Awake from Hibernation");
RedditComment commentToReplyTo = findInterestingCommentPopularity(subreddit);
System.out.println("-> Generating Reply for " + commentToReplyTo.getBody());
String generatedReply = generateCommentFor(commentToReplyTo, classifier);
System.out.println("-> Generated " + generatedReply);
System.out.println("-> Posting..");
postCommentAsReplyTo(generatedReply, commentToReplyTo);
System.out.println("-> Going Back to Sleep...");
///---------------------
//DBHandler.closeHandler();
}
public static RedditComment findInterestingCommentRelevance(String subreddit) {
//Get the first 25 posts.
try {
List<RedditLink> links = reddit.listingFor(subreddit, "");
Collections.shuffle(links);
RedditLink linkOfInterest = links.get(0);
System.out.println(" findInterestingComment post: " + linkOfInterest);
List<RedditComment> comments = getAllCommentsForLink(linkOfInterest, subreddit);
ArrayList<ClassificationResult> classifications = new ArrayList<ClassificationResult>();
for (RedditComment redditComment : comments) {
classifications.add(classifyCommentBayes(redditComment));
}
RedditComment bestComment = null;
double max_prob = 0;
int i=0;
for (RedditComment redditComment : comments) {
double prob = classifications.get(i).probability;
if (prob>max_prob && convertStringToStemmedList(redditComment.getBody()).size()>0) {
max_prob = prob;
bestComment = redditComment;
}
i++;
}
System.out.println(" findInterestingComment comment: " + bestComment);
return bestComment;
} catch (Exception e) {
System.out.println("ERROR, trying next time: " + e.getLocalizedMessage());
}
return null;
}
public static RedditComment findInterestingCommentPopularity(String subreddit) {
//Get the first 25 posts.
try {
List<RedditLink> links = reddit.listingFor(subreddit, "");
Collections.shuffle(links);
RedditLink linkOfInterest = links.get(0);
System.out.println(" findInterestingComment post: " + linkOfInterest);
List<RedditComment> comments = getAllCommentsForLink(linkOfInterest, subreddit);
RedditComment bestComment = null;
long max_karma = 0;
for (RedditComment redditComment : comments) {
if (redditComment.getUps()-redditComment.getDowns() > max_karma) {
//if (redditComment.getReplies().toString().length() <= 10) {
max_karma = redditComment.getUps()-redditComment.getDowns();
bestComment = redditComment;
//}
}
}
System.out.println(" findInterestingComment comment: " + bestComment);
return bestComment;
} catch (Exception e) {
System.out.println("ERROR, trying next time: " + e.getLocalizedMessage());
}
return null;
}
public static String generateCommentFor(RedditComment comment, int classifierID) {
String generated = "";
if (classifierID == 1) {
generated = classifyCommentBayes(comment).resultString;
} else if (classifierID == 2) {
generated = classifyCommentSVM(comment);
} else if (classifierID == 3) {
generated = classifyCommentRandom(comment);
} else {
System.out.println("Choose a valid classifier dude.");
System.exit(1);
}
return generated;
}
public static void postCommentAsReplyTo(String comment, RedditComment parent) {
try {
System.out.println(" postCommentAsReplyTo response: "+reddit.comment(comment, parent.getName()));
} catch (RedditException e) {
System.out.println("ERROR, trying next time: " + e.getLocalizedMessage());
}
}
public static String classifyCommentSVM(RedditComment comment) {
if (model == null) {
try {
model = SVMPredictor.loadModel(subreddit + ".model");
} catch (Exception e1) {
System.out.println("ERROR: Couldnt load SVM model. Exitting");
System.exit(1);
}
KernelManager.setCustomKernel(new LinearKernel());
System.out.println(" classifyCommentSVM: loaded model!!");
}
ArrayList<String> inputlist = convertStringToStemmedList(comment.getBody());
SparseVector vec = new SparseVector();
for (Word word : words) {
int value = 0;
if(inputlist.contains(word.word)) {
value = 1;
}
vec.add(words.indexOf(word), value);
}
Instance inst = new Instance(0, vec);
double result = SVMPredictor.predict(inst, model, false);
return statements.get((int) result).text;
}
public static ClassificationResult classifyCommentBayes(RedditComment comment) {
if (bayes == null) {
// Create a new bayes classifier with string categories and string features.
bayes = new BayesClassifier<String, String>();
// Change the memory capacity. New learned classifications (using
// learn method are stored in a queue with the size given here and
// used to classify unknown sentences.
bayes.setMemoryCapacity(50000);
TypedQuery<Statement> query=DBHandler.em.createQuery("Select o from Statement o where o.text != \"[deleted]\" and o.parentStatement!= null and o.length>0 and o.length < " + max_reply_length,Statement.class);
List<Statement> statements = query.getResultList();
System.out.println(" classifyCommentBayes analyzing " + statements.size() + " statements... ");
for (Statement statement : statements) {
ArrayList<String> wordStrings = new ArrayList<String>();
for (Word word : statement.parentStatement.includedWords) {
wordStrings.add(word.word);
}
//LEARN
bayes.learn(statement.text, wordStrings);
}
}
ArrayList<String> list = convertStringToStemmedList(comment.getBody());
Classification<String,String> result = bayes.classify(list);
System.out.println(" classifyCommentBayes " + list + " prob " + result.getProbability());
return new ClassificationResult(result.getCategory(), result.getProbability());
}
public static String classifyCommentRandom(RedditComment comment) {
String result = statements.get(randomGenerator.nextInt(statements.size())).text;
System.out.println(" classifyCommentRandom ");
return result;
}
public static List<RedditComment>getAllRepliesForComment(RedditComment redditComment) {
List<RedditComment> thelist = new ArrayList<RedditComment>();
try {
thelist.add(redditComment);
if (redditComment.getReplies().toString().length() >= 10) {
final RedditJsonParser parser = new RedditJsonParser(redditComment.getReplies());
List<RedditComment> redditReplies = parser.parseCommentsOnly();
for (RedditComment redditCommentReply : redditReplies) {
List<RedditComment> additionalList = getAllRepliesForComment(redditCommentReply);
for (RedditComment redditComment2 : additionalList) {
redditComment2.parent = redditComment;
}
thelist.addAll(additionalList);
}
}
} catch (RedditException e) {
e.printStackTrace();
}
return thelist;
}
public static List<RedditComment>getAllCommentsForLink(RedditLink redditLink, String subreddit) {
List<RedditComment> thelist = new ArrayList<RedditComment>();
try {
if (redditLink.getNum_comments()>0) {
RedditComments comments;
comments = reddit.commentsFor(subreddit, redditLink.getId());
for (RedditComment redditComment : comments.getComments()) {
List<RedditComment> additionalList = getAllRepliesForComment(redditComment);
thelist.addAll(additionalList);
}
}
} catch (RedditException e) {
e.printStackTrace();
}
return thelist;
}
public static ArrayList<String> convertStringToStemmedList(String input) {
ArrayList<String> wordStrings = new ArrayList<String>();
for (String string : input.split("\\s+")) {
String pruned = string.replaceAll("[^a-zA-Z]", "").toLowerCase();
String stemmed = StemmerHelper.stemWord(pruned);
if (DBHandler.checkWord(stemmed)) {
wordStrings.add(stemmed);
}
}
return wordStrings;
}
}
| elggem/redditbot | src/rb/Poster.java | Java | gpl-2.0 | 11,681 |
<?php
class WebApplication extends CWebApplication
{
public $keywords;
public $description;
} | daixianceng/microwall | protected/components/WebApplication.php | PHP | gpl-2.0 | 95 |
#ifndef __ANSI_H__
#define __ANSI_H__
#define STATE_ESC_SET 0x01
#define STATE_FONT_SET 0x02
#define STATE_NEW_LINE 0x04
#define STATE_QUOTE_LINE 0x08
#define STATE_NONE 0x00
#define STATE_UBB_START 0x10
#define STATE_UBB_MIDDLE 0x20
#define STATE_UBB_END 0x40
#define STATE_TEX_SET 0x80
enum UBBTYPE {UBB_TYPE_IMG,
UBB_TYPE_ITALICIZE,
UBB_TYPE_UNDERLINE,
UBB_TYPE_BOLD,
UBB_TYPE_FLY,
UBB_TYPE_RM,
UBB_TYPE_FLASH,
UBB_TYPE_CENTER,
UBB_TYPE_EMAIL,
UBB_TYPE_HTTPLINK,
UBB_TYPE_QUOTE,
UBB_TYPE_QUICKTIME,
UBB_TYPE_SHOCKWAVE,
UBB_TYPE_MOVE,
UBB_TYPE_GLOW,
UBB_TYPE_SHADOW,
UBB_TYPE_FACE,
UBB_TYPE_SOUND,
UBB_TYPE_ATTACH
};
enum ATTACHMENTTYPE {
ATTACH_IMG,
ATTACH_FLASH,
ATTACH_OTHERS
};
#define STATE_SET(s, b) ((s) |= (b))
#define STATE_CLR(s, b) ((s) &= ~(b))
#define STATE_ISSET(s, b) ((s) & (b))
#define STATE_ZERO(s) (s = 0)
#define STYLE_SET_FG(s, c) (s = (s & ~0x07) | (c & 0x07))
#define STYLE_SET_BG(s, c) (s = (s & ~0x70) | ((c & 0x07) << 4))
#define STYLE_GET_FG(s) (s & 0x0F)
#define STYLE_GET_BG(s) ((s & 0x70) >> 4)
#define STYLE_CLR_FG(s) (s &= ~0x0F)
#define STYLE_CLR_BG(s) (s &= ~0xF0)
#define STYLE_ZERO(s) (s = 0)
#define STYLE_SET(s, b) (s |= b)
#define STYLE_CLR(s, b) (s &= ~b)
#define STYLE_ISSET(s, b) (s & b)
#define FONT_STYLE_UL 0x0100
#define FONT_STYLE_BLINK 0x0200
#define FONT_STYLE_ITALIC 0x0400
#define FONT_FG_BOLD 0x08
#define FONT_COLOR_BLACK 0x00
#define FONT_COLOR_RED 0x01
#define FONT_COLOR_GREEN 0x02
#define FONT_COLOR_YELLOW 0x03
#define FONT_COLOR_BULE 0x04
#define FONT_COLOR_MAGENTA 0x05
#define FONT_COLOR_CYAN 0x06
#define FONT_COLOR_WHITE 0x07
//#define FONT_STYLE_QUOTE FONT_STYLE_ITALIC
#define FONT_STYLE_QUOTE 0x0000
#define FONT_COLOR_QUOTE FONT_COLOR_CYAN
#define FONT_BG_SET 0x80
#endif /* __ANSI_H__ */
| fushengqian/kbs | src/ansi.h | C | gpl-2.0 | 2,178 |
using System;
using Server.Misc;
using Server.Network;
using System.Collections;
using Server.Items;
using Server.Targeting;
namespace Server.Mobiles
{
public class KhaldunZealot : BaseCreature
{
public override bool ClickTitle{ get{ return false; } }
public override bool ShowFameTitle{ get{ return false; } }
[Constructable]
public KhaldunZealot(): base( AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4 )
{
Body = 0x190;
Name = "Zealot of Khaldun";
Title = "the Knight";
Hue = 0;
SetStr( 351, 400 );
SetDex( 151, 165 );
SetInt( 76, 100 );
SetHits( 448, 470 );
SetDamage( 15, 25 );
SetDamageType( ResistanceType.Physical, 75 );
SetDamageType( ResistanceType.Cold, 25 );
SetResistance( ResistanceType.Physical, 35, 45 );
SetResistance( ResistanceType.Fire, 25, 30 );
SetResistance( ResistanceType.Cold, 50, 60 );
SetResistance( ResistanceType.Poison, 25, 35 );
SetResistance( ResistanceType.Energy, 25, 35 );
SetSkill( SkillName.Wrestling, 70.1, 80.0 );
SetSkill( SkillName.Swords, 120.1, 130.0 );
SetSkill( SkillName.Anatomy, 120.1, 130.0 );
SetSkill( SkillName.MagicResist, 90.1, 100.0 );
SetSkill( SkillName.Tactics, 90.1, 100.0 );
Fame = 10000;
Karma = -10000;
VirtualArmor = 40;
VikingSword weapon = new VikingSword();
weapon.Hue = 0x835;
weapon.Movable = false;
AddItem( weapon );
MetalShield shield = new MetalShield();
shield.Hue = 0x835;
shield.Movable = false;
AddItem( shield );
BoneHelm helm = new BoneHelm();
helm.Hue = 0x835;
AddItem( helm );
BoneArms arms = new BoneArms();
arms.Hue = 0x835;
AddItem( arms );
BoneGloves gloves = new BoneGloves();
gloves.Hue = 0x835;
AddItem( gloves );
BoneChest tunic = new BoneChest();
tunic.Hue = 0x835;
AddItem( tunic );
BoneLegs legs = new BoneLegs();
legs.Hue = 0x835;
AddItem( legs );
AddItem( new Boots() );
}
public override int GetIdleSound()
{
return 0x184;
}
public override int GetAngerSound()
{
return 0x286;
}
public override int GetDeathSound()
{
return 0x288;
}
public override int GetHurtSound()
{
return 0x19F;
}
public override bool AlwaysMurderer{ get{ return true; } }
public override bool Unprovokable{ get{ return true; } }
public override Poison PoisonImmune{ get{ return Poison.Deadly; } }
public KhaldunZealot( Serial serial ) : base( serial )
{
}
public override bool OnBeforeDeath()
{
BoneKnight rm = new BoneKnight();
rm.Team = this.Team;
rm.Combatant = this.Combatant;
rm.NoKillAwards = true;
if ( rm.Backpack == null )
{
Backpack pack = new Backpack();
pack.Movable = false;
rm.AddItem( pack );
}
for ( int i = 0; i < 2; i++ )
{
LootPack.FilthyRich.Generate( this, rm.Backpack, true, LootPack.GetLuckChanceForKiller( this ) );
LootPack.FilthyRich.Generate( this, rm.Backpack, false, LootPack.GetLuckChanceForKiller( this ) );
}
Effects.PlaySound(this, Map, GetDeathSound());
Effects.SendLocationEffect( Location, Map, 0x3709, 30, 10, 0x835, 0 );
rm.MoveToWorld( Location, Map );
Delete();
return false;
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
/*int version = */reader.ReadInt();
}
}
} | brodock/sunuo | scripts/legacy/Mobiles/Monsters/Humanoid/Melee/KhaldunZealot.cs | C# | gpl-2.0 | 3,472 |
<?php
/**
* WordPress CRON API
*
* @package WordPress
*/
/**
* Schedules a hook to run only once.
*
* Schedules a hook which will be executed once by the Wordpress actions core at
* a time which you specify. The action will fire off when someone visits your
* WordPress site, if the schedule time has passed.
*
* @since 2.1.0
* @link http://codex.wordpress.org/Function_Reference/wp_schedule_single_event
*
* @param int $timestamp Timestamp for when to run the event.
* @param callback $hook Function or method to call, when cron is run.
* @param array $args Optional. Arguments to pass to the hook function.
*/
function wp_schedule_single_event( $timestamp, $hook, $args = array()) {
// don't schedule a duplicate if there's already an identical event due in the next 10 minutes
$next = wp_next_scheduled($hook, $args);
if ( $next && $next <= $timestamp + 600 )
return;
$crons = _get_cron_array();
$key = md5(serialize($args));
$crons[$timestamp][$hook][$key] = array( 'schedule' => false, 'args' => $args );
uksort( $crons, "strnatcasecmp" );
_set_cron_array( $crons );
}
/**
* Schedule a periodic event.
*
* Schedules a hook which will be executed by the WordPress actions core on a
* specific interval, specified by you. The action will trigger when someone
* visits your WordPress site, if the scheduled time has passed.
*
* @since 2.1.0
*
* @param int $timestamp Timestamp for when to run the event.
* @param string $recurrence How often the event should recur.
* @param callback $hook Function or method to call, when cron is run.
* @param array $args Optional. Arguments to pass to the hook function.
* @return bool|null False on failure, null when complete with scheduling event.
*/
function wp_schedule_event( $timestamp, $recurrence, $hook, $args = array()) {
$crons = _get_cron_array();
$schedules = wp_get_schedules();
$key = md5(serialize($args));
if ( !isset( $schedules[$recurrence] ) )
return false;
$crons[$timestamp][$hook][$key] = array( 'schedule' => $recurrence, 'args' => $args, 'interval' => $schedules[$recurrence]['interval'] );
uksort( $crons, "strnatcasecmp" );
_set_cron_array( $crons );
}
/**
* Reschedule a recurring event.
*
* @since 2.1.0
*
* @param int $timestamp Timestamp for when to run the event.
* @param string $recurrence How often the event should recur.
* @param callback $hook Function or method to call, when cron is run.
* @param array $args Optional. Arguments to pass to the hook function.
* @return bool|null False on failure. Null when event is rescheduled.
*/
function wp_reschedule_event( $timestamp, $recurrence, $hook, $args = array()) {
$crons = _get_cron_array();
$schedules = wp_get_schedules();
$key = md5(serialize($args));
$interval = 0;
// First we try to get it from the schedule
if ( 0 == $interval )
$interval = $schedules[$recurrence]['interval'];
// Now we try to get it from the saved interval in case the schedule disappears
if ( 0 == $interval )
$interval = $crons[$timestamp][$hook][$key]['interval'];
// Now we assume something is wrong and fail to schedule
if ( 0 == $interval )
return false;
while ( $timestamp < time() + 1 )
$timestamp += $interval;
wp_schedule_event( $timestamp, $recurrence, $hook, $args );
}
/**
* Unschedule a previously scheduled cron job.
*
* The $timestamp and $hook parameters are required, so that the event can be
* identified.
*
* @since 2.1.0
*
* @param int $timestamp Timestamp for when to run the event.
* @param callback $hook Function or method to call, when cron is run.
* @param array $args Optional. Arguments to pass to the hook function.
*/
function wp_unschedule_event( $timestamp, $hook, $args = array() ) {
$crons = _get_cron_array();
$key = md5(serialize($args));
unset( $crons[$timestamp][$hook][$key] );
if ( empty($crons[$timestamp][$hook]) )
unset( $crons[$timestamp][$hook] );
if ( empty($crons[$timestamp]) )
unset( $crons[$timestamp] );
_set_cron_array( $crons );
}
/**
* Unschedule all cron jobs attached to a specific hook.
*
* @since 2.1.0
*
* @param callback $hook Function or method to call, when cron is run.
* @param mixed $args,... Optional. Event arguments.
*/
function wp_clear_scheduled_hook( $hook ) {
$args = array_slice( func_get_args(), 1 );
while ( $timestamp = wp_next_scheduled( $hook, $args ) )
wp_unschedule_event( $timestamp, $hook, $args );
}
/**
* Retrieve the next timestamp for a cron event.
*
* @since 2.1.0
*
* @param callback $hook Function or method to call, when cron is run.
* @param array $args Optional. Arguments to pass to the hook function.
* @return bool|int The UNIX timestamp of the next time the scheduled event will occur.
*/
function wp_next_scheduled( $hook, $args = array() ) {
$crons = _get_cron_array();
$key = md5(serialize($args));
if ( empty($crons) )
return false;
foreach ( $crons as $timestamp => $cron ) {
if ( isset( $cron[$hook][$key] ) )
return $timestamp;
}
return false;
}
/**
* Send request to run cron through HTTP request that doesn't halt page loading.
*
* @since 2.1.0
*
* @return null Cron could not be spawned, because it is not needed to run.
*/
function spawn_cron( $local_time ) {
/*
* do not even start the cron if local server timer has drifted
* such as due to power failure, or misconfiguration
*/
$timer_accurate = check_server_timer( $local_time );
if ( !$timer_accurate )
return;
//sanity check
$crons = _get_cron_array();
if ( !is_array($crons) )
return;
$keys = array_keys( $crons );
$timestamp = $keys[0];
if ( $timestamp > $local_time )
return;
$cron_url = get_option( 'siteurl' ) . '/wp-cron.php?check=' . wp_hash('187425');
/*
* multiple processes on multiple web servers can run this code concurrently
* try to make this as atomic as possible by setting doing_cron switch
*/
$flag = get_option('doing_cron');
// clean up potential invalid value resulted from various system chaos
if ( $flag != 0 ) {
if ( $flag > $local_time + 10*60 || $flag < $local_time - 10*60 ) {
update_option('doing_cron', 0);
$flag = 0;
}
}
//don't run if another process is currently running it
if ( $flag > $local_time )
return;
update_option( 'doing_cron', $local_time + 30 );
wp_remote_post($cron_url, array('timeout' => 0.01, 'blocking' => false));
}
/**
* Run scheduled callbacks or spawn cron for all scheduled events.
*
* @since 2.1.0
*
* @return null When doesn't need to run Cron.
*/
function wp_cron() {
// Prevent infinite loops caused by lack of wp-cron.php
if ( strpos($_SERVER['REQUEST_URI'], '/wp-cron.php') !== false )
return;
$crons = _get_cron_array();
if ( !is_array($crons) )
return;
$keys = array_keys( $crons );
if ( isset($keys[0]) && $keys[0] > time() )
return;
$local_time = time();
$schedules = wp_get_schedules();
foreach ( $crons as $timestamp => $cronhooks ) {
if ( $timestamp > $local_time ) break;
foreach ( (array) $cronhooks as $hook => $args ) {
if ( isset($schedules[$hook]['callback']) && !call_user_func( $schedules[$hook]['callback'] ) )
continue;
spawn_cron( $local_time );
break 2;
}
}
}
/**
* Retrieve supported and filtered Cron recurrences.
*
* The supported recurrences are 'hourly' and 'daily'. A plugin may add more by
* hooking into the 'cron_schedules' filter. The filter accepts an array of
* arrays. The outer array has a key that is the name of the schedule or for
* example 'weekly'. The value is an array with two keys, one is 'interval' and
* the other is 'display'.
*
* The 'interval' is a number in seconds of when the cron job should run. So for
* 'hourly', the time is 3600 or 60*60. For weekly, the value would be
* 60*60*24*7 or 604800. The value of 'interval' would then be 604800.
*
* The 'display' is the description. For the 'weekly' key, the 'display' would
* be <code>__('Once Weekly')</code>.
*
* For your plugin, you will be passed an array. you can easily add your
* schedule by doing the following.
* <code>
* // filter parameter variable name is 'array'
* $array['weekly'] = array(
* 'interval' => 604800,
* 'display' => __('Once Weekly')
* );
* </code>
*
* @since 2.1.0
*
* @return array
*/
function wp_get_schedules() {
$schedules = array(
'hourly' => array( 'interval' => 3600, 'display' => __('Once Hourly') ),
'twicedaily' => array( 'interval' => 43200, 'display' => __('Twice Daily') ),
'daily' => array( 'interval' => 86400, 'display' => __('Once Daily') ),
);
return array_merge( apply_filters( 'cron_schedules', array() ), $schedules );
}
/**
* Retrieve Cron schedule for hook with arguments.
*
* @since 2.1.0
*
* @param callback $hook Function or method to call, when cron is run.
* @param array $args Optional. Arguments to pass to the hook function.
* @return string|bool False, if no schedule. Schedule on success.
*/
function wp_get_schedule($hook, $args = array()) {
$crons = _get_cron_array();
$key = md5(serialize($args));
if ( empty($crons) )
return false;
foreach ( $crons as $timestamp => $cron ) {
if ( isset( $cron[$hook][$key] ) )
return $cron[$hook][$key]['schedule'];
}
return false;
}
//
// Private functions
//
/**
* Retrieve cron info array option.
*
* @since 2.1.0
* @access private
*
* @return array CRON info array.
*/
function _get_cron_array() {
$cron = get_option('cron');
if ( ! is_array($cron) )
return false;
if ( !isset($cron['version']) )
$cron = _upgrade_cron_array($cron);
unset($cron['version']);
return $cron;
}
/**
* Updates the CRON option with the new CRON array.
*
* @since 2.1.0
* @access private
*
* @param array $cron Cron info array from {@link _get_cron_array()}.
*/
function _set_cron_array($cron) {
$cron['version'] = 2;
update_option( 'cron', $cron );
}
/**
* Upgrade a Cron info array.
*
* This function upgrades the Cron info array to version 2.
*
* @since 2.1.0
* @access private
*
* @param array $cron Cron info array from {@link _get_cron_array()}.
* @return array An upgraded Cron info array.
*/
function _upgrade_cron_array($cron) {
if ( isset($cron['version']) && 2 == $cron['version'])
return $cron;
$new_cron = array();
foreach ( (array) $cron as $timestamp => $hooks) {
foreach ( (array) $hooks as $hook => $args ) {
$key = md5(serialize($args['args']));
$new_cron[$timestamp][$hook][$key] = $args;
}
}
$new_cron['version'] = 2;
update_option( 'cron', $new_cron );
return $new_cron;
}
// stub for checking server timer accuracy, using outside standard time sources
function check_server_timer( $local_time ) {
return true;
}
?>
| pravinhirmukhe/flow1 | wp-includes/cron.php | PHP | gpl-2.0 | 11,000 |
#!/usr/bin/env python
## tumblrserv.py implements a Tumblr (http://www.tumblr.com) markup parsing
## engine and compatible webserver.
##
## Version: 0.2 final
##
## Copyright (C) 2009 Jeremy Herbert
## Contact mailto:[email protected]
##
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License
## as published by the Free Software Foundation; either version 2
## of the License, or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
## 02110-1301, USA.
import os, sys, ftplib, yaml, cherrypy, re, urllib2
from src.post_classes import *
from src import json
from src.constants import *
from src.support import *
from src.net import *
from src.server import *
post_types = ['Regular', 'Photo', 'Quote', 'Link', 'Conversation', 'Video', 'Audio', 'Conversation']
args_dict = {
'autoreload': 0, # Whether to add the meta refresh tag
'publish': False, # Whether to push the new theme data to tumblr
'data_source': DATA_LOCAL, # Whether to use local data in the theme
}
########################################
# take the arguments and place them in a mutable list
arguments = sys.argv
# if the script has been run with the interpreter prefix, get rid of it
if arguments[0] == 'python' or arguments[0] == 'ipython' \
or arguments[0] == 'python2.5':
arguments.pop(0)
# pop off the script name
arguments.pop(0)
# load the configuration file
config_path = 'data/config.yml'
if contains(arguments, '--config'):
if os.path.exists(next_arg(arguments, '--config')):
config_path = next_arg(arguments, '--config')
config = get_config(config_path)
# now we check if there are any data processing flags
if contains(arguments, '--pull-data'):
# call pull_data with the argument after the flag
pull_data( next_arg(arguments, '--pull-data') )
if contains(arguments, '--theme'):
if not os.path.exists("themes/" + next_arg(arguments, '--theme') + '.thtml'):
err_exit("The theme file %s.thtml does not exist in the themes\
directory." % next_arg(arguments, '--theme'))
config['defaults']['theme_name'] = next_arg(arguments, '--theme')
if contains(arguments, '--publish'):
if not has_keys(config['publishing_info'], \
( 'url', 'username', 'password' )):
err_exit('The configuration file is missing some critical publishing\
information. Please make sure you have specified your url, username and\
password.')
publish_theme(config['publishing_info']['url'],\
config['publishing_info']['username'],\
config['publishing_info']['password'],\
get_markup('themes/%s.thtml' % config['defaults']['theme_name']))
if contains(arguments, '--do-nothing'):
config['optimisations']['do_nothing'] = True
# start the server up
cherrypy.config.update('data/cherrypy.conf')
cherrypy.quickstart(TumblrServ(config), '/') | jeremyherbert/TumblrServ | tumblrserv.py | Python | gpl-2.0 | 3,373 |
package pf::Switch::Motorola;
=head1 NAME
pf::Switch::Motorola
=head1 SYNOPSIS
The pf::Switch::Motorola module implements an object oriented interface to
manage Motorola RF Switches (Wireless Controllers)
=head1 STATUS
Developed and tested on RFS7000 running OS release 4.3.0.0-059R,
and RFS6000 running OS 5.2.0.0-069R.
=over
=item Supports
=over
=item Deauthentication with RADIUS Disconnect (RFC3576)
=item Deauthentication with SNMP
=item Roles-assignment through RADIUS
=back
=back
=head1 BUGS AND LIMITATIONS
=over
=item Firmware 4.x support
Deauthentication against firmware 4.x series is done using SNMP
=item Firmware 5.x support
Deauthentication against firmware 5.x series is done using RADIUS CoA.
=item SNMPv3
SNMPv3 support is untested.
=back
=cut
use strict;
use warnings;
use base ('pf::Switch');
use pf::accounting qw(node_accounting_current_sessionid);
use pf::constants;
use pf::config qw(
$MAC
$SSID
);
use pf::util;
=head1 SUBROUTINES
=over
=cut
# CAPABILITIES
# access technology supported
sub supportsRoleBasedEnforcement { return $TRUE; }
sub supportsWirelessDot1x { return $TRUE; }
sub supportsWirelessMacAuth { return $TRUE; }
# inline capabilities
sub inlineCapabilities { return ($MAC,$SSID); }
=item getVersion
obtain image version information from switch
=cut
sub getVersion {
my ($self) = @_;
my $oid_sysDescr = '1.3.6.1.2.1.1.1.0';
my $logger = $self->logger;
if ( !$self->connectRead() ) {
return '';
}
$logger->trace("SNMP get_request for sysDescr: $oid_sysDescr");
my $result = $self->{_sessionRead}->get_request( -varbindlist => [$oid_sysDescr] );
my $sysDescr = ( $result->{$oid_sysDescr} || '' );
# sysDescr sample output:
# RFS7000 Wireless Switch, Version 4.3.0.0-059R MIB=01a
# all non-whitespace characters grouped after the string Version
if ( $sysDescr =~ / Version (\S+)/ ) {
return $1;
} else {
$logger->warn("couldn't extract exact version information, returning SNMP System Description instead");
return $sysDescr;
}
}
=item parseTrap
Parsing SNMP Traps - WIDS stuff only, other types are discarded
=cut
sub parseTrap {
my ( $self, $trapString ) = @_;
my $trapHashRef;
my $logger = $self->logger;
# Handle WIPS Trap
if ( $trapString =~ /BEGIN VARIABLEBINDINGS.*\.1\.3\.6\.1\.4\.1\.388\.50\.1\.2\.1\.4 = STRING: "Unsanctioned AP ([A-F0-9]{2}-[A-F0-9]{2}-[A-F0-9]{2}-[A-F0-9]{2}-[A-F0-9]{2}-[A-F0-9]{2})/){
$trapHashRef->{'trapType'} = 'wirelessIPS';
$trapHashRef->{'trapMac'} = clean_mac($1);
} else {
$logger->debug("trap currently not handled");
$trapHashRef->{'trapType'} = 'unknown';
}
return $trapHashRef;
}
=item deauthenticateMacDefault
De-authenticate a MAC address from wireless network (including 802.1x).
New implementation using RADIUS Disconnect-Request.
=cut
sub deauthenticateMacDefault {
my ( $self, $mac, $is_dot1x ) = @_;
my $logger = $self->logger;
if ( !$self->isProductionMode() ) {
$logger->info("not in production mode... we won't perform deauthentication");
return 1;
}
if ($self->getVersion() =~ /^5/) {
#Fetching the acct-session-id, mandatory for Motorola
my $acctsessionid = node_accounting_current_sessionid($mac);
$logger->debug("deauthenticate $mac using RADIUS Disconnect-Request deauth method");
return $self->radiusDisconnect( $mac, { 'Acct-Session-Id' => $acctsessionid } );
} else {
$logger->debug("deauthenticate $mac using SNMP deauth method");
return $self->_deauthenticateMacSNMP($mac);
}
}
=item _deauthenticateMacSNMP
deauthenticate a MAC address from wireless network (including 802.1x)
=cut
sub _deauthenticateMacSNMP {
my ($self, $mac) = @_;
my $logger = $self->logger;
my $oid_wsCcRfMuDisassociateNow = '1.3.6.1.4.1.388.14.3.2.1.12.3.1.19'; # from WS-CC-RF-MIB
if ( !$self->isProductionMode() ) {
$logger->info("not in production mode ... we won't write to wsCcRfMuDisassociateNow");
return 1;
}
# handles if deauth should be performed against controller or actual device. Returns sessionWrite hash key to use.
my $performDeauthOn = $self->getDeauthSnmpConnectionKey();
if ( !defined($performDeauthOn) ) {
return;
}
# append MAC to deauthenticate to oid to set
$oid_wsCcRfMuDisassociateNow .= '.' . mac2oid($mac);
$logger->info("deauthenticate mac $mac from controller: " . $self->{_ip});
$logger->trace("SNMP set_request for wsCcRfMuDisassociateNow: $oid_wsCcRfMuDisassociateNow");
my $result = $self->{$performDeauthOn}->set_request(
-varbindlist => [ "$oid_wsCcRfMuDisassociateNow", Net::SNMP::INTEGER, $TRUE ]
);
if (defined($result)) {
$logger->debug("deauthenticatation successful");
return $TRUE;
} else {
$logger->warn("deauthenticatation failed with " . $self->{$performDeauthOn}->error());
return;
}
}
=item returnRoleAttribute
Motorola uses the following VSA for role assignment
=cut
sub returnRoleAttribute {
my ($self) = @_;
return 'Symbol-User-Group';
}
=item deauthTechniques
Return the reference to the deauth technique or the default deauth technique.
=cut
sub deauthTechniques {
my ($self, $method) = @_;
my $logger = $self->logger;
my $default = $SNMP::SNMP;
my %tech = (
$SNMP::SNMP => 'deauthenticateMacDefault',
);
if (!defined($method) || !defined($tech{$method})) {
$method = $default;
}
return $method,$tech{$method};
}
=back
=head1 AUTHOR
Inverse inc. <[email protected]>
=head1 COPYRIGHT
Copyright (C) 2005-2017 Inverse inc.
=head1 LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
=cut
1;
# vim: set shiftwidth=4:
# vim: set expandtab:
# vim: set backspace=indent,eol,start:
| jrouzierinverse/packetfence | lib/pf/Switch/Motorola.pm | Perl | gpl-2.0 | 6,574 |
/*
* Copyright 2006-2016 The MZmine 3 Development Team
*
* This file is part of MZmine 3.
*
* MZmine 3 is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* MZmine 3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with MZmine 3; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.github.mzmine.util;
import java.io.File;
import java.util.List;
import javax.annotation.Nonnull;
import com.google.common.io.Files;
/**
* File name utilities
*/
public class FileNameUtil {
public static @Nonnull String findCommonPrefix(@Nonnull List<File> fileNames) {
if (fileNames.size() < 2)
return "";
String firstName = fileNames.get(0).getName();
for (int prefixLen = 0; prefixLen < firstName.length(); prefixLen++) {
char c = firstName.charAt(prefixLen);
for (int i = 1; i < fileNames.size(); i++) {
String ithName = fileNames.get(i).getName();
if (prefixLen >= ithName.length() || ithName.charAt(prefixLen) != c) {
// Mismatch found
return ithName.substring(0, prefixLen);
}
}
}
return firstName;
}
public static @Nonnull String findCommonSuffix(@Nonnull List<File> fileNames) {
if (fileNames.isEmpty())
return "";
if (fileNames.size() == 1) {
// Return file extension
String ext = Files.getFileExtension(fileNames.get(0).getAbsolutePath());
return "." + ext;
}
String firstName = fileNames.get(0).getName();
for (int suffixLen = 0; suffixLen < firstName.length(); suffixLen++) {
char c = firstName.charAt(firstName.length() - 1 - suffixLen);
for (int i = 1; i < fileNames.size(); i++) {
String ithName = fileNames.get(i).getName();
if (suffixLen >= ithName.length()
|| ithName.charAt(ithName.length() - 1 - suffixLen) != c) {
// Mismatch found
return ithName.substring(ithName.length() - suffixLen);
}
}
}
return firstName;
}
}
| DrewG/mzmine3 | src/main/java/io/github/mzmine/util/FileNameUtil.java | Java | gpl-2.0 | 2,482 |
/*
PHYML : a program that computes maximum likelihood phylogenies from
DNA or AA homologous sequences
Copyright (C) Stephane Guindon. Oct 2003 onward
All parts of the source except where indicated are distributed under
the GNU public licence. See http://www.opensource.org for details.
*/
#include <config.h>
#ifndef IO_H
#define IO_H
#include "utilities.h"
t_tree *Read_Tree(char **s_tree);
void R_rtree(char *s_tree_a,char *s_tree_d,t_node *a,t_tree *tree,int *n_int,int *n_ext);
void Read_Branch_Label(char *s_d,char *s_a,t_edge *b);
void Read_Branch_Length(char *s_d,char *s_a,t_tree *tree);
void Read_Node_Name(t_node *d,char *s_tree_d,t_tree *tree);
void Clean_Multifurcation(char **subtrees,int current_deg,int end_deg);
char **Sub_Trees(char *tree,int *degree);
int Next_Par(char *s,int pos);
void Print_Tree(FILE *fp,t_tree *tree);
char *Write_Tree(t_tree *tree,int custom);
void R_wtree(t_node *pere,t_node *fils,int *available,char **s_tree,t_tree *tree);
void R_wtree_Custom(t_node *pere,t_node *fils,int *available,char **s_tree,int *pos,t_tree *tree);
void Detect_Align_File_Format(option *io);
void Detect_Tree_File_Format(option *io);
align **Get_Seq(option *io);
void Get_Nexus_Data(FILE *fp,option *io);
int Get_Token(FILE *fp,char *token);
align **Get_Seq_Phylip(option *io);
void Read_Ntax_Len_Phylip(FILE *fp,int *n_otu,int *n_tax);
align **Read_Seq_Sequential(option *io);
align **Read_Seq_Interleaved(option *io);
int Read_One_Line_Seq(align ***data,int num_otu,FILE *in);
t_tree *Read_Tree_File(option *io);
char *Return_Tree_String_Phylip(FILE *fp_input_tree);
t_tree *Read_Tree_File_Phylip(FILE *fp_input_tree);
void Print_Site_Lk(t_tree *tree,FILE *fp);
void Print_Seq(FILE *fp, align **data, int n_otu);
void Print_CSeq(FILE *fp,int compressed,calign *cdata);
void Print_CSeq_Select(FILE *fp,int compressed,calign *cdata,t_tree *tree);
void Print_Dist(matrix *mat);
void Print_Node(t_node *a,t_node *d,t_tree *tree);
void Print_Model(t_mod *mod);
void Print_Mat(matrix *mat);
FILE *Openfile(char *filename,int mode);
void Print_Fp_Out(FILE *fp_out,time_t t_beg,time_t t_end,t_tree *tree,option *io,int n_data_set,int num_tree, int add_citation);
void Print_Fp_Out_Lines(FILE *fp_out,time_t t_beg,time_t t_end,t_tree *tree,option *io,int n_data_set);
void Print_Freq(t_tree *tree);
void Print_Settings(option *io);
void Print_Banner(FILE *fp);
void Print_Banner_Small(FILE *fp);
void Print_Data_Set_Number(option *io,FILE *fp);
void Print_Lk(t_tree *tree,char *string);
void Print_Pars(t_tree *tree);
void Print_Lk_And_Pars(t_tree *tree);
void Read_Qmat(phydbl *daa,phydbl *pi,FILE *fp);
void Print_Qmat_AA(phydbl *daa,phydbl *pi);
void Print_Square_Matrix_Generic(int n,phydbl *mat);
void Print_Diversity(FILE *fp,t_tree *tree);
void Print_Diversity_Pre(t_node *a,t_node *d,t_edge *b,FILE *fp,t_tree *tree);
t_tree *Read_User_Tree(calign *cdata,t_mod *mod,option *io);
void Print_Time_Info(time_t t_beg,time_t t_end);
void PhyML_Printf(char *format,...);
void PhyML_Fprintf(FILE *fp,char *format,...);
void Read_Clade_Priors(char *file_name,t_tree *tree);
option *Get_Input(int argc,char **argv);
void Print_Data_Structure(int final, FILE *fp, t_tree *root);
int Set_Whichmodel(int select);
void Print_Site(calign *cdata, int num, int n_otu, char *sep, int stepsize, FILE *fp);
option *PhyML_XML(char *xml_filename);
void Check_Taxa_Sets(t_tree *mixt_tree);
void Make_Ratematrice_From_XML_Node(xml_node *instance, option *io, t_mod *mod);
void Make_Efrq_From_XML_Node(xml_node *instance, option *io, t_mod *mod);
void Make_Topology_From_XML_Node(xml_node *instance, option *io, t_mod *mod);
void Make_RAS_From_XML_Node(xml_node *parent, t_mod *mod);
void Post_Process_Data(option *io);
int *Return_Int(int in);
void Print_All_Edge_PMats(t_tree* tree);
void Print_All_Edge_Likelihoods(t_tree* tree);
void Print_Edge_Likelihoods(t_tree* tree, t_edge* b, bool scientific);
void Print_Edge_PMats(t_tree* tree, t_edge* b);
void Print_Tip_Partials(t_tree* tree, t_node* d);
void Dump_Arr_D(phydbl* arr, int num);
void Dump_Arr_S(short int* arr, int num);
void Dump_Arr_I(int* arr, int num);
void Print_Tree_Structure(t_tree* tree);
void Print_Node_Brief(t_node *a, t_node *d, t_tree *tree, FILE *fp);
void Generic_Exit(const char *file, int line, const char *function);
#endif
| hedjour/phyml | src/io.h | C | gpl-2.0 | 4,313 |
/*
* computeOnsetFeatures.c
*
* Code generation for function 'computeOnsetFeatures'
*
* C source code generated on: Fri Apr 25 23:35:45 2014
*
*/
/* Include files */
#include "rt_nonfinite.h"
#include "computeOnsetFeatures_export.h"
/* Type Definitions */
#ifndef struct_emxArray__common
#define struct_emxArray__common
struct emxArray__common
{
void *data;
int32_T *size;
int32_T allocatedSize;
int32_T numDimensions;
boolean_T canFreeData;
};
#endif /*struct_emxArray__common*/
#ifndef typedef_emxArray__common
#define typedef_emxArray__common
typedef struct emxArray__common emxArray__common;
#endif /*typedef_emxArray__common*/
#ifndef struct_emxArray_int32_T
#define struct_emxArray_int32_T
struct emxArray_int32_T
{
int32_T *data;
int32_T *size;
int32_T allocatedSize;
int32_T numDimensions;
boolean_T canFreeData;
};
#endif /*struct_emxArray_int32_T*/
#ifndef typedef_emxArray_int32_T
#define typedef_emxArray_int32_T
typedef struct emxArray_int32_T emxArray_int32_T;
#endif /*typedef_emxArray_int32_T*/
/* Function Declarations */
static void ConstantPad(const emxArray_real_T *a, const real_T padSize[2],
emxArray_real_T *b);
static void b_eml_li_find(const boolean_T x[12], int32_T y_data[12], int32_T
y_size[1]);
static void b_eml_null_assignment(emxArray_boolean_T *x, const emxArray_real_T
*idx);
static void b_emxInit_boolean_T(emxArray_boolean_T **pEmxArray, int32_T
numDimensions);
static void b_emxInit_real_T(emxArray_real_T **pEmxArray, int32_T numDimensions);
static real_T b_std(const real_T varargin_1[17]);
static void bsxfun(const real_T a[17], real_T b, real_T c[17]);
static void c_eml_null_assignment(emxArray_real_T *x, const emxArray_real_T *idx);
static real_T c_std(const real_T varargin_1[17]);
static int32_T div_s32(int32_T numerator, int32_T denominator);
static void eml_li_find(const emxArray_boolean_T *x, emxArray_int32_T *y);
static void eml_null_assignment(emxArray_boolean_T *x);
static void eml_sort(const real_T x[17], real_T y[17], int32_T idx[17]);
static void emxEnsureCapacity(emxArray__common *emxArray, int32_T oldNumel,
int32_T elementSize);
static void emxFree_boolean_T(emxArray_boolean_T **pEmxArray);
static void emxFree_int32_T(emxArray_int32_T **pEmxArray);
static void emxFree_real_T(emxArray_real_T **pEmxArray);
static void emxInit_boolean_T(emxArray_boolean_T **pEmxArray, int32_T
numDimensions);
static void emxInit_int32_T(emxArray_int32_T **pEmxArray, int32_T numDimensions);
static void emxInit_real_T(emxArray_real_T **pEmxArray, int32_T numDimensions);
static real_T featureSpectralCentroid(real_T S[17]);
static real_T featureSpectralCrest(const real_T S[17]);
static void filter(const emxArray_real_T *x, real_T zi, emxArray_real_T *y);
static void filtfilt(const emxArray_real_T *x_in, emxArray_real_T *y_out);
static void histogramFeatures(const real_T ioiHist[17], real_T features[12]);
static void ioiHistogram(emxArray_boolean_T *onsets, const emxArray_real_T *T,
real_T ioiHist[17]);
static void onsetDetection(const emxArray_real_T *spec, emxArray_boolean_T
*onsets, emxArray_real_T *flux);
static void onsetFlux(const emxArray_real_T *S, emxArray_real_T *flux);
static void padarray(const emxArray_real_T *varargin_1, emxArray_real_T *b);
static void rdivide(const emxArray_real_T *x, real_T y, emxArray_real_T *z);
static real_T rt_powd_snf(real_T u0, real_T u1);
/* Function Definitions */
static void ConstantPad(const emxArray_real_T *a, const real_T padSize[2],
emxArray_real_T *b)
{
real_T sizeB[2];
int32_T cdiff;
uint32_T varargin_1[2];
int32_T ndbl;
emxArray_real_T *idxB;
emxArray_int32_T *r7;
emxArray_real_T *r8;
emxArray_real_T *r9;
int32_T k;
int32_T absb;
int32_T apnd;
int32_T i4;
emxArray_boolean_T *x;
real_T idxB1;
real_T idxB2;
int32_T b_sizeB[2];
int32_T outsize[2];
for (cdiff = 0; cdiff < 2; cdiff++) {
sizeB[cdiff] = 0.0;
}
for (cdiff = 0; cdiff < 2; cdiff++) {
varargin_1[cdiff] = (uint32_T)a->size[cdiff];
}
ndbl = (int32_T)varargin_1[0];
if ((int32_T)varargin_1[1] > (int32_T)varargin_1[0]) {
ndbl = (int32_T)varargin_1[1];
}
emxInit_real_T(&idxB, 2);
cdiff = idxB->size[0] * idxB->size[1];
idxB->size[0] = ndbl;
idxB->size[1] = 2;
emxEnsureCapacity((emxArray__common *)idxB, cdiff, (int32_T)sizeof(real_T));
ndbl <<= 1;
for (cdiff = 0; cdiff < ndbl; cdiff++) {
idxB->data[cdiff] = 0.0;
}
emxInit_int32_T(&r7, 1);
emxInit_real_T(&r8, 2);
emxInit_real_T(&r9, 2);
for (k = 0; k < 2; k++) {
sizeB[k] = (real_T)a->size[k] + 2.0 * padSize[k];
if (1 > a->size[k]) {
ndbl = 0;
} else {
ndbl = a->size[k];
}
cdiff = r7->size[0];
r7->size[0] = ndbl;
emxEnsureCapacity((emxArray__common *)r7, cdiff, (int32_T)sizeof(int32_T));
for (cdiff = 0; cdiff < ndbl; cdiff++) {
r7->data[cdiff] = cdiff;
}
if (a->size[k] < 1) {
absb = -1;
apnd = 0;
} else {
ndbl = (int32_T)floor(((real_T)a->size[k] - 1.0) + 0.5);
apnd = ndbl + 1;
cdiff = (ndbl - a->size[k]) + 1;
absb = a->size[k];
if (1 > absb) {
i4 = 1;
} else {
i4 = absb;
}
if (fabs(cdiff) < 4.4408920985006262E-16 * (real_T)i4) {
ndbl++;
apnd = a->size[k];
} else if (cdiff > 0) {
apnd = ndbl;
} else {
ndbl++;
}
absb = ndbl - 1;
}
cdiff = r8->size[0] * r8->size[1];
r8->size[0] = 1;
r8->size[1] = absb + 1;
emxEnsureCapacity((emxArray__common *)r8, cdiff, (int32_T)sizeof(real_T));
if (absb + 1 > 0) {
r8->data[0] = 1.0;
if (absb + 1 > 1) {
r8->data[absb] = apnd;
ndbl = absb / 2;
for (cdiff = 1; cdiff < ndbl; cdiff++) {
r8->data[cdiff] = 1.0 + (real_T)cdiff;
r8->data[absb - cdiff] = apnd - cdiff;
}
if (ndbl << 1 == absb) {
r8->data[ndbl] = (1.0 + (real_T)apnd) / 2.0;
} else {
r8->data[ndbl] = 1.0 + (real_T)ndbl;
r8->data[ndbl + 1] = apnd - ndbl;
}
}
}
cdiff = r9->size[0] * r9->size[1];
r9->size[0] = 1;
r9->size[1] = r8->size[1];
emxEnsureCapacity((emxArray__common *)r9, cdiff, (int32_T)sizeof(real_T));
ndbl = r8->size[1];
for (cdiff = 0; cdiff < ndbl; cdiff++) {
r9->data[r9->size[0] * cdiff] = r8->data[r8->size[0] * cdiff] + padSize[k];
}
ndbl = r7->size[0];
for (cdiff = 0; cdiff < ndbl; cdiff++) {
idxB->data[r7->data[cdiff] + idxB->size[0] * k] = r9->data[cdiff];
}
}
emxFree_real_T(&r9);
emxFree_real_T(&r8);
emxFree_int32_T(&r7);
b_emxInit_boolean_T(&x, 1);
ndbl = idxB->size[0];
cdiff = x->size[0];
x->size[0] = ndbl;
emxEnsureCapacity((emxArray__common *)x, cdiff, (int32_T)sizeof(boolean_T));
for (cdiff = 0; cdiff < ndbl; cdiff++) {
x->data[cdiff] = (idxB->data[cdiff] != 0.0);
}
if (x->size[0] == 0) {
idxB1 = 0.0;
} else {
idxB1 = x->data[0];
for (k = 2; k <= x->size[0]; k++) {
idxB1 += (real_T)x->data[k - 1];
}
}
ndbl = idxB->size[0];
cdiff = x->size[0];
x->size[0] = ndbl;
emxEnsureCapacity((emxArray__common *)x, cdiff, (int32_T)sizeof(boolean_T));
for (cdiff = 0; cdiff < ndbl; cdiff++) {
x->data[cdiff] = (idxB->data[cdiff + idxB->size[0]] != 0.0);
}
if (x->size[0] == 0) {
idxB2 = 0.0;
} else {
idxB2 = x->data[0];
for (k = 2; k <= x->size[0]; k++) {
idxB2 += (real_T)x->data[k - 1];
}
}
emxFree_boolean_T(&x);
b_sizeB[0] = (int32_T)sizeB[0];
b_sizeB[1] = (int32_T)sizeB[1];
for (cdiff = 0; cdiff < 2; cdiff++) {
outsize[cdiff] = b_sizeB[cdiff];
}
cdiff = b->size[0] * b->size[1];
b->size[0] = outsize[0];
emxEnsureCapacity((emxArray__common *)b, cdiff, (int32_T)sizeof(real_T));
cdiff = b->size[0] * b->size[1];
b->size[1] = outsize[1];
emxEnsureCapacity((emxArray__common *)b, cdiff, (int32_T)sizeof(real_T));
ndbl = outsize[0] * outsize[1];
for (cdiff = 0; cdiff < ndbl; cdiff++) {
b->data[cdiff] = 0.0;
}
for (ndbl = 0; ndbl < (int32_T)idxB1; ndbl++) {
for (cdiff = 0; cdiff < (int32_T)idxB2; cdiff++) {
b->data[((int32_T)idxB->data[(int32_T)(1.0 + (real_T)ndbl) - 1] + b->size
[0] * ((int32_T)idxB->data[((int32_T)(1.0 + (real_T)cdiff) +
idxB->size[0]) - 1] - 1)) - 1] = a->data[((int32_T)(1.0 +
(real_T)ndbl) + a->size[0] * ((int32_T)(1.0 + (real_T)cdiff) - 1)) - 1];
}
}
emxFree_real_T(&idxB);
}
static void b_eml_li_find(const boolean_T x[12], int32_T y_data[12], int32_T
y_size[1])
{
int32_T k;
int32_T i;
k = 0;
for (i = 0; i < 12; i++) {
if (x[i]) {
k++;
}
}
y_size[0] = k;
k = 0;
for (i = 0; i < 12; i++) {
if (x[i]) {
y_data[k] = i + 1;
k++;
}
}
}
static void b_eml_null_assignment(emxArray_boolean_T *x, const emxArray_real_T
*idx)
{
int32_T nxin;
int32_T k;
emxArray_int32_T *r13;
emxArray_boolean_T *b_x;
emxArray_boolean_T *c_x;
int32_T nxout;
int32_T i6;
int32_T k0;
emxArray_boolean_T *b;
nxin = x->size[0] * x->size[1];
if (idx->size[1] == 1) {
for (k = (int32_T)idx->data[0]; k < nxin; k++) {
x->data[k - 1] = x->data[k];
}
emxInit_int32_T(&r13, 1);
emxInit_boolean_T(&b_x, 2);
b_emxInit_boolean_T(&c_x, 1);
if ((x->size[0] != 1) && (x->size[1] == 1)) {
if (1 > nxin - 1) {
nxout = 0;
} else {
nxout = nxin - 1;
}
i6 = c_x->size[0];
c_x->size[0] = nxout;
emxEnsureCapacity((emxArray__common *)c_x, i6, (int32_T)sizeof(boolean_T));
for (i6 = 0; i6 < nxout; i6++) {
c_x->data[i6] = x->data[i6];
}
i6 = x->size[0] * x->size[1];
x->size[0] = nxout;
x->size[1] = 1;
emxEnsureCapacity((emxArray__common *)x, i6, (int32_T)sizeof(boolean_T));
i6 = 0;
while (i6 <= 0) {
for (i6 = 0; i6 < nxout; i6++) {
x->data[i6] = c_x->data[i6];
}
i6 = 1;
}
} else {
if (1 > nxin - 1) {
nxout = 0;
} else {
nxout = nxin - 1;
}
i6 = r13->size[0];
r13->size[0] = nxout;
emxEnsureCapacity((emxArray__common *)r13, i6, (int32_T)sizeof(int32_T));
for (i6 = 0; i6 < nxout; i6++) {
r13->data[i6] = 1 + i6;
}
nxout = r13->size[0];
i6 = b_x->size[0] * b_x->size[1];
b_x->size[0] = 1;
b_x->size[1] = nxout;
emxEnsureCapacity((emxArray__common *)b_x, i6, (int32_T)sizeof(boolean_T));
for (i6 = 0; i6 < nxout; i6++) {
k = 0;
while (k <= 0) {
b_x->data[b_x->size[0] * i6] = x->data[r13->data[i6] - 1];
k = 1;
}
}
i6 = x->size[0] * x->size[1];
x->size[0] = b_x->size[0];
x->size[1] = b_x->size[1];
emxEnsureCapacity((emxArray__common *)x, i6, (int32_T)sizeof(boolean_T));
nxout = b_x->size[1];
for (i6 = 0; i6 < nxout; i6++) {
k0 = b_x->size[0];
for (k = 0; k < k0; k++) {
x->data[k + x->size[0] * i6] = b_x->data[k + b_x->size[0] * i6];
}
}
}
emxFree_boolean_T(&c_x);
emxFree_boolean_T(&b_x);
emxFree_int32_T(&r13);
} else {
emxInit_boolean_T(&b, 2);
i6 = b->size[0] * b->size[1];
b->size[0] = 1;
b->size[1] = nxin;
emxEnsureCapacity((emxArray__common *)b, i6, (int32_T)sizeof(boolean_T));
for (i6 = 0; i6 < nxin; i6++) {
b->data[i6] = FALSE;
}
for (k = 1; k <= idx->size[1]; k++) {
b->data[(int32_T)idx->data[k - 1] - 1] = TRUE;
}
nxout = 0;
for (k = 1; k <= b->size[1]; k++) {
nxout += b->data[k - 1];
}
nxout = nxin - nxout;
k0 = -1;
for (k = 1; k <= nxin; k++) {
if ((k > b->size[1]) || (!b->data[k - 1])) {
k0++;
x->data[k0] = x->data[k - 1];
}
}
emxFree_boolean_T(&b);
emxInit_int32_T(&r13, 1);
emxInit_boolean_T(&b_x, 2);
b_emxInit_boolean_T(&c_x, 1);
if ((x->size[0] != 1) && (x->size[1] == 1)) {
if (1 > nxout) {
nxout = 0;
}
i6 = c_x->size[0];
c_x->size[0] = nxout;
emxEnsureCapacity((emxArray__common *)c_x, i6, (int32_T)sizeof(boolean_T));
for (i6 = 0; i6 < nxout; i6++) {
c_x->data[i6] = x->data[i6];
}
i6 = x->size[0] * x->size[1];
x->size[0] = nxout;
x->size[1] = 1;
emxEnsureCapacity((emxArray__common *)x, i6, (int32_T)sizeof(boolean_T));
i6 = 0;
while (i6 <= 0) {
for (i6 = 0; i6 < nxout; i6++) {
x->data[i6] = c_x->data[i6];
}
i6 = 1;
}
} else {
if (1 > nxout) {
nxout = 0;
}
i6 = r13->size[0];
r13->size[0] = nxout;
emxEnsureCapacity((emxArray__common *)r13, i6, (int32_T)sizeof(int32_T));
for (i6 = 0; i6 < nxout; i6++) {
r13->data[i6] = 1 + i6;
}
nxout = r13->size[0];
i6 = b_x->size[0] * b_x->size[1];
b_x->size[0] = 1;
b_x->size[1] = nxout;
emxEnsureCapacity((emxArray__common *)b_x, i6, (int32_T)sizeof(boolean_T));
for (i6 = 0; i6 < nxout; i6++) {
k = 0;
while (k <= 0) {
b_x->data[b_x->size[0] * i6] = x->data[r13->data[i6] - 1];
k = 1;
}
}
i6 = x->size[0] * x->size[1];
x->size[0] = b_x->size[0];
x->size[1] = b_x->size[1];
emxEnsureCapacity((emxArray__common *)x, i6, (int32_T)sizeof(boolean_T));
nxout = b_x->size[1];
for (i6 = 0; i6 < nxout; i6++) {
k0 = b_x->size[0];
for (k = 0; k < k0; k++) {
x->data[k + x->size[0] * i6] = b_x->data[k + b_x->size[0] * i6];
}
}
}
emxFree_boolean_T(&c_x);
emxFree_boolean_T(&b_x);
emxFree_int32_T(&r13);
}
}
static void b_emxInit_boolean_T(emxArray_boolean_T **pEmxArray, int32_T
numDimensions)
{
emxArray_boolean_T *emxArray;
int32_T i;
*pEmxArray = (emxArray_boolean_T *)malloc(sizeof(emxArray_boolean_T));
emxArray = *pEmxArray;
emxArray->data = (boolean_T *)NULL;
emxArray->numDimensions = numDimensions;
emxArray->size = (int32_T *)malloc((uint32_T)(sizeof(int32_T) * numDimensions));
emxArray->allocatedSize = 0;
emxArray->canFreeData = TRUE;
for (i = 0; i < numDimensions; i++) {
emxArray->size[i] = 0;
}
}
static void b_emxInit_real_T(emxArray_real_T **pEmxArray, int32_T numDimensions)
{
emxArray_real_T *emxArray;
int32_T i;
*pEmxArray = (emxArray_real_T *)malloc(sizeof(emxArray_real_T));
emxArray = *pEmxArray;
emxArray->data = (real_T *)NULL;
emxArray->numDimensions = numDimensions;
emxArray->size = (int32_T *)malloc((uint32_T)(sizeof(int32_T) * numDimensions));
emxArray->allocatedSize = 0;
emxArray->canFreeData = TRUE;
for (i = 0; i < numDimensions; i++) {
emxArray->size[i] = 0;
}
}
static real_T b_std(const real_T varargin_1[17])
{
real_T y;
int32_T ix;
real_T xbar;
int32_T k;
real_T r;
ix = 0;
xbar = varargin_1[0];
for (k = 0; k < 16; k++) {
ix++;
xbar += varargin_1[ix];
}
xbar /= 17.0;
ix = 0;
r = varargin_1[0] - xbar;
y = r * r;
for (k = 0; k < 16; k++) {
ix++;
r = varargin_1[ix] - xbar;
y += r * r;
}
y /= 16.0;
return sqrt(y);
}
static void bsxfun(const real_T a[17], real_T b, real_T c[17])
{
int32_T k;
for (k = 0; k < 17; k++) {
c[k] = a[k] - b;
}
}
static void c_eml_null_assignment(emxArray_real_T *x, const emxArray_real_T *idx)
{
int32_T nxin;
int32_T k;
emxArray_int32_T *r14;
emxArray_real_T *b_x;
emxArray_real_T *c_x;
int32_T nxout;
int32_T i7;
int32_T k0;
emxArray_boolean_T *b;
nxin = x->size[0] * x->size[1];
if (idx->size[1] == 1) {
for (k = (int32_T)idx->data[0]; k < nxin; k++) {
x->data[k - 1] = x->data[k];
}
emxInit_int32_T(&r14, 1);
emxInit_real_T(&b_x, 2);
b_emxInit_real_T(&c_x, 1);
if ((x->size[0] != 1) && (x->size[1] == 1)) {
if (1 > nxin - 1) {
nxout = 0;
} else {
nxout = nxin - 1;
}
i7 = c_x->size[0];
c_x->size[0] = nxout;
emxEnsureCapacity((emxArray__common *)c_x, i7, (int32_T)sizeof(real_T));
for (i7 = 0; i7 < nxout; i7++) {
c_x->data[i7] = x->data[i7];
}
i7 = x->size[0] * x->size[1];
x->size[0] = nxout;
x->size[1] = 1;
emxEnsureCapacity((emxArray__common *)x, i7, (int32_T)sizeof(real_T));
i7 = 0;
while (i7 <= 0) {
for (i7 = 0; i7 < nxout; i7++) {
x->data[i7] = c_x->data[i7];
}
i7 = 1;
}
} else {
if (1 > nxin - 1) {
nxout = 0;
} else {
nxout = nxin - 1;
}
i7 = r14->size[0];
r14->size[0] = nxout;
emxEnsureCapacity((emxArray__common *)r14, i7, (int32_T)sizeof(int32_T));
for (i7 = 0; i7 < nxout; i7++) {
r14->data[i7] = 1 + i7;
}
nxout = r14->size[0];
i7 = b_x->size[0] * b_x->size[1];
b_x->size[0] = 1;
b_x->size[1] = nxout;
emxEnsureCapacity((emxArray__common *)b_x, i7, (int32_T)sizeof(real_T));
for (i7 = 0; i7 < nxout; i7++) {
k = 0;
while (k <= 0) {
b_x->data[b_x->size[0] * i7] = x->data[r14->data[i7] - 1];
k = 1;
}
}
i7 = x->size[0] * x->size[1];
x->size[0] = b_x->size[0];
x->size[1] = b_x->size[1];
emxEnsureCapacity((emxArray__common *)x, i7, (int32_T)sizeof(real_T));
nxout = b_x->size[1];
for (i7 = 0; i7 < nxout; i7++) {
k0 = b_x->size[0];
for (k = 0; k < k0; k++) {
x->data[k + x->size[0] * i7] = b_x->data[k + b_x->size[0] * i7];
}
}
}
emxFree_real_T(&c_x);
emxFree_real_T(&b_x);
emxFree_int32_T(&r14);
} else {
emxInit_boolean_T(&b, 2);
i7 = b->size[0] * b->size[1];
b->size[0] = 1;
b->size[1] = nxin;
emxEnsureCapacity((emxArray__common *)b, i7, (int32_T)sizeof(boolean_T));
for (i7 = 0; i7 < nxin; i7++) {
b->data[i7] = FALSE;
}
for (k = 1; k <= idx->size[1]; k++) {
b->data[(int32_T)idx->data[k - 1] - 1] = TRUE;
}
nxout = 0;
for (k = 1; k <= b->size[1]; k++) {
nxout += b->data[k - 1];
}
nxout = nxin - nxout;
k0 = -1;
for (k = 1; k <= nxin; k++) {
if ((k > b->size[1]) || (!b->data[k - 1])) {
k0++;
x->data[k0] = x->data[k - 1];
}
}
emxFree_boolean_T(&b);
emxInit_int32_T(&r14, 1);
emxInit_real_T(&b_x, 2);
b_emxInit_real_T(&c_x, 1);
if ((x->size[0] != 1) && (x->size[1] == 1)) {
if (1 > nxout) {
nxout = 0;
}
i7 = c_x->size[0];
c_x->size[0] = nxout;
emxEnsureCapacity((emxArray__common *)c_x, i7, (int32_T)sizeof(real_T));
for (i7 = 0; i7 < nxout; i7++) {
c_x->data[i7] = x->data[i7];
}
i7 = x->size[0] * x->size[1];
x->size[0] = nxout;
x->size[1] = 1;
emxEnsureCapacity((emxArray__common *)x, i7, (int32_T)sizeof(real_T));
i7 = 0;
while (i7 <= 0) {
for (i7 = 0; i7 < nxout; i7++) {
x->data[i7] = c_x->data[i7];
}
i7 = 1;
}
} else {
if (1 > nxout) {
nxout = 0;
}
i7 = r14->size[0];
r14->size[0] = nxout;
emxEnsureCapacity((emxArray__common *)r14, i7, (int32_T)sizeof(int32_T));
for (i7 = 0; i7 < nxout; i7++) {
r14->data[i7] = 1 + i7;
}
nxout = r14->size[0];
i7 = b_x->size[0] * b_x->size[1];
b_x->size[0] = 1;
b_x->size[1] = nxout;
emxEnsureCapacity((emxArray__common *)b_x, i7, (int32_T)sizeof(real_T));
for (i7 = 0; i7 < nxout; i7++) {
k = 0;
while (k <= 0) {
b_x->data[b_x->size[0] * i7] = x->data[r14->data[i7] - 1];
k = 1;
}
}
i7 = x->size[0] * x->size[1];
x->size[0] = b_x->size[0];
x->size[1] = b_x->size[1];
emxEnsureCapacity((emxArray__common *)x, i7, (int32_T)sizeof(real_T));
nxout = b_x->size[1];
for (i7 = 0; i7 < nxout; i7++) {
k0 = b_x->size[0];
for (k = 0; k < k0; k++) {
x->data[k + x->size[0] * i7] = b_x->data[k + b_x->size[0] * i7];
}
}
}
emxFree_real_T(&c_x);
emxFree_real_T(&b_x);
emxFree_int32_T(&r14);
}
}
static real_T c_std(const real_T varargin_1[17])
{
real_T y;
int32_T ix;
real_T xbar;
int32_T k;
real_T r;
ix = 0;
xbar = varargin_1[0];
for (k = 0; k < 16; k++) {
ix++;
xbar += varargin_1[ix];
}
xbar /= 17.0;
ix = 0;
r = varargin_1[0] - xbar;
y = r * r;
for (k = 0; k < 16; k++) {
ix++;
r = varargin_1[ix] - xbar;
y += r * r;
}
y /= 17.0;
return sqrt(y);
}
static int32_T div_s32(int32_T numerator, int32_T denominator)
{
int32_T quotient;
uint32_T absNumerator;
uint32_T absDenominator;
int32_T quotientNeedsNegation;
if (denominator == 0) {
if (numerator >= 0) {
quotient = MAX_int32_T;
} else {
quotient = MIN_int32_T;
}
} else {
if (numerator >= 0) {
absNumerator = (uint32_T)numerator;
} else {
absNumerator = (uint32_T)-numerator;
}
if (denominator >= 0) {
absDenominator = (uint32_T)denominator;
} else {
absDenominator = (uint32_T)-denominator;
}
quotientNeedsNegation = ((numerator < 0) != (denominator < 0));
absNumerator /= absDenominator;
if ((uint32_T)quotientNeedsNegation) {
quotient = -(int32_T)absNumerator;
} else {
quotient = (int32_T)absNumerator;
}
}
return quotient;
}
static void eml_li_find(const emxArray_boolean_T *x, emxArray_int32_T *y)
{
int32_T n;
int32_T k;
int32_T i;
int32_T j;
n = x->size[0] * x->size[1];
k = 0;
for (i = 1; i <= n; i++) {
if (x->data[i - 1]) {
k++;
}
}
j = y->size[0];
y->size[0] = k;
emxEnsureCapacity((emxArray__common *)y, j, (int32_T)sizeof(int32_T));
j = 0;
for (i = 1; i <= n; i++) {
if (x->data[i - 1]) {
y->data[j] = i;
j++;
}
}
}
static void eml_null_assignment(emxArray_boolean_T *x)
{
emxArray_boolean_T *b;
int32_T nxin;
int32_T i5;
int32_T k;
int32_T nxout;
int32_T k0;
emxArray_int32_T *r12;
emxArray_boolean_T *b_x;
emxArray_boolean_T *c_x;
emxInit_boolean_T(&b, 2);
nxin = x->size[0] * x->size[1];
i5 = b->size[0] * b->size[1];
b->size[0] = 1;
b->size[1] = nxin;
emxEnsureCapacity((emxArray__common *)b, i5, (int32_T)sizeof(boolean_T));
for (i5 = 0; i5 < nxin; i5++) {
b->data[i5] = FALSE;
}
for (k = 0; k < 2; k++) {
b->data[k] = TRUE;
}
nxout = 0;
for (k = 1; k <= b->size[1]; k++) {
nxout += b->data[k - 1];
}
nxout = nxin - nxout;
k0 = -1;
for (k = 1; k <= nxin; k++) {
if ((k > b->size[1]) || (!b->data[k - 1])) {
k0++;
x->data[k0] = x->data[k - 1];
}
}
emxFree_boolean_T(&b);
emxInit_int32_T(&r12, 1);
emxInit_boolean_T(&b_x, 2);
b_emxInit_boolean_T(&c_x, 1);
if ((x->size[0] != 1) && (x->size[1] == 1)) {
if (1 > nxout) {
nxout = 0;
}
i5 = c_x->size[0];
c_x->size[0] = nxout;
emxEnsureCapacity((emxArray__common *)c_x, i5, (int32_T)sizeof(boolean_T));
for (i5 = 0; i5 < nxout; i5++) {
c_x->data[i5] = x->data[i5];
}
i5 = x->size[0] * x->size[1];
x->size[0] = nxout;
x->size[1] = 1;
emxEnsureCapacity((emxArray__common *)x, i5, (int32_T)sizeof(boolean_T));
i5 = 0;
while (i5 <= 0) {
for (i5 = 0; i5 < nxout; i5++) {
x->data[i5] = c_x->data[i5];
}
i5 = 1;
}
} else {
if (1 > nxout) {
nxout = 0;
}
i5 = r12->size[0];
r12->size[0] = nxout;
emxEnsureCapacity((emxArray__common *)r12, i5, (int32_T)sizeof(int32_T));
for (i5 = 0; i5 < nxout; i5++) {
r12->data[i5] = 1 + i5;
}
nxout = r12->size[0];
i5 = b_x->size[0] * b_x->size[1];
b_x->size[0] = 1;
b_x->size[1] = nxout;
emxEnsureCapacity((emxArray__common *)b_x, i5, (int32_T)sizeof(boolean_T));
for (i5 = 0; i5 < nxout; i5++) {
k = 0;
while (k <= 0) {
b_x->data[b_x->size[0] * i5] = x->data[r12->data[i5] - 1];
k = 1;
}
}
i5 = x->size[0] * x->size[1];
x->size[0] = b_x->size[0];
x->size[1] = b_x->size[1];
emxEnsureCapacity((emxArray__common *)x, i5, (int32_T)sizeof(boolean_T));
nxout = b_x->size[1];
for (i5 = 0; i5 < nxout; i5++) {
k0 = b_x->size[0];
for (k = 0; k < k0; k++) {
x->data[k + x->size[0] * i5] = b_x->data[k + b_x->size[0] * i5];
}
}
}
emxFree_boolean_T(&c_x);
emxFree_boolean_T(&b_x);
emxFree_int32_T(&r12);
}
static void eml_sort(const real_T x[17], real_T y[17], int32_T idx[17])
{
int32_T k;
boolean_T p;
int8_T idx0[17];
int32_T i;
int32_T i2;
int32_T j;
int32_T pEnd;
int32_T b_p;
int32_T q;
int32_T qEnd;
int32_T kEnd;
for (k = 0; k < 17; k++) {
idx[k] = k + 1;
}
for (k = 0; k < 15; k += 2) {
if ((x[k] <= x[k + 1]) || rtIsNaN(x[k + 1])) {
p = TRUE;
} else {
p = FALSE;
}
if (p) {
} else {
idx[k] = k + 2;
idx[k + 1] = k + 1;
}
}
for (i = 0; i < 17; i++) {
idx0[i] = 1;
}
i = 2;
while (i < 17) {
i2 = i << 1;
j = 1;
for (pEnd = 1 + i; pEnd < 18; pEnd = qEnd + i) {
b_p = j;
q = pEnd - 1;
qEnd = j + i2;
if (qEnd > 18) {
qEnd = 18;
}
k = 0;
kEnd = qEnd - j;
while (k + 1 <= kEnd) {
if ((x[idx[b_p - 1] - 1] <= x[idx[q] - 1]) || rtIsNaN(x[idx[q] - 1])) {
p = TRUE;
} else {
p = FALSE;
}
if (p) {
idx0[k] = (int8_T)idx[b_p - 1];
b_p++;
if (b_p == pEnd) {
while (q + 1 < qEnd) {
k++;
idx0[k] = (int8_T)idx[q];
q++;
}
}
} else {
idx0[k] = (int8_T)idx[q];
q++;
if (q + 1 == qEnd) {
while (b_p < pEnd) {
k++;
idx0[k] = (int8_T)idx[b_p - 1];
b_p++;
}
}
}
k++;
}
for (k = 0; k + 1 <= kEnd; k++) {
idx[(j + k) - 1] = idx0[k];
}
j = qEnd;
}
i = i2;
}
for (k = 0; k < 17; k++) {
y[k] = x[idx[k] - 1];
}
}
static void emxEnsureCapacity(emxArray__common *emxArray, int32_T oldNumel,
int32_T elementSize)
{
int32_T newNumel;
int32_T i;
void *newData;
newNumel = 1;
for (i = 0; i < emxArray->numDimensions; i++) {
newNumel *= emxArray->size[i];
}
if (newNumel > emxArray->allocatedSize) {
i = emxArray->allocatedSize;
if (i < 16) {
i = 16;
}
while (i < newNumel) {
i <<= 1;
}
newData = calloc((uint32_T)i, (uint32_T)elementSize);
if (emxArray->data != NULL) {
memcpy(newData, emxArray->data, (uint32_T)(elementSize * oldNumel));
if (emxArray->canFreeData) {
free(emxArray->data);
}
}
emxArray->data = newData;
emxArray->allocatedSize = i;
emxArray->canFreeData = TRUE;
}
}
static void emxFree_boolean_T(emxArray_boolean_T **pEmxArray)
{
if (*pEmxArray != (emxArray_boolean_T *)NULL) {
if ((*pEmxArray)->canFreeData) {
free((void *)(*pEmxArray)->data);
}
free((void *)(*pEmxArray)->size);
free((void *)*pEmxArray);
*pEmxArray = (emxArray_boolean_T *)NULL;
}
}
static void emxFree_int32_T(emxArray_int32_T **pEmxArray)
{
if (*pEmxArray != (emxArray_int32_T *)NULL) {
if ((*pEmxArray)->canFreeData) {
free((void *)(*pEmxArray)->data);
}
free((void *)(*pEmxArray)->size);
free((void *)*pEmxArray);
*pEmxArray = (emxArray_int32_T *)NULL;
}
}
static void emxFree_real_T(emxArray_real_T **pEmxArray)
{
if (*pEmxArray != (emxArray_real_T *)NULL) {
if ((*pEmxArray)->canFreeData) {
free((void *)(*pEmxArray)->data);
}
free((void *)(*pEmxArray)->size);
free((void *)*pEmxArray);
*pEmxArray = (emxArray_real_T *)NULL;
}
}
static void emxInit_boolean_T(emxArray_boolean_T **pEmxArray, int32_T
numDimensions)
{
emxArray_boolean_T *emxArray;
int32_T i;
*pEmxArray = (emxArray_boolean_T *)malloc(sizeof(emxArray_boolean_T));
emxArray = *pEmxArray;
emxArray->data = (boolean_T *)NULL;
emxArray->numDimensions = numDimensions;
emxArray->size = (int32_T *)malloc((uint32_T)(sizeof(int32_T) * numDimensions));
emxArray->allocatedSize = 0;
emxArray->canFreeData = TRUE;
for (i = 0; i < numDimensions; i++) {
emxArray->size[i] = 0;
}
}
static void emxInit_int32_T(emxArray_int32_T **pEmxArray, int32_T numDimensions)
{
emxArray_int32_T *emxArray;
int32_T i;
*pEmxArray = (emxArray_int32_T *)malloc(sizeof(emxArray_int32_T));
emxArray = *pEmxArray;
emxArray->data = (int32_T *)NULL;
emxArray->numDimensions = numDimensions;
emxArray->size = (int32_T *)malloc((uint32_T)(sizeof(int32_T) * numDimensions));
emxArray->allocatedSize = 0;
emxArray->canFreeData = TRUE;
for (i = 0; i < numDimensions; i++) {
emxArray->size[i] = 0;
}
}
static void emxInit_real_T(emxArray_real_T **pEmxArray, int32_T numDimensions)
{
emxArray_real_T *emxArray;
int32_T i;
*pEmxArray = (emxArray_real_T *)malloc(sizeof(emxArray_real_T));
emxArray = *pEmxArray;
emxArray->data = (real_T *)NULL;
emxArray->numDimensions = numDimensions;
emxArray->size = (int32_T *)malloc((uint32_T)(sizeof(int32_T) * numDimensions));
emxArray->allocatedSize = 0;
emxArray->canFreeData = TRUE;
for (i = 0; i < numDimensions; i++) {
emxArray->size[i] = 0;
}
}
static real_T featureSpectralCentroid(real_T S[17])
{
real_T y;
int32_T i;
real_T b_y;
/* FEATURESPECTRALCENTROID Computes spectral centroid feature */
/* It is the mass center of the spectrum */
/* [r,c] = size(S); */
/* feature = sum(repmat((1:r)',1,c).* S)./sum(S); */
y = 0.0;
for (i = 0; i < 17; i++) {
b_y = S[i] * S[i];
y += (((real_T)i + 1.0) - 1.0) * b_y;
S[i] = b_y;
}
b_y = S[0];
for (i = 0; i < 16; i++) {
b_y += S[i + 1];
}
return y / b_y;
}
static real_T featureSpectralCrest(const real_T S[17])
{
int32_T ixstart;
real_T mtmp;
int32_T ix;
boolean_T exitg1;
real_T y;
/* FEATURESPECTRALCREST Computes spectral crest */
/* It is a rough measure of tonality */
ixstart = 1;
mtmp = S[0];
if (rtIsNaN(S[0])) {
ix = 2;
exitg1 = FALSE;
while ((exitg1 == FALSE) && (ix < 18)) {
ixstart = ix;
if (!rtIsNaN(S[ix - 1])) {
mtmp = S[ix - 1];
exitg1 = TRUE;
} else {
ix++;
}
}
}
if (ixstart < 17) {
while (ixstart + 1 < 18) {
if (S[ixstart] > mtmp) {
mtmp = S[ixstart];
}
ixstart++;
}
}
y = S[0];
for (ixstart = 0; ixstart < 16; ixstart++) {
y += S[ixstart + 1];
}
return mtmp / y;
}
static void filter(const emxArray_real_T *x, real_T zi, emxArray_real_T *y)
{
uint32_T unnamed_idx_0;
int32_T j;
real_T dbuffer[2];
int32_T k;
real_T b_dbuffer;
unnamed_idx_0 = (uint32_T)x->size[0];
j = y->size[0];
y->size[0] = (int32_T)unnamed_idx_0;
emxEnsureCapacity((emxArray__common *)y, j, (int32_T)sizeof(real_T));
dbuffer[1] = zi;
for (j = 0; j + 1 <= x->size[0]; j++) {
dbuffer[0] = dbuffer[1];
dbuffer[1] = 0.0;
for (k = 0; k < 2; k++) {
b_dbuffer = dbuffer[k] + x->data[j] * 0.33333333333333331;
dbuffer[k] = b_dbuffer;
}
y->data[j] = dbuffer[0];
}
}
static void filtfilt(const emxArray_real_T *x_in, emxArray_real_T *y_out)
{
emxArray_real_T *x;
int32_T i2;
int32_T loop_ub;
emxArray_real_T *y;
real_T xtmp;
real_T b_y;
int32_T md2;
emxArray_real_T *c_y;
int32_T m;
emxArray_real_T *d_y;
emxArray_int32_T *r6;
b_emxInit_real_T(&x, 1);
if (x_in->size[0] == 1) {
i2 = x->size[0];
x->size[0] = 1;
emxEnsureCapacity((emxArray__common *)x, i2, (int32_T)sizeof(real_T));
x->data[0] = x_in->data[0];
} else {
i2 = x->size[0];
x->size[0] = x_in->size[0];
emxEnsureCapacity((emxArray__common *)x, i2, (int32_T)sizeof(real_T));
loop_ub = x_in->size[0];
for (i2 = 0; i2 < loop_ub; i2++) {
x->data[i2] = x_in->data[i2];
}
}
if (x->size[0] == 0) {
i2 = y_out->size[0] * y_out->size[1];
y_out->size[0] = 0;
y_out->size[1] = 0;
emxEnsureCapacity((emxArray__common *)y_out, i2, (int32_T)sizeof(real_T));
} else {
b_emxInit_real_T(&y, 1);
xtmp = 2.0 * x->data[0];
b_y = 2.0 * x->data[x->size[0] - 1];
md2 = x->size[0] - 1;
i2 = y->size[0];
y->size[0] = 6 + x->size[0];
emxEnsureCapacity((emxArray__common *)y, i2, (int32_T)sizeof(real_T));
for (i2 = 0; i2 < 3; i2++) {
y->data[i2] = xtmp - x->data[3 - i2];
}
loop_ub = x->size[0];
for (i2 = 0; i2 < loop_ub; i2++) {
y->data[i2 + 3] = x->data[i2];
}
for (i2 = 0; i2 < 3; i2++) {
y->data[(i2 + x->size[0]) + 3] = b_y - x->data[(md2 - i2) - 1];
}
b_emxInit_real_T(&c_y, 1);
i2 = c_y->size[0];
c_y->size[0] = y->size[0];
emxEnsureCapacity((emxArray__common *)c_y, i2, (int32_T)sizeof(real_T));
loop_ub = y->size[0];
for (i2 = 0; i2 < loop_ub; i2++) {
c_y->data[i2] = y->data[i2];
}
xtmp = y->data[0];
filter(c_y, 0.33333333333333331 * xtmp, y);
m = y->size[0];
i2 = y->size[0];
md2 = i2 / 2;
loop_ub = 1;
emxFree_real_T(&c_y);
while (loop_ub <= md2) {
xtmp = y->data[loop_ub - 1];
y->data[loop_ub - 1] = y->data[m - loop_ub];
y->data[m - loop_ub] = xtmp;
loop_ub++;
}
b_emxInit_real_T(&d_y, 1);
i2 = d_y->size[0];
d_y->size[0] = y->size[0];
emxEnsureCapacity((emxArray__common *)d_y, i2, (int32_T)sizeof(real_T));
loop_ub = y->size[0];
for (i2 = 0; i2 < loop_ub; i2++) {
d_y->data[i2] = y->data[i2];
}
xtmp = y->data[0];
filter(d_y, 0.33333333333333331 * xtmp, y);
m = y->size[0];
i2 = y->size[0];
md2 = i2 / 2;
loop_ub = 1;
emxFree_real_T(&d_y);
while (loop_ub <= md2) {
xtmp = y->data[loop_ub - 1];
y->data[loop_ub - 1] = y->data[m - loop_ub];
y->data[m - loop_ub] = xtmp;
loop_ub++;
}
if (x_in->size[0] == 1) {
emxInit_int32_T(&r6, 1);
loop_ub = (int32_T)((real_T)x->size[0] + 3.0) - 4;
i2 = r6->size[0];
r6->size[0] = loop_ub + 1;
emxEnsureCapacity((emxArray__common *)r6, i2, (int32_T)sizeof(int32_T));
for (i2 = 0; i2 <= loop_ub; i2++) {
r6->data[i2] = 4 + i2;
}
i2 = y_out->size[0] * y_out->size[1];
y_out->size[0] = 1;
emxEnsureCapacity((emxArray__common *)y_out, i2, (int32_T)sizeof(real_T));
md2 = r6->size[0];
i2 = y_out->size[0] * y_out->size[1];
y_out->size[1] = md2;
emxEnsureCapacity((emxArray__common *)y_out, i2, (int32_T)sizeof(real_T));
loop_ub = r6->size[0];
for (i2 = 0; i2 < loop_ub; i2++) {
y_out->data[i2] = y->data[r6->data[i2] - 1];
}
emxFree_int32_T(&r6);
} else {
emxInit_int32_T(&r6, 1);
loop_ub = (int32_T)((real_T)x->size[0] + 3.0) - 3;
i2 = y_out->size[0] * y_out->size[1];
y_out->size[0] = loop_ub;
y_out->size[1] = 1;
emxEnsureCapacity((emxArray__common *)y_out, i2, (int32_T)sizeof(real_T));
md2 = (int32_T)((real_T)x->size[0] + 3.0) - 4;
i2 = r6->size[0];
r6->size[0] = md2 + 1;
emxEnsureCapacity((emxArray__common *)r6, i2, (int32_T)sizeof(int32_T));
for (i2 = 0; i2 <= md2; i2++) {
r6->data[i2] = 4 + i2;
}
for (i2 = 0; i2 < loop_ub; i2++) {
y_out->data[i2] = y->data[r6->data[i2] - 1];
}
emxFree_int32_T(&r6);
}
emxFree_real_T(&y);
}
emxFree_real_T(&x);
}
static void histogramFeatures(const real_T ioiHist[17], real_T features[12])
{
int32_T iidx[17];
real_T k[17];
int32_T ind[17];
boolean_T S[17];
int32_T cindx;
real_T xlast;
int32_T b_k;
real_T b_ioiHist[17];
real_T sigma;
real_T b_S[17];
real_T b[17];
int32_T ix;
boolean_T x;
int8_T S_size[2];
int8_T outsz[2];
int32_T loop_ub;
int32_T iindx_data[1];
int32_T b_ix;
int32_T indx_data[1];
/* UNTITLED Summary of this function goes here */
/* Detailed explanation goes here */
/* features(1) = mean(ioiHist); */
features[0] = b_std(ioiHist);
eml_sort(ioiHist, k, iidx);
features[1] = k[16] / k[15];
for (cindx = 0; cindx < 17; cindx++) {
ind[cindx] = iidx[cindx];
S[cindx] = (ioiHist[cindx] == 0.0);
}
features[2] = (real_T)ind[16] / (real_T)ind[15];
xlast = S[0];
for (b_k = 0; b_k < 16; b_k++) {
xlast += (real_T)S[b_k + 1];
}
features[3] = xlast / 17.0;
for (cindx = 0; cindx < 17; cindx++) {
b_ioiHist[cindx] = ioiHist[cindx];
/* FEATURESPECTRALDECREASE Computes the Spectral Decrease */
/* A measure of steepness of spectral envelope over frequency */
k[cindx] = cindx;
}
features[4] = featureSpectralCentroid(b_ioiHist);
features[5] = featureSpectralCrest(ioiHist);
k[0] = 1.0;
xlast = 0.0;
for (cindx = 0; cindx < 17; cindx++) {
/* compute slope */
xlast += 1.0 / k[cindx] * (ioiHist[cindx] - ioiHist[0]);
}
sigma = ioiHist[1];
for (b_k = 0; b_k < 15; b_k++) {
sigma += ioiHist[b_k + 2];
}
features[6] = xlast / sigma;
/* FEATURESPECTRALKURTOSIS Computes the Spectral Kurtosis */
/* It is a measure of gaussianity of a spectrum */
sigma = c_std(ioiHist);
/* Subtracting means */
xlast = ioiHist[0];
for (b_k = 0; b_k < 16; b_k++) {
xlast += ioiHist[b_k + 1];
}
bsxfun(ioiHist, xlast / 17.0, b_S);
for (b_k = 0; b_k < 17; b_k++) {
k[b_k] = rt_powd_snf(b_S[b_k], 4.0) / (rt_powd_snf(sigma, 4.0) * 17.0);
}
sigma = k[0];
for (b_k = 0; b_k < 16; b_k++) {
sigma += k[b_k + 1];
}
features[7] = sigma;
/* FEATURESPECTRALROLLOFF Computes Spectral Rolloff */
/* Finds frequency bin where cumsum reaches 0.85 of magnitude */
/* compute rolloff */
xlast = ioiHist[0];
for (b_k = 0; b_k < 16; b_k++) {
xlast += ioiHist[b_k + 1];
}
sigma = 0.85 * xlast;
/* Find indices where cumulative sum is greater */
memcpy(&b[0], &ioiHist[0], 17U * sizeof(real_T));
ix = 0;
xlast = ioiHist[0];
for (b_k = 0; b_k < 16; b_k++) {
ix++;
xlast += b[ix];
b[ix] = xlast;
}
for (b_k = 0; b_k < 17; b_k++) {
S[b_k] = (b[b_k] >= sigma);
}
/* Find the maximum value */
xlast = S[0];
for (b_k = 0; b_k < 16; b_k++) {
xlast += (real_T)S[b_k + 1];
}
x = (xlast > 0.0);
b_k = 0;
if (x) {
b_k = 1;
}
S_size[0] = 17;
S_size[1] = (int8_T)b_k;
for (cindx = 0; cindx < 2; cindx++) {
outsz[cindx] = S_size[cindx];
}
loop_ub = outsz[1];
for (cindx = 0; cindx < loop_ub; cindx++) {
iindx_data[cindx] = 1;
}
ix = -16;
cindx = 1;
while (cindx <= b_k) {
ix += 17;
x = S[(ix - 1) % 17];
loop_ub = 1;
cindx = 1;
if (ix < ix + 16) {
for (b_ix = ix; b_ix + 1 <= ix + 16; b_ix++) {
cindx++;
if (S[b_ix % 17] > x) {
x = S[b_ix % 17];
loop_ub = cindx;
}
}
}
iindx_data[0] = loop_ub;
cindx = 2;
}
loop_ub = outsz[1];
for (cindx = 0; cindx < loop_ub; cindx++) {
indx_data[cindx] = iindx_data[cindx];
}
features[8] = indx_data[0];
/* FEATURESPECTRALSKEWNESS Compute spectral skewness */
/* A measure of symmettricity of pdf */
sigma = c_std(ioiHist);
/* Subtracting means */
xlast = ioiHist[0];
for (b_k = 0; b_k < 16; b_k++) {
xlast += ioiHist[b_k + 1];
}
bsxfun(ioiHist, xlast / 17.0, b_S);
for (b_k = 0; b_k < 17; b_k++) {
k[b_k] = rt_powd_snf(b_S[b_k], 3.0) / (rt_powd_snf(sigma, 3.0) * 17.0);
}
sigma = k[0];
for (b_k = 0; b_k < 16; b_k++) {
sigma += k[b_k + 1];
}
features[9] = sigma;
/* FUNCTIONSPECTRALSLOPE Computes the spectral slope */
/* */
/* compute index vector */
/* compute slope */
xlast = ioiHist[0];
for (b_k = 0; b_k < 16; b_k++) {
xlast += ioiHist[b_k + 1];
}
bsxfun(ioiHist, xlast / 17.0, b_S);
xlast = 0.0;
sigma = 0.0;
for (b_k = 0; b_k < 17; b_k++) {
xlast += (-8.5 + (((real_T)b_k + 1.0) - 1.0)) * b_S[b_k];
sigma += (-8.5 + (((real_T)b_k + 1.0) - 1.0)) * (-8.5 + (((real_T)b_k + 1.0)
- 1.0));
b_ioiHist[b_k] = ioiHist[b_k];
k[b_k] = b_k;
b_S[b_k] = ioiHist[b_k] * ioiHist[b_k];
}
features[10] = xlast / sigma;
/* FEATURESPECTRALSPREAD Computes spectral spread */
/* Concentration of energy around spectral centroid */
bsxfun(k, featureSpectralCentroid(b_ioiHist), b);
for (b_k = 0; b_k < 17; b_k++) {
k[b_k] = b[b_k] * b[b_k] * b_S[b_k];
}
xlast = k[0];
sigma = b_S[0];
for (b_k = 0; b_k < 16; b_k++) {
xlast += k[b_k + 1];
sigma += b_S[b_k + 1];
}
features[11] = sqrt(xlast / sigma);
}
static void ioiHistogram(emxArray_boolean_T *onsets, const emxArray_real_T *T,
real_T ioiHist[17])
{
emxArray_real_T *tOnset;
emxArray_int32_T *r10;
int32_T high_i;
int32_T ixLead;
emxArray_real_T *ioi;
emxArray_real_T *b_y1;
int32_T iyLead;
real_T work_data_idx_0;
real_T tmp1;
real_T tmp2;
int32_T sz[2];
real_T meanIOI_data[1];
int32_T meanIOI_size[2];
int32_T k;
emxArray_real_T *r11;
emxArray_real_T b_meanIOI_data;
int32_T d;
real_T stdIOI_data[1];
boolean_T goodInd_data[1];
real_T histEdges[17];
int32_T exitg1;
b_emxInit_real_T(&tOnset, 1);
emxInit_int32_T(&r10, 1);
/* UNTITLED2 Summary of this function goes here */
/* Detailed explanation goes here */
/* Setting the first one as true */
onsets->data[0] = TRUE;
/* onsetInd = onsets; */
eml_li_find(onsets, r10);
high_i = tOnset->size[0];
tOnset->size[0] = r10->size[0];
emxEnsureCapacity((emxArray__common *)tOnset, high_i, (int32_T)sizeof(real_T));
ixLead = r10->size[0];
for (high_i = 0; high_i < ixLead; high_i++) {
tOnset->data[high_i] = T->data[r10->data[high_i] - 1];
}
emxFree_int32_T(&r10);
emxInit_real_T(&ioi, 2);
if (tOnset->size[0] == 0) {
high_i = ioi->size[0] * ioi->size[1];
ioi->size[0] = 0;
ioi->size[1] = 1;
emxEnsureCapacity((emxArray__common *)ioi, high_i, (int32_T)sizeof(real_T));
} else {
ixLead = tOnset->size[0] - 1;
if (ixLead <= 1) {
} else {
ixLead = 1;
}
if (ixLead < 1) {
high_i = ioi->size[0] * ioi->size[1];
ioi->size[0] = 0;
ioi->size[1] = 0;
emxEnsureCapacity((emxArray__common *)ioi, high_i, (int32_T)sizeof(real_T));
} else {
b_emxInit_real_T(&b_y1, 1);
high_i = b_y1->size[0];
b_y1->size[0] = tOnset->size[0] - 1;
emxEnsureCapacity((emxArray__common *)b_y1, high_i, (int32_T)sizeof(real_T));
ixLead = 1;
iyLead = 0;
work_data_idx_0 = tOnset->data[0];
for (high_i = 2; high_i <= tOnset->size[0]; high_i++) {
tmp1 = tOnset->data[ixLead];
tmp2 = work_data_idx_0;
work_data_idx_0 = tmp1;
tmp1 -= tmp2;
ixLead++;
b_y1->data[iyLead] = tmp1;
iyLead++;
}
ixLead = b_y1->size[0];
high_i = ioi->size[0] * ioi->size[1];
ioi->size[0] = ixLead;
emxEnsureCapacity((emxArray__common *)ioi, high_i, (int32_T)sizeof(real_T));
high_i = ioi->size[0] * ioi->size[1];
ioi->size[1] = 1;
emxEnsureCapacity((emxArray__common *)ioi, high_i, (int32_T)sizeof(real_T));
ixLead = b_y1->size[0];
for (high_i = 0; high_i < ixLead; high_i++) {
ioi->data[high_i] = b_y1->data[high_i];
}
emxFree_real_T(&b_y1);
}
}
emxFree_real_T(&tOnset);
for (high_i = 0; high_i < 2; high_i++) {
sz[high_i] = ioi->size[high_i];
}
meanIOI_size[0] = 1;
meanIOI_size[1] = sz[1];
if ((ioi->size[0] == 0) || (ioi->size[1] == 0)) {
meanIOI_size[0] = 1;
meanIOI_size[1] = sz[1];
ixLead = sz[1];
for (high_i = 0; high_i < ixLead; high_i++) {
meanIOI_data[high_i] = 0.0;
}
} else {
iyLead = -1;
work_data_idx_0 = ioi->data[0];
for (k = 2; k <= ioi->size[0]; k++) {
iyLead++;
work_data_idx_0 += ioi->data[iyLead + 1];
}
meanIOI_data[0] = work_data_idx_0;
}
emxInit_real_T(&r11, 2);
b_meanIOI_data.data = (real_T *)&meanIOI_data;
b_meanIOI_data.size = (int32_T *)&meanIOI_size;
b_meanIOI_data.allocatedSize = 1;
b_meanIOI_data.numDimensions = 2;
b_meanIOI_data.canFreeData = FALSE;
rdivide(&b_meanIOI_data, ioi->size[0], r11);
meanIOI_size[0] = 1;
meanIOI_size[1] = r11->size[1];
ixLead = r11->size[0] * r11->size[1];
for (high_i = 0; high_i < ixLead; high_i++) {
meanIOI_data[high_i] = r11->data[high_i];
}
emxFree_real_T(&r11);
if (ioi->size[0] > 1) {
d = ioi->size[0] - 1;
} else {
d = ioi->size[0];
}
for (high_i = 0; high_i < 2; high_i++) {
sz[high_i] = ioi->size[high_i];
}
iyLead = 0;
ixLead = 1;
while (ixLead <= ioi->size[1]) {
if ((ioi->size[0] == 0) || (ioi->size[1] == 0)) {
work_data_idx_0 = rtNaN;
} else {
ixLead = iyLead;
tmp1 = ioi->data[iyLead];
for (k = 0; k <= ioi->size[0] - 2; k++) {
ixLead++;
tmp1 += ioi->data[ixLead];
}
tmp1 /= (real_T)ioi->size[0];
ixLead = iyLead;
tmp2 = ioi->data[iyLead] - tmp1;
work_data_idx_0 = tmp2 * tmp2;
for (k = 0; k <= ioi->size[0] - 2; k++) {
ixLead++;
tmp2 = ioi->data[ixLead] - tmp1;
work_data_idx_0 += tmp2 * tmp2;
}
work_data_idx_0 /= (real_T)d;
}
stdIOI_data[0] = work_data_idx_0;
iyLead += ioi->size[0];
ixLead = 2;
}
k = 0;
while (k <= sz[1] - 1) {
stdIOI_data[0] = sqrt(stdIOI_data[0]);
k = 1;
}
iyLead = ioi->size[1];
ixLead = ioi->size[0] * ioi->size[1];
for (high_i = 0; high_i < ixLead; high_i++) {
goodInd_data[high_i] = ((ioi->data[high_i] > meanIOI_data[high_i] - 2.0 *
stdIOI_data[high_i]) && (ioi->data[high_i] < meanIOI_data[high_i] + 2.0 *
stdIOI_data[high_i]));
}
k = 0;
ixLead = 1;
while (ixLead <= iyLead) {
if (goodInd_data[0]) {
k++;
}
ixLead = 2;
}
/* Avoiding code export bug */
/* ioi(ioi>upperThresh) = []; */
/* ioi(ioi<lowerThresh) = []; */
/* nBins = 16; */
for (high_i = 0; high_i < 17; high_i++) {
histEdges[high_i] = 0.125 * (real_T)high_i;
ioiHist[high_i] = 0.0;
}
histEdges[16] = rtInf;
high_i = 0;
do {
exitg1 = 0;
if (high_i < 16) {
if (histEdges[1 + high_i] < histEdges[high_i]) {
for (high_i = 0; high_i < 17; high_i++) {
ioiHist[high_i] = rtNaN;
}
exitg1 = 1;
} else {
high_i++;
}
} else {
ixLead = 0;
while (ixLead <= k - 1) {
ixLead = 0;
if (!rtIsNaN(ioi->data[0])) {
if ((ioi->data[0] >= 0.0) && (ioi->data[0] < rtInf)) {
ixLead = 1;
iyLead = 2;
high_i = 17;
while (high_i > iyLead) {
d = (ixLead + high_i) >> 1;
if (ioi->data[0] >= histEdges[d - 1]) {
ixLead = d;
iyLead = d + 1;
} else {
high_i = d;
}
}
}
if (ioi->data[0] == rtInf) {
ixLead = 17;
}
}
if (ixLead > 0) {
ioiHist[ixLead - 1]++;
}
ixLead = 1;
}
exitg1 = 1;
}
} while (exitg1 == 0);
emxFree_real_T(&ioi);
work_data_idx_0 = ioiHist[0];
for (k = 0; k < 16; k++) {
work_data_idx_0 += ioiHist[k + 1];
}
for (high_i = 0; high_i < 17; high_i++) {
ioiHist[high_i] /= work_data_idx_0;
}
}
static void onsetDetection(const emxArray_real_T *spec, emxArray_boolean_T
*onsets, emxArray_real_T *flux)
{
emxArray_real_T *b_flux;
int32_T ixstart;
real_T mtmp;
int32_T k0;
boolean_T exitg1;
int32_T i0;
emxArray_real_T *flux1;
int32_T varargin_1[2];
int32_T i;
boolean_T x[7];
int32_T k;
emxArray_real_T *r0;
int32_T nxin;
emxArray_real_T *r1;
emxArray_real_T *mask2;
emxArray_boolean_T *b;
emxArray_int32_T *r2;
emxArray_real_T *b_mask2;
emxArray_real_T *c_mask2;
emxArray_real_T *r3;
int32_T vstride;
int32_T npages;
int32_T dim;
int32_T j;
int32_T ia;
b_emxInit_real_T(&b_flux, 1);
/* UNTITLED2 Summary of this function goes here */
/* Detailed explanation goes here */
onsetFlux(spec, b_flux);
/* Normalizing */
ixstart = 1;
mtmp = b_flux->data[0];
if (b_flux->size[0] > 1) {
if (rtIsNaN(b_flux->data[0])) {
k0 = 2;
exitg1 = FALSE;
while ((exitg1 == FALSE) && (k0 <= b_flux->size[0])) {
ixstart = k0;
if (!rtIsNaN(b_flux->data[k0 - 1])) {
mtmp = b_flux->data[k0 - 1];
exitg1 = TRUE;
} else {
k0++;
}
}
}
if (ixstart < b_flux->size[0]) {
while (ixstart + 1 <= b_flux->size[0]) {
if (b_flux->data[ixstart] > mtmp) {
mtmp = b_flux->data[ixstart];
}
ixstart++;
}
}
}
i0 = b_flux->size[0];
emxEnsureCapacity((emxArray__common *)b_flux, i0, (int32_T)sizeof(real_T));
ixstart = b_flux->size[0];
for (i0 = 0; i0 < ixstart; i0++) {
b_flux->data[i0] /= mtmp;
}
emxInit_real_T(&flux1, 2);
/* Smoothing */
/* h=fdesign.lowpass('N,F3dB',12,0.15); */
/* d1 = design(h,'elliptic'); */
/* flux = filtfilt(d1.sosMatrix,d1.ScaleValues,flux); */
filtfilt(b_flux, flux);
/* h = 1/4*ones(4,1); */
/* flux = filter(h,1,flux); */
/* Peak picking */
/* w = 2; % Size of window to find local maxima */
padarray(flux, flux1);
emxFree_real_T(&b_flux);
for (i0 = 0; i0 < 2; i0++) {
varargin_1[i0] = flux1->size[i0];
}
i0 = onsets->size[0] * onsets->size[1];
onsets->size[0] = varargin_1[0];
emxEnsureCapacity((emxArray__common *)onsets, i0, (int32_T)sizeof(boolean_T));
i0 = onsets->size[0] * onsets->size[1];
onsets->size[1] = varargin_1[1];
emxEnsureCapacity((emxArray__common *)onsets, i0, (int32_T)sizeof(boolean_T));
ixstart = varargin_1[0] * varargin_1[1];
for (i0 = 0; i0 < ixstart; i0++) {
onsets->data[i0] = FALSE;
}
if ((0 == flux1->size[0]) || (0 == flux1->size[1])) {
ixstart = 0;
} else if (flux1->size[0] > flux1->size[1]) {
ixstart = flux1->size[0];
} else {
ixstart = flux1->size[1];
}
for (i = 3; i - 3 <= ixstart - 7; i++) {
mtmp = flux1->data[i];
for (i0 = 0; i0 < 7; i0++) {
x[i0] = (mtmp >= flux1->data[(i0 + i) - 3]);
}
mtmp = x[0];
for (k = 0; k < 6; k++) {
mtmp += (real_T)x[k + 1];
}
if (mtmp == 7.0) {
onsets->data[i] = TRUE;
}
}
b_emxInit_real_T(&r0, 1);
/* Remove m elements at the start and end */
eml_null_assignment(onsets);
mtmp = (real_T)(onsets->size[0] * onsets->size[1]) - 3.0;
i0 = onsets->size[0] * onsets->size[1];
nxin = r0->size[0];
r0->size[0] = (int32_T)((real_T)i0 - mtmp) + 1;
emxEnsureCapacity((emxArray__common *)r0, nxin, (int32_T)sizeof(real_T));
ixstart = (int32_T)((real_T)i0 - mtmp);
for (i0 = 0; i0 <= ixstart; i0++) {
r0->data[i0] = mtmp + (real_T)i0;
}
emxInit_real_T(&r1, 2);
i0 = r1->size[0] * r1->size[1];
r1->size[0] = 1;
emxEnsureCapacity((emxArray__common *)r1, i0, (int32_T)sizeof(real_T));
ixstart = r0->size[0];
i0 = r1->size[0] * r1->size[1];
r1->size[1] = ixstart;
emxEnsureCapacity((emxArray__common *)r1, i0, (int32_T)sizeof(real_T));
ixstart = r0->size[0];
for (i0 = 0; i0 < ixstart; i0++) {
r1->data[i0] = r0->data[i0];
}
emxFree_real_T(&r0);
b_eml_null_assignment(onsets, r1);
/* Perform second thresholding operation */
/* m = 1; % Multiplier so mean is calculated over a larger range before peak */
/* delta = 0.01; % Threshold above local mean */
padarray(flux, flux1);
for (i0 = 0; i0 < 2; i0++) {
varargin_1[i0] = flux1->size[i0];
}
emxInit_real_T(&mask2, 2);
i0 = mask2->size[0] * mask2->size[1];
mask2->size[0] = varargin_1[0];
emxEnsureCapacity((emxArray__common *)mask2, i0, (int32_T)sizeof(real_T));
i0 = mask2->size[0] * mask2->size[1];
mask2->size[1] = varargin_1[1];
emxEnsureCapacity((emxArray__common *)mask2, i0, (int32_T)sizeof(real_T));
ixstart = varargin_1[0] * varargin_1[1];
for (i0 = 0; i0 < ixstart; i0++) {
mask2->data[i0] = 0.0;
}
if ((0 == flux1->size[0]) || (0 == flux1->size[1])) {
ixstart = 0;
} else if (flux1->size[0] > flux1->size[1]) {
ixstart = flux1->size[0];
} else {
ixstart = flux1->size[1];
}
for (i = 3; i - 3 <= ixstart - 7; i++) {
/* flux = onsetDetection(denoisedSpec); */
mtmp = flux1->data[-3 + i];
for (k = 0; k < 6; k++) {
mtmp += flux1->data[(k + i) - 2];
}
if (flux1->data[i] >= mtmp / 7.0 + 0.01) {
mask2->data[i] = 1.0;
}
}
emxFree_real_T(&flux1);
emxInit_boolean_T(&b, 2);
/* Remove mw elements at the start and end */
nxin = mask2->size[0] * mask2->size[1];
i0 = b->size[0] * b->size[1];
b->size[0] = 1;
b->size[1] = nxin;
emxEnsureCapacity((emxArray__common *)b, i0, (int32_T)sizeof(boolean_T));
for (i0 = 0; i0 < nxin; i0++) {
b->data[i0] = FALSE;
}
for (k = 0; k < 2; k++) {
b->data[k] = TRUE;
}
ixstart = 0;
for (k = 1; k <= b->size[1]; k++) {
ixstart += b->data[k - 1];
}
ixstart = nxin - ixstart;
k0 = -1;
for (k = 1; k <= nxin; k++) {
if ((k > b->size[1]) || (!b->data[k - 1])) {
k0++;
mask2->data[k0] = mask2->data[k - 1];
}
}
emxInit_int32_T(&r2, 1);
emxInit_real_T(&b_mask2, 2);
b_emxInit_real_T(&c_mask2, 1);
if ((mask2->size[0] != 1) && (mask2->size[1] == 1)) {
if (1 > ixstart) {
ixstart = 0;
}
i0 = c_mask2->size[0];
c_mask2->size[0] = ixstart;
emxEnsureCapacity((emxArray__common *)c_mask2, i0, (int32_T)sizeof(real_T));
for (i0 = 0; i0 < ixstart; i0++) {
c_mask2->data[i0] = mask2->data[i0];
}
i0 = mask2->size[0] * mask2->size[1];
mask2->size[0] = ixstart;
mask2->size[1] = 1;
emxEnsureCapacity((emxArray__common *)mask2, i0, (int32_T)sizeof(real_T));
i0 = 0;
while (i0 <= 0) {
for (i0 = 0; i0 < ixstart; i0++) {
mask2->data[i0] = c_mask2->data[i0];
}
i0 = 1;
}
} else {
if (1 > ixstart) {
ixstart = 0;
}
i0 = r2->size[0];
r2->size[0] = ixstart;
emxEnsureCapacity((emxArray__common *)r2, i0, (int32_T)sizeof(int32_T));
for (i0 = 0; i0 < ixstart; i0++) {
r2->data[i0] = 1 + i0;
}
ixstart = r2->size[0];
i0 = b_mask2->size[0] * b_mask2->size[1];
b_mask2->size[0] = 1;
b_mask2->size[1] = ixstart;
emxEnsureCapacity((emxArray__common *)b_mask2, i0, (int32_T)sizeof(real_T));
for (i0 = 0; i0 < ixstart; i0++) {
nxin = 0;
while (nxin <= 0) {
b_mask2->data[b_mask2->size[0] * i0] = mask2->data[r2->data[i0] - 1];
nxin = 1;
}
}
i0 = mask2->size[0] * mask2->size[1];
mask2->size[0] = b_mask2->size[0];
mask2->size[1] = b_mask2->size[1];
emxEnsureCapacity((emxArray__common *)mask2, i0, (int32_T)sizeof(real_T));
ixstart = b_mask2->size[1];
for (i0 = 0; i0 < ixstart; i0++) {
k0 = b_mask2->size[0];
for (nxin = 0; nxin < k0; nxin++) {
mask2->data[nxin + mask2->size[0] * i0] = b_mask2->data[nxin +
b_mask2->size[0] * i0];
}
}
}
emxFree_real_T(&c_mask2);
emxFree_real_T(&b_mask2);
emxFree_int32_T(&r2);
b_emxInit_real_T(&r3, 1);
mtmp = (real_T)(mask2->size[0] * mask2->size[1]) - 3.0;
i0 = mask2->size[0] * mask2->size[1];
nxin = r3->size[0];
r3->size[0] = (int32_T)((real_T)i0 - mtmp) + 1;
emxEnsureCapacity((emxArray__common *)r3, nxin, (int32_T)sizeof(real_T));
ixstart = (int32_T)((real_T)i0 - mtmp);
for (i0 = 0; i0 <= ixstart; i0++) {
r3->data[i0] = mtmp + (real_T)i0;
}
i0 = r1->size[0] * r1->size[1];
r1->size[0] = 1;
emxEnsureCapacity((emxArray__common *)r1, i0, (int32_T)sizeof(real_T));
ixstart = r3->size[0];
i0 = r1->size[0] * r1->size[1];
r1->size[1] = ixstart;
emxEnsureCapacity((emxArray__common *)r1, i0, (int32_T)sizeof(real_T));
ixstart = r3->size[0];
for (i0 = 0; i0 < ixstart; i0++) {
r1->data[i0] = r3->data[i0];
}
emxFree_real_T(&r3);
c_eml_null_assignment(mask2, r1);
i0 = onsets->size[0] * onsets->size[1];
emxEnsureCapacity((emxArray__common *)onsets, i0, (int32_T)sizeof(boolean_T));
ixstart = onsets->size[0];
k0 = onsets->size[1];
ixstart *= k0;
emxFree_real_T(&r1);
for (i0 = 0; i0 < ixstart; i0++) {
onsets->data[i0] = (onsets->data[i0] && (mask2->data[i0] != 0.0));
}
emxFree_real_T(&mask2);
onsets->data[0] = FALSE;
if ((onsets->size[0] == 0) || (onsets->size[1] == 0) || ((onsets->size[0] == 1)
&& (onsets->size[1] == 1))) {
} else {
for (i0 = 0; i0 < 2; i0++) {
varargin_1[i0] = onsets->size[i0];
}
ixstart = varargin_1[0];
if (varargin_1[1] > varargin_1[0]) {
ixstart = varargin_1[1];
}
i0 = b->size[0] * b->size[1];
b->size[0] = 1;
b->size[1] = ixstart;
emxEnsureCapacity((emxArray__common *)b, i0, (int32_T)sizeof(boolean_T));
vstride = 1;
npages = onsets->size[0] * onsets->size[1];
for (dim = 0; dim < 2; dim++) {
i0 = onsets->size[dim];
npages = div_s32(npages, onsets->size[dim]);
if (onsets->size[dim] > 1) {
ixstart = (int32_T)fabs(-1.0 + (((real_T)dim + 1.0) - 1.0));
if (ixstart - div_s32(ixstart, onsets->size[dim]) * onsets->size[dim] >
0) {
ixstart = (onsets->size[dim] - 1) * vstride;
k0 = 0;
for (i = 1; i <= npages; i++) {
nxin = k0;
k0 += ixstart;
for (j = 1; j <= vstride; j++) {
nxin++;
k0++;
ia = nxin;
for (k = 1; k <= i0; k++) {
b->data[k - 1] = onsets->data[ia - 1];
ia += vstride;
}
ia = nxin - 1;
for (k = 2; k <= i0; k++) {
onsets->data[ia] = b->data[k - 1];
ia += vstride;
}
onsets->data[ia] = b->data[0];
}
}
}
}
vstride *= i0;
}
}
emxFree_boolean_T(&b);
/* Some post processing to remove sequences of onsets */
/* Changing to non vectorized versions for export */
if ((0 == onsets->size[0]) || (0 == onsets->size[1])) {
ixstart = 0;
} else if (onsets->size[0] > onsets->size[1]) {
ixstart = onsets->size[0];
} else {
ixstart = onsets->size[1];
}
for (i = 0; i <= ixstart - 3; i++) {
if ((onsets->data[i] == 1) && (onsets->data[i + 1] == 1)) {
if (onsets->data[i + 2] == 1) {
onsets->data[i + 2] = FALSE;
}
onsets->data[i + 1] = FALSE;
}
}
/* tripleInd = strfind(onsets',[1,1,1]); */
/* onsets(tripleInd+1) = 0; */
/* onsets(tripleInd+2) = 0; */
/* */
/* doubleInd = strfind(onsets',[1,1]); */
/* onsets(doubleInd+1) = 0; */
/* onsets(1) = 0; */
/* flux(1) = 0; */
/* onsets(end+1) = 0; */
/* flux(end+1) = 0; */
/* xmin = 1; */
/* xmax = length(flux); */
/* */
/* figure */
/* subplot(4,1,1) */
/* stem(mask1); */
/* axis([xmin xmax 0 1]); */
/* subplot(4,1,2) */
/* stem(mask2); */
/* axis([xmin xmax 0 1]); */
/* subplot(4,1,3) */
/* stem(mask1&mask2); */
/* axis([xmin xmax 0 1]); */
/* subplot(4,1,4); */
/* imagesc(denoisedSpec); */
/* axis([xmin xmax 0 512]); */
/* axis('xy'); */
/* colormap(hot); */
}
static void onsetFlux(const emxArray_real_T *S, emxArray_real_T *flux)
{
emxArray_real_T *b_S;
int32_T iyLead;
int32_T loop_ub;
int32_T ixLead;
int32_T iy;
emxArray_real_T *x;
int32_T d;
emxArray_real_T *b_y1;
uint32_T ySize[2];
int32_T ix;
real_T work;
real_T tmp2;
emxArray_real_T *r4;
emxArray_real_T *b_flux;
real_T y;
real_T r;
emxArray_real_T *c_flux;
emxArray_boolean_T *b_x;
emxArray_int32_T *r5;
b_emxInit_real_T(&b_S, 1);
/* ONSETFLUX Computes new spectral flux */
/* Detailed explanation goes here */
/* Just to be sure */
/* S = abs(S); */
iyLead = S->size[0];
loop_ub = S->size[0];
ixLead = S->size[1];
iy = b_S->size[0];
b_S->size[0] = loop_ub;
emxEnsureCapacity((emxArray__common *)b_S, iy, (int32_T)sizeof(real_T));
for (iy = 0; iy < loop_ub; iy++) {
b_S->data[iy] = S->data[iy + S->size[0] * (ixLead - 1)];
}
emxInit_real_T(&x, 2);
iy = x->size[0] * x->size[1];
x->size[0] = S->size[0];
x->size[1] = S->size[1] + 1;
emxEnsureCapacity((emxArray__common *)x, iy, (int32_T)sizeof(real_T));
loop_ub = S->size[1];
for (iy = 0; iy < loop_ub; iy++) {
d = S->size[0];
for (ixLead = 0; ixLead < d; ixLead++) {
x->data[ixLead + x->size[0] * iy] = S->data[ixLead + S->size[0] * iy];
}
}
iy = 0;
while (iy <= 0) {
for (iy = 0; iy < iyLead; iy++) {
x->data[iy + x->size[0] * S->size[1]] = b_S->data[iy];
}
iy = 1;
}
emxFree_real_T(&b_S);
emxInit_real_T(&b_y1, 2);
if (1 >= x->size[1]) {
for (iy = 0; iy < 2; iy++) {
ySize[iy] = (uint32_T)x->size[iy];
}
iy = b_y1->size[0] * b_y1->size[1];
b_y1->size[0] = (int32_T)ySize[0];
emxEnsureCapacity((emxArray__common *)b_y1, iy, (int32_T)sizeof(real_T));
iy = b_y1->size[0] * b_y1->size[1];
b_y1->size[1] = 0;
emxEnsureCapacity((emxArray__common *)b_y1, iy, (int32_T)sizeof(real_T));
} else {
for (iy = 0; iy < 2; iy++) {
ySize[iy] = (uint32_T)x->size[iy];
}
iy = b_y1->size[0] * b_y1->size[1];
b_y1->size[0] = (int32_T)ySize[0];
b_y1->size[1] = x->size[1] - 1;
emxEnsureCapacity((emxArray__common *)b_y1, iy, (int32_T)sizeof(real_T));
ix = 0;
iy = 1;
for (d = 1; d <= x->size[0]; d++) {
ixLead = ix + x->size[0];
iyLead = iy;
work = x->data[ix];
for (loop_ub = 2; loop_ub <= x->size[1]; loop_ub++) {
tmp2 = work;
work = x->data[ixLead];
tmp2 = x->data[ixLead] - tmp2;
ixLead += x->size[0];
b_y1->data[iyLead - 1] = tmp2;
iyLead += x->size[0];
}
ix++;
iy++;
}
}
emxFree_real_T(&x);
/* Half wave rectification */
for (iy = 0; iy < 2; iy++) {
ySize[iy] = (uint32_T)b_y1->size[iy];
}
emxInit_real_T(&r4, 2);
iy = r4->size[0] * r4->size[1];
r4->size[0] = (int32_T)ySize[0];
r4->size[1] = (int32_T)ySize[1];
emxEnsureCapacity((emxArray__common *)r4, iy, (int32_T)sizeof(real_T));
iy = b_y1->size[0] * b_y1->size[1];
for (loop_ub = 0; loop_ub < iy; loop_ub++) {
r4->data[(int32_T)(1.0 + (real_T)loop_ub) - 1] = fabs(b_y1->data[(int32_T)
(1.0 + (real_T)loop_ub) - 1]);
}
iy = b_y1->size[0] * b_y1->size[1];
emxEnsureCapacity((emxArray__common *)b_y1, iy, (int32_T)sizeof(real_T));
ixLead = b_y1->size[0];
d = b_y1->size[1];
iyLead = ixLead * d;
for (iy = 0; iy < iyLead; iy++) {
b_y1->data[iy] = (b_y1->data[iy] + r4->data[iy]) / 2.0;
}
emxFree_real_T(&r4);
/* Summed across all bins */
for (iy = 0; iy < 2; iy++) {
ySize[iy] = (uint32_T)b_y1->size[iy];
}
emxInit_real_T(&b_flux, 2);
iy = b_flux->size[0] * b_flux->size[1];
b_flux->size[0] = 1;
b_flux->size[1] = (int32_T)ySize[1];
emxEnsureCapacity((emxArray__common *)b_flux, iy, (int32_T)sizeof(real_T));
if ((b_y1->size[0] == 0) || (b_y1->size[1] == 0)) {
iy = b_flux->size[0] * b_flux->size[1];
b_flux->size[0] = 1;
emxEnsureCapacity((emxArray__common *)b_flux, iy, (int32_T)sizeof(real_T));
iy = b_flux->size[0] * b_flux->size[1];
b_flux->size[1] = (int32_T)ySize[1];
emxEnsureCapacity((emxArray__common *)b_flux, iy, (int32_T)sizeof(real_T));
iyLead = (int32_T)ySize[1];
for (iy = 0; iy < iyLead; iy++) {
b_flux->data[iy] = 0.0;
}
} else {
ix = -1;
iy = -1;
for (d = 1; d <= b_y1->size[1]; d++) {
ixLead = ix + 1;
ix++;
tmp2 = b_y1->data[ixLead];
for (loop_ub = 2; loop_ub <= b_y1->size[0]; loop_ub++) {
ix++;
tmp2 += b_y1->data[ix];
}
iy++;
b_flux->data[iy] = tmp2;
}
}
emxFree_real_T(&b_y1);
if (b_flux->size[1] == 0) {
tmp2 = 0.0;
} else {
tmp2 = b_flux->data[0];
for (loop_ub = 2; loop_ub <= b_flux->size[1]; loop_ub++) {
tmp2 += b_flux->data[loop_ub - 1];
}
}
tmp2 /= (real_T)b_flux->size[1];
if (b_flux->size[1] > 1) {
d = b_flux->size[1] - 1;
} else {
d = b_flux->size[1];
}
if (b_flux->size[1] == 0) {
y = rtNaN;
} else {
ix = 0;
work = b_flux->data[0];
for (loop_ub = 0; loop_ub <= b_flux->size[1] - 2; loop_ub++) {
ix++;
work += b_flux->data[ix];
}
work /= (real_T)b_flux->size[1];
ix = 0;
r = b_flux->data[0] - work;
y = r * r;
for (loop_ub = 0; loop_ub <= b_flux->size[1] - 2; loop_ub++) {
ix++;
r = b_flux->data[ix] - work;
y += r * r;
}
y /= (real_T)d;
}
emxInit_real_T(&c_flux, 2);
iy = c_flux->size[0] * c_flux->size[1];
c_flux->size[0] = 1;
c_flux->size[1] = b_flux->size[1];
emxEnsureCapacity((emxArray__common *)c_flux, iy, (int32_T)sizeof(real_T));
iyLead = b_flux->size[0] * b_flux->size[1];
for (iy = 0; iy < iyLead; iy++) {
c_flux->data[iy] = b_flux->data[iy] - tmp2;
}
rdivide(c_flux, y, b_flux);
iy = flux->size[0];
flux->size[0] = b_flux->size[1];
emxEnsureCapacity((emxArray__common *)flux, iy, (int32_T)sizeof(real_T));
iyLead = b_flux->size[1];
emxFree_real_T(&c_flux);
for (iy = 0; iy < iyLead; iy++) {
flux->data[iy] = b_flux->data[iy];
}
emxFree_real_T(&b_flux);
b_emxInit_boolean_T(&b_x, 1);
iy = b_x->size[0];
b_x->size[0] = flux->size[0];
emxEnsureCapacity((emxArray__common *)b_x, iy, (int32_T)sizeof(boolean_T));
iyLead = flux->size[0];
for (iy = 0; iy < iyLead; iy++) {
b_x->data[iy] = (flux->data[iy] < 0.0);
}
loop_ub = 0;
for (d = 1; d <= b_x->size[0]; d++) {
if (b_x->data[d - 1]) {
loop_ub++;
}
}
emxInit_int32_T(&r5, 1);
iy = r5->size[0];
r5->size[0] = loop_ub;
emxEnsureCapacity((emxArray__common *)r5, iy, (int32_T)sizeof(int32_T));
ixLead = 0;
for (d = 1; d <= b_x->size[0]; d++) {
if (b_x->data[d - 1]) {
r5->data[ixLead] = d;
ixLead++;
}
}
emxFree_boolean_T(&b_x);
iyLead = r5->size[0];
for (iy = 0; iy < iyLead; iy++) {
flux->data[r5->data[iy] - 1] = 0.0;
}
emxFree_int32_T(&r5);
}
static void padarray(const emxArray_real_T *varargin_1, emxArray_real_T *b)
{
real_T sizeB[2];
int32_T i3;
real_T b_sizeB;
int32_T c_sizeB[2];
int32_T outsize[2];
int32_T loop_ub;
for (i3 = 0; i3 < 2; i3++) {
sizeB[i3] = 0.0;
}
sizeB[0] = 3.0;
if ((varargin_1->size[0] == 0) || (varargin_1->size[1] == 0)) {
for (i3 = 0; i3 < 2; i3++) {
b_sizeB = (real_T)varargin_1->size[i3] + 2.0 * sizeB[i3];
sizeB[i3] = b_sizeB;
}
c_sizeB[0] = (int32_T)sizeB[0];
c_sizeB[1] = (int32_T)sizeB[1];
for (i3 = 0; i3 < 2; i3++) {
outsize[i3] = c_sizeB[i3];
}
i3 = b->size[0] * b->size[1];
b->size[0] = outsize[0];
emxEnsureCapacity((emxArray__common *)b, i3, (int32_T)sizeof(real_T));
i3 = b->size[0] * b->size[1];
b->size[1] = outsize[1];
emxEnsureCapacity((emxArray__common *)b, i3, (int32_T)sizeof(real_T));
loop_ub = outsize[0] * outsize[1];
for (i3 = 0; i3 < loop_ub; i3++) {
b->data[i3] = 0.0;
}
} else {
ConstantPad(varargin_1, sizeB, b);
}
}
static void rdivide(const emxArray_real_T *x, real_T y, emxArray_real_T *z)
{
int32_T i1;
int32_T loop_ub;
i1 = z->size[0] * z->size[1];
z->size[0] = 1;
z->size[1] = x->size[1];
emxEnsureCapacity((emxArray__common *)z, i1, (int32_T)sizeof(real_T));
loop_ub = x->size[0] * x->size[1];
for (i1 = 0; i1 < loop_ub; i1++) {
z->data[i1] = x->data[i1] / y;
}
}
static real_T rt_powd_snf(real_T u0, real_T u1)
{
real_T y;
real_T d0;
real_T d1;
if (rtIsNaN(u0) || rtIsNaN(u1)) {
y = rtNaN;
} else {
d0 = fabs(u0);
d1 = fabs(u1);
if (rtIsInf(u1)) {
if (d0 == 1.0) {
y = rtNaN;
} else if (d0 > 1.0) {
if (u1 > 0.0) {
y = rtInf;
} else {
y = 0.0;
}
} else if (u1 > 0.0) {
y = 0.0;
} else {
y = rtInf;
}
} else if (d1 == 0.0) {
y = 1.0;
} else if (d1 == 1.0) {
if (u1 > 0.0) {
y = u0;
} else {
y = 1.0 / u0;
}
} else if (u1 == 2.0) {
y = u0 * u0;
} else if ((u1 == 0.5) && (u0 >= 0.0)) {
y = sqrt(u0);
} else if ((u0 < 0.0) && (u1 > floor(u1))) {
y = rtNaN;
} else {
y = pow(u0, u1);
}
}
return y;
}
void computeOnsetFeatures(const emxArray_real_T *denoisedSpectrum, const
emxArray_real_T *T, real_T ioiFeatures[12], emxArray_boolean_T *onsets)
{
emxArray_real_T *unusedU0;
emxArray_boolean_T *b_onsets;
int32_T i;
int32_T loop_ub;
real_T ioiHist[17];
boolean_T bv0[12];
int32_T tmp_size[1];
int32_T tmp_data[12];
emxInit_real_T(&unusedU0, 2);
emxInit_boolean_T(&b_onsets, 2);
/* COMPUTEONSETFEATURES Computes onset features */
onsetDetection(denoisedSpectrum, onsets, unusedU0);
/* Collecting number of onsets per 2 second window */
/* onsetFeatures1 = onsetFeatures(onsets,T); */
/* Collect IOI histogram */
i = b_onsets->size[0] * b_onsets->size[1];
b_onsets->size[0] = onsets->size[0];
b_onsets->size[1] = onsets->size[1];
emxEnsureCapacity((emxArray__common *)b_onsets, i, (int32_T)sizeof(boolean_T));
loop_ub = onsets->size[0] * onsets->size[1];
emxFree_real_T(&unusedU0);
for (i = 0; i < loop_ub; i++) {
b_onsets->data[i] = onsets->data[i];
}
ioiHistogram(b_onsets, T, ioiHist);
histogramFeatures(ioiHist, ioiFeatures);
/* ioiFeatures = vertcat(ioiFeatures,onsetFeatures1); */
emxFree_boolean_T(&b_onsets);
for (i = 0; i < 12; i++) {
bv0[i] = rtIsNaN(ioiFeatures[i]);
}
b_eml_li_find(bv0, tmp_data, tmp_size);
loop_ub = tmp_size[0];
for (i = 0; i < loop_ub; i++) {
ioiFeatures[tmp_data[i] - 1] = 0.0;
}
for (i = 0; i < 12; i++) {
bv0[i] = rtIsInf(ioiFeatures[i]);
}
b_eml_li_find(bv0, tmp_data, tmp_size);
loop_ub = tmp_size[0];
for (i = 0; i < loop_ub; i++) {
ioiFeatures[tmp_data[i] - 1] = 0.0;
}
}
void computeOnsetFeatures_initialize(void)
{
rt_InitInfAndNaN(8U);
}
void computeOnsetFeatures_terminate(void)
{
/* (no terminate code required) */
}
emxArray_boolean_T *emxCreateND_boolean_T(int32_T numDimensions, int32_T *size)
{
emxArray_boolean_T *emx;
int32_T numEl;
int32_T i;
emxInit_boolean_T(&emx, numDimensions);
numEl = 1;
for (i = 0; i < numDimensions; i++) {
numEl *= size[i];
emx->size[i] = size[i];
}
emx->data = (boolean_T *)calloc((uint32_T)numEl, sizeof(boolean_T));
emx->numDimensions = numDimensions;
emx->allocatedSize = numEl;
return emx;
}
//emxArray_real_T *emxCreateND_real_T(int32_T numDimensions, int32_T *size)
//{
// emxArray_real_T *emx;
// int32_T numEl;
// int32_T i;
// emxInit_real_T(&emx, numDimensions);
// numEl = 1;
// for (i = 0; i < numDimensions; i++) {
// numEl *= size[i];
// emx->size[i] = size[i];
// }
//
// emx->data = (real_T *)calloc((uint32_T)numEl, sizeof(real_T));
// emx->numDimensions = numDimensions;
// emx->allocatedSize = numEl;
// return emx;
//}
emxArray_boolean_T *emxCreateWrapperND_boolean_T(boolean_T *data, int32_T
numDimensions, int32_T *size)
{
emxArray_boolean_T *emx;
int32_T numEl;
int32_T i;
emxInit_boolean_T(&emx, numDimensions);
numEl = 1;
for (i = 0; i < numDimensions; i++) {
numEl *= size[i];
emx->size[i] = size[i];
}
emx->data = data;
emx->numDimensions = numDimensions;
emx->allocatedSize = numEl;
emx->canFreeData = FALSE;
return emx;
}
//emxArray_real_T *emxCreateWrapperND_real_T(real_T *data, int32_T numDimensions,
// int32_T *size)
//{
// emxArray_real_T *emx;
// int32_T numEl;
// int32_T i;
// emxInit_real_T(&emx, numDimensions);
// numEl = 1;
// for (i = 0; i < numDimensions; i++) {
// numEl *= size[i];
// emx->size[i] = size[i];
// }
//
// emx->data = data;
// emx->numDimensions = numDimensions;
// emx->allocatedSize = numEl;
// emx->canFreeData = FALSE;
// return emx;
//}
emxArray_boolean_T *emxCreateWrapper_boolean_T(boolean_T *data, int32_T rows,
int32_T cols)
{
emxArray_boolean_T *emx;
int32_T size[2];
int32_T numEl;
int32_T i;
size[0] = rows;
size[1] = cols;
emxInit_boolean_T(&emx, 2);
numEl = 1;
for (i = 0; i < 2; i++) {
numEl *= size[i];
emx->size[i] = size[i];
}
emx->data = data;
emx->numDimensions = 2;
emx->allocatedSize = numEl;
emx->canFreeData = FALSE;
return emx;
}
//emxArray_real_T *emxCreateWrapper_real_T(real_T *data, int32_T rows, int32_T
// cols)
//{
// emxArray_real_T *emx;
// int32_T size[2];
// int32_T numEl;
// int32_T i;
// size[0] = rows;
// size[1] = cols;
// emxInit_real_T(&emx, 2);
// numEl = 1;
// for (i = 0; i < 2; i++) {
// numEl *= size[i];
// emx->size[i] = size[i];
// }
//
// emx->data = data;
// emx->numDimensions = 2;
// emx->allocatedSize = numEl;
// emx->canFreeData = FALSE;
// return emx;
//}
emxArray_boolean_T *emxCreate_boolean_T(int32_T rows, int32_T cols)
{
emxArray_boolean_T *emx;
int32_T size[2];
int32_T numEl;
int32_T i;
size[0] = rows;
size[1] = cols;
emxInit_boolean_T(&emx, 2);
numEl = 1;
for (i = 0; i < 2; i++) {
numEl *= size[i];
emx->size[i] = size[i];
}
emx->data = (boolean_T *)calloc((uint32_T)numEl, sizeof(boolean_T));
emx->numDimensions = 2;
emx->allocatedSize = numEl;
return emx;
}
//emxArray_real_T *emxCreate_real_T(int32_T rows, int32_T cols)
//{
// emxArray_real_T *emx;
// int32_T size[2];
// int32_T numEl;
// int32_T i;
// size[0] = rows;
// size[1] = cols;
// emxInit_real_T(&emx, 2);
// numEl = 1;
// for (i = 0; i < 2; i++) {
// numEl *= size[i];
// emx->size[i] = size[i];
// }
//
// emx->data = (real_T *)calloc((uint32_T)numEl, sizeof(real_T));
// emx->numDimensions = 2;
// emx->allocatedSize = numEl;
// return emx;
//}
void emxDestroyArray_boolean_T(emxArray_boolean_T *emxArray)
{
emxFree_boolean_T(&emxArray);
}
//void emxDestroyArray_real_T(emxArray_real_T *emxArray)
//{
// emxFree_real_T(&emxArray);
//}
/* End of code generation (computeOnsetFeatures.c) */
| aneeshvartakavi/birdID | birdID/Source/Export/computeOnsetFeatures_export.c | C | gpl-2.0 | 74,844 |
/*
* Copyright (C) 2009-2015 Pivotal Software, Inc
*
* This program is is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
.tundra .dijitDialogRtl .dijitDialogCloseIcon {
right: auto;
left: 5px;
}
| pivotal/tcs-hq-management-plugin | com.springsource.hq.plugin.tcserver.serverconfig.web/src/main/webapp/dijit/themes/tundra/Dialog_rtl.css | CSS | gpl-2.0 | 795 |
<?php locate_template( array( 'mobile/header-mobile.php' ), true, false ); ?>
<?php if ( have_posts() ) { ?>
<?php while ( have_posts() ) {
the_post(); ?>
<div <?php post_class( 'tbm-post tbm-padded' ) ?> id="post-<?php the_ID(); ?>">
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<?php wp_link_pages('before=<div class="tbm-pc-navi">' . __('Pages', 'fastfood') . ':&after=</div>'); ?>
</div>
<?php comments_template('/mobile/comments-mobile.php'); ?>
<?php
$tbm_args = array(
'post_type' => 'page',
'post_parent' => $post->ID,
'order' => 'ASC',
'orderby' => 'menu_order',
'numberposts' => 0
);
$tbm_sub_pages = get_posts( $tbm_args ); // retrieve the child pages
if (!empty($tbm_sub_pages)) { ?>
<?php echo fastfood_mobile_seztitle( 'before' ) . __( 'Child pages', 'fastfood' ) . fastfood_mobile_seztitle( 'after' ); ?>
<ul class="tbm-group">
<?php
foreach ( $tbm_sub_pages as $tbm_children ) {
echo '<li class="outset"><a href="' . get_permalink( $tbm_children ) . '" title="' . esc_attr( strip_tags( get_the_title( $tbm_children ) ) ) . '">' . get_the_title( $tbm_children ) . '</a></li>';
}
?>
</ul>
<?php } ?>
<?php $tbm_the_parent_page = $post->post_parent; // retrieve the parent page
if ( $tbm_the_parent_page ) {?>
<?php echo fastfood_mobile_seztitle( 'before' ) . __( 'Parent page', 'fastfood' ) . fastfood_mobile_seztitle( 'after' ); ?>
<ul class="tbm-group">
<li class="outset"><a href="<?php echo get_permalink( $tbm_the_parent_page ); ?>" title="<?php echo esc_attr( strip_tags( get_the_title( $tbm_the_parent_page ) ) ); ?>"><?php echo get_the_title( $tbm_the_parent_page ); ?></a></li>
</ul>
<?php } ?>
<?php } ?>
<?php } else { ?>
<p class="tbm-padded"><?php _e( 'Sorry, no posts matched your criteria.', 'fastfood' );?></p>
<?php } ?>
<?php locate_template( array( 'mobile/footer-mobile.php' ), true, false ); ?>
| zdislaw/phenon_wp | wp-content/themes/fastfood/mobile/loop-page-mobile.php | PHP | gpl-2.0 | 1,989 |
<?php
// The name of this module
define("_MI_MEDIAWIKI_NAME", "MediaWiki");
// A brief description of this module
define("_MI_MEDIAWIKI_DESC", "MediaWiki For XOOPS Community");
// Configs
define("_MI_MEDIAWIKI_STYLE", "Interface style");
define("_MI_MEDIAWIKI_STYLE_DESC", "Xoops style, MediaWiki style, or user selectable");
define("_MI_MEDIAWIKI_BLOCK_SIDEBAR", "MediaWiki Sidebar");
define("_MI_MEDIAWIKI_BLOCK_RECENTCHANGES", "MediaWiki Recent changes");
define("_MI_MEDIAWIKI_BLOCK_TOP", "Most revisions");
define("_MI_MEDIAWIKI_BLOCK_HOT", "Hot contents");
?> | Devanshg/Mediawiki | language/english/modinfo.php | PHP | gpl-2.0 | 568 |
/*
* Copyright (C) 2016, 2017 by Rafael Santiago
*
* This is a free software. You can redistribute it and/or modify under
* the terms of the GNU General Public License version 2.
*
*/
#include <cpu/itp/itp0.h>
#include <ctx/ctx.h>
#include <vid/vid.h>
unsigned short itp0_gate(const unsigned short nnn, struct cp8_ctx *cp8) {
unsigned short next = 2;
switch (nnn) {
case 0x00e0:
// INFO(Rafael): CLS
cp8_vidcls();
break;
case 0x00ee:
// INFO(Rafael): RET
cp8->pc = cp8_pop(cp8);
break;
default:
// INFO(Rafael): SYS addr is a pretty old stuff and should be ignored.
break;
}
return (cp8->pc + next);
}
| rafael-santiago/CP-8 | src/cpu/itp/itp0.c | C | gpl-2.0 | 777 |
package nl.pelagic.musicTree.flac2mp3.cli;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.pelagic.audio.conversion.flac2mp3.api.Flac2Mp3Configuration;
import nl.pelagic.audio.conversion.flac2mp3.api.FlacToMp3;
import nl.pelagic.audio.musicTree.configuration.api.MusicTreeConfiguration;
import nl.pelagic.audio.musicTree.configuration.api.MusicTreeConstants;
import nl.pelagic.audio.musicTree.syncer.api.Syncer;
import nl.pelagic.audio.musicTree.util.MusicTreeHelpers;
import nl.pelagic.musicTree.flac2mp3.cli.i18n.Messages;
import nl.pelagic.shell.script.listener.api.ShellScriptListener;
import nl.pelagic.shutdownhook.api.ShutdownHookParticipant;
import nl.pelagic.util.file.FileUtils;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
/**
* The main program that synchronises a flac tree into a mp3 tree or just
* converts one or more flac files in mp3 files, based on a music tree
* configuration
*/
@Component(property = {
"main.thread=true" /* Signal the launcher that this is the main thread */
})
public class Main implements Runnable, ShutdownHookParticipant {
/** the application logger name */
static private final String LOGGER_APPLICATION_NAME = "nl.pelagic"; //$NON-NLS-1$
/** the application logger level to allow */
static private final Level LOGGER_APPLICATION_LEVEL = Level.SEVERE;
/** the jaudiotagger library logger name */
static private final String LOGGER_JAUDIOTAGGER_NAME = "org.jaudiotagger"; //$NON-NLS-1$
/** the jaudiotagger library logger level to allow */
static private final Level LOGGER_JAUDIOTAGGER_LEVEL = Level.SEVERE;
/** the program name */
static final String PROGRAM_NAME = "flac2mp3"; //$NON-NLS-1$
/** the application logger */
private final Logger applicationLogger;
/** the jaudiotagger library logger */
private final Logger jaudiotaggerLogger;
/** the list of extension to use in the flac tree */
private final HashSet<String> extensionsList = new HashSet<>();
/** the filenames for covers to use in the flac tree */
private final HashSet<String> coversList = new HashSet<>();
/*
* Construction
*/
/**
* Default constructor
*/
public Main() {
super();
/**
* <pre>
* 1=timestamp
* 2=level
* 3=logger
* 4=class method
* 5=message
* 6=stack trace, preceded by a newline (if exception is present)
* </pre>
*/
System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] %4$10s %2$s : %5$s%6$s%n"); //$NON-NLS-1$ //$NON-NLS-2$
applicationLogger = Logger.getLogger(LOGGER_APPLICATION_NAME);
applicationLogger.setLevel(LOGGER_APPLICATION_LEVEL);
jaudiotaggerLogger = Logger.getLogger(LOGGER_JAUDIOTAGGER_NAME);
jaudiotaggerLogger.setLevel(LOGGER_JAUDIOTAGGER_LEVEL);
extensionsList.add(MusicTreeConstants.FLACEXTENSION);
coversList.add(MusicTreeConstants.COVER);
}
/*
* Consumed Services
*/
/** the shell script listener (optional) */
private ShellScriptListener shellScriptListener = null;
/**
* @param shellScriptListener the shellScriptListener to set
*/
@Reference
void setShellScriptListener(ShellScriptListener shellScriptListener) {
this.shellScriptListener = shellScriptListener;
}
/** the flac2Mp3 service */
private FlacToMp3 flacToMp3 = null;
/**
* @param flacToMp3 the flacToMp3 to set
*/
@Reference
void setFlacToMp3(FlacToMp3 flacToMp3) {
this.flacToMp3 = flacToMp3;
}
/** the syncer service */
private Syncer syncer = null;
/**
* @param syncer the syncer to set
*/
@Reference
void setSyncer(Syncer syncer) {
this.syncer = syncer;
}
/*
* Command line arguments
*/
/** the launcher arguments property name */
static final String LAUNCHER_ARGUMENTS = "launcher.arguments"; //$NON-NLS-1$
/** the command line arguments */
private String[] args = null;
/**
* The bnd launcher provides access to the command line arguments via the
* Launcher object. This object is also registered under Object.
*
* @param done unused
* @param parameters the launcher parameters, which includes the command line
* arguments
*/
@Reference
void setDone(@SuppressWarnings("unused") Object done, Map<String, Object> parameters) {
args = (String[]) parameters.get(LAUNCHER_ARGUMENTS);
}
/*
* Bundle
*/
/** The setting name for the stayAlive property */
public static final String SETTING_STAYALIVE = "stayAlive"; //$NON-NLS-1$
/** true when the application should NOT automatically exit when done */
private boolean stayAlive = false;
/**
* Bundle activator
*
* @param bundleContext the bundle context
*/
@Activate
void activate(BundleContext bundleContext) {
String ex = bundleContext.getProperty(PROGRAM_NAME + "." + SETTING_STAYALIVE); //$NON-NLS-1$
if (ex != null) {
stayAlive = Boolean.parseBoolean(ex);
}
}
/**
* Bundle deactivator
*/
@Deactivate
void deactivate() {
/* nothing to do */
}
/*
* Helpers
*/
/**
* Read a filelist file into a list of entries to convert
*
* @param out the stream to print the error messages to
* @param fileList the filelist file
* @param entriesToConvert a list of files to convert, to which the files read
* from the filelist file must be added
* @return true when successful
*/
static boolean readFileList(PrintStream out, File fileList, List<String> entriesToConvert) {
assert (out != null);
assert (fileList != null);
assert (entriesToConvert != null);
if (!fileList.isFile()) {
out.printf(Messages.getString("Main.8"), fileList.getPath()); //$NON-NLS-1$
return false;
}
try (BufferedReader reader =
new BufferedReader(new InputStreamReader(Files.newInputStream(fileList.toPath()), "UTF-8"))) { //$NON-NLS-1$
String line = null;
while ((line = reader.readLine()) != null) {
/* skip empty lines */
if (line.trim().isEmpty()) {
continue;
}
entriesToConvert.add(line);
}
}
catch (IOException e) {
/* can't be covered in a test */
out.printf(Messages.getString("Main.11"), fileList, e.getLocalizedMessage()); //$NON-NLS-1$
return false;
}
return true;
}
/**
* Validate the entry to convert to filter out non-existing directories and
* files. An entry to convert must exist and be below the flac base directory.
*
* @param out the stream to print the error messages to
* @param musicTreeConfiguration the music tree configuration
* @param entryToConvert the entry to convert
* @return true when validation is successful
*/
static boolean validateEntryToConvert(PrintStream out, MusicTreeConfiguration musicTreeConfiguration,
File entryToConvert) {
assert (out != null);
assert (musicTreeConfiguration != null);
assert (entryToConvert != null);
/* check that the entry exists */
if (!entryToConvert.exists()) {
out.printf(Messages.getString("Main.5"), entryToConvert.getPath()); //$NON-NLS-1$
return false;
}
/*
* check that entry is below the flac base directory so that it doesn't
* escape the base directory by doing a ../../..
*/
if (!FileUtils.isFileBelowDirectory(musicTreeConfiguration.getFlacBaseDir(), entryToConvert, true)) {
out.printf(Messages.getString("Main.6"), //$NON-NLS-1$
entryToConvert.getPath(), musicTreeConfiguration.getFlacBaseDir().getPath());
return false;
}
return true;
}
/**
* Convert a flac file into an mp3 file.
*
* @param err the stream to print to
* @param flac2Mp3Configuration the conversion configuration. When null then
* the default configuration is used.
* @param musicTreeConfiguration the music tree configuration
* @param simulate true to simulate conversion
* @param fileToConvert the flac file to convert
*
* @return true when successful
*/
boolean convertFile(PrintStream err, Flac2Mp3Configuration flac2Mp3Configuration,
MusicTreeConfiguration musicTreeConfiguration, boolean simulate, File fileToConvert) {
assert (err != null);
assert (flac2Mp3Configuration != null);
assert (musicTreeConfiguration != null);
assert (fileToConvert != null);
assert (fileToConvert.isFile());
File mp3File = MusicTreeHelpers.flacFileToMp3File(musicTreeConfiguration, fileToConvert);
if (mp3File == null) {
err.printf(Messages.getString("Main.12"), fileToConvert.getPath(), //$NON-NLS-1$
musicTreeConfiguration.getMp3BaseDir().getPath());
return false;
}
boolean doConversion = !mp3File.exists() || (fileToConvert.lastModified() > mp3File.lastModified());
if (!doConversion) {
return true;
}
boolean converted = false;
try {
converted = flacToMp3.convert(flac2Mp3Configuration, fileToConvert, mp3File, simulate);
if (!converted) {
err.printf(Messages.getString("Main.1"), fileToConvert.getPath()); //$NON-NLS-1$
}
}
catch (IOException e) {
converted = false;
err.printf(Messages.getString("Main.2"), fileToConvert.getPath(), e.getLocalizedMessage()); //$NON-NLS-1$
}
return converted;
}
/**
* Stay alive, if needed (which is when the component has a SETTING_STAYALIVE
* property set to true).
*
* @param err the stream to print a 'staying alive' message to
*/
void stayAlive(PrintStream err) {
if (!stayAlive) {
return;
}
err.printf(Messages.getString("Main.7")); //$NON-NLS-1$
try {
Thread.sleep(Long.MAX_VALUE);
}
catch (InterruptedException e) {
/* swallow */
}
}
/*
* ShutdownHookParticipant
*/
/** true when we have to stop */
private AtomicBoolean stop = new AtomicBoolean(false);
@Override
public void shutdownHook() {
stop.set(true);
}
/*
* Main
*/
/**
* Run the main program
*
* @param err the stream to print errors to
* @return true when successful
*/
boolean doMain(PrintStream err) {
if (args == null) {
/*
* the launcher didn't set our command line options so set empty arguments
* (use defaults)
*/
args = new String[0];
}
/*
* Parse the command line
*/
CommandLineOptions commandLineOptions = new CommandLineOptions();
CmdLineParser parser = new CmdLineParser(commandLineOptions);
try {
parser.parseArgument(args);
}
catch (CmdLineException e) {
err.printf(Messages.getString("Main.4"), e.getLocalizedMessage()); //$NON-NLS-1$
commandLineOptions.setErrorReported(true);
}
/*
* Process command-line options
*/
/* print usage when so requested and exit */
if (commandLineOptions.isHelp() || commandLineOptions.isErrorReported()) {
try {
/* can't be covered by a test */
int cols = Integer.parseInt(System.getenv("COLUMNS")); //$NON-NLS-1$
if (cols > 80) {
parser.getProperties().withUsageWidth(cols);
}
}
catch (NumberFormatException e) {
/* swallow, can't be covered by a test */
}
CommandLineOptions.usage(err, PROGRAM_NAME, parser);
return false;
}
/*
* Setup verbose modes in the shell script listener
*/
shellScriptListener.setVerbose(commandLineOptions.isVerbose(), commandLineOptions.isExtraVerbose(),
commandLineOptions.isQuiet());
/*
* Setup & validate the music tree configuration
*/
MusicTreeConfiguration musicTreeConfiguration =
new MusicTreeConfiguration(commandLineOptions.getFlacBaseDir(), commandLineOptions.getMp3BaseDir());
List<String> errors = musicTreeConfiguration.validate(true);
if (errors != null) {
for (String error : errors) {
err.println(error);
}
return false;
}
/*
* Setup & validate the flac2mp3 configuration
*/
Flac2Mp3Configuration flac2Mp3Configuration = new Flac2Mp3Configuration();
flac2Mp3Configuration.setFlacExecutable(commandLineOptions.getFlacExecutable().getPath());
flac2Mp3Configuration.setLameExecutable(commandLineOptions.getLameExecutable().getPath());
flac2Mp3Configuration.setFlacOptions(commandLineOptions.getFlacOptions());
flac2Mp3Configuration.setLameOptions(commandLineOptions.getLameOptions());
flac2Mp3Configuration.setUseId3V1Tags(commandLineOptions.isUseID3v1());
flac2Mp3Configuration.setUseId3V24Tags(commandLineOptions.isUseID3v24());
flac2Mp3Configuration.setForceConversion(commandLineOptions.isForceConversion());
flac2Mp3Configuration.setRunFlacLame(!commandLineOptions.isDoNotRunFlacAndLame());
flac2Mp3Configuration.setCopyTag(!commandLineOptions.isDoNotCopyTag());
flac2Mp3Configuration.setCopyTimestamp(!commandLineOptions.isDoNotCopyTimestamp());
errors = flac2Mp3Configuration.validate();
if (errors != null) {
/* can't be covered by a test */
for (String error : errors) {
err.println(error);
}
return false;
}
/*
* Setup the entries to convert: first get them from the command-line (if
* specified) and then add those in the file list (if set)
*/
List<String> entriesToConvert = commandLineOptions.getEntriesToConvert();
File fileList = commandLineOptions.getFileList();
if (fileList != null) {
readFileList(err, fileList, entriesToConvert);
}
if (entriesToConvert.isEmpty()) {
/*
* no entries to convert, so default to the flac base directory: sync the
* whole tree
*/
entriesToConvert.add(musicTreeConfiguration.getFlacBaseDir().getAbsolutePath());
}
/*
* Run
*/
boolean result = true;
for (String entryToConvert : entriesToConvert) {
if (stop.get()) {
break;
}
File entryToConvertFile = new File(entryToConvert);
boolean validationResult = validateEntryToConvert(err, musicTreeConfiguration, entryToConvertFile);
if (validationResult) {
if (entryToConvertFile.isDirectory()) {
result = result && syncer.syncFlac2Mp3(flac2Mp3Configuration, musicTreeConfiguration, entryToConvertFile,
extensionsList, coversList, commandLineOptions.isSimulate());
} else if (entryToConvertFile.isFile()) {
result = result && convertFile(err, flac2Mp3Configuration, musicTreeConfiguration,
commandLineOptions.isSimulate(), entryToConvertFile);
} else {
/* can't be covered by a test */
err.printf(Messages.getString("Main.3"), entryToConvert); //$NON-NLS-1$
}
} else {
result = false;
}
}
return result;
}
/*
* Since we're registered as a Runnable with the main.thread property we get
* called when the system is fully initialised.
*/
@Override
public void run() {
boolean success = doMain(System.err);
stayAlive(System.err);
if (!success) {
/* can't be covered by a test */
System.exit(1);
}
}
}
| fhuberts/musicTreePrograms | nl.pelagic.musicTree.flac2mp3.cli/src/nl/pelagic/musicTree/flac2mp3/cli/Main.java | Java | gpl-2.0 | 15,761 |
--真竜皇リトスアジムD
function c30539496.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(30539496,0))
e1:SetCategory(CATEGORY_DESTROY+CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,30539496)
e1:SetTarget(c30539496.sptg)
e1:SetOperation(c30539496.spop)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(30539496,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DELAY)
e2:SetCode(EVENT_DESTROYED)
e2:SetCountLimit(1,30539497)
e2:SetCondition(c30539496.spcon2)
e2:SetTarget(c30539496.sptg2)
e2:SetOperation(c30539496.spop2)
c:RegisterEffect(e2)
end
function c30539496.desfilter(c)
return c:IsType(TYPE_MONSTER) and ((c:IsLocation(LOCATION_MZONE) and c:IsFaceup()) or c:IsLocation(LOCATION_HAND))
end
function c30539496.locfilter(c,tp)
return c:IsLocation(LOCATION_MZONE) and c:IsControler(tp)
end
function c30539496.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
local loc=LOCATION_MZONE+LOCATION_HAND
if ft<0 then loc=LOCATION_MZONE end
local loc2=0
if Duel.IsPlayerAffectedByEffect(tp,88581108) then loc2=LOCATION_MZONE end
local g=Duel.GetMatchingGroup(c30539496.desfilter,tp,loc,loc2,c)
if chk==0 then return c:IsCanBeSpecialSummoned(e,0,tp,false,false)
and g:GetCount()>=2 and g:IsExists(Card.IsAttribute,1,nil,ATTRIBUTE_EARTH)
and (ft>0 or g:IsExists(c30539496.locfilter,-ft+1,nil,tp)) end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,nil,2,tp,loc)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0)
end
function c30539496.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
local loc=LOCATION_MZONE+LOCATION_HAND
if ft<0 then loc=LOCATION_MZONE end
local loc2=0
if Duel.IsPlayerAffectedByEffect(tp,88581108) then loc2=LOCATION_MZONE end
local g=Duel.GetMatchingGroup(c30539496.desfilter,tp,loc,loc2,c)
if g:GetCount()<2 or not g:IsExists(Card.IsAttribute,1,nil,ATTRIBUTE_EARTH) then return end
local g1=nil local g2=nil
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
if ft<1 then
g1=g:FilterSelect(tp,c30539496.locfilter,1,1,nil,tp)
else
g1=g:Select(tp,1,1,nil)
end
g:RemoveCard(g1:GetFirst())
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
if g1:GetFirst():IsAttribute(ATTRIBUTE_EARTH) then
g2=g:Select(tp,1,1,nil)
else
g2=g:FilterSelect(tp,Card.IsAttribute,1,1,nil,ATTRIBUTE_EARTH)
end
g1:Merge(g2)
local rm=g1:IsExists(Card.IsAttribute,2,nil,ATTRIBUTE_EARTH)
if Duel.Destroy(g1,REASON_EFFECT)==2 then
if not c:IsRelateToEffect(e) then return end
if Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)==0 then
return
end
local rg=Duel.GetMatchingGroup(Card.IsAbleToRemove,tp,0,LOCATION_EXTRA,nil)
if rm and rg:GetCount()>0 and Duel.SelectYesNo(tp,aux.Stringid(30539496,2)) then
Duel.ConfirmCards(tp,rg)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local tg=rg:SelectSubGroup(tp,aux.dncheck,false,1,3)
Duel.Remove(tg,POS_FACEUP,REASON_EFFECT)
Duel.ShuffleExtra(1-tp)
end
end
end
function c30539496.spcon2(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsReason(REASON_EFFECT)
end
function c30539496.thfilter(c,e,tp)
return not c:IsAttribute(ATTRIBUTE_EARTH) and c:IsRace(RACE_WYRM) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c30539496.sptg2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c30539496.thfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE)
end
function c30539496.spop2(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c30539496.thfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| Fluorohydride/ygopro-scripts | c30539496.lua | Lua | gpl-2.0 | 4,106 |
/**
* \file ApplyMaskImageFilterParallel.h
* \brief Definition of the thelib::ApplyMaskImageFilterParallel class.
*/
#ifndef THELIB_APPLYMASKIMAGEFILTERPARALLEL_H
#define THELIB_APPLYMASKIMAGEFILTERPARALLEL_H
// ITK
#include <itkImageToImageFilter.h>
// namespace
namespace thelib
{
/**
* \brief Mask an input image (input 0) using a mask image (input 1) (parrallel).
* \ingroup TheLib
*/
template< class T >
class ApplyMaskImageFilterParallel : public itk::ImageToImageFilter<T,T>
{
public:
//! Standard class typedefs.
typedef ApplyMaskImageFilterParallel Self;
typedef itk::ImageToImageFilter<T,T> Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
//! Method for creation through the object factory.
itkNewMacro(Self);
//! Run-time type information (and related methods).
itkTypeMacro(ApplyMaskImageFilter, ImageToImageFilter);
//! Set the invert flag.
itkSetMacro(InvertMask, bool);
//! Get the invert flag.
itkGetConstMacro(InvertMask, bool);
/**
* Print information about this class.
* \param os The stream to output to.
* \param indent The indent to apply to the output.
*/
void PrintSelf(std::ostream& os, itk::Indent indent) const;
protected:
//! Constructor: protect from instantiation.
ApplyMaskImageFilterParallel();
//! Destructor: protect from instantiation.
~ApplyMaskImageFilterParallel();
/**
* Main method.
* \param outputRegionForThread Image region to apply the filter to.
* \param threadId The thread identifier.
*/
void ThreadedGenerateData(
const typename itk::ImageSource<T>::OutputImageRegionType& outputRegionForThread,
itk::ThreadIdType threadId);
private:
//! Copy constructor: purposely not implemented.
ApplyMaskImageFilterParallel( const Self& filter);
//! Assignement operator: purposely not implemented.
void operator=( const Self& filter);
//! Flag to invert the mask or not
bool m_InvertMask;
}; // class ApplyMaskImageFilterParallel
} // namespace thelib
#endif //THELIB_APPLYMASKIMAGEFILTERPARALLEL_H
| ivmartel/semex | TheLib/include/ApplyMaskImageFilterParallel.h | C | gpl-2.0 | 2,279 |
<?php
/**
* @author Linkero
* @filename fselink.class.php
* @copyright 2014
* @version 0.1b
*/
class fseLink
{
protected $userKey = "INSERT_USER_KEY"; //User Key
protected $groupKey = "INSERT_GROUP_KEY"; //Group Key
protected $groupId = "INSERT_GROUP_ID"; //Group ID
/* --------DO NOT EDIT BELOW THIS LINE-------- */
/* --Define initial arrays-- */
public $memberArray = array();
public $groupArray = array();
public $aircraftArray = array();
/* --Initializer-- */
public function startFSELink()
{
/* --Sets up groupArray-- */
/* --Structure: Flights, Time, Distance, Profit-- */
$this->groupArray = array(
0,
0,
0,
number_format(0.00, 2));
/* --Loads Aircraft feed and sets up aircraftArray-- */
/* --Structure: Registration, Make/Model, Flights, Time, Distance, Profit-- */
$ac = simplexml_load_file("http://www.fseconomy.net/data?userkey=$this->userKey&format=xml&query=aircraft&search=key&readaccesskey=$this->groupKey");
foreach ($ac->Aircraft as $aircraft) {
array_push($this->aircraftArray, array(
"$aircraft->Registration",
"$aircraft->MakeModel",
0,
0,
0,
number_format(0.00, 2)));
}
/* --Loads Group Member feed and sets up memberArray-- */
/* --Structure: Pilot Name, Group Status, Flights, Time, Distance, Profit-- */
$mem = simplexml_load_file("http://www.fseconomy.net/data?userkey=$this->userKey&format=xml&query=group&search=members&readaccesskey=$this->groupKey");
foreach ($mem->Member as $Member) {
array_push($this->memberArray, array(
"$Member->Name",
"$Member->Status",
0,
0,
0,
number_format(0.00, 2))); //name, status, flights, time, distance, profit
}
/* --Populate arrays and return for use-- */
$this->populateArrays($this->memberArray, $this->groupArray, $this->
aircraftArray);
return $this->memberArray;
return $this->groupArray;
return $this->aircraftArray;
}
/* --Populate Arrays-- */
private function populateArrays(&$memberArray, &$groupArray, &$aircraftArray)
{
/* --Loads Flight Log feed(LIMIT 500) and starts populating-- */
$logs = simplexml_load_file("http://www.fseconomy.net/data?userkey=$this->userKey&format=xml&query=flightlogs&search=id&readaccesskey=$this->groupKey&fromid=$this->groupId");
foreach ($logs->FlightLog as $log) {
$ft = explode(":", $log->FlightTime); //Split time for use
/* --Populate memberArray-- */
for ($x = 0; $x < count($memberArray); $x++) {
if (strcmp($memberArray[$x][0], $log->Pilot) == 0) {
$memberArray[$x][2] = $memberArray[$x][2] + 1; //Increment flight counter
$memberArray[$x][3] = $memberArray[$x][3] + $ft[1] + ($ft[0] * 60); //Add Flight time(in minutes)
$memberArray[$x][4] = $memberArray[$x][4] + $log->Distance; //Add Distance
$memberArray[$x][5] = $memberArray[$x][5] + floatval($log->PilotFee); //Add Pilot's Pay
}
}
/* --Populates groupArray-- */
$groupArray[1] = $groupArray[1] + $ft[1] + ($ft[0] * 60); //Add Flight time(in minutes)
$groupArray[2] = $groupArray[2] + $log->Distance; //Add Distance
$groupArray[3] = $groupArray[3] + floatval($log->Income) - floatval($log->
PilotFee) - floatval($log->CrewCost) - floatval($log->BookingFee) - floatval($log->
FuelCost) - floatval($log->GCF) - floatval($log->RentalCost); //Calculate Profit
/* --Populates aircraftArray-- */
for ($x = 0; $x < count($aircraftArray); $x++) {
if (strcmp($aircraftArray[$x][0], $log->Aircraft) == 0) {
$aircraftArray[$x][2] = $aircraftArray[$x][2] + 1; //Increment flight counter
$aircraftArray[$x][3] = $aircraftArray[$x][3] + $ft[1] + ($ft[0] * 60); //Add Flight time(in minutes)
$aircraftArray[$x][4] = $aircraftArray[$x][4] + $log->Distance; //Add Distance
$aircraftArray[$x][5] = $aircraftArray[$x][5] + floatval($log->Income) -
floatval($log->CrewCost) - floatval($log->BookingFee) - floatval($log->FuelCost) -
floatval($log->GCF); //Calculate Profit
}
}
$groupArray[0] = count($logs->FlightLog); //Increment flight counter
}
/* --Returns populated arrays-- */
return $aircraftArray;
return $memberArray;
return $groupArray;
}
/* --Display sortable Pilot stats table-- */
public function displayPilotStats()
{
echo "<table id=\"memberTable\" class=\"tablesorter\"><thead><tr><th>Pilot</th><th>Status</th><th>Total Flights</th><th>Total Time</th><th>Total Distance</th><th>Total Profit</th></tr></thead><tbody>";
for ($x = 0; $x < count($this->memberArray); $x++) {
echo "<tr><td>" . $this->memberArray[$x][0] . "</td><td>" . ucfirst($this->
memberArray[$x][1]) . "</td><td>" . $this->memberArray[$x][2] . "</td><td>" . $this->
formatTime($this->memberArray[$x][3]) . "</td><td>" . $this->memberArray[$x][4] .
"nm</td><td>$" . number_format($this->memberArray[$x][5], 2) . "</td></tr>";
}
echo "</tbody></table>";
}
/* --Display sortable Pilot stats table-- */
public function displayGroupStats()
{
echo "<table id=\"groupTable\" class=\"tablesorter\"><thead><tr><th>Total Flights</th><th>Total Time</th><th>Total Distance</th><th>Total Profit</th></tr></thead><tbody>";
echo "<tr><td>" . $this->groupArray[0] . "</td><td>" . $this->formatTime($this->
groupArray[1]) . "</td><td>" . $this->groupArray[2] . "nm</td><td>$" .
number_format($this->groupArray[3], 2) . "</td></tr> ";
echo "</tbody></table>";
}
/* --Display sortable Pilot stats table-- */
public function displayAircraftStats()
{
echo "<table id=\"aircraftTable\" class=\"tablesorter\"><thead><tr><th>Aircraft Registration</th><th>Make/Model</th><th>Total Flights</th><th>Total Time</th><th>Total Distance</th><th>Total Profit</th></tr></thead><tbody>";
for ($x = 0; $x < count($this->aircraftArray); $x++) {
echo "<tr><td>" . $this->aircraftArray[$x][0] . "</td><td>" . $this->
aircraftArray[$x][1] . "</td><td>" . $this->aircraftArray[$x][2] . "</td><td>" .
$this->formatTime($this->aircraftArray[$x][3]) . "</td><td>" . $this->
aircraftArray[$x][4] . "nm</td><td>$" . number_format($this->aircraftArray[$x][5],
2) . "</td></tr>";
}
echo "</tbody></table> ";
}
/* --Formats time-- */
public function formatTime($minutes)
{
$hours = floor($minutes / 60);
$min = $minutes - ($hours * 60);
$formattedTime = $hours . ":" . $min;
return $formattedTime;
}
}
?>
| linkerovx9/FSELink | fselink.class.php | PHP | gpl-2.0 | 7,357 |
<?php
/**
* @file
* The PHP page that serves all page requests on a Drupal installation.
*
* The routines here dispatch control to the appropriate handler, which then
* prints the appropriate page.
*
* All Drupal code is released under the GNU General Public License.
* See COPYRIGHT.txt and LICENSE.txt.
*/
/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();
| sagarw/lantra | index.php | PHP | gpl-2.0 | 532 |
/*
* This file contains work-arounds for many known PCI hardware
* bugs. Devices present only on certain architectures (host
* bridges et cetera) should be handled in arch-specific code.
*
* Note: any quirks for hotpluggable devices must _NOT_ be declared __init.
*
* Copyright (c) 1999 Martin Mares <[email protected]>
*
* Init/reset quirks for USB host controllers should be in the
* USB quirks file, where their drivers can access reuse it.
*/
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/acpi.h>
#include <linux/kallsyms.h>
#include <linux/dmi.h>
#include <linux/pci-aspm.h>
#include <linux/ioport.h>
#include <linux/sched.h>
#include <linux/ktime.h>
#include <linux/mm.h>
#include <asm/dma.h> /* isa_dma_bridge_buggy */
#include "pci.h"
/*
* Decoding should be disabled for a PCI device during BAR sizing to avoid
* conflict. But doing so may cause problems on host bridge and perhaps other
* key system devices. For devices that need to have mmio decoding always-on,
* we need to set the dev->mmio_always_on bit.
*/
static void quirk_mmio_always_on(struct pci_dev *dev)
{
dev->mmio_always_on = 1;
}
DECLARE_PCI_FIXUP_CLASS_EARLY(PCI_ANY_ID, PCI_ANY_ID,
PCI_CLASS_BRIDGE_HOST, 8, quirk_mmio_always_on);
/* The Mellanox Tavor device gives false positive parity errors
* Mark this device with a broken_parity_status, to allow
* PCI scanning code to "skip" this now blacklisted device.
*/
static void quirk_mellanox_tavor(struct pci_dev *dev)
{
dev->broken_parity_status = 1; /* This device gives false positives */
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_MELLANOX, PCI_DEVICE_ID_MELLANOX_TAVOR, quirk_mellanox_tavor);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_MELLANOX, PCI_DEVICE_ID_MELLANOX_TAVOR_BRIDGE, quirk_mellanox_tavor);
/* Deal with broken BIOSes that neglect to enable passive release,
which can cause problems in combination with the 82441FX/PPro MTRRs */
static void quirk_passive_release(struct pci_dev *dev)
{
struct pci_dev *d = NULL;
unsigned char dlc;
/* We have to make sure a particular bit is set in the PIIX3
ISA bridge, so we have to go out and find it. */
while ((d = pci_get_device(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371SB_0, d))) {
pci_read_config_byte(d, 0x82, &dlc);
if (!(dlc & 1<<1)) {
dev_info(&d->dev, "PIIX3: Enabling Passive Release\n");
dlc |= 1<<1;
pci_write_config_byte(d, 0x82, dlc);
}
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82441, quirk_passive_release);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82441, quirk_passive_release);
/* The VIA VP2/VP3/MVP3 seem to have some 'features'. There may be a workaround
but VIA don't answer queries. If you happen to have good contacts at VIA
ask them for me please -- Alan
This appears to be BIOS not version dependent. So presumably there is a
chipset level fix */
static void quirk_isa_dma_hangs(struct pci_dev *dev)
{
if (!isa_dma_bridge_buggy) {
isa_dma_bridge_buggy = 1;
dev_info(&dev->dev, "Activating ISA DMA hang workarounds\n");
}
}
/*
* Its not totally clear which chipsets are the problematic ones
* We know 82C586 and 82C596 variants are affected.
*/
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C586_0, quirk_isa_dma_hangs);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C596, quirk_isa_dma_hangs);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371SB_0, quirk_isa_dma_hangs);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M1533, quirk_isa_dma_hangs);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_NEC, PCI_DEVICE_ID_NEC_CBUS_1, quirk_isa_dma_hangs);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_NEC, PCI_DEVICE_ID_NEC_CBUS_2, quirk_isa_dma_hangs);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_NEC, PCI_DEVICE_ID_NEC_CBUS_3, quirk_isa_dma_hangs);
/*
* Intel NM10 "TigerPoint" LPC PM1a_STS.BM_STS must be clear
* for some HT machines to use C4 w/o hanging.
*/
static void quirk_tigerpoint_bm_sts(struct pci_dev *dev)
{
u32 pmbase;
u16 pm1a;
pci_read_config_dword(dev, 0x40, &pmbase);
pmbase = pmbase & 0xff80;
pm1a = inw(pmbase);
if (pm1a & 0x10) {
dev_info(&dev->dev, FW_BUG "TigerPoint LPC.BM_STS cleared\n");
outw(0x10, pmbase);
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_TGP_LPC, quirk_tigerpoint_bm_sts);
/*
* Chipsets where PCI->PCI transfers vanish or hang
*/
static void quirk_nopcipci(struct pci_dev *dev)
{
if ((pci_pci_problems & PCIPCI_FAIL) == 0) {
dev_info(&dev->dev, "Disabling direct PCI/PCI transfers\n");
pci_pci_problems |= PCIPCI_FAIL;
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_5597, quirk_nopcipci);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_496, quirk_nopcipci);
static void quirk_nopciamd(struct pci_dev *dev)
{
u8 rev;
pci_read_config_byte(dev, 0x08, &rev);
if (rev == 0x13) {
/* Erratum 24 */
dev_info(&dev->dev, "Chipset erratum: Disabling direct PCI/AGP transfers\n");
pci_pci_problems |= PCIAGP_FAIL;
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8151_0, quirk_nopciamd);
/*
* Triton requires workarounds to be used by the drivers
*/
static void quirk_triton(struct pci_dev *dev)
{
if ((pci_pci_problems&PCIPCI_TRITON) == 0) {
dev_info(&dev->dev, "Limiting direct PCI/PCI transfers\n");
pci_pci_problems |= PCIPCI_TRITON;
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82437, quirk_triton);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82437VX, quirk_triton);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82439, quirk_triton);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82439TX, quirk_triton);
/*
* VIA Apollo KT133 needs PCI latency patch
* Made according to a windows driver based patch by George E. Breese
* see PCI Latency Adjust on http://www.viahardware.com/download/viatweak.shtm
* Also see http://www.au-ja.org/review-kt133a-1-en.phtml for
* the info on which Mr Breese based his work.
*
* Updated based on further information from the site and also on
* information provided by VIA
*/
static void quirk_vialatency(struct pci_dev *dev)
{
struct pci_dev *p;
u8 busarb;
/* Ok we have a potential problem chipset here. Now see if we have
a buggy southbridge */
p = pci_get_device(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686, NULL);
if (p != NULL) {
/* 0x40 - 0x4f == 686B, 0x10 - 0x2f == 686A; thanks Dan Hollis */
/* Check for buggy part revisions */
if (p->revision < 0x40 || p->revision > 0x42)
goto exit;
} else {
p = pci_get_device(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8231, NULL);
if (p == NULL) /* No problem parts */
goto exit;
/* Check for buggy part revisions */
if (p->revision < 0x10 || p->revision > 0x12)
goto exit;
}
/*
* Ok we have the problem. Now set the PCI master grant to
* occur every master grant. The apparent bug is that under high
* PCI load (quite common in Linux of course) you can get data
* loss when the CPU is held off the bus for 3 bus master requests
* This happens to include the IDE controllers....
*
* VIA only apply this fix when an SB Live! is present but under
* both Linux and Windows this isn't enough, and we have seen
* corruption without SB Live! but with things like 3 UDMA IDE
* controllers. So we ignore that bit of the VIA recommendation..
*/
pci_read_config_byte(dev, 0x76, &busarb);
/* Set bit 4 and bi 5 of byte 76 to 0x01
"Master priority rotation on every PCI master grant */
busarb &= ~(1<<5);
busarb |= (1<<4);
pci_write_config_byte(dev, 0x76, busarb);
dev_info(&dev->dev, "Applying VIA southbridge workaround\n");
exit:
pci_dev_put(p);
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8363_0, quirk_vialatency);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8371_1, quirk_vialatency);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8361, quirk_vialatency);
/* Must restore this on a resume from RAM */
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8363_0, quirk_vialatency);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8371_1, quirk_vialatency);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8361, quirk_vialatency);
/*
* VIA Apollo VP3 needs ETBF on BT848/878
*/
static void quirk_viaetbf(struct pci_dev *dev)
{
if ((pci_pci_problems&PCIPCI_VIAETBF) == 0) {
dev_info(&dev->dev, "Limiting direct PCI/PCI transfers\n");
pci_pci_problems |= PCIPCI_VIAETBF;
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C597_0, quirk_viaetbf);
static void quirk_vsfx(struct pci_dev *dev)
{
if ((pci_pci_problems&PCIPCI_VSFX) == 0) {
dev_info(&dev->dev, "Limiting direct PCI/PCI transfers\n");
pci_pci_problems |= PCIPCI_VSFX;
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C576, quirk_vsfx);
/*
* Ali Magik requires workarounds to be used by the drivers
* that DMA to AGP space. Latency must be set to 0xA and triton
* workaround applied too
* [Info kindly provided by ALi]
*/
static void quirk_alimagik(struct pci_dev *dev)
{
if ((pci_pci_problems&PCIPCI_ALIMAGIK) == 0) {
dev_info(&dev->dev, "Limiting direct PCI/PCI transfers\n");
pci_pci_problems |= PCIPCI_ALIMAGIK|PCIPCI_TRITON;
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M1647, quirk_alimagik);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M1651, quirk_alimagik);
/*
* Natoma has some interesting boundary conditions with Zoran stuff
* at least
*/
static void quirk_natoma(struct pci_dev *dev)
{
if ((pci_pci_problems&PCIPCI_NATOMA) == 0) {
dev_info(&dev->dev, "Limiting direct PCI/PCI transfers\n");
pci_pci_problems |= PCIPCI_NATOMA;
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82441, quirk_natoma);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82443LX_0, quirk_natoma);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82443LX_1, quirk_natoma);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82443BX_0, quirk_natoma);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82443BX_1, quirk_natoma);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82443BX_2, quirk_natoma);
/*
* This chip can cause PCI parity errors if config register 0xA0 is read
* while DMAs are occurring.
*/
static void quirk_citrine(struct pci_dev *dev)
{
dev->cfg_size = 0xA0;
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_IBM, PCI_DEVICE_ID_IBM_CITRINE, quirk_citrine);
/*
* This chip can cause bus lockups if config addresses above 0x600
* are read or written.
*/
static void quirk_nfp6000(struct pci_dev *dev)
{
dev->cfg_size = 0x600;
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_NETRONOME, PCI_DEVICE_ID_NETRONOME_NFP4000, quirk_nfp6000);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_NETRONOME, PCI_DEVICE_ID_NETRONOME_NFP6000, quirk_nfp6000);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_NETRONOME, PCI_DEVICE_ID_NETRONOME_NFP6000_VF, quirk_nfp6000);
/* On IBM Crocodile ipr SAS adapters, expand BAR to system page size */
static void quirk_extend_bar_to_page(struct pci_dev *dev)
{
int i;
for (i = 0; i < PCI_STD_RESOURCE_END; i++) {
struct resource *r = &dev->resource[i];
if (r->flags & IORESOURCE_MEM && resource_size(r) < PAGE_SIZE) {
r->end = PAGE_SIZE - 1;
r->start = 0;
r->flags |= IORESOURCE_UNSET;
dev_info(&dev->dev, "expanded BAR %d to page size: %pR\n",
i, r);
}
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_IBM, 0x034a, quirk_extend_bar_to_page);
/*
* S3 868 and 968 chips report region size equal to 32M, but they decode 64M.
* If it's needed, re-allocate the region.
*/
static void quirk_s3_64M(struct pci_dev *dev)
{
struct resource *r = &dev->resource[0];
if ((r->start & 0x3ffffff) || r->end != r->start + 0x3ffffff) {
r->flags |= IORESOURCE_UNSET;
r->start = 0;
r->end = 0x3ffffff;
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_S3, PCI_DEVICE_ID_S3_868, quirk_s3_64M);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_S3, PCI_DEVICE_ID_S3_968, quirk_s3_64M);
static void quirk_io(struct pci_dev *dev, int pos, unsigned size,
const char *name)
{
u32 region;
struct pci_bus_region bus_region;
struct resource *res = dev->resource + pos;
pci_read_config_dword(dev, PCI_BASE_ADDRESS_0 + (pos << 2), ®ion);
if (!region)
return;
res->name = pci_name(dev);
res->flags = region & ~PCI_BASE_ADDRESS_IO_MASK;
res->flags |=
(IORESOURCE_IO | IORESOURCE_PCI_FIXED | IORESOURCE_SIZEALIGN);
region &= ~(size - 1);
/* Convert from PCI bus to resource space */
bus_region.start = region;
bus_region.end = region + size - 1;
pcibios_bus_to_resource(dev->bus, res, &bus_region);
dev_info(&dev->dev, FW_BUG "%s quirk: reg 0x%x: %pR\n",
name, PCI_BASE_ADDRESS_0 + (pos << 2), res);
}
/*
* Some CS5536 BIOSes (for example, the Soekris NET5501 board w/ comBIOS
* ver. 1.33 20070103) don't set the correct ISA PCI region header info.
* BAR0 should be 8 bytes; instead, it may be set to something like 8k
* (which conflicts w/ BAR1's memory range).
*
* CS553x's ISA PCI BARs may also be read-only (ref:
* https://bugzilla.kernel.org/show_bug.cgi?id=85991 - Comment #4 forward).
*/
static void quirk_cs5536_vsa(struct pci_dev *dev)
{
static char *name = "CS5536 ISA bridge";
if (pci_resource_len(dev, 0) != 8) {
quirk_io(dev, 0, 8, name); /* SMB */
quirk_io(dev, 1, 256, name); /* GPIO */
quirk_io(dev, 2, 64, name); /* MFGPT */
dev_info(&dev->dev, "%s bug detected (incorrect header); workaround applied\n",
name);
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_CS5536_ISA, quirk_cs5536_vsa);
static void quirk_io_region(struct pci_dev *dev, int port,
unsigned size, int nr, const char *name)
{
u16 region;
struct pci_bus_region bus_region;
struct resource *res = dev->resource + nr;
pci_read_config_word(dev, port, ®ion);
region &= ~(size - 1);
if (!region)
return;
res->name = pci_name(dev);
res->flags = IORESOURCE_IO;
/* Convert from PCI bus to resource space */
bus_region.start = region;
bus_region.end = region + size - 1;
pcibios_bus_to_resource(dev->bus, res, &bus_region);
if (!pci_claim_resource(dev, nr))
dev_info(&dev->dev, "quirk: %pR claimed by %s\n", res, name);
}
/*
* ATI Northbridge setups MCE the processor if you even
* read somewhere between 0x3b0->0x3bb or read 0x3d3
*/
static void quirk_ati_exploding_mce(struct pci_dev *dev)
{
dev_info(&dev->dev, "ATI Northbridge, reserving I/O ports 0x3b0 to 0x3bb\n");
/* Mae rhaid i ni beidio ag edrych ar y lleoliadiau I/O hyn */
request_region(0x3b0, 0x0C, "RadeonIGP");
request_region(0x3d3, 0x01, "RadeonIGP");
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RS100, quirk_ati_exploding_mce);
/*
* In the AMD NL platform, this device ([1022:7912]) has a class code of
* PCI_CLASS_SERIAL_USB_XHCI (0x0c0330), which means the xhci driver will
* claim it.
* But the dwc3 driver is a more specific driver for this device, and we'd
* prefer to use it instead of xhci. To prevent xhci from claiming the
* device, change the class code to 0x0c03fe, which the PCI r3.0 spec
* defines as "USB device (not host controller)". The dwc3 driver can then
* claim it based on its Vendor and Device ID.
*/
static void quirk_amd_nl_class(struct pci_dev *pdev)
{
u32 class = pdev->class;
/* Use "USB Device (not host controller)" class */
pdev->class = PCI_CLASS_SERIAL_USB_DEVICE;
dev_info(&pdev->dev, "PCI class overridden (%#08x -> %#08x) so dwc3 driver can claim this instead of xhci\n",
class, pdev->class);
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_NL_USB,
quirk_amd_nl_class);
/*
* Let's make the southbridge information explicit instead
* of having to worry about people probing the ACPI areas,
* for example.. (Yes, it happens, and if you read the wrong
* ACPI register it will put the machine to sleep with no
* way of waking it up again. Bummer).
*
* ALI M7101: Two IO regions pointed to by words at
* 0xE0 (64 bytes of ACPI registers)
* 0xE2 (32 bytes of SMB registers)
*/
static void quirk_ali7101_acpi(struct pci_dev *dev)
{
quirk_io_region(dev, 0xE0, 64, PCI_BRIDGE_RESOURCES, "ali7101 ACPI");
quirk_io_region(dev, 0xE2, 32, PCI_BRIDGE_RESOURCES+1, "ali7101 SMB");
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AL, PCI_DEVICE_ID_AL_M7101, quirk_ali7101_acpi);
static void piix4_io_quirk(struct pci_dev *dev, const char *name, unsigned int port, unsigned int enable)
{
u32 devres;
u32 mask, size, base;
pci_read_config_dword(dev, port, &devres);
if ((devres & enable) != enable)
return;
mask = (devres >> 16) & 15;
base = devres & 0xffff;
size = 16;
for (;;) {
unsigned bit = size >> 1;
if ((bit & mask) == bit)
break;
size = bit;
}
/*
* For now we only print it out. Eventually we'll want to
* reserve it (at least if it's in the 0x1000+ range), but
* let's get enough confirmation reports first.
*/
base &= -size;
dev_info(&dev->dev, "%s PIO at %04x-%04x\n", name, base,
base + size - 1);
}
static void piix4_mem_quirk(struct pci_dev *dev, const char *name, unsigned int port, unsigned int enable)
{
u32 devres;
u32 mask, size, base;
pci_read_config_dword(dev, port, &devres);
if ((devres & enable) != enable)
return;
base = devres & 0xffff0000;
mask = (devres & 0x3f) << 16;
size = 128 << 16;
for (;;) {
unsigned bit = size >> 1;
if ((bit & mask) == bit)
break;
size = bit;
}
/*
* For now we only print it out. Eventually we'll want to
* reserve it, but let's get enough confirmation reports first.
*/
base &= -size;
dev_info(&dev->dev, "%s MMIO at %04x-%04x\n", name, base,
base + size - 1);
}
/*
* PIIX4 ACPI: Two IO regions pointed to by longwords at
* 0x40 (64 bytes of ACPI registers)
* 0x90 (16 bytes of SMB registers)
* and a few strange programmable PIIX4 device resources.
*/
static void quirk_piix4_acpi(struct pci_dev *dev)
{
u32 res_a;
quirk_io_region(dev, 0x40, 64, PCI_BRIDGE_RESOURCES, "PIIX4 ACPI");
quirk_io_region(dev, 0x90, 16, PCI_BRIDGE_RESOURCES+1, "PIIX4 SMB");
/* Device resource A has enables for some of the other ones */
pci_read_config_dword(dev, 0x5c, &res_a);
piix4_io_quirk(dev, "PIIX4 devres B", 0x60, 3 << 21);
piix4_io_quirk(dev, "PIIX4 devres C", 0x64, 3 << 21);
/* Device resource D is just bitfields for static resources */
/* Device 12 enabled? */
if (res_a & (1 << 29)) {
piix4_io_quirk(dev, "PIIX4 devres E", 0x68, 1 << 20);
piix4_mem_quirk(dev, "PIIX4 devres F", 0x6c, 1 << 7);
}
/* Device 13 enabled? */
if (res_a & (1 << 30)) {
piix4_io_quirk(dev, "PIIX4 devres G", 0x70, 1 << 20);
piix4_mem_quirk(dev, "PIIX4 devres H", 0x74, 1 << 7);
}
piix4_io_quirk(dev, "PIIX4 devres I", 0x78, 1 << 20);
piix4_io_quirk(dev, "PIIX4 devres J", 0x7c, 1 << 20);
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82371AB_3, quirk_piix4_acpi);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82443MX_3, quirk_piix4_acpi);
#define ICH_PMBASE 0x40
#define ICH_ACPI_CNTL 0x44
#define ICH4_ACPI_EN 0x10
#define ICH6_ACPI_EN 0x80
#define ICH4_GPIOBASE 0x58
#define ICH4_GPIO_CNTL 0x5c
#define ICH4_GPIO_EN 0x10
#define ICH6_GPIOBASE 0x48
#define ICH6_GPIO_CNTL 0x4c
#define ICH6_GPIO_EN 0x10
/*
* ICH4, ICH4-M, ICH5, ICH5-M ACPI: Three IO regions pointed to by longwords at
* 0x40 (128 bytes of ACPI, GPIO & TCO registers)
* 0x58 (64 bytes of GPIO I/O space)
*/
static void quirk_ich4_lpc_acpi(struct pci_dev *dev)
{
u8 enable;
/*
* The check for PCIBIOS_MIN_IO is to ensure we won't create a conflict
* with low legacy (and fixed) ports. We don't know the decoding
* priority and can't tell whether the legacy device or the one created
* here is really at that address. This happens on boards with broken
* BIOSes.
*/
pci_read_config_byte(dev, ICH_ACPI_CNTL, &enable);
if (enable & ICH4_ACPI_EN)
quirk_io_region(dev, ICH_PMBASE, 128, PCI_BRIDGE_RESOURCES,
"ICH4 ACPI/GPIO/TCO");
pci_read_config_byte(dev, ICH4_GPIO_CNTL, &enable);
if (enable & ICH4_GPIO_EN)
quirk_io_region(dev, ICH4_GPIOBASE, 64, PCI_BRIDGE_RESOURCES+1,
"ICH4 GPIO");
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AA_0, quirk_ich4_lpc_acpi);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AB_0, quirk_ich4_lpc_acpi);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_0, quirk_ich4_lpc_acpi);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_10, quirk_ich4_lpc_acpi);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_0, quirk_ich4_lpc_acpi);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_12, quirk_ich4_lpc_acpi);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_0, quirk_ich4_lpc_acpi);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_12, quirk_ich4_lpc_acpi);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801EB_0, quirk_ich4_lpc_acpi);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ESB_1, quirk_ich4_lpc_acpi);
static void ich6_lpc_acpi_gpio(struct pci_dev *dev)
{
u8 enable;
pci_read_config_byte(dev, ICH_ACPI_CNTL, &enable);
if (enable & ICH6_ACPI_EN)
quirk_io_region(dev, ICH_PMBASE, 128, PCI_BRIDGE_RESOURCES,
"ICH6 ACPI/GPIO/TCO");
pci_read_config_byte(dev, ICH6_GPIO_CNTL, &enable);
if (enable & ICH6_GPIO_EN)
quirk_io_region(dev, ICH6_GPIOBASE, 64, PCI_BRIDGE_RESOURCES+1,
"ICH6 GPIO");
}
static void ich6_lpc_generic_decode(struct pci_dev *dev, unsigned reg, const char *name, int dynsize)
{
u32 val;
u32 size, base;
pci_read_config_dword(dev, reg, &val);
/* Enabled? */
if (!(val & 1))
return;
base = val & 0xfffc;
if (dynsize) {
/*
* This is not correct. It is 16, 32 or 64 bytes depending on
* register D31:F0:ADh bits 5:4.
*
* But this gets us at least _part_ of it.
*/
size = 16;
} else {
size = 128;
}
base &= ~(size-1);
/* Just print it out for now. We should reserve it after more debugging */
dev_info(&dev->dev, "%s PIO at %04x-%04x\n", name, base, base+size-1);
}
static void quirk_ich6_lpc(struct pci_dev *dev)
{
/* Shared ACPI/GPIO decode with all ICH6+ */
ich6_lpc_acpi_gpio(dev);
/* ICH6-specific generic IO decode */
ich6_lpc_generic_decode(dev, 0x84, "LPC Generic IO decode 1", 0);
ich6_lpc_generic_decode(dev, 0x88, "LPC Generic IO decode 2", 1);
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH6_0, quirk_ich6_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH6_1, quirk_ich6_lpc);
static void ich7_lpc_generic_decode(struct pci_dev *dev, unsigned reg, const char *name)
{
u32 val;
u32 mask, base;
pci_read_config_dword(dev, reg, &val);
/* Enabled? */
if (!(val & 1))
return;
/*
* IO base in bits 15:2, mask in bits 23:18, both
* are dword-based
*/
base = val & 0xfffc;
mask = (val >> 16) & 0xfc;
mask |= 3;
/* Just print it out for now. We should reserve it after more debugging */
dev_info(&dev->dev, "%s PIO at %04x (mask %04x)\n", name, base, mask);
}
/* ICH7-10 has the same common LPC generic IO decode registers */
static void quirk_ich7_lpc(struct pci_dev *dev)
{
/* We share the common ACPI/GPIO decode with ICH6 */
ich6_lpc_acpi_gpio(dev);
/* And have 4 ICH7+ generic decodes */
ich7_lpc_generic_decode(dev, 0x84, "ICH7 LPC Generic IO decode 1");
ich7_lpc_generic_decode(dev, 0x88, "ICH7 LPC Generic IO decode 2");
ich7_lpc_generic_decode(dev, 0x8c, "ICH7 LPC Generic IO decode 3");
ich7_lpc_generic_decode(dev, 0x90, "ICH7 LPC Generic IO decode 4");
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH7_0, quirk_ich7_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH7_1, quirk_ich7_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH7_31, quirk_ich7_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH8_0, quirk_ich7_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH8_2, quirk_ich7_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH8_3, quirk_ich7_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH8_1, quirk_ich7_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH8_4, quirk_ich7_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH9_2, quirk_ich7_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH9_4, quirk_ich7_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH9_7, quirk_ich7_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH9_8, quirk_ich7_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH10_1, quirk_ich7_lpc);
/*
* VIA ACPI: One IO region pointed to by longword at
* 0x48 or 0x20 (256 bytes of ACPI registers)
*/
static void quirk_vt82c586_acpi(struct pci_dev *dev)
{
if (dev->revision & 0x10)
quirk_io_region(dev, 0x48, 256, PCI_BRIDGE_RESOURCES,
"vt82c586 ACPI");
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C586_3, quirk_vt82c586_acpi);
/*
* VIA VT82C686 ACPI: Three IO region pointed to by (long)words at
* 0x48 (256 bytes of ACPI registers)
* 0x70 (128 bytes of hardware monitoring register)
* 0x90 (16 bytes of SMB registers)
*/
static void quirk_vt82c686_acpi(struct pci_dev *dev)
{
quirk_vt82c586_acpi(dev);
quirk_io_region(dev, 0x70, 128, PCI_BRIDGE_RESOURCES+1,
"vt82c686 HW-mon");
quirk_io_region(dev, 0x90, 16, PCI_BRIDGE_RESOURCES+2, "vt82c686 SMB");
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686_4, quirk_vt82c686_acpi);
/*
* VIA VT8235 ISA Bridge: Two IO regions pointed to by words at
* 0x88 (128 bytes of power management registers)
* 0xd0 (16 bytes of SMB registers)
*/
static void quirk_vt8235_acpi(struct pci_dev *dev)
{
quirk_io_region(dev, 0x88, 128, PCI_BRIDGE_RESOURCES, "vt8235 PM");
quirk_io_region(dev, 0xd0, 16, PCI_BRIDGE_RESOURCES+1, "vt8235 SMB");
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8235, quirk_vt8235_acpi);
/*
* TI XIO2000a PCIe-PCI Bridge erroneously reports it supports fast back-to-back:
* Disable fast back-to-back on the secondary bus segment
*/
static void quirk_xio2000a(struct pci_dev *dev)
{
struct pci_dev *pdev;
u16 command;
dev_warn(&dev->dev, "TI XIO2000a quirk detected; secondary bus fast back-to-back transfers disabled\n");
list_for_each_entry(pdev, &dev->subordinate->devices, bus_list) {
pci_read_config_word(pdev, PCI_COMMAND, &command);
if (command & PCI_COMMAND_FAST_BACK)
pci_write_config_word(pdev, PCI_COMMAND, command & ~PCI_COMMAND_FAST_BACK);
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_XIO2000A,
quirk_xio2000a);
#ifdef CONFIG_X86_IO_APIC
#include <asm/io_apic.h>
/*
* VIA 686A/B: If an IO-APIC is active, we need to route all on-chip
* devices to the external APIC.
*
* TODO: When we have device-specific interrupt routers,
* this code will go away from quirks.
*/
static void quirk_via_ioapic(struct pci_dev *dev)
{
u8 tmp;
if (nr_ioapics < 1)
tmp = 0; /* nothing routed to external APIC */
else
tmp = 0x1f; /* all known bits (4-0) routed to external APIC */
dev_info(&dev->dev, "%sbling VIA external APIC routing\n",
tmp == 0 ? "Disa" : "Ena");
/* Offset 0x58: External APIC IRQ output control */
pci_write_config_byte(dev, 0x58, tmp);
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686, quirk_via_ioapic);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686, quirk_via_ioapic);
/*
* VIA 8237: Some BIOSes don't set the 'Bypass APIC De-Assert Message' Bit.
* This leads to doubled level interrupt rates.
* Set this bit to get rid of cycle wastage.
* Otherwise uncritical.
*/
static void quirk_via_vt8237_bypass_apic_deassert(struct pci_dev *dev)
{
u8 misc_control2;
#define BYPASS_APIC_DEASSERT 8
pci_read_config_byte(dev, 0x5B, &misc_control2);
if (!(misc_control2 & BYPASS_APIC_DEASSERT)) {
dev_info(&dev->dev, "Bypassing VIA 8237 APIC De-Assert Message\n");
pci_write_config_byte(dev, 0x5B, misc_control2|BYPASS_APIC_DEASSERT);
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237, quirk_via_vt8237_bypass_apic_deassert);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237, quirk_via_vt8237_bypass_apic_deassert);
/*
* The AMD io apic can hang the box when an apic irq is masked.
* We check all revs >= B0 (yet not in the pre production!) as the bug
* is currently marked NoFix
*
* We have multiple reports of hangs with this chipset that went away with
* noapic specified. For the moment we assume it's the erratum. We may be wrong
* of course. However the advice is demonstrably good even if so..
*/
static void quirk_amd_ioapic(struct pci_dev *dev)
{
if (dev->revision >= 0x02) {
dev_warn(&dev->dev, "I/O APIC: AMD Erratum #22 may be present. In the event of instability try\n");
dev_warn(&dev->dev, " : booting with the \"noapic\" option\n");
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_VIPER_7410, quirk_amd_ioapic);
#endif /* CONFIG_X86_IO_APIC */
#if defined(CONFIG_ARM64) && defined(CONFIG_PCI_ATS)
static void quirk_cavium_sriov_rnm_link(struct pci_dev *dev)
{
/* Fix for improper SRIOV configuration on Cavium cn88xx RNM device */
if (dev->subsystem_device == 0xa118)
dev->sriov->link = dev->devfn;
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CAVIUM, 0xa018, quirk_cavium_sriov_rnm_link);
#endif
/*
* Some settings of MMRBC can lead to data corruption so block changes.
* See AMD 8131 HyperTransport PCI-X Tunnel Revision Guide
*/
static void quirk_amd_8131_mmrbc(struct pci_dev *dev)
{
if (dev->subordinate && dev->revision <= 0x12) {
dev_info(&dev->dev, "AMD8131 rev %x detected; disabling PCI-X MMRBC\n",
dev->revision);
dev->subordinate->bus_flags |= PCI_BUS_FLAGS_NO_MMRBC;
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8131_BRIDGE, quirk_amd_8131_mmrbc);
/*
* FIXME: it is questionable that quirk_via_acpi
* is needed. It shows up as an ISA bridge, and does not
* support the PCI_INTERRUPT_LINE register at all. Therefore
* it seems like setting the pci_dev's 'irq' to the
* value of the ACPI SCI interrupt is only done for convenience.
* -jgarzik
*/
static void quirk_via_acpi(struct pci_dev *d)
{
/*
* VIA ACPI device: SCI IRQ line in PCI config byte 0x42
*/
u8 irq;
pci_read_config_byte(d, 0x42, &irq);
irq &= 0xf;
if (irq && (irq != 2))
d->irq = irq;
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C586_3, quirk_via_acpi);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686_4, quirk_via_acpi);
/*
* VIA bridges which have VLink
*/
static int via_vlink_dev_lo = -1, via_vlink_dev_hi = 18;
static void quirk_via_bridge(struct pci_dev *dev)
{
/* See what bridge we have and find the device ranges */
switch (dev->device) {
case PCI_DEVICE_ID_VIA_82C686:
/* The VT82C686 is special, it attaches to PCI and can have
any device number. All its subdevices are functions of
that single device. */
via_vlink_dev_lo = PCI_SLOT(dev->devfn);
via_vlink_dev_hi = PCI_SLOT(dev->devfn);
break;
case PCI_DEVICE_ID_VIA_8237:
case PCI_DEVICE_ID_VIA_8237A:
via_vlink_dev_lo = 15;
break;
case PCI_DEVICE_ID_VIA_8235:
via_vlink_dev_lo = 16;
break;
case PCI_DEVICE_ID_VIA_8231:
case PCI_DEVICE_ID_VIA_8233_0:
case PCI_DEVICE_ID_VIA_8233A:
case PCI_DEVICE_ID_VIA_8233C_0:
via_vlink_dev_lo = 17;
break;
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C686, quirk_via_bridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8231, quirk_via_bridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8233_0, quirk_via_bridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8233A, quirk_via_bridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8233C_0, quirk_via_bridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8235, quirk_via_bridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237, quirk_via_bridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237A, quirk_via_bridge);
/**
* quirk_via_vlink - VIA VLink IRQ number update
* @dev: PCI device
*
* If the device we are dealing with is on a PIC IRQ we need to
* ensure that the IRQ line register which usually is not relevant
* for PCI cards, is actually written so that interrupts get sent
* to the right place.
* We only do this on systems where a VIA south bridge was detected,
* and only for VIA devices on the motherboard (see quirk_via_bridge
* above).
*/
static void quirk_via_vlink(struct pci_dev *dev)
{
u8 irq, new_irq;
/* Check if we have VLink at all */
if (via_vlink_dev_lo == -1)
return;
new_irq = dev->irq;
/* Don't quirk interrupts outside the legacy IRQ range */
if (!new_irq || new_irq > 15)
return;
/* Internal device ? */
if (dev->bus->number != 0 || PCI_SLOT(dev->devfn) > via_vlink_dev_hi ||
PCI_SLOT(dev->devfn) < via_vlink_dev_lo)
return;
/* This is an internal VLink device on a PIC interrupt. The BIOS
ought to have set this but may not have, so we redo it */
pci_read_config_byte(dev, PCI_INTERRUPT_LINE, &irq);
if (new_irq != irq) {
dev_info(&dev->dev, "VIA VLink IRQ fixup, from %d to %d\n",
irq, new_irq);
udelay(15); /* unknown if delay really needed */
pci_write_config_byte(dev, PCI_INTERRUPT_LINE, new_irq);
}
}
DECLARE_PCI_FIXUP_ENABLE(PCI_VENDOR_ID_VIA, PCI_ANY_ID, quirk_via_vlink);
/*
* VIA VT82C598 has its device ID settable and many BIOSes
* set it to the ID of VT82C597 for backward compatibility.
* We need to switch it off to be able to recognize the real
* type of the chip.
*/
static void quirk_vt82c598_id(struct pci_dev *dev)
{
pci_write_config_byte(dev, 0xfc, 0);
pci_read_config_word(dev, PCI_DEVICE_ID, &dev->device);
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_82C597_0, quirk_vt82c598_id);
/*
* CardBus controllers have a legacy base address that enables them
* to respond as i82365 pcmcia controllers. We don't want them to
* do this even if the Linux CardBus driver is not loaded, because
* the Linux i82365 driver does not (and should not) handle CardBus.
*/
static void quirk_cardbus_legacy(struct pci_dev *dev)
{
pci_write_config_dword(dev, PCI_CB_LEGACY_MODE_BASE, 0);
}
DECLARE_PCI_FIXUP_CLASS_FINAL(PCI_ANY_ID, PCI_ANY_ID,
PCI_CLASS_BRIDGE_CARDBUS, 8, quirk_cardbus_legacy);
DECLARE_PCI_FIXUP_CLASS_RESUME_EARLY(PCI_ANY_ID, PCI_ANY_ID,
PCI_CLASS_BRIDGE_CARDBUS, 8, quirk_cardbus_legacy);
/*
* Following the PCI ordering rules is optional on the AMD762. I'm not
* sure what the designers were smoking but let's not inhale...
*
* To be fair to AMD, it follows the spec by default, its BIOS people
* who turn it off!
*/
static void quirk_amd_ordering(struct pci_dev *dev)
{
u32 pcic;
pci_read_config_dword(dev, 0x4C, &pcic);
if ((pcic & 6) != 6) {
pcic |= 6;
dev_warn(&dev->dev, "BIOS failed to enable PCI standards compliance; fixing this error\n");
pci_write_config_dword(dev, 0x4C, pcic);
pci_read_config_dword(dev, 0x84, &pcic);
pcic |= (1 << 23); /* Required in this mode */
pci_write_config_dword(dev, 0x84, pcic);
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_FE_GATE_700C, quirk_amd_ordering);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_FE_GATE_700C, quirk_amd_ordering);
/*
* DreamWorks provided workaround for Dunord I-3000 problem
*
* This card decodes and responds to addresses not apparently
* assigned to it. We force a larger allocation to ensure that
* nothing gets put too close to it.
*/
static void quirk_dunord(struct pci_dev *dev)
{
struct resource *r = &dev->resource[1];
r->flags |= IORESOURCE_UNSET;
r->start = 0;
r->end = 0xffffff;
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_DUNORD, PCI_DEVICE_ID_DUNORD_I3000, quirk_dunord);
/*
* i82380FB mobile docking controller: its PCI-to-PCI bridge
* is subtractive decoding (transparent), and does indicate this
* in the ProgIf. Unfortunately, the ProgIf value is wrong - 0x80
* instead of 0x01.
*/
static void quirk_transparent_bridge(struct pci_dev *dev)
{
dev->transparent = 1;
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82380FB, quirk_transparent_bridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_TOSHIBA, 0x605, quirk_transparent_bridge);
/*
* Common misconfiguration of the MediaGX/Geode PCI master that will
* reduce PCI bandwidth from 70MB/s to 25MB/s. See the GXM/GXLV/GX1
* datasheets found at http://www.national.com/analog for info on what
* these bits do. <[email protected]>
*/
static void quirk_mediagx_master(struct pci_dev *dev)
{
u8 reg;
pci_read_config_byte(dev, 0x41, ®);
if (reg & 2) {
reg &= ~2;
dev_info(&dev->dev, "Fixup for MediaGX/Geode Slave Disconnect Boundary (0x41=0x%02x)\n",
reg);
pci_write_config_byte(dev, 0x41, reg);
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CYRIX, PCI_DEVICE_ID_CYRIX_PCI_MASTER, quirk_mediagx_master);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_CYRIX, PCI_DEVICE_ID_CYRIX_PCI_MASTER, quirk_mediagx_master);
/*
* Ensure C0 rev restreaming is off. This is normally done by
* the BIOS but in the odd case it is not the results are corruption
* hence the presence of a Linux check
*/
static void quirk_disable_pxb(struct pci_dev *pdev)
{
u16 config;
if (pdev->revision != 0x04) /* Only C0 requires this */
return;
pci_read_config_word(pdev, 0x40, &config);
if (config & (1<<6)) {
config &= ~(1<<6);
pci_write_config_word(pdev, 0x40, config);
dev_info(&pdev->dev, "C0 revision 450NX. Disabling PCI restreaming\n");
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82454NX, quirk_disable_pxb);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82454NX, quirk_disable_pxb);
static void quirk_amd_ide_mode(struct pci_dev *pdev)
{
/* set SBX00/Hudson-2 SATA in IDE mode to AHCI mode */
u8 tmp;
pci_read_config_byte(pdev, PCI_CLASS_DEVICE, &tmp);
if (tmp == 0x01) {
pci_read_config_byte(pdev, 0x40, &tmp);
pci_write_config_byte(pdev, 0x40, tmp|1);
pci_write_config_byte(pdev, 0x9, 1);
pci_write_config_byte(pdev, 0xa, 6);
pci_write_config_byte(pdev, 0x40, tmp);
pdev->class = PCI_CLASS_STORAGE_SATA_AHCI;
dev_info(&pdev->dev, "set SATA to AHCI mode\n");
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_IXP600_SATA, quirk_amd_ide_mode);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_IXP600_SATA, quirk_amd_ide_mode);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_IXP700_SATA, quirk_amd_ide_mode);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_IXP700_SATA, quirk_amd_ide_mode);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_HUDSON2_SATA_IDE, quirk_amd_ide_mode);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_HUDSON2_SATA_IDE, quirk_amd_ide_mode);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, 0x7900, quirk_amd_ide_mode);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_AMD, 0x7900, quirk_amd_ide_mode);
/*
* Serverworks CSB5 IDE does not fully support native mode
*/
static void quirk_svwks_csb5ide(struct pci_dev *pdev)
{
u8 prog;
pci_read_config_byte(pdev, PCI_CLASS_PROG, &prog);
if (prog & 5) {
prog &= ~5;
pdev->class &= ~5;
pci_write_config_byte(pdev, PCI_CLASS_PROG, prog);
/* PCI layer will sort out resources */
}
}
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_CSB5IDE, quirk_svwks_csb5ide);
/*
* Intel 82801CAM ICH3-M datasheet says IDE modes must be the same
*/
static void quirk_ide_samemode(struct pci_dev *pdev)
{
u8 prog;
pci_read_config_byte(pdev, PCI_CLASS_PROG, &prog);
if (((prog & 1) && !(prog & 4)) || ((prog & 4) && !(prog & 1))) {
dev_info(&pdev->dev, "IDE mode mismatch; forcing legacy mode\n");
prog &= ~5;
pdev->class &= ~5;
pci_write_config_byte(pdev, PCI_CLASS_PROG, prog);
}
}
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_10, quirk_ide_samemode);
/*
* Some ATA devices break if put into D3
*/
static void quirk_no_ata_d3(struct pci_dev *pdev)
{
pdev->dev_flags |= PCI_DEV_FLAGS_NO_D3;
}
/* Quirk the legacy ATA devices only. The AHCI ones are ok */
DECLARE_PCI_FIXUP_CLASS_EARLY(PCI_VENDOR_ID_SERVERWORKS, PCI_ANY_ID,
PCI_CLASS_STORAGE_IDE, 8, quirk_no_ata_d3);
DECLARE_PCI_FIXUP_CLASS_EARLY(PCI_VENDOR_ID_ATI, PCI_ANY_ID,
PCI_CLASS_STORAGE_IDE, 8, quirk_no_ata_d3);
/* ALi loses some register settings that we cannot then restore */
DECLARE_PCI_FIXUP_CLASS_EARLY(PCI_VENDOR_ID_AL, PCI_ANY_ID,
PCI_CLASS_STORAGE_IDE, 8, quirk_no_ata_d3);
/* VIA comes back fine but we need to keep it alive or ACPI GTM failures
occur when mode detecting */
DECLARE_PCI_FIXUP_CLASS_EARLY(PCI_VENDOR_ID_VIA, PCI_ANY_ID,
PCI_CLASS_STORAGE_IDE, 8, quirk_no_ata_d3);
/* This was originally an Alpha specific thing, but it really fits here.
* The i82375 PCI/EISA bridge appears as non-classified. Fix that.
*/
static void quirk_eisa_bridge(struct pci_dev *dev)
{
dev->class = PCI_CLASS_BRIDGE_EISA << 8;
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82375, quirk_eisa_bridge);
/*
* On ASUS P4B boards, the SMBus PCI Device within the ICH2/4 southbridge
* is not activated. The myth is that Asus said that they do not want the
* users to be irritated by just another PCI Device in the Win98 device
* manager. (see the file prog/hotplug/README.p4b in the lm_sensors
* package 2.7.0 for details)
*
* The SMBus PCI Device can be activated by setting a bit in the ICH LPC
* bridge. Unfortunately, this device has no subvendor/subdevice ID. So it
* becomes necessary to do this tweak in two steps -- the chosen trigger
* is either the Host bridge (preferred) or on-board VGA controller.
*
* Note that we used to unhide the SMBus that way on Toshiba laptops
* (Satellite A40 and Tecra M2) but then found that the thermal management
* was done by SMM code, which could cause unsynchronized concurrent
* accesses to the SMBus registers, with potentially bad effects. Thus you
* should be very careful when adding new entries: if SMM is accessing the
* Intel SMBus, this is a very good reason to leave it hidden.
*
* Likewise, many recent laptops use ACPI for thermal management. If the
* ACPI DSDT code accesses the SMBus, then Linux should not access it
* natively, and keeping the SMBus hidden is the right thing to do. If you
* are about to add an entry in the table below, please first disassemble
* the DSDT and double-check that there is no code accessing the SMBus.
*/
static int asus_hides_smbus;
static void asus_hides_smbus_hostbridge(struct pci_dev *dev)
{
if (unlikely(dev->subsystem_vendor == PCI_VENDOR_ID_ASUSTEK)) {
if (dev->device == PCI_DEVICE_ID_INTEL_82845_HB)
switch (dev->subsystem_device) {
case 0x8025: /* P4B-LX */
case 0x8070: /* P4B */
case 0x8088: /* P4B533 */
case 0x1626: /* L3C notebook */
asus_hides_smbus = 1;
}
else if (dev->device == PCI_DEVICE_ID_INTEL_82845G_HB)
switch (dev->subsystem_device) {
case 0x80b1: /* P4GE-V */
case 0x80b2: /* P4PE */
case 0x8093: /* P4B533-V */
asus_hides_smbus = 1;
}
else if (dev->device == PCI_DEVICE_ID_INTEL_82850_HB)
switch (dev->subsystem_device) {
case 0x8030: /* P4T533 */
asus_hides_smbus = 1;
}
else if (dev->device == PCI_DEVICE_ID_INTEL_7205_0)
switch (dev->subsystem_device) {
case 0x8070: /* P4G8X Deluxe */
asus_hides_smbus = 1;
}
else if (dev->device == PCI_DEVICE_ID_INTEL_E7501_MCH)
switch (dev->subsystem_device) {
case 0x80c9: /* PU-DLS */
asus_hides_smbus = 1;
}
else if (dev->device == PCI_DEVICE_ID_INTEL_82855GM_HB)
switch (dev->subsystem_device) {
case 0x1751: /* M2N notebook */
case 0x1821: /* M5N notebook */
case 0x1897: /* A6L notebook */
asus_hides_smbus = 1;
}
else if (dev->device == PCI_DEVICE_ID_INTEL_82855PM_HB)
switch (dev->subsystem_device) {
case 0x184b: /* W1N notebook */
case 0x186a: /* M6Ne notebook */
asus_hides_smbus = 1;
}
else if (dev->device == PCI_DEVICE_ID_INTEL_82865_HB)
switch (dev->subsystem_device) {
case 0x80f2: /* P4P800-X */
asus_hides_smbus = 1;
}
else if (dev->device == PCI_DEVICE_ID_INTEL_82915GM_HB)
switch (dev->subsystem_device) {
case 0x1882: /* M6V notebook */
case 0x1977: /* A6VA notebook */
asus_hides_smbus = 1;
}
} else if (unlikely(dev->subsystem_vendor == PCI_VENDOR_ID_HP)) {
if (dev->device == PCI_DEVICE_ID_INTEL_82855PM_HB)
switch (dev->subsystem_device) {
case 0x088C: /* HP Compaq nc8000 */
case 0x0890: /* HP Compaq nc6000 */
asus_hides_smbus = 1;
}
else if (dev->device == PCI_DEVICE_ID_INTEL_82865_HB)
switch (dev->subsystem_device) {
case 0x12bc: /* HP D330L */
case 0x12bd: /* HP D530 */
case 0x006a: /* HP Compaq nx9500 */
asus_hides_smbus = 1;
}
else if (dev->device == PCI_DEVICE_ID_INTEL_82875_HB)
switch (dev->subsystem_device) {
case 0x12bf: /* HP xw4100 */
asus_hides_smbus = 1;
}
} else if (unlikely(dev->subsystem_vendor == PCI_VENDOR_ID_SAMSUNG)) {
if (dev->device == PCI_DEVICE_ID_INTEL_82855PM_HB)
switch (dev->subsystem_device) {
case 0xC00C: /* Samsung P35 notebook */
asus_hides_smbus = 1;
}
} else if (unlikely(dev->subsystem_vendor == PCI_VENDOR_ID_COMPAQ)) {
if (dev->device == PCI_DEVICE_ID_INTEL_82855PM_HB)
switch (dev->subsystem_device) {
case 0x0058: /* Compaq Evo N620c */
asus_hides_smbus = 1;
}
else if (dev->device == PCI_DEVICE_ID_INTEL_82810_IG3)
switch (dev->subsystem_device) {
case 0xB16C: /* Compaq Deskpro EP 401963-001 (PCA# 010174) */
/* Motherboard doesn't have Host bridge
* subvendor/subdevice IDs, therefore checking
* its on-board VGA controller */
asus_hides_smbus = 1;
}
else if (dev->device == PCI_DEVICE_ID_INTEL_82801DB_2)
switch (dev->subsystem_device) {
case 0x00b8: /* Compaq Evo D510 CMT */
case 0x00b9: /* Compaq Evo D510 SFF */
case 0x00ba: /* Compaq Evo D510 USDT */
/* Motherboard doesn't have Host bridge
* subvendor/subdevice IDs and on-board VGA
* controller is disabled if an AGP card is
* inserted, therefore checking USB UHCI
* Controller #1 */
asus_hides_smbus = 1;
}
else if (dev->device == PCI_DEVICE_ID_INTEL_82815_CGC)
switch (dev->subsystem_device) {
case 0x001A: /* Compaq Deskpro EN SSF P667 815E */
/* Motherboard doesn't have host bridge
* subvendor/subdevice IDs, therefore checking
* its on-board VGA controller */
asus_hides_smbus = 1;
}
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82845_HB, asus_hides_smbus_hostbridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82845G_HB, asus_hides_smbus_hostbridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82850_HB, asus_hides_smbus_hostbridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82865_HB, asus_hides_smbus_hostbridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82875_HB, asus_hides_smbus_hostbridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_7205_0, asus_hides_smbus_hostbridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_E7501_MCH, asus_hides_smbus_hostbridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82855PM_HB, asus_hides_smbus_hostbridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82855GM_HB, asus_hides_smbus_hostbridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82915GM_HB, asus_hides_smbus_hostbridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82810_IG3, asus_hides_smbus_hostbridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_2, asus_hides_smbus_hostbridge);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82815_CGC, asus_hides_smbus_hostbridge);
static void asus_hides_smbus_lpc(struct pci_dev *dev)
{
u16 val;
if (likely(!asus_hides_smbus))
return;
pci_read_config_word(dev, 0xF2, &val);
if (val & 0x8) {
pci_write_config_word(dev, 0xF2, val & (~0x8));
pci_read_config_word(dev, 0xF2, &val);
if (val & 0x8)
dev_info(&dev->dev, "i801 SMBus device continues to play 'hide and seek'! 0x%x\n",
val);
else
dev_info(&dev->dev, "Enabled i801 SMBus device\n");
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AA_0, asus_hides_smbus_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_0, asus_hides_smbus_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_0, asus_hides_smbus_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_0, asus_hides_smbus_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_12, asus_hides_smbus_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_12, asus_hides_smbus_lpc);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801EB_0, asus_hides_smbus_lpc);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801AA_0, asus_hides_smbus_lpc);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_0, asus_hides_smbus_lpc);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_0, asus_hides_smbus_lpc);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_0, asus_hides_smbus_lpc);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_12, asus_hides_smbus_lpc);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_12, asus_hides_smbus_lpc);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801EB_0, asus_hides_smbus_lpc);
/* It appears we just have one such device. If not, we have a warning */
static void __iomem *asus_rcba_base;
static void asus_hides_smbus_lpc_ich6_suspend(struct pci_dev *dev)
{
u32 rcba;
if (likely(!asus_hides_smbus))
return;
WARN_ON(asus_rcba_base);
pci_read_config_dword(dev, 0xF0, &rcba);
/* use bits 31:14, 16 kB aligned */
asus_rcba_base = ioremap_nocache(rcba & 0xFFFFC000, 0x4000);
if (asus_rcba_base == NULL)
return;
}
static void asus_hides_smbus_lpc_ich6_resume_early(struct pci_dev *dev)
{
u32 val;
if (likely(!asus_hides_smbus || !asus_rcba_base))
return;
/* read the Function Disable register, dword mode only */
val = readl(asus_rcba_base + 0x3418);
writel(val & 0xFFFFFFF7, asus_rcba_base + 0x3418); /* enable the SMBus device */
}
static void asus_hides_smbus_lpc_ich6_resume(struct pci_dev *dev)
{
if (likely(!asus_hides_smbus || !asus_rcba_base))
return;
iounmap(asus_rcba_base);
asus_rcba_base = NULL;
dev_info(&dev->dev, "Enabled ICH6/i801 SMBus device\n");
}
static void asus_hides_smbus_lpc_ich6(struct pci_dev *dev)
{
asus_hides_smbus_lpc_ich6_suspend(dev);
asus_hides_smbus_lpc_ich6_resume_early(dev);
asus_hides_smbus_lpc_ich6_resume(dev);
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH6_1, asus_hides_smbus_lpc_ich6);
DECLARE_PCI_FIXUP_SUSPEND(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH6_1, asus_hides_smbus_lpc_ich6_suspend);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH6_1, asus_hides_smbus_lpc_ich6_resume);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ICH6_1, asus_hides_smbus_lpc_ich6_resume_early);
/*
* SiS 96x south bridge: BIOS typically hides SMBus device...
*/
static void quirk_sis_96x_smbus(struct pci_dev *dev)
{
u8 val = 0;
pci_read_config_byte(dev, 0x77, &val);
if (val & 0x10) {
dev_info(&dev->dev, "Enabling SiS 96x SMBus\n");
pci_write_config_byte(dev, 0x77, val & ~0x10);
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_961, quirk_sis_96x_smbus);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_962, quirk_sis_96x_smbus);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_963, quirk_sis_96x_smbus);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_LPC, quirk_sis_96x_smbus);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_961, quirk_sis_96x_smbus);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_962, quirk_sis_96x_smbus);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_963, quirk_sis_96x_smbus);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_LPC, quirk_sis_96x_smbus);
/*
* ... This is further complicated by the fact that some SiS96x south
* bridges pretend to be 85C503/5513 instead. In that case see if we
* spotted a compatible north bridge to make sure.
* (pci_find_device doesn't work yet)
*
* We can also enable the sis96x bit in the discovery register..
*/
#define SIS_DETECT_REGISTER 0x40
static void quirk_sis_503(struct pci_dev *dev)
{
u8 reg;
u16 devid;
pci_read_config_byte(dev, SIS_DETECT_REGISTER, ®);
pci_write_config_byte(dev, SIS_DETECT_REGISTER, reg | (1 << 6));
pci_read_config_word(dev, PCI_DEVICE_ID, &devid);
if (((devid & 0xfff0) != 0x0960) && (devid != 0x0018)) {
pci_write_config_byte(dev, SIS_DETECT_REGISTER, reg);
return;
}
/*
* Ok, it now shows up as a 96x.. run the 96x quirk by
* hand in case it has already been processed.
* (depends on link order, which is apparently not guaranteed)
*/
dev->device = devid;
quirk_sis_96x_smbus(dev);
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_503, quirk_sis_503);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_SI, PCI_DEVICE_ID_SI_503, quirk_sis_503);
/*
* On ASUS A8V and A8V Deluxe boards, the onboard AC97 audio controller
* and MC97 modem controller are disabled when a second PCI soundcard is
* present. This patch, tweaking the VT8237 ISA bridge, enables them.
* -- bjd
*/
static void asus_hides_ac97_lpc(struct pci_dev *dev)
{
u8 val;
int asus_hides_ac97 = 0;
if (likely(dev->subsystem_vendor == PCI_VENDOR_ID_ASUSTEK)) {
if (dev->device == PCI_DEVICE_ID_VIA_8237)
asus_hides_ac97 = 1;
}
if (!asus_hides_ac97)
return;
pci_read_config_byte(dev, 0x50, &val);
if (val & 0xc0) {
pci_write_config_byte(dev, 0x50, val & (~0xc0));
pci_read_config_byte(dev, 0x50, &val);
if (val & 0xc0)
dev_info(&dev->dev, "Onboard AC97/MC97 devices continue to play 'hide and seek'! 0x%x\n",
val);
else
dev_info(&dev->dev, "Enabled onboard AC97/MC97 devices\n");
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237, asus_hides_ac97_lpc);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8237, asus_hides_ac97_lpc);
#if defined(CONFIG_ATA) || defined(CONFIG_ATA_MODULE)
/*
* If we are using libata we can drive this chip properly but must
* do this early on to make the additional device appear during
* the PCI scanning.
*/
static void quirk_jmicron_ata(struct pci_dev *pdev)
{
u32 conf1, conf5, class;
u8 hdr;
/* Only poke fn 0 */
if (PCI_FUNC(pdev->devfn))
return;
pci_read_config_dword(pdev, 0x40, &conf1);
pci_read_config_dword(pdev, 0x80, &conf5);
conf1 &= ~0x00CFF302; /* Clear bit 1, 8, 9, 12-19, 22, 23 */
conf5 &= ~(1 << 24); /* Clear bit 24 */
switch (pdev->device) {
case PCI_DEVICE_ID_JMICRON_JMB360: /* SATA single port */
case PCI_DEVICE_ID_JMICRON_JMB362: /* SATA dual ports */
case PCI_DEVICE_ID_JMICRON_JMB364: /* SATA dual ports */
/* The controller should be in single function ahci mode */
conf1 |= 0x0002A100; /* Set 8, 13, 15, 17 */
break;
case PCI_DEVICE_ID_JMICRON_JMB365:
case PCI_DEVICE_ID_JMICRON_JMB366:
/* Redirect IDE second PATA port to the right spot */
conf5 |= (1 << 24);
/* Fall through */
case PCI_DEVICE_ID_JMICRON_JMB361:
case PCI_DEVICE_ID_JMICRON_JMB363:
case PCI_DEVICE_ID_JMICRON_JMB369:
/* Enable dual function mode, AHCI on fn 0, IDE fn1 */
/* Set the class codes correctly and then direct IDE 0 */
conf1 |= 0x00C2A1B3; /* Set 0, 1, 4, 5, 7, 8, 13, 15, 17, 22, 23 */
break;
case PCI_DEVICE_ID_JMICRON_JMB368:
/* The controller should be in single function IDE mode */
conf1 |= 0x00C00000; /* Set 22, 23 */
break;
}
pci_write_config_dword(pdev, 0x40, conf1);
pci_write_config_dword(pdev, 0x80, conf5);
/* Update pdev accordingly */
pci_read_config_byte(pdev, PCI_HEADER_TYPE, &hdr);
pdev->hdr_type = hdr & 0x7f;
pdev->multifunction = !!(hdr & 0x80);
pci_read_config_dword(pdev, PCI_CLASS_REVISION, &class);
pdev->class = class >> 8;
}
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB360, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB361, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB362, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB363, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB364, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB365, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB366, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB368, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB369, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB360, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB361, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB362, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB363, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB364, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB365, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB366, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB368, quirk_jmicron_ata);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB369, quirk_jmicron_ata);
#endif
static void quirk_jmicron_async_suspend(struct pci_dev *dev)
{
if (dev->multifunction) {
device_disable_async_suspend(&dev->dev);
dev_info(&dev->dev, "async suspend disabled to avoid multi-function power-on ordering issue\n");
}
}
DECLARE_PCI_FIXUP_CLASS_FINAL(PCI_VENDOR_ID_JMICRON, PCI_ANY_ID, PCI_CLASS_STORAGE_IDE, 8, quirk_jmicron_async_suspend);
DECLARE_PCI_FIXUP_CLASS_FINAL(PCI_VENDOR_ID_JMICRON, PCI_ANY_ID, PCI_CLASS_STORAGE_SATA_AHCI, 0, quirk_jmicron_async_suspend);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_JMICRON, 0x2362, quirk_jmicron_async_suspend);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_JMICRON, 0x236f, quirk_jmicron_async_suspend);
#ifdef CONFIG_X86_IO_APIC
static void quirk_alder_ioapic(struct pci_dev *pdev)
{
int i;
if ((pdev->class >> 8) != 0xff00)
return;
/* the first BAR is the location of the IO APIC...we must
* not touch this (and it's already covered by the fixmap), so
* forcibly insert it into the resource tree */
if (pci_resource_start(pdev, 0) && pci_resource_len(pdev, 0))
insert_resource(&iomem_resource, &pdev->resource[0]);
/* The next five BARs all seem to be rubbish, so just clean
* them out */
for (i = 1; i < 6; i++)
memset(&pdev->resource[i], 0, sizeof(pdev->resource[i]));
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_EESSC, quirk_alder_ioapic);
#endif
static void quirk_pcie_mch(struct pci_dev *pdev)
{
pdev->no_msi = 1;
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_E7520_MCH, quirk_pcie_mch);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_E7320_MCH, quirk_pcie_mch);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_E7525_MCH, quirk_pcie_mch);
/*
* It's possible for the MSI to get corrupted if shpc and acpi
* are used together on certain PXH-based systems.
*/
static void quirk_pcie_pxh(struct pci_dev *dev)
{
dev->no_msi = 1;
dev_warn(&dev->dev, "PXH quirk detected; SHPC device MSI disabled\n");
}
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXHD_0, quirk_pcie_pxh);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXHD_1, quirk_pcie_pxh);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_0, quirk_pcie_pxh);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_1, quirk_pcie_pxh);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXHV, quirk_pcie_pxh);
/*
* Some Intel PCI Express chipsets have trouble with downstream
* device power management.
*/
static void quirk_intel_pcie_pm(struct pci_dev *dev)
{
pci_pm_d3_delay = 120;
dev->no_d1d2 = 1;
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25e2, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25e3, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25e4, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25e5, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25e6, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25e7, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25f7, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25f8, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25f9, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x25fa, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2601, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2602, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2603, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2604, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2605, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2606, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2607, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2608, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2609, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x260a, quirk_intel_pcie_pm);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x260b, quirk_intel_pcie_pm);
#ifdef CONFIG_X86_IO_APIC
/*
* Boot interrupts on some chipsets cannot be turned off. For these chipsets,
* remap the original interrupt in the linux kernel to the boot interrupt, so
* that a PCI device's interrupt handler is installed on the boot interrupt
* line instead.
*/
static void quirk_reroute_to_boot_interrupts_intel(struct pci_dev *dev)
{
if (noioapicquirk || noioapicreroute)
return;
dev->irq_reroute_variant = INTEL_IRQ_REROUTE_VARIANT;
dev_info(&dev->dev, "rerouting interrupts for [%04x:%04x]\n",
dev->vendor, dev->device);
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80333_0, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80333_1, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ESB2_0, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_0, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_1, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXHV, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80332_0, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80332_1, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80333_0, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80333_1, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ESB2_0, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_0, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXH_1, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PXHV, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80332_0, quirk_reroute_to_boot_interrupts_intel);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_80332_1, quirk_reroute_to_boot_interrupts_intel);
/*
* On some chipsets we can disable the generation of legacy INTx boot
* interrupts.
*/
/*
* IO-APIC1 on 6300ESB generates boot interrupts, see intel order no
* 300641-004US, section 5.7.3.
*/
#define INTEL_6300_IOAPIC_ABAR 0x40
#define INTEL_6300_DISABLE_BOOT_IRQ (1<<14)
static void quirk_disable_intel_boot_interrupt(struct pci_dev *dev)
{
u16 pci_config_word;
if (noioapicquirk)
return;
pci_read_config_word(dev, INTEL_6300_IOAPIC_ABAR, &pci_config_word);
pci_config_word |= INTEL_6300_DISABLE_BOOT_IRQ;
pci_write_config_word(dev, INTEL_6300_IOAPIC_ABAR, pci_config_word);
dev_info(&dev->dev, "disabled boot interrupts on device [%04x:%04x]\n",
dev->vendor, dev->device);
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ESB_10, quirk_disable_intel_boot_interrupt);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ESB_10, quirk_disable_intel_boot_interrupt);
/*
* disable boot interrupts on HT-1000
*/
#define BC_HT1000_FEATURE_REG 0x64
#define BC_HT1000_PIC_REGS_ENABLE (1<<0)
#define BC_HT1000_MAP_IDX 0xC00
#define BC_HT1000_MAP_DATA 0xC01
static void quirk_disable_broadcom_boot_interrupt(struct pci_dev *dev)
{
u32 pci_config_dword;
u8 irq;
if (noioapicquirk)
return;
pci_read_config_dword(dev, BC_HT1000_FEATURE_REG, &pci_config_dword);
pci_write_config_dword(dev, BC_HT1000_FEATURE_REG, pci_config_dword |
BC_HT1000_PIC_REGS_ENABLE);
for (irq = 0x10; irq < 0x10 + 32; irq++) {
outb(irq, BC_HT1000_MAP_IDX);
outb(0x00, BC_HT1000_MAP_DATA);
}
pci_write_config_dword(dev, BC_HT1000_FEATURE_REG, pci_config_dword);
dev_info(&dev->dev, "disabled boot interrupts on device [%04x:%04x]\n",
dev->vendor, dev->device);
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_HT1000SB, quirk_disable_broadcom_boot_interrupt);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_HT1000SB, quirk_disable_broadcom_boot_interrupt);
/*
* disable boot interrupts on AMD and ATI chipsets
*/
/*
* NOIOAMODE needs to be disabled to disable "boot interrupts". For AMD 8131
* rev. A0 and B0, NOIOAMODE needs to be disabled anyway to fix IO-APIC mode
* (due to an erratum).
*/
#define AMD_813X_MISC 0x40
#define AMD_813X_NOIOAMODE (1<<0)
#define AMD_813X_REV_B1 0x12
#define AMD_813X_REV_B2 0x13
static void quirk_disable_amd_813x_boot_interrupt(struct pci_dev *dev)
{
u32 pci_config_dword;
if (noioapicquirk)
return;
if ((dev->revision == AMD_813X_REV_B1) ||
(dev->revision == AMD_813X_REV_B2))
return;
pci_read_config_dword(dev, AMD_813X_MISC, &pci_config_dword);
pci_config_dword &= ~AMD_813X_NOIOAMODE;
pci_write_config_dword(dev, AMD_813X_MISC, pci_config_dword);
dev_info(&dev->dev, "disabled boot interrupts on device [%04x:%04x]\n",
dev->vendor, dev->device);
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8131_BRIDGE, quirk_disable_amd_813x_boot_interrupt);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8131_BRIDGE, quirk_disable_amd_813x_boot_interrupt);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8132_BRIDGE, quirk_disable_amd_813x_boot_interrupt);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8132_BRIDGE, quirk_disable_amd_813x_boot_interrupt);
#define AMD_8111_PCI_IRQ_ROUTING 0x56
static void quirk_disable_amd_8111_boot_interrupt(struct pci_dev *dev)
{
u16 pci_config_word;
if (noioapicquirk)
return;
pci_read_config_word(dev, AMD_8111_PCI_IRQ_ROUTING, &pci_config_word);
if (!pci_config_word) {
dev_info(&dev->dev, "boot interrupts on device [%04x:%04x] already disabled\n",
dev->vendor, dev->device);
return;
}
pci_write_config_word(dev, AMD_8111_PCI_IRQ_ROUTING, 0);
dev_info(&dev->dev, "disabled boot interrupts on device [%04x:%04x]\n",
dev->vendor, dev->device);
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8111_SMBUS, quirk_disable_amd_8111_boot_interrupt);
DECLARE_PCI_FIXUP_RESUME(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8111_SMBUS, quirk_disable_amd_8111_boot_interrupt);
#endif /* CONFIG_X86_IO_APIC */
/*
* Toshiba TC86C001 IDE controller reports the standard 8-byte BAR0 size
* but the PIO transfers won't work if BAR0 falls at the odd 8 bytes.
* Re-allocate the region if needed...
*/
static void quirk_tc86c001_ide(struct pci_dev *dev)
{
struct resource *r = &dev->resource[0];
if (r->start & 0x8) {
r->flags |= IORESOURCE_UNSET;
r->start = 0;
r->end = 0xf;
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_TOSHIBA_2,
PCI_DEVICE_ID_TOSHIBA_TC86C001_IDE,
quirk_tc86c001_ide);
/*
* PLX PCI 9050 PCI Target bridge controller has an errata that prevents the
* local configuration registers accessible via BAR0 (memory) or BAR1 (i/o)
* being read correctly if bit 7 of the base address is set.
* The BAR0 or BAR1 region may be disabled (size 0) or enabled (size 128).
* Re-allocate the regions to a 256-byte boundary if necessary.
*/
static void quirk_plx_pci9050(struct pci_dev *dev)
{
unsigned int bar;
/* Fixed in revision 2 (PCI 9052). */
if (dev->revision >= 2)
return;
for (bar = 0; bar <= 1; bar++)
if (pci_resource_len(dev, bar) == 0x80 &&
(pci_resource_start(dev, bar) & 0x80)) {
struct resource *r = &dev->resource[bar];
dev_info(&dev->dev, "Re-allocating PLX PCI 9050 BAR %u to length 256 to avoid bit 7 bug\n",
bar);
r->flags |= IORESOURCE_UNSET;
r->start = 0;
r->end = 0xff;
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_PLX, PCI_DEVICE_ID_PLX_9050,
quirk_plx_pci9050);
/*
* The following Meilhaus (vendor ID 0x1402) device IDs (amongst others)
* may be using the PLX PCI 9050: 0x0630, 0x0940, 0x0950, 0x0960, 0x100b,
* 0x1400, 0x140a, 0x140b, 0x14e0, 0x14ea, 0x14eb, 0x1604, 0x1608, 0x160c,
* 0x168f, 0x2000, 0x2600, 0x3000, 0x810a, 0x810b.
*
* Currently, device IDs 0x2000 and 0x2600 are used by the Comedi "me_daq"
* driver.
*/
DECLARE_PCI_FIXUP_HEADER(0x1402, 0x2000, quirk_plx_pci9050);
DECLARE_PCI_FIXUP_HEADER(0x1402, 0x2600, quirk_plx_pci9050);
static void quirk_netmos(struct pci_dev *dev)
{
unsigned int num_parallel = (dev->subsystem_device & 0xf0) >> 4;
unsigned int num_serial = dev->subsystem_device & 0xf;
/*
* These Netmos parts are multiport serial devices with optional
* parallel ports. Even when parallel ports are present, they
* are identified as class SERIAL, which means the serial driver
* will claim them. To prevent this, mark them as class OTHER.
* These combo devices should be claimed by parport_serial.
*
* The subdevice ID is of the form 0x00PS, where <P> is the number
* of parallel ports and <S> is the number of serial ports.
*/
switch (dev->device) {
case PCI_DEVICE_ID_NETMOS_9835:
/* Well, this rule doesn't hold for the following 9835 device */
if (dev->subsystem_vendor == PCI_VENDOR_ID_IBM &&
dev->subsystem_device == 0x0299)
return;
case PCI_DEVICE_ID_NETMOS_9735:
case PCI_DEVICE_ID_NETMOS_9745:
case PCI_DEVICE_ID_NETMOS_9845:
case PCI_DEVICE_ID_NETMOS_9855:
if (num_parallel) {
dev_info(&dev->dev, "Netmos %04x (%u parallel, %u serial); changing class SERIAL to OTHER (use parport_serial)\n",
dev->device, num_parallel, num_serial);
dev->class = (PCI_CLASS_COMMUNICATION_OTHER << 8) |
(dev->class & 0xff);
}
}
}
DECLARE_PCI_FIXUP_CLASS_HEADER(PCI_VENDOR_ID_NETMOS, PCI_ANY_ID,
PCI_CLASS_COMMUNICATION_SERIAL, 8, quirk_netmos);
/*
* Quirk non-zero PCI functions to route VPD access through function 0 for
* devices that share VPD resources between functions. The functions are
* expected to be identical devices.
*/
static void quirk_f0_vpd_link(struct pci_dev *dev)
{
struct pci_dev *f0;
if (!PCI_FUNC(dev->devfn))
return;
f0 = pci_get_slot(dev->bus, PCI_DEVFN(PCI_SLOT(dev->devfn), 0));
if (!f0)
return;
if (f0->vpd && dev->class == f0->class &&
dev->vendor == f0->vendor && dev->device == f0->device)
dev->dev_flags |= PCI_DEV_FLAGS_VPD_REF_F0;
pci_dev_put(f0);
}
DECLARE_PCI_FIXUP_CLASS_EARLY(PCI_VENDOR_ID_INTEL, PCI_ANY_ID,
PCI_CLASS_NETWORK_ETHERNET, 8, quirk_f0_vpd_link);
static void quirk_e100_interrupt(struct pci_dev *dev)
{
u16 command, pmcsr;
u8 __iomem *csr;
u8 cmd_hi;
switch (dev->device) {
/* PCI IDs taken from drivers/net/e100.c */
case 0x1029:
case 0x1030 ... 0x1034:
case 0x1038 ... 0x103E:
case 0x1050 ... 0x1057:
case 0x1059:
case 0x1064 ... 0x106B:
case 0x1091 ... 0x1095:
case 0x1209:
case 0x1229:
case 0x2449:
case 0x2459:
case 0x245D:
case 0x27DC:
break;
default:
return;
}
/*
* Some firmware hands off the e100 with interrupts enabled,
* which can cause a flood of interrupts if packets are
* received before the driver attaches to the device. So
* disable all e100 interrupts here. The driver will
* re-enable them when it's ready.
*/
pci_read_config_word(dev, PCI_COMMAND, &command);
if (!(command & PCI_COMMAND_MEMORY) || !pci_resource_start(dev, 0))
return;
/*
* Check that the device is in the D0 power state. If it's not,
* there is no point to look any further.
*/
if (dev->pm_cap) {
pci_read_config_word(dev, dev->pm_cap + PCI_PM_CTRL, &pmcsr);
if ((pmcsr & PCI_PM_CTRL_STATE_MASK) != PCI_D0)
return;
}
/* Convert from PCI bus to resource space. */
csr = ioremap(pci_resource_start(dev, 0), 8);
if (!csr) {
dev_warn(&dev->dev, "Can't map e100 registers\n");
return;
}
cmd_hi = readb(csr + 3);
if (cmd_hi == 0) {
dev_warn(&dev->dev, "Firmware left e100 interrupts enabled; disabling\n");
writeb(1, csr + 3);
}
iounmap(csr);
}
DECLARE_PCI_FIXUP_CLASS_FINAL(PCI_VENDOR_ID_INTEL, PCI_ANY_ID,
PCI_CLASS_NETWORK_ETHERNET, 8, quirk_e100_interrupt);
/*
* The 82575 and 82598 may experience data corruption issues when transitioning
* out of L0S. To prevent this we need to disable L0S on the pci-e link
*/
static void quirk_disable_aspm_l0s(struct pci_dev *dev)
{
dev_info(&dev->dev, "Disabling L0s\n");
pci_disable_link_state(dev, PCIE_LINK_STATE_L0S);
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10a7, quirk_disable_aspm_l0s);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10a9, quirk_disable_aspm_l0s);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10b6, quirk_disable_aspm_l0s);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10c6, quirk_disable_aspm_l0s);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10c7, quirk_disable_aspm_l0s);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10c8, quirk_disable_aspm_l0s);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10d6, quirk_disable_aspm_l0s);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10db, quirk_disable_aspm_l0s);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10dd, quirk_disable_aspm_l0s);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10e1, quirk_disable_aspm_l0s);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10ec, quirk_disable_aspm_l0s);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10f1, quirk_disable_aspm_l0s);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x10f4, quirk_disable_aspm_l0s);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1508, quirk_disable_aspm_l0s);
static void fixup_rev1_53c810(struct pci_dev *dev)
{
u32 class = dev->class;
/*
* rev 1 ncr53c810 chips don't set the class at all which means
* they don't get their resources remapped. Fix that here.
*/
if (class)
return;
dev->class = PCI_CLASS_STORAGE_SCSI << 8;
dev_info(&dev->dev, "NCR 53c810 rev 1 PCI class overridden (%#08x -> %#08x)\n",
class, dev->class);
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_NCR, PCI_DEVICE_ID_NCR_53C810, fixup_rev1_53c810);
/* Enable 1k I/O space granularity on the Intel P64H2 */
static void quirk_p64h2_1k_io(struct pci_dev *dev)
{
u16 en1k;
pci_read_config_word(dev, 0x40, &en1k);
if (en1k & 0x200) {
dev_info(&dev->dev, "Enable I/O Space to 1KB granularity\n");
dev->io_window_1k = 1;
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x1460, quirk_p64h2_1k_io);
/* Under some circumstances, AER is not linked with extended capabilities.
* Force it to be linked by setting the corresponding control bit in the
* config space.
*/
static void quirk_nvidia_ck804_pcie_aer_ext_cap(struct pci_dev *dev)
{
uint8_t b;
if (pci_read_config_byte(dev, 0xf41, &b) == 0) {
if (!(b & 0x20)) {
pci_write_config_byte(dev, 0xf41, b | 0x20);
dev_info(&dev->dev, "Linking AER extended capability\n");
}
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_NVIDIA, PCI_DEVICE_ID_NVIDIA_CK804_PCIE,
quirk_nvidia_ck804_pcie_aer_ext_cap);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_NVIDIA, PCI_DEVICE_ID_NVIDIA_CK804_PCIE,
quirk_nvidia_ck804_pcie_aer_ext_cap);
static void quirk_via_cx700_pci_parking_caching(struct pci_dev *dev)
{
/*
* Disable PCI Bus Parking and PCI Master read caching on CX700
* which causes unspecified timing errors with a VT6212L on the PCI
* bus leading to USB2.0 packet loss.
*
* This quirk is only enabled if a second (on the external PCI bus)
* VT6212L is found -- the CX700 core itself also contains a USB
* host controller with the same PCI ID as the VT6212L.
*/
/* Count VT6212L instances */
struct pci_dev *p = pci_get_device(PCI_VENDOR_ID_VIA,
PCI_DEVICE_ID_VIA_8235_USB_2, NULL);
uint8_t b;
/* p should contain the first (internal) VT6212L -- see if we have
an external one by searching again */
p = pci_get_device(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8235_USB_2, p);
if (!p)
return;
pci_dev_put(p);
if (pci_read_config_byte(dev, 0x76, &b) == 0) {
if (b & 0x40) {
/* Turn off PCI Bus Parking */
pci_write_config_byte(dev, 0x76, b ^ 0x40);
dev_info(&dev->dev, "Disabling VIA CX700 PCI parking\n");
}
}
if (pci_read_config_byte(dev, 0x72, &b) == 0) {
if (b != 0) {
/* Turn off PCI Master read caching */
pci_write_config_byte(dev, 0x72, 0x0);
/* Set PCI Master Bus time-out to "1x16 PCLK" */
pci_write_config_byte(dev, 0x75, 0x1);
/* Disable "Read FIFO Timer" */
pci_write_config_byte(dev, 0x77, 0x0);
dev_info(&dev->dev, "Disabling VIA CX700 PCI caching\n");
}
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, 0x324e, quirk_via_cx700_pci_parking_caching);
/*
* If a device follows the VPD format spec, the PCI core will not read or
* write past the VPD End Tag. But some vendors do not follow the VPD
* format spec, so we can't tell how much data is safe to access. Devices
* may behave unpredictably if we access too much. Blacklist these devices
* so we don't touch VPD at all.
*/
static void quirk_blacklist_vpd(struct pci_dev *dev)
{
if (dev->vpd) {
dev->vpd->len = 0;
dev_warn(&dev->dev, FW_BUG "disabling VPD access (can't determine size of non-standard VPD format)\n");
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x0060, quirk_blacklist_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x007c, quirk_blacklist_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x0413, quirk_blacklist_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x0078, quirk_blacklist_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x0079, quirk_blacklist_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x0073, quirk_blacklist_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x0071, quirk_blacklist_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x005b, quirk_blacklist_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x002f, quirk_blacklist_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x005d, quirk_blacklist_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_LSI_LOGIC, 0x005f, quirk_blacklist_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, PCI_ANY_ID,
quirk_blacklist_vpd);
/*
* For Broadcom 5706, 5708, 5709 rev. A nics, any read beyond the
* VPD end tag will hang the device. This problem was initially
* observed when a vpd entry was created in sysfs
* ('/sys/bus/pci/devices/<id>/vpd'). A read to this sysfs entry
* will dump 32k of data. Reading a full 32k will cause an access
* beyond the VPD end tag causing the device to hang. Once the device
* is hung, the bnx2 driver will not be able to reset the device.
* We believe that it is legal to read beyond the end tag and
* therefore the solution is to limit the read/write length.
*/
static void quirk_brcm_570x_limit_vpd(struct pci_dev *dev)
{
/*
* Only disable the VPD capability for 5706, 5706S, 5708,
* 5708S and 5709 rev. A
*/
if ((dev->device == PCI_DEVICE_ID_NX2_5706) ||
(dev->device == PCI_DEVICE_ID_NX2_5706S) ||
(dev->device == PCI_DEVICE_ID_NX2_5708) ||
(dev->device == PCI_DEVICE_ID_NX2_5708S) ||
((dev->device == PCI_DEVICE_ID_NX2_5709) &&
(dev->revision & 0xf0) == 0x0)) {
if (dev->vpd)
dev->vpd->len = 0x80;
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM,
PCI_DEVICE_ID_NX2_5706,
quirk_brcm_570x_limit_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM,
PCI_DEVICE_ID_NX2_5706S,
quirk_brcm_570x_limit_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM,
PCI_DEVICE_ID_NX2_5708,
quirk_brcm_570x_limit_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM,
PCI_DEVICE_ID_NX2_5708S,
quirk_brcm_570x_limit_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM,
PCI_DEVICE_ID_NX2_5709,
quirk_brcm_570x_limit_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM,
PCI_DEVICE_ID_NX2_5709S,
quirk_brcm_570x_limit_vpd);
static void quirk_brcm_5719_limit_mrrs(struct pci_dev *dev)
{
u32 rev;
pci_read_config_dword(dev, 0xf4, &rev);
/* Only CAP the MRRS if the device is a 5719 A0 */
if (rev == 0x05719000) {
int readrq = pcie_get_readrq(dev);
if (readrq > 2048)
pcie_set_readrq(dev, 2048);
}
}
DECLARE_PCI_FIXUP_ENABLE(PCI_VENDOR_ID_BROADCOM,
PCI_DEVICE_ID_TIGON3_5719,
quirk_brcm_5719_limit_mrrs);
/* Originally in EDAC sources for i82875P:
* Intel tells BIOS developers to hide device 6 which
* configures the overflow device access containing
* the DRBs - this is where we expose device 6.
* http://www.x86-secret.com/articles/tweak/pat/patsecrets-2.htm
*/
static void quirk_unhide_mch_dev6(struct pci_dev *dev)
{
u8 reg;
if (pci_read_config_byte(dev, 0xF4, ®) == 0 && !(reg & 0x02)) {
dev_info(&dev->dev, "Enabling MCH 'Overflow' Device\n");
pci_write_config_byte(dev, 0xF4, reg | 0x02);
}
}
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82865_HB,
quirk_unhide_mch_dev6);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82875_HB,
quirk_unhide_mch_dev6);
#ifdef CONFIG_TILEPRO
/*
* The Tilera TILEmpower tilepro platform needs to set the link speed
* to 2.5GT(Giga-Transfers)/s (Gen 1). The default link speed
* setting is 5GT/s (Gen 2). 0x98 is the Link Control2 PCIe
* capability register of the PEX8624 PCIe switch. The switch
* supports link speed auto negotiation, but falsely sets
* the link speed to 5GT/s.
*/
static void quirk_tile_plx_gen1(struct pci_dev *dev)
{
if (tile_plx_gen1) {
pci_write_config_dword(dev, 0x98, 0x1);
mdelay(50);
}
}
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_PLX, 0x8624, quirk_tile_plx_gen1);
#endif /* CONFIG_TILEPRO */
#ifdef CONFIG_PCI_MSI
/* Some chipsets do not support MSI. We cannot easily rely on setting
* PCI_BUS_FLAGS_NO_MSI in its bus flags because there are actually
* some other buses controlled by the chipset even if Linux is not
* aware of it. Instead of setting the flag on all buses in the
* machine, simply disable MSI globally.
*/
static void quirk_disable_all_msi(struct pci_dev *dev)
{
pci_no_msi();
dev_warn(&dev->dev, "MSI quirk detected; MSI disabled\n");
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_GCNB_LE, quirk_disable_all_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RS400_200, quirk_disable_all_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_RS480, quirk_disable_all_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_VT3336, quirk_disable_all_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_VT3351, quirk_disable_all_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_VT3364, quirk_disable_all_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, PCI_DEVICE_ID_VIA_8380_0, quirk_disable_all_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SI, 0x0761, quirk_disable_all_msi);
/* Disable MSI on chipsets that are known to not support it */
static void quirk_disable_msi(struct pci_dev *dev)
{
if (dev->subordinate) {
dev_warn(&dev->dev, "MSI quirk detected; subordinate MSI disabled\n");
dev->subordinate->bus_flags |= PCI_BUS_FLAGS_NO_MSI;
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8131_BRIDGE, quirk_disable_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_VIA, 0xa238, quirk_disable_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x5a3f, quirk_disable_msi);
/*
* The APC bridge device in AMD 780 family northbridges has some random
* OEM subsystem ID in its vendor ID register (erratum 18), so instead
* we use the possible vendor/device IDs of the host bridge for the
* declared quirk, and search for the APC bridge by slot number.
*/
static void quirk_amd_780_apc_msi(struct pci_dev *host_bridge)
{
struct pci_dev *apc_bridge;
apc_bridge = pci_get_slot(host_bridge->bus, PCI_DEVFN(1, 0));
if (apc_bridge) {
if (apc_bridge->device == 0x9602)
quirk_disable_msi(apc_bridge);
pci_dev_put(apc_bridge);
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, 0x9600, quirk_amd_780_apc_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AMD, 0x9601, quirk_amd_780_apc_msi);
/* Go through the list of Hypertransport capabilities and
* return 1 if a HT MSI capability is found and enabled */
static int msi_ht_cap_enabled(struct pci_dev *dev)
{
int pos, ttl = PCI_FIND_CAP_TTL;
pos = pci_find_ht_capability(dev, HT_CAPTYPE_MSI_MAPPING);
while (pos && ttl--) {
u8 flags;
if (pci_read_config_byte(dev, pos + HT_MSI_FLAGS,
&flags) == 0) {
dev_info(&dev->dev, "Found %s HT MSI Mapping\n",
flags & HT_MSI_FLAGS_ENABLE ?
"enabled" : "disabled");
return (flags & HT_MSI_FLAGS_ENABLE) != 0;
}
pos = pci_find_next_ht_capability(dev, pos,
HT_CAPTYPE_MSI_MAPPING);
}
return 0;
}
/* Check the hypertransport MSI mapping to know whether MSI is enabled or not */
static void quirk_msi_ht_cap(struct pci_dev *dev)
{
if (dev->subordinate && !msi_ht_cap_enabled(dev)) {
dev_warn(&dev->dev, "MSI quirk detected; subordinate MSI disabled\n");
dev->subordinate->bus_flags |= PCI_BUS_FLAGS_NO_MSI;
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_SERVERWORKS, PCI_DEVICE_ID_SERVERWORKS_HT2000_PCIE,
quirk_msi_ht_cap);
/* The nVidia CK804 chipset may have 2 HT MSI mappings.
* MSI are supported if the MSI capability set in any of these mappings.
*/
static void quirk_nvidia_ck804_msi_ht_cap(struct pci_dev *dev)
{
struct pci_dev *pdev;
if (!dev->subordinate)
return;
/* check HT MSI cap on this chipset and the root one.
* a single one having MSI is enough to be sure that MSI are supported.
*/
pdev = pci_get_slot(dev->bus, 0);
if (!pdev)
return;
if (!msi_ht_cap_enabled(dev) && !msi_ht_cap_enabled(pdev)) {
dev_warn(&dev->dev, "MSI quirk detected; subordinate MSI disabled\n");
dev->subordinate->bus_flags |= PCI_BUS_FLAGS_NO_MSI;
}
pci_dev_put(pdev);
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_NVIDIA, PCI_DEVICE_ID_NVIDIA_CK804_PCIE,
quirk_nvidia_ck804_msi_ht_cap);
/* Force enable MSI mapping capability on HT bridges */
static void ht_enable_msi_mapping(struct pci_dev *dev)
{
int pos, ttl = PCI_FIND_CAP_TTL;
pos = pci_find_ht_capability(dev, HT_CAPTYPE_MSI_MAPPING);
while (pos && ttl--) {
u8 flags;
if (pci_read_config_byte(dev, pos + HT_MSI_FLAGS,
&flags) == 0) {
dev_info(&dev->dev, "Enabling HT MSI Mapping\n");
pci_write_config_byte(dev, pos + HT_MSI_FLAGS,
flags | HT_MSI_FLAGS_ENABLE);
}
pos = pci_find_next_ht_capability(dev, pos,
HT_CAPTYPE_MSI_MAPPING);
}
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SERVERWORKS,
PCI_DEVICE_ID_SERVERWORKS_HT1000_PXB,
ht_enable_msi_mapping);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD_8132_BRIDGE,
ht_enable_msi_mapping);
/* The P5N32-SLI motherboards from Asus have a problem with msi
* for the MCP55 NIC. It is not yet determined whether the msi problem
* also affects other devices. As for now, turn off msi for this device.
*/
static void nvenet_msi_disable(struct pci_dev *dev)
{
const char *board_name = dmi_get_system_info(DMI_BOARD_NAME);
if (board_name &&
(strstr(board_name, "P5N32-SLI PREMIUM") ||
strstr(board_name, "P5N32-E SLI"))) {
dev_info(&dev->dev, "Disabling msi for MCP55 NIC on P5N32-SLI\n");
dev->no_msi = 1;
}
}
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_NVIDIA,
PCI_DEVICE_ID_NVIDIA_NVENET_15,
nvenet_msi_disable);
/*
* Some versions of the MCP55 bridge from Nvidia have a legacy IRQ routing
* config register. This register controls the routing of legacy
* interrupts from devices that route through the MCP55. If this register
* is misprogrammed, interrupts are only sent to the BSP, unlike
* conventional systems where the IRQ is broadcast to all online CPUs. Not
* having this register set properly prevents kdump from booting up
* properly, so let's make sure that we have it set correctly.
* Note that this is an undocumented register.
*/
static void nvbridge_check_legacy_irq_routing(struct pci_dev *dev)
{
u32 cfg;
if (!pci_find_capability(dev, PCI_CAP_ID_HT))
return;
pci_read_config_dword(dev, 0x74, &cfg);
if (cfg & ((1 << 2) | (1 << 15))) {
printk(KERN_INFO "Rewriting irq routing register on MCP55\n");
cfg &= ~((1 << 2) | (1 << 15));
pci_write_config_dword(dev, 0x74, cfg);
}
}
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_NVIDIA,
PCI_DEVICE_ID_NVIDIA_MCP55_BRIDGE_V0,
nvbridge_check_legacy_irq_routing);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_NVIDIA,
PCI_DEVICE_ID_NVIDIA_MCP55_BRIDGE_V4,
nvbridge_check_legacy_irq_routing);
static int ht_check_msi_mapping(struct pci_dev *dev)
{
int pos, ttl = PCI_FIND_CAP_TTL;
int found = 0;
/* check if there is HT MSI cap or enabled on this device */
pos = pci_find_ht_capability(dev, HT_CAPTYPE_MSI_MAPPING);
while (pos && ttl--) {
u8 flags;
if (found < 1)
found = 1;
if (pci_read_config_byte(dev, pos + HT_MSI_FLAGS,
&flags) == 0) {
if (flags & HT_MSI_FLAGS_ENABLE) {
if (found < 2) {
found = 2;
break;
}
}
}
pos = pci_find_next_ht_capability(dev, pos,
HT_CAPTYPE_MSI_MAPPING);
}
return found;
}
static int host_bridge_with_leaf(struct pci_dev *host_bridge)
{
struct pci_dev *dev;
int pos;
int i, dev_no;
int found = 0;
dev_no = host_bridge->devfn >> 3;
for (i = dev_no + 1; i < 0x20; i++) {
dev = pci_get_slot(host_bridge->bus, PCI_DEVFN(i, 0));
if (!dev)
continue;
/* found next host bridge ?*/
pos = pci_find_ht_capability(dev, HT_CAPTYPE_SLAVE);
if (pos != 0) {
pci_dev_put(dev);
break;
}
if (ht_check_msi_mapping(dev)) {
found = 1;
pci_dev_put(dev);
break;
}
pci_dev_put(dev);
}
return found;
}
#define PCI_HT_CAP_SLAVE_CTRL0 4 /* link control */
#define PCI_HT_CAP_SLAVE_CTRL1 8 /* link control to */
static int is_end_of_ht_chain(struct pci_dev *dev)
{
int pos, ctrl_off;
int end = 0;
u16 flags, ctrl;
pos = pci_find_ht_capability(dev, HT_CAPTYPE_SLAVE);
if (!pos)
goto out;
pci_read_config_word(dev, pos + PCI_CAP_FLAGS, &flags);
ctrl_off = ((flags >> 10) & 1) ?
PCI_HT_CAP_SLAVE_CTRL0 : PCI_HT_CAP_SLAVE_CTRL1;
pci_read_config_word(dev, pos + ctrl_off, &ctrl);
if (ctrl & (1 << 6))
end = 1;
out:
return end;
}
static void nv_ht_enable_msi_mapping(struct pci_dev *dev)
{
struct pci_dev *host_bridge;
int pos;
int i, dev_no;
int found = 0;
dev_no = dev->devfn >> 3;
for (i = dev_no; i >= 0; i--) {
host_bridge = pci_get_slot(dev->bus, PCI_DEVFN(i, 0));
if (!host_bridge)
continue;
pos = pci_find_ht_capability(host_bridge, HT_CAPTYPE_SLAVE);
if (pos != 0) {
found = 1;
break;
}
pci_dev_put(host_bridge);
}
if (!found)
return;
/* don't enable end_device/host_bridge with leaf directly here */
if (host_bridge == dev && is_end_of_ht_chain(host_bridge) &&
host_bridge_with_leaf(host_bridge))
goto out;
/* root did that ! */
if (msi_ht_cap_enabled(host_bridge))
goto out;
ht_enable_msi_mapping(dev);
out:
pci_dev_put(host_bridge);
}
static void ht_disable_msi_mapping(struct pci_dev *dev)
{
int pos, ttl = PCI_FIND_CAP_TTL;
pos = pci_find_ht_capability(dev, HT_CAPTYPE_MSI_MAPPING);
while (pos && ttl--) {
u8 flags;
if (pci_read_config_byte(dev, pos + HT_MSI_FLAGS,
&flags) == 0) {
dev_info(&dev->dev, "Disabling HT MSI Mapping\n");
pci_write_config_byte(dev, pos + HT_MSI_FLAGS,
flags & ~HT_MSI_FLAGS_ENABLE);
}
pos = pci_find_next_ht_capability(dev, pos,
HT_CAPTYPE_MSI_MAPPING);
}
}
static void __nv_msi_ht_cap_quirk(struct pci_dev *dev, int all)
{
struct pci_dev *host_bridge;
int pos;
int found;
if (!pci_msi_enabled())
return;
/* check if there is HT MSI cap or enabled on this device */
found = ht_check_msi_mapping(dev);
/* no HT MSI CAP */
if (found == 0)
return;
/*
* HT MSI mapping should be disabled on devices that are below
* a non-Hypertransport host bridge. Locate the host bridge...
*/
host_bridge = pci_get_bus_and_slot(0, PCI_DEVFN(0, 0));
if (host_bridge == NULL) {
dev_warn(&dev->dev, "nv_msi_ht_cap_quirk didn't locate host bridge\n");
return;
}
pos = pci_find_ht_capability(host_bridge, HT_CAPTYPE_SLAVE);
if (pos != 0) {
/* Host bridge is to HT */
if (found == 1) {
/* it is not enabled, try to enable it */
if (all)
ht_enable_msi_mapping(dev);
else
nv_ht_enable_msi_mapping(dev);
}
goto out;
}
/* HT MSI is not enabled */
if (found == 1)
goto out;
/* Host bridge is not to HT, disable HT MSI mapping on this device */
ht_disable_msi_mapping(dev);
out:
pci_dev_put(host_bridge);
}
static void nv_msi_ht_cap_quirk_all(struct pci_dev *dev)
{
return __nv_msi_ht_cap_quirk(dev, 1);
}
static void nv_msi_ht_cap_quirk_leaf(struct pci_dev *dev)
{
return __nv_msi_ht_cap_quirk(dev, 0);
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID, nv_msi_ht_cap_quirk_leaf);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID, nv_msi_ht_cap_quirk_leaf);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_AL, PCI_ANY_ID, nv_msi_ht_cap_quirk_all);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_AL, PCI_ANY_ID, nv_msi_ht_cap_quirk_all);
static void quirk_msi_intx_disable_bug(struct pci_dev *dev)
{
dev->dev_flags |= PCI_DEV_FLAGS_MSI_INTX_DISABLE_BUG;
}
static void quirk_msi_intx_disable_ati_bug(struct pci_dev *dev)
{
struct pci_dev *p;
/* SB700 MSI issue will be fixed at HW level from revision A21,
* we need check PCI REVISION ID of SMBus controller to get SB700
* revision.
*/
p = pci_get_device(PCI_VENDOR_ID_ATI, PCI_DEVICE_ID_ATI_SBX00_SMBUS,
NULL);
if (!p)
return;
if ((p->revision < 0x3B) && (p->revision >= 0x30))
dev->dev_flags |= PCI_DEV_FLAGS_MSI_INTX_DISABLE_BUG;
pci_dev_put(p);
}
static void quirk_msi_intx_disable_qca_bug(struct pci_dev *dev)
{
/* AR816X/AR817X/E210X MSI is fixed at HW level from revision 0x18 */
if (dev->revision < 0x18) {
dev_info(&dev->dev, "set MSI_INTX_DISABLE_BUG flag\n");
dev->dev_flags |= PCI_DEV_FLAGS_MSI_INTX_DISABLE_BUG;
}
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM,
PCI_DEVICE_ID_TIGON3_5780,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM,
PCI_DEVICE_ID_TIGON3_5780S,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM,
PCI_DEVICE_ID_TIGON3_5714,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM,
PCI_DEVICE_ID_TIGON3_5714S,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM,
PCI_DEVICE_ID_TIGON3_5715,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_BROADCOM,
PCI_DEVICE_ID_TIGON3_5715S,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4390,
quirk_msi_intx_disable_ati_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4391,
quirk_msi_intx_disable_ati_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4392,
quirk_msi_intx_disable_ati_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4393,
quirk_msi_intx_disable_ati_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4394,
quirk_msi_intx_disable_ati_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4373,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4374,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATI, 0x4375,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x1062,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x1063,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x2060,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x2062,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x1073,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x1083,
quirk_msi_intx_disable_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x1090,
quirk_msi_intx_disable_qca_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x1091,
quirk_msi_intx_disable_qca_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x10a0,
quirk_msi_intx_disable_qca_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0x10a1,
quirk_msi_intx_disable_qca_bug);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_ATTANSIC, 0xe091,
quirk_msi_intx_disable_qca_bug);
#endif /* CONFIG_PCI_MSI */
/* Allow manual resource allocation for PCI hotplug bridges
* via pci=hpmemsize=nnM and pci=hpiosize=nnM parameters. For
* some PCI-PCI hotplug bridges, like PLX 6254 (former HINT HB6),
* kernel fails to allocate resources when hotplug device is
* inserted and PCI bus is rescanned.
*/
static void quirk_hotplug_bridge(struct pci_dev *dev)
{
dev->is_hotplug_bridge = 1;
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_HINT, 0x0020, quirk_hotplug_bridge);
/*
* This is a quirk for the Ricoh MMC controller found as a part of
* some mulifunction chips.
* This is very similar and based on the ricoh_mmc driver written by
* Philip Langdale. Thank you for these magic sequences.
*
* These chips implement the four main memory card controllers (SD, MMC, MS, xD)
* and one or both of cardbus or firewire.
*
* It happens that they implement SD and MMC
* support as separate controllers (and PCI functions). The linux SDHCI
* driver supports MMC cards but the chip detects MMC cards in hardware
* and directs them to the MMC controller - so the SDHCI driver never sees
* them.
*
* To get around this, we must disable the useless MMC controller.
* At that point, the SDHCI controller will start seeing them
* It seems to be the case that the relevant PCI registers to deactivate the
* MMC controller live on PCI function 0, which might be the cardbus controller
* or the firewire controller, depending on the particular chip in question
*
* This has to be done early, because as soon as we disable the MMC controller
* other pci functions shift up one level, e.g. function #2 becomes function
* #1, and this will confuse the pci core.
*/
#ifdef CONFIG_MMC_RICOH_MMC
static void ricoh_mmc_fixup_rl5c476(struct pci_dev *dev)
{
/* disable via cardbus interface */
u8 write_enable;
u8 write_target;
u8 disable;
/* disable must be done via function #0 */
if (PCI_FUNC(dev->devfn))
return;
pci_read_config_byte(dev, 0xB7, &disable);
if (disable & 0x02)
return;
pci_read_config_byte(dev, 0x8E, &write_enable);
pci_write_config_byte(dev, 0x8E, 0xAA);
pci_read_config_byte(dev, 0x8D, &write_target);
pci_write_config_byte(dev, 0x8D, 0xB7);
pci_write_config_byte(dev, 0xB7, disable | 0x02);
pci_write_config_byte(dev, 0x8E, write_enable);
pci_write_config_byte(dev, 0x8D, write_target);
dev_notice(&dev->dev, "proprietary Ricoh MMC controller disabled (via cardbus function)\n");
dev_notice(&dev->dev, "MMC cards are now supported by standard SDHCI controller\n");
}
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_RL5C476, ricoh_mmc_fixup_rl5c476);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_RL5C476, ricoh_mmc_fixup_rl5c476);
static void ricoh_mmc_fixup_r5c832(struct pci_dev *dev)
{
/* disable via firewire interface */
u8 write_enable;
u8 disable;
/* disable must be done via function #0 */
if (PCI_FUNC(dev->devfn))
return;
/*
* RICOH 0xe822 and 0xe823 SD/MMC card readers fail to recognize
* certain types of SD/MMC cards. Lowering the SD base
* clock frequency from 200Mhz to 50Mhz fixes this issue.
*
* 0x150 - SD2.0 mode enable for changing base clock
* frequency to 50Mhz
* 0xe1 - Base clock frequency
* 0x32 - 50Mhz new clock frequency
* 0xf9 - Key register for 0x150
* 0xfc - key register for 0xe1
*/
if (dev->device == PCI_DEVICE_ID_RICOH_R5CE822 ||
dev->device == PCI_DEVICE_ID_RICOH_R5CE823) {
pci_write_config_byte(dev, 0xf9, 0xfc);
pci_write_config_byte(dev, 0x150, 0x10);
pci_write_config_byte(dev, 0xf9, 0x00);
pci_write_config_byte(dev, 0xfc, 0x01);
pci_write_config_byte(dev, 0xe1, 0x32);
pci_write_config_byte(dev, 0xfc, 0x00);
dev_notice(&dev->dev, "MMC controller base frequency changed to 50Mhz.\n");
}
pci_read_config_byte(dev, 0xCB, &disable);
if (disable & 0x02)
return;
pci_read_config_byte(dev, 0xCA, &write_enable);
pci_write_config_byte(dev, 0xCA, 0x57);
pci_write_config_byte(dev, 0xCB, disable | 0x02);
pci_write_config_byte(dev, 0xCA, write_enable);
dev_notice(&dev->dev, "proprietary Ricoh MMC controller disabled (via firewire function)\n");
dev_notice(&dev->dev, "MMC cards are now supported by standard SDHCI controller\n");
}
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_R5C832, ricoh_mmc_fixup_r5c832);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_R5C832, ricoh_mmc_fixup_r5c832);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_R5CE822, ricoh_mmc_fixup_r5c832);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_R5CE822, ricoh_mmc_fixup_r5c832);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_R5CE823, ricoh_mmc_fixup_r5c832);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_R5CE823, ricoh_mmc_fixup_r5c832);
#endif /*CONFIG_MMC_RICOH_MMC*/
#ifdef CONFIG_DMAR_TABLE
#define VTUNCERRMSK_REG 0x1ac
#define VTD_MSK_SPEC_ERRORS (1 << 31)
/*
* This is a quirk for masking vt-d spec defined errors to platform error
* handling logic. With out this, platforms using Intel 7500, 5500 chipsets
* (and the derivative chipsets like X58 etc) seem to generate NMI/SMI (based
* on the RAS config settings of the platform) when a vt-d fault happens.
* The resulting SMI caused the system to hang.
*
* VT-d spec related errors are already handled by the VT-d OS code, so no
* need to report the same error through other channels.
*/
static void vtd_mask_spec_errors(struct pci_dev *dev)
{
u32 word;
pci_read_config_dword(dev, VTUNCERRMSK_REG, &word);
pci_write_config_dword(dev, VTUNCERRMSK_REG, word | VTD_MSK_SPEC_ERRORS);
}
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, 0x342e, vtd_mask_spec_errors);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, 0x3c28, vtd_mask_spec_errors);
#endif
static void fixup_ti816x_class(struct pci_dev *dev)
{
u32 class = dev->class;
/* TI 816x devices do not have class code set when in PCIe boot mode */
dev->class = PCI_CLASS_MULTIMEDIA_VIDEO << 8;
dev_info(&dev->dev, "PCI class overridden (%#08x -> %#08x)\n",
class, dev->class);
}
DECLARE_PCI_FIXUP_CLASS_EARLY(PCI_VENDOR_ID_TI, 0xb800,
PCI_CLASS_NOT_DEFINED, 8, fixup_ti816x_class);
/* Some PCIe devices do not work reliably with the claimed maximum
* payload size supported.
*/
static void fixup_mpss_256(struct pci_dev *dev)
{
dev->pcie_mpss = 1; /* 256 bytes */
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SOLARFLARE,
PCI_DEVICE_ID_SOLARFLARE_SFC4000A_0, fixup_mpss_256);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SOLARFLARE,
PCI_DEVICE_ID_SOLARFLARE_SFC4000A_1, fixup_mpss_256);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_SOLARFLARE,
PCI_DEVICE_ID_SOLARFLARE_SFC4000B, fixup_mpss_256);
/* Intel 5000 and 5100 Memory controllers have an errata with read completion
* coalescing (which is enabled by default on some BIOSes) and MPS of 256B.
* Since there is no way of knowing what the PCIE MPS on each fabric will be
* until all of the devices are discovered and buses walked, read completion
* coalescing must be disabled. Unfortunately, it cannot be re-enabled because
* it is possible to hotplug a device with MPS of 256B.
*/
static void quirk_intel_mc_errata(struct pci_dev *dev)
{
int err;
u16 rcc;
if (pcie_bus_config == PCIE_BUS_TUNE_OFF ||
pcie_bus_config == PCIE_BUS_DEFAULT)
return;
/* Intel errata specifies bits to change but does not say what they are.
* Keeping them magical until such time as the registers and values can
* be explained.
*/
err = pci_read_config_word(dev, 0x48, &rcc);
if (err) {
dev_err(&dev->dev, "Error attempting to read the read completion coalescing register\n");
return;
}
if (!(rcc & (1 << 10)))
return;
rcc &= ~(1 << 10);
err = pci_write_config_word(dev, 0x48, rcc);
if (err) {
dev_err(&dev->dev, "Error attempting to write the read completion coalescing register\n");
return;
}
pr_info_once("Read completion coalescing disabled due to hardware errata relating to 256B MPS\n");
}
/* Intel 5000 series memory controllers and ports 2-7 */
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25c0, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25d0, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25d4, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25d8, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25e2, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25e3, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25e4, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25e5, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25e6, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25e7, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25f7, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25f8, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25f9, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x25fa, quirk_intel_mc_errata);
/* Intel 5100 series memory controllers and ports 2-7 */
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65c0, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65e2, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65e3, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65e4, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65e5, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65e6, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65e7, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65f7, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65f8, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65f9, quirk_intel_mc_errata);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x65fa, quirk_intel_mc_errata);
/*
* Ivytown NTB BAR sizes are misreported by the hardware due to an erratum. To
* work around this, query the size it should be configured to by the device and
* modify the resource end to correspond to this new size.
*/
static void quirk_intel_ntb(struct pci_dev *dev)
{
int rc;
u8 val;
rc = pci_read_config_byte(dev, 0x00D0, &val);
if (rc)
return;
dev->resource[2].end = dev->resource[2].start + ((u64) 1 << val) - 1;
rc = pci_read_config_byte(dev, 0x00D1, &val);
if (rc)
return;
dev->resource[4].end = dev->resource[4].start + ((u64) 1 << val) - 1;
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x0e08, quirk_intel_ntb);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x0e0d, quirk_intel_ntb);
static ktime_t fixup_debug_start(struct pci_dev *dev,
void (*fn)(struct pci_dev *dev))
{
ktime_t calltime = 0;
dev_dbg(&dev->dev, "calling %pF\n", fn);
if (initcall_debug) {
pr_debug("calling %pF @ %i for %s\n",
fn, task_pid_nr(current), dev_name(&dev->dev));
calltime = ktime_get();
}
return calltime;
}
static void fixup_debug_report(struct pci_dev *dev, ktime_t calltime,
void (*fn)(struct pci_dev *dev))
{
ktime_t delta, rettime;
unsigned long long duration;
if (initcall_debug) {
rettime = ktime_get();
delta = ktime_sub(rettime, calltime);
duration = (unsigned long long) ktime_to_ns(delta) >> 10;
pr_debug("pci fixup %pF returned after %lld usecs for %s\n",
fn, duration, dev_name(&dev->dev));
}
}
/*
* Some BIOS implementations leave the Intel GPU interrupts enabled,
* even though no one is handling them (f.e. i915 driver is never loaded).
* Additionally the interrupt destination is not set up properly
* and the interrupt ends up -somewhere-.
*
* These spurious interrupts are "sticky" and the kernel disables
* the (shared) interrupt line after 100.000+ generated interrupts.
*
* Fix it by disabling the still enabled interrupts.
* This resolves crashes often seen on monitor unplug.
*/
#define I915_DEIER_REG 0x4400c
static void disable_igfx_irq(struct pci_dev *dev)
{
void __iomem *regs = pci_iomap(dev, 0, 0);
if (regs == NULL) {
dev_warn(&dev->dev, "igfx quirk: Can't iomap PCI device\n");
return;
}
/* Check if any interrupt line is still enabled */
if (readl(regs + I915_DEIER_REG) != 0) {
dev_warn(&dev->dev, "BIOS left Intel GPU interrupts enabled; disabling\n");
writel(0, regs + I915_DEIER_REG);
}
pci_iounmap(dev, regs);
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x0102, disable_igfx_irq);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x010a, disable_igfx_irq);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x0152, disable_igfx_irq);
/*
* PCI devices which are on Intel chips can skip the 10ms delay
* before entering D3 mode.
*/
static void quirk_remove_d3_delay(struct pci_dev *dev)
{
dev->d3_delay = 0;
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x0c00, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x0412, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x0c0c, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c31, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c3a, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c3d, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c2d, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c20, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c18, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c1c, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c26, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c4e, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c02, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x8c22, quirk_remove_d3_delay);
/* Intel Cherrytrail devices do not need 10ms d3_delay */
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2280, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x22b0, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x22b8, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x22d8, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x22dc, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x22b5, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x22b7, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x2298, quirk_remove_d3_delay);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x229c, quirk_remove_d3_delay);
/*
* Some devices may pass our check in pci_intx_mask_supported() if
* PCI_COMMAND_INTX_DISABLE works though they actually do not properly
* support this feature.
*/
static void quirk_broken_intx_masking(struct pci_dev *dev)
{
dev->broken_intx_masking = 1;
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x0030,
quirk_broken_intx_masking);
DECLARE_PCI_FIXUP_FINAL(0x1814, 0x0601, /* Ralink RT2800 802.11n PCI */
quirk_broken_intx_masking);
/*
* Realtek RTL8169 PCI Gigabit Ethernet Controller (rev 10)
* Subsystem: Realtek RTL8169/8110 Family PCI Gigabit Ethernet NIC
*
* RTL8110SC - Fails under PCI device assignment using DisINTx masking.
*/
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_REALTEK, 0x8169,
quirk_broken_intx_masking);
/*
* Intel i40e (XL710/X710) 10/20/40GbE NICs all have broken INTx masking,
* DisINTx can be set but the interrupt status bit is non-functional.
*/
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1572,
quirk_broken_intx_masking);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1574,
quirk_broken_intx_masking);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1580,
quirk_broken_intx_masking);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1581,
quirk_broken_intx_masking);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1583,
quirk_broken_intx_masking);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1584,
quirk_broken_intx_masking);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1585,
quirk_broken_intx_masking);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1586,
quirk_broken_intx_masking);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1587,
quirk_broken_intx_masking);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1588,
quirk_broken_intx_masking);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x1589,
quirk_broken_intx_masking);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x37d0,
quirk_broken_intx_masking);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x37d1,
quirk_broken_intx_masking);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, 0x37d2,
quirk_broken_intx_masking);
static u16 mellanox_broken_intx_devs[] = {
PCI_DEVICE_ID_MELLANOX_HERMON_SDR,
PCI_DEVICE_ID_MELLANOX_HERMON_DDR,
PCI_DEVICE_ID_MELLANOX_HERMON_QDR,
PCI_DEVICE_ID_MELLANOX_HERMON_DDR_GEN2,
PCI_DEVICE_ID_MELLANOX_HERMON_QDR_GEN2,
PCI_DEVICE_ID_MELLANOX_HERMON_EN,
PCI_DEVICE_ID_MELLANOX_HERMON_EN_GEN2,
PCI_DEVICE_ID_MELLANOX_CONNECTX_EN,
PCI_DEVICE_ID_MELLANOX_CONNECTX_EN_T_GEN2,
PCI_DEVICE_ID_MELLANOX_CONNECTX_EN_GEN2,
PCI_DEVICE_ID_MELLANOX_CONNECTX_EN_5_GEN2,
PCI_DEVICE_ID_MELLANOX_CONNECTX2,
PCI_DEVICE_ID_MELLANOX_CONNECTX3,
PCI_DEVICE_ID_MELLANOX_CONNECTX3_PRO,
};
#define CONNECTX_4_CURR_MAX_MINOR 99
#define CONNECTX_4_INTX_SUPPORT_MINOR 14
/*
* Check ConnectX-4/LX FW version to see if it supports legacy interrupts.
* If so, don't mark it as broken.
* FW minor > 99 means older FW version format and no INTx masking support.
* FW minor < 14 means new FW version format and no INTx masking support.
*/
static void mellanox_check_broken_intx_masking(struct pci_dev *pdev)
{
__be32 __iomem *fw_ver;
u16 fw_major;
u16 fw_minor;
u16 fw_subminor;
u32 fw_maj_min;
u32 fw_sub_min;
int i;
for (i = 0; i < ARRAY_SIZE(mellanox_broken_intx_devs); i++) {
if (pdev->device == mellanox_broken_intx_devs[i]) {
pdev->broken_intx_masking = 1;
return;
}
}
/* Getting here means Connect-IB cards and up. Connect-IB has no INTx
* support so shouldn't be checked further
*/
if (pdev->device == PCI_DEVICE_ID_MELLANOX_CONNECTIB)
return;
if (pdev->device != PCI_DEVICE_ID_MELLANOX_CONNECTX4 &&
pdev->device != PCI_DEVICE_ID_MELLANOX_CONNECTX4_LX)
return;
/* For ConnectX-4 and ConnectX-4LX, need to check FW support */
if (pci_enable_device_mem(pdev)) {
dev_warn(&pdev->dev, "Can't enable device memory\n");
return;
}
fw_ver = ioremap(pci_resource_start(pdev, 0), 4);
if (!fw_ver) {
dev_warn(&pdev->dev, "Can't map ConnectX-4 initialization segment\n");
goto out;
}
/* Reading from resource space should be 32b aligned */
fw_maj_min = ioread32be(fw_ver);
fw_sub_min = ioread32be(fw_ver + 1);
fw_major = fw_maj_min & 0xffff;
fw_minor = fw_maj_min >> 16;
fw_subminor = fw_sub_min & 0xffff;
if (fw_minor > CONNECTX_4_CURR_MAX_MINOR ||
fw_minor < CONNECTX_4_INTX_SUPPORT_MINOR) {
dev_warn(&pdev->dev, "ConnectX-4: FW %u.%u.%u doesn't support INTx masking, disabling. Please upgrade FW to %d.14.1100 and up for INTx support\n",
fw_major, fw_minor, fw_subminor, pdev->device ==
PCI_DEVICE_ID_MELLANOX_CONNECTX4 ? 12 : 14);
pdev->broken_intx_masking = 1;
}
iounmap(fw_ver);
out:
pci_disable_device(pdev);
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_MELLANOX, PCI_ANY_ID,
mellanox_check_broken_intx_masking);
static void quirk_no_bus_reset(struct pci_dev *dev)
{
dev->dev_flags |= PCI_DEV_FLAGS_NO_BUS_RESET;
}
/*
* Some Atheros AR9xxx and QCA988x chips do not behave after a bus reset.
* The device will throw a Link Down error on AER-capable systems and
* regardless of AER, config space of the device is never accessible again
* and typically causes the system to hang or reset when access is attempted.
* http://www.spinics.net/lists/linux-pci/msg34797.html
*/
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATHEROS, 0x0030, quirk_no_bus_reset);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATHEROS, 0x0032, quirk_no_bus_reset);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATHEROS, 0x003c, quirk_no_bus_reset);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATHEROS, 0x0033, quirk_no_bus_reset);
static void quirk_no_pm_reset(struct pci_dev *dev)
{
/*
* We can't do a bus reset on root bus devices, but an ineffective
* PM reset may be better than nothing.
*/
if (!pci_is_root_bus(dev->bus))
dev->dev_flags |= PCI_DEV_FLAGS_NO_PM_RESET;
}
/*
* Some AMD/ATI GPUS (HD8570 - Oland) report that a D3hot->D0 transition
* causes a reset (i.e., they advertise NoSoftRst-). This transition seems
* to have no effect on the device: it retains the framebuffer contents and
* monitor sync. Advertising this support makes other layers, like VFIO,
* assume pci_reset_function() is viable for this device. Mark it as
* unavailable to skip it when testing reset methods.
*/
DECLARE_PCI_FIXUP_CLASS_HEADER(PCI_VENDOR_ID_ATI, PCI_ANY_ID,
PCI_CLASS_DISPLAY_VGA, 8, quirk_no_pm_reset);
/*
* Thunderbolt controllers with broken MSI hotplug signaling:
* Entire 1st generation (Light Ridge, Eagle Ridge, Light Peak) and part
* of the 2nd generation (Cactus Ridge 4C up to revision 1, Port Ridge).
*/
static void quirk_thunderbolt_hotplug_msi(struct pci_dev *pdev)
{
if (pdev->is_hotplug_bridge &&
(pdev->device != PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C ||
pdev->revision <= 1))
pdev->no_msi = 1;
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_LIGHT_RIDGE,
quirk_thunderbolt_hotplug_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_EAGLE_RIDGE,
quirk_thunderbolt_hotplug_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_LIGHT_PEAK,
quirk_thunderbolt_hotplug_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C,
quirk_thunderbolt_hotplug_msi);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_PORT_RIDGE,
quirk_thunderbolt_hotplug_msi);
static void quirk_chelsio_extend_vpd(struct pci_dev *dev)
{
pci_set_vpd_size(dev, 8192);
}
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x20, quirk_chelsio_extend_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x21, quirk_chelsio_extend_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x22, quirk_chelsio_extend_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x23, quirk_chelsio_extend_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x24, quirk_chelsio_extend_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x25, quirk_chelsio_extend_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x26, quirk_chelsio_extend_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x30, quirk_chelsio_extend_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x31, quirk_chelsio_extend_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x32, quirk_chelsio_extend_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x35, quirk_chelsio_extend_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x36, quirk_chelsio_extend_vpd);
DECLARE_PCI_FIXUP_FINAL(PCI_VENDOR_ID_CHELSIO, 0x37, quirk_chelsio_extend_vpd);
#ifdef CONFIG_ACPI
/*
* Apple: Shutdown Cactus Ridge Thunderbolt controller.
*
* On Apple hardware the Cactus Ridge Thunderbolt controller needs to be
* shutdown before suspend. Otherwise the native host interface (NHI) will not
* be present after resume if a device was plugged in before suspend.
*
* The thunderbolt controller consists of a pcie switch with downstream
* bridges leading to the NHI and to the tunnel pci bridges.
*
* This quirk cuts power to the whole chip. Therefore we have to apply it
* during suspend_noirq of the upstream bridge.
*
* Power is automagically restored before resume. No action is needed.
*/
static void quirk_apple_poweroff_thunderbolt(struct pci_dev *dev)
{
acpi_handle bridge, SXIO, SXFP, SXLV;
if (!dmi_match(DMI_BOARD_VENDOR, "Apple Inc."))
return;
if (pci_pcie_type(dev) != PCI_EXP_TYPE_UPSTREAM)
return;
bridge = ACPI_HANDLE(&dev->dev);
if (!bridge)
return;
/*
* SXIO and SXLV are present only on machines requiring this quirk.
* TB bridges in external devices might have the same device id as those
* on the host, but they will not have the associated ACPI methods. This
* implicitly checks that we are at the right bridge.
*/
if (ACPI_FAILURE(acpi_get_handle(bridge, "DSB0.NHI0.SXIO", &SXIO))
|| ACPI_FAILURE(acpi_get_handle(bridge, "DSB0.NHI0.SXFP", &SXFP))
|| ACPI_FAILURE(acpi_get_handle(bridge, "DSB0.NHI0.SXLV", &SXLV)))
return;
dev_info(&dev->dev, "quirk: cutting power to thunderbolt controller...\n");
/* magic sequence */
acpi_execute_simple_method(SXIO, NULL, 1);
acpi_execute_simple_method(SXFP, NULL, 0);
msleep(300);
acpi_execute_simple_method(SXLV, NULL, 0);
acpi_execute_simple_method(SXIO, NULL, 0);
acpi_execute_simple_method(SXLV, NULL, 0);
}
DECLARE_PCI_FIXUP_SUSPEND_LATE(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C,
quirk_apple_poweroff_thunderbolt);
/*
* Apple: Wait for the thunderbolt controller to reestablish pci tunnels.
*
* During suspend the thunderbolt controller is reset and all pci
* tunnels are lost. The NHI driver will try to reestablish all tunnels
* during resume. We have to manually wait for the NHI since there is
* no parent child relationship between the NHI and the tunneled
* bridges.
*/
static void quirk_apple_wait_for_thunderbolt(struct pci_dev *dev)
{
struct pci_dev *sibling = NULL;
struct pci_dev *nhi = NULL;
if (!dmi_match(DMI_BOARD_VENDOR, "Apple Inc."))
return;
if (pci_pcie_type(dev) != PCI_EXP_TYPE_DOWNSTREAM)
return;
/*
* Find the NHI and confirm that we are a bridge on the tb host
* controller and not on a tb endpoint.
*/
sibling = pci_get_slot(dev->bus, 0x0);
if (sibling == dev)
goto out; /* we are the downstream bridge to the NHI */
if (!sibling || !sibling->subordinate)
goto out;
nhi = pci_get_slot(sibling->subordinate, 0x0);
if (!nhi)
goto out;
if (nhi->vendor != PCI_VENDOR_ID_INTEL
|| (nhi->device != PCI_DEVICE_ID_INTEL_LIGHT_RIDGE &&
nhi->device != PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C &&
nhi->device != PCI_DEVICE_ID_INTEL_FALCON_RIDGE_2C_NHI &&
nhi->device != PCI_DEVICE_ID_INTEL_FALCON_RIDGE_4C_NHI)
|| nhi->class != PCI_CLASS_SYSTEM_OTHER << 8)
goto out;
dev_info(&dev->dev, "quirk: waiting for thunderbolt to reestablish PCI tunnels...\n");
device_pm_wait_for_dev(&dev->dev, &nhi->dev);
out:
pci_dev_put(nhi);
pci_dev_put(sibling);
}
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_LIGHT_RIDGE,
quirk_apple_wait_for_thunderbolt);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C,
quirk_apple_wait_for_thunderbolt);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_FALCON_RIDGE_2C_BRIDGE,
quirk_apple_wait_for_thunderbolt);
DECLARE_PCI_FIXUP_RESUME_EARLY(PCI_VENDOR_ID_INTEL,
PCI_DEVICE_ID_INTEL_FALCON_RIDGE_4C_BRIDGE,
quirk_apple_wait_for_thunderbolt);
#endif
static void pci_do_fixups(struct pci_dev *dev, struct pci_fixup *f,
struct pci_fixup *end)
{
ktime_t calltime;
for (; f < end; f++)
if ((f->class == (u32) (dev->class >> f->class_shift) ||
f->class == (u32) PCI_ANY_ID) &&
(f->vendor == dev->vendor ||
f->vendor == (u16) PCI_ANY_ID) &&
(f->device == dev->device ||
f->device == (u16) PCI_ANY_ID)) {
calltime = fixup_debug_start(dev, f->hook);
f->hook(dev);
fixup_debug_report(dev, calltime, f->hook);
}
}
extern struct pci_fixup __start_pci_fixups_early[];
extern struct pci_fixup __end_pci_fixups_early[];
extern struct pci_fixup __start_pci_fixups_header[];
extern struct pci_fixup __end_pci_fixups_header[];
extern struct pci_fixup __start_pci_fixups_final[];
extern struct pci_fixup __end_pci_fixups_final[];
extern struct pci_fixup __start_pci_fixups_enable[];
extern struct pci_fixup __end_pci_fixups_enable[];
extern struct pci_fixup __start_pci_fixups_resume[];
extern struct pci_fixup __end_pci_fixups_resume[];
extern struct pci_fixup __start_pci_fixups_resume_early[];
extern struct pci_fixup __end_pci_fixups_resume_early[];
extern struct pci_fixup __start_pci_fixups_suspend[];
extern struct pci_fixup __end_pci_fixups_suspend[];
extern struct pci_fixup __start_pci_fixups_suspend_late[];
extern struct pci_fixup __end_pci_fixups_suspend_late[];
static bool pci_apply_fixup_final_quirks;
void pci_fixup_device(enum pci_fixup_pass pass, struct pci_dev *dev)
{
struct pci_fixup *start, *end;
switch (pass) {
case pci_fixup_early:
start = __start_pci_fixups_early;
end = __end_pci_fixups_early;
break;
case pci_fixup_header:
start = __start_pci_fixups_header;
end = __end_pci_fixups_header;
break;
case pci_fixup_final:
if (!pci_apply_fixup_final_quirks)
return;
start = __start_pci_fixups_final;
end = __end_pci_fixups_final;
break;
case pci_fixup_enable:
start = __start_pci_fixups_enable;
end = __end_pci_fixups_enable;
break;
case pci_fixup_resume:
start = __start_pci_fixups_resume;
end = __end_pci_fixups_resume;
break;
case pci_fixup_resume_early:
start = __start_pci_fixups_resume_early;
end = __end_pci_fixups_resume_early;
break;
case pci_fixup_suspend:
start = __start_pci_fixups_suspend;
end = __end_pci_fixups_suspend;
break;
case pci_fixup_suspend_late:
start = __start_pci_fixups_suspend_late;
end = __end_pci_fixups_suspend_late;
break;
default:
/* stupid compiler warning, you would think with an enum... */
return;
}
pci_do_fixups(dev, start, end);
}
EXPORT_SYMBOL(pci_fixup_device);
static int __init pci_apply_final_quirks(void)
{
struct pci_dev *dev = NULL;
u8 cls = 0;
u8 tmp;
if (pci_cache_line_size)
printk(KERN_DEBUG "PCI: CLS %u bytes\n",
pci_cache_line_size << 2);
pci_apply_fixup_final_quirks = true;
for_each_pci_dev(dev) {
pci_fixup_device(pci_fixup_final, dev);
/*
* If arch hasn't set it explicitly yet, use the CLS
* value shared by all PCI devices. If there's a
* mismatch, fall back to the default value.
*/
if (!pci_cache_line_size) {
pci_read_config_byte(dev, PCI_CACHE_LINE_SIZE, &tmp);
if (!cls)
cls = tmp;
if (!tmp || cls == tmp)
continue;
printk(KERN_DEBUG "PCI: CLS mismatch (%u != %u), using %u bytes\n",
cls << 2, tmp << 2,
pci_dfl_cache_line_size << 2);
pci_cache_line_size = pci_dfl_cache_line_size;
}
}
if (!pci_cache_line_size) {
printk(KERN_DEBUG "PCI: CLS %u bytes, default %u\n",
cls << 2, pci_dfl_cache_line_size << 2);
pci_cache_line_size = cls ? cls : pci_dfl_cache_line_size;
}
return 0;
}
fs_initcall_sync(pci_apply_final_quirks);
/*
* Following are device-specific reset methods which can be used to
* reset a single function if other methods (e.g. FLR, PM D0->D3) are
* not available.
*/
static int reset_intel_82599_sfp_virtfn(struct pci_dev *dev, int probe)
{
/*
* http://www.intel.com/content/dam/doc/datasheet/82599-10-gbe-controller-datasheet.pdf
*
* The 82599 supports FLR on VFs, but FLR support is reported only
* in the PF DEVCAP (sec 9.3.10.4), not in the VF DEVCAP (sec 9.5).
* Therefore, we can't use pcie_flr(), which checks the VF DEVCAP.
*/
if (probe)
return 0;
if (!pci_wait_for_pending_transaction(dev))
dev_err(&dev->dev, "transaction is not cleared; proceeding with reset anyway\n");
pcie_capability_set_word(dev, PCI_EXP_DEVCTL, PCI_EXP_DEVCTL_BCR_FLR);
msleep(100);
return 0;
}
#define SOUTH_CHICKEN2 0xc2004
#define PCH_PP_STATUS 0xc7200
#define PCH_PP_CONTROL 0xc7204
#define MSG_CTL 0x45010
#define NSDE_PWR_STATE 0xd0100
#define IGD_OPERATION_TIMEOUT 10000 /* set timeout 10 seconds */
static int reset_ivb_igd(struct pci_dev *dev, int probe)
{
void __iomem *mmio_base;
unsigned long timeout;
u32 val;
if (probe)
return 0;
mmio_base = pci_iomap(dev, 0, 0);
if (!mmio_base)
return -ENOMEM;
iowrite32(0x00000002, mmio_base + MSG_CTL);
/*
* Clobbering SOUTH_CHICKEN2 register is fine only if the next
* driver loaded sets the right bits. However, this's a reset and
* the bits have been set by i915 previously, so we clobber
* SOUTH_CHICKEN2 register directly here.
*/
iowrite32(0x00000005, mmio_base + SOUTH_CHICKEN2);
val = ioread32(mmio_base + PCH_PP_CONTROL) & 0xfffffffe;
iowrite32(val, mmio_base + PCH_PP_CONTROL);
timeout = jiffies + msecs_to_jiffies(IGD_OPERATION_TIMEOUT);
do {
val = ioread32(mmio_base + PCH_PP_STATUS);
if ((val & 0xb0000000) == 0)
goto reset_complete;
msleep(10);
} while (time_before(jiffies, timeout));
dev_warn(&dev->dev, "timeout during reset\n");
reset_complete:
iowrite32(0x00000002, mmio_base + NSDE_PWR_STATE);
pci_iounmap(dev, mmio_base);
return 0;
}
/*
* Device-specific reset method for Chelsio T4-based adapters.
*/
static int reset_chelsio_generic_dev(struct pci_dev *dev, int probe)
{
u16 old_command;
u16 msix_flags;
/*
* If this isn't a Chelsio T4-based device, return -ENOTTY indicating
* that we have no device-specific reset method.
*/
if ((dev->device & 0xf000) != 0x4000)
return -ENOTTY;
/*
* If this is the "probe" phase, return 0 indicating that we can
* reset this device.
*/
if (probe)
return 0;
/*
* T4 can wedge if there are DMAs in flight within the chip and Bus
* Master has been disabled. We need to have it on till the Function
* Level Reset completes. (BUS_MASTER is disabled in
* pci_reset_function()).
*/
pci_read_config_word(dev, PCI_COMMAND, &old_command);
pci_write_config_word(dev, PCI_COMMAND,
old_command | PCI_COMMAND_MASTER);
/*
* Perform the actual device function reset, saving and restoring
* configuration information around the reset.
*/
pci_save_state(dev);
/*
* T4 also suffers a Head-Of-Line blocking problem if MSI-X interrupts
* are disabled when an MSI-X interrupt message needs to be delivered.
* So we briefly re-enable MSI-X interrupts for the duration of the
* FLR. The pci_restore_state() below will restore the original
* MSI-X state.
*/
pci_read_config_word(dev, dev->msix_cap+PCI_MSIX_FLAGS, &msix_flags);
if ((msix_flags & PCI_MSIX_FLAGS_ENABLE) == 0)
pci_write_config_word(dev, dev->msix_cap+PCI_MSIX_FLAGS,
msix_flags |
PCI_MSIX_FLAGS_ENABLE |
PCI_MSIX_FLAGS_MASKALL);
/*
* Start of pcie_flr() code sequence. This reset code is a copy of
* the guts of pcie_flr() because that's not an exported function.
*/
if (!pci_wait_for_pending_transaction(dev))
dev_err(&dev->dev, "transaction is not cleared; proceeding with reset anyway\n");
pcie_capability_set_word(dev, PCI_EXP_DEVCTL, PCI_EXP_DEVCTL_BCR_FLR);
msleep(100);
/*
* End of pcie_flr() code sequence.
*/
/*
* Restore the configuration information (BAR values, etc.) including
* the original PCI Configuration Space Command word, and return
* success.
*/
pci_restore_state(dev);
pci_write_config_word(dev, PCI_COMMAND, old_command);
return 0;
}
#define PCI_DEVICE_ID_INTEL_82599_SFP_VF 0x10ed
#define PCI_DEVICE_ID_INTEL_IVB_M_VGA 0x0156
#define PCI_DEVICE_ID_INTEL_IVB_M2_VGA 0x0166
static const struct pci_dev_reset_methods pci_dev_reset_methods[] = {
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82599_SFP_VF,
reset_intel_82599_sfp_virtfn },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_IVB_M_VGA,
reset_ivb_igd },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_IVB_M2_VGA,
reset_ivb_igd },
{ PCI_VENDOR_ID_CHELSIO, PCI_ANY_ID,
reset_chelsio_generic_dev },
{ 0 }
};
/*
* These device-specific reset methods are here rather than in a driver
* because when a host assigns a device to a guest VM, the host may need
* to reset the device but probably doesn't have a driver for it.
*/
int pci_dev_specific_reset(struct pci_dev *dev, int probe)
{
const struct pci_dev_reset_methods *i;
for (i = pci_dev_reset_methods; i->reset; i++) {
if ((i->vendor == dev->vendor ||
i->vendor == (u16)PCI_ANY_ID) &&
(i->device == dev->device ||
i->device == (u16)PCI_ANY_ID))
return i->reset(dev, probe);
}
return -ENOTTY;
}
static void quirk_dma_func0_alias(struct pci_dev *dev)
{
if (PCI_FUNC(dev->devfn) != 0)
pci_add_dma_alias(dev, PCI_DEVFN(PCI_SLOT(dev->devfn), 0));
}
/*
* https://bugzilla.redhat.com/show_bug.cgi?id=605888
*
* Some Ricoh devices use function 0 as the PCIe requester ID for DMA.
*/
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_RICOH, 0xe832, quirk_dma_func0_alias);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_RICOH, 0xe476, quirk_dma_func0_alias);
static void quirk_dma_func1_alias(struct pci_dev *dev)
{
if (PCI_FUNC(dev->devfn) != 1)
pci_add_dma_alias(dev, PCI_DEVFN(PCI_SLOT(dev->devfn), 1));
}
/*
* Marvell 88SE9123 uses function 1 as the requester ID for DMA. In some
* SKUs function 1 is present and is a legacy IDE controller, in other
* SKUs this function is not present, making this a ghost requester.
* https://bugzilla.kernel.org/show_bug.cgi?id=42679
*/
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x9120,
quirk_dma_func1_alias);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x9123,
quirk_dma_func1_alias);
/* https://bugzilla.kernel.org/show_bug.cgi?id=42679#c14 */
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x9130,
quirk_dma_func1_alias);
/* https://bugzilla.kernel.org/show_bug.cgi?id=42679#c47 + c57 */
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x9172,
quirk_dma_func1_alias);
/* https://bugzilla.kernel.org/show_bug.cgi?id=42679#c59 */
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x917a,
quirk_dma_func1_alias);
/* https://bugzilla.kernel.org/show_bug.cgi?id=42679#c78 */
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x9182,
quirk_dma_func1_alias);
/* https://bugzilla.kernel.org/show_bug.cgi?id=42679#c46 */
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x91a0,
quirk_dma_func1_alias);
/* https://bugzilla.kernel.org/show_bug.cgi?id=42679#c49 */
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_MARVELL_EXT, 0x9230,
quirk_dma_func1_alias);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_TTI, 0x0642,
quirk_dma_func1_alias);
/* https://bugs.gentoo.org/show_bug.cgi?id=497630 */
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_JMICRON,
PCI_DEVICE_ID_JMICRON_JMB388_ESD,
quirk_dma_func1_alias);
/* https://bugzilla.kernel.org/show_bug.cgi?id=42679#c117 */
DECLARE_PCI_FIXUP_HEADER(0x1c28, /* Lite-On */
0x0122, /* Plextor M6E (Marvell 88SS9183)*/
quirk_dma_func1_alias);
/*
* Some devices DMA with the wrong devfn, not just the wrong function.
* quirk_fixed_dma_alias() uses this table to create fixed aliases, where
* the alias is "fixed" and independent of the device devfn.
*
* For example, the Adaptec 3405 is a PCIe card with an Intel 80333 I/O
* processor. To software, this appears as a PCIe-to-PCI/X bridge with a
* single device on the secondary bus. In reality, the single exposed
* device at 0e.0 is the Address Translation Unit (ATU) of the controller
* that provides a bridge to the internal bus of the I/O processor. The
* controller supports private devices, which can be hidden from PCI config
* space. In the case of the Adaptec 3405, a private device at 01.0
* appears to be the DMA engine, which therefore needs to become a DMA
* alias for the device.
*/
static const struct pci_device_id fixed_dma_alias_tbl[] = {
{ PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x0285,
PCI_VENDOR_ID_ADAPTEC2, 0x02bb), /* Adaptec 3405 */
.driver_data = PCI_DEVFN(1, 0) },
{ PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x0285,
PCI_VENDOR_ID_ADAPTEC2, 0x02bc), /* Adaptec 3805 */
.driver_data = PCI_DEVFN(1, 0) },
{ 0 }
};
static void quirk_fixed_dma_alias(struct pci_dev *dev)
{
const struct pci_device_id *id;
id = pci_match_id(fixed_dma_alias_tbl, dev);
if (id)
pci_add_dma_alias(dev, id->driver_data);
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ADAPTEC2, 0x0285, quirk_fixed_dma_alias);
/*
* A few PCIe-to-PCI bridges fail to expose a PCIe capability, resulting in
* using the wrong DMA alias for the device. Some of these devices can be
* used as either forward or reverse bridges, so we need to test whether the
* device is operating in the correct mode. We could probably apply this
* quirk to PCI_ANY_ID, but for now we'll just use known offenders. The test
* is for a non-root, non-PCIe bridge where the upstream device is PCIe and
* is not a PCIe-to-PCI bridge, then @pdev is actually a PCIe-to-PCI bridge.
*/
static void quirk_use_pcie_bridge_dma_alias(struct pci_dev *pdev)
{
if (!pci_is_root_bus(pdev->bus) &&
pdev->hdr_type == PCI_HEADER_TYPE_BRIDGE &&
!pci_is_pcie(pdev) && pci_is_pcie(pdev->bus->self) &&
pci_pcie_type(pdev->bus->self) != PCI_EXP_TYPE_PCI_BRIDGE)
pdev->dev_flags |= PCI_DEV_FLAG_PCIE_BRIDGE_ALIAS;
}
/* ASM1083/1085, https://bugzilla.kernel.org/show_bug.cgi?id=44881#c46 */
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ASMEDIA, 0x1080,
quirk_use_pcie_bridge_dma_alias);
/* Tundra 8113, https://bugzilla.kernel.org/show_bug.cgi?id=44881#c43 */
DECLARE_PCI_FIXUP_HEADER(0x10e3, 0x8113, quirk_use_pcie_bridge_dma_alias);
/* ITE 8892, https://bugzilla.kernel.org/show_bug.cgi?id=73551 */
DECLARE_PCI_FIXUP_HEADER(0x1283, 0x8892, quirk_use_pcie_bridge_dma_alias);
/* Intel 82801, https://bugzilla.kernel.org/show_bug.cgi?id=44881#c49 */
DECLARE_PCI_FIXUP_HEADER(0x8086, 0x244e, quirk_use_pcie_bridge_dma_alias);
/*
* MIC x200 NTB forwards PCIe traffic using multiple alien RIDs. They have to
* be added as aliases to the DMA device in order to allow buffer access
* when IOMMU is enabled. Following devfns have to match RIT-LUT table
* programmed in the EEPROM.
*/
static void quirk_mic_x200_dma_alias(struct pci_dev *pdev)
{
pci_add_dma_alias(pdev, PCI_DEVFN(0x10, 0x0));
pci_add_dma_alias(pdev, PCI_DEVFN(0x11, 0x0));
pci_add_dma_alias(pdev, PCI_DEVFN(0x12, 0x3));
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2260, quirk_mic_x200_dma_alias);
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2264, quirk_mic_x200_dma_alias);
/*
* Intersil/Techwell TW686[4589]-based video capture cards have an empty (zero)
* class code. Fix it.
*/
static void quirk_tw686x_class(struct pci_dev *pdev)
{
u32 class = pdev->class;
/* Use "Multimedia controller" class */
pdev->class = (PCI_CLASS_MULTIMEDIA_OTHER << 8) | 0x01;
dev_info(&pdev->dev, "TW686x PCI class overridden (%#08x -> %#08x)\n",
class, pdev->class);
}
DECLARE_PCI_FIXUP_CLASS_EARLY(0x1797, 0x6864, PCI_CLASS_NOT_DEFINED, 8,
quirk_tw686x_class);
DECLARE_PCI_FIXUP_CLASS_EARLY(0x1797, 0x6865, PCI_CLASS_NOT_DEFINED, 8,
quirk_tw686x_class);
DECLARE_PCI_FIXUP_CLASS_EARLY(0x1797, 0x6868, PCI_CLASS_NOT_DEFINED, 8,
quirk_tw686x_class);
DECLARE_PCI_FIXUP_CLASS_EARLY(0x1797, 0x6869, PCI_CLASS_NOT_DEFINED, 8,
quirk_tw686x_class);
/*
* Per PCIe r3.0, sec 2.2.9, "Completion headers must supply the same
* values for the Attribute as were supplied in the header of the
* corresponding Request, except as explicitly allowed when IDO is used."
*
* If a non-compliant device generates a completion with a different
* attribute than the request, the receiver may accept it (which itself
* seems non-compliant based on sec 2.3.2), or it may handle it as a
* Malformed TLP or an Unexpected Completion, which will probably lead to a
* device access timeout.
*
* If the non-compliant device generates completions with zero attributes
* (instead of copying the attributes from the request), we can work around
* this by disabling the "Relaxed Ordering" and "No Snoop" attributes in
* upstream devices so they always generate requests with zero attributes.
*
* This affects other devices under the same Root Port, but since these
* attributes are performance hints, there should be no functional problem.
*
* Note that Configuration Space accesses are never supposed to have TLP
* Attributes, so we're safe waiting till after any Configuration Space
* accesses to do the Root Port fixup.
*/
static void quirk_disable_root_port_attributes(struct pci_dev *pdev)
{
struct pci_dev *root_port = pci_find_pcie_root_port(pdev);
if (!root_port) {
dev_warn(&pdev->dev, "PCIe Completion erratum may cause device errors\n");
return;
}
dev_info(&root_port->dev, "Disabling No Snoop/Relaxed Ordering Attributes to avoid PCIe Completion erratum in %s\n",
dev_name(&pdev->dev));
pcie_capability_clear_and_set_word(root_port, PCI_EXP_DEVCTL,
PCI_EXP_DEVCTL_RELAX_EN |
PCI_EXP_DEVCTL_NOSNOOP_EN, 0);
}
/*
* The Chelsio T5 chip fails to copy TLP Attributes from a Request to the
* Completion it generates.
*/
static void quirk_chelsio_T5_disable_root_port_attributes(struct pci_dev *pdev)
{
/*
* This mask/compare operation selects for Physical Function 4 on a
* T5. We only need to fix up the Root Port once for any of the
* PFs. PF[0..3] have PCI Device IDs of 0x50xx, but PF4 is uniquely
* 0x54xx so we use that one,
*/
if ((pdev->device & 0xff00) == 0x5400)
quirk_disable_root_port_attributes(pdev);
}
DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_CHELSIO, PCI_ANY_ID,
quirk_chelsio_T5_disable_root_port_attributes);
/*
* AMD has indicated that the devices below do not support peer-to-peer
* in any system where they are found in the southbridge with an AMD
* IOMMU in the system. Multifunction devices that do not support
* peer-to-peer between functions can claim to support a subset of ACS.
* Such devices effectively enable request redirect (RR) and completion
* redirect (CR) since all transactions are redirected to the upstream
* root complex.
*
* http://permalink.gmane.org/gmane.comp.emulators.kvm.devel/94086
* http://permalink.gmane.org/gmane.comp.emulators.kvm.devel/94102
* http://permalink.gmane.org/gmane.comp.emulators.kvm.devel/99402
*
* 1002:4385 SBx00 SMBus Controller
* 1002:439c SB7x0/SB8x0/SB9x0 IDE Controller
* 1002:4383 SBx00 Azalia (Intel HDA)
* 1002:439d SB7x0/SB8x0/SB9x0 LPC host controller
* 1002:4384 SBx00 PCI to PCI Bridge
* 1002:4399 SB7x0/SB8x0/SB9x0 USB OHCI2 Controller
*
* https://bugzilla.kernel.org/show_bug.cgi?id=81841#c15
*
* 1022:780f [AMD] FCH PCI Bridge
* 1022:7809 [AMD] FCH USB OHCI Controller
*/
static int pci_quirk_amd_sb_acs(struct pci_dev *dev, u16 acs_flags)
{
#ifdef CONFIG_ACPI
struct acpi_table_header *header = NULL;
acpi_status status;
/* Targeting multifunction devices on the SB (appears on root bus) */
if (!dev->multifunction || !pci_is_root_bus(dev->bus))
return -ENODEV;
/* The IVRS table describes the AMD IOMMU */
status = acpi_get_table("IVRS", 0, &header);
if (ACPI_FAILURE(status))
return -ENODEV;
/* Filter out flags not applicable to multifunction */
acs_flags &= (PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_EC | PCI_ACS_DT);
return acs_flags & ~(PCI_ACS_RR | PCI_ACS_CR) ? 0 : 1;
#else
return -ENODEV;
#endif
}
static int pci_quirk_cavium_acs(struct pci_dev *dev, u16 acs_flags)
{
/*
* Cavium devices matching this quirk do not perform peer-to-peer
* with other functions, allowing masking out these bits as if they
* were unimplemented in the ACS capability.
*/
acs_flags &= ~(PCI_ACS_SV | PCI_ACS_TB | PCI_ACS_RR |
PCI_ACS_CR | PCI_ACS_UF | PCI_ACS_DT);
return acs_flags ? 0 : 1;
}
/*
* Many Intel PCH root ports do provide ACS-like features to disable peer
* transactions and validate bus numbers in requests, but do not provide an
* actual PCIe ACS capability. This is the list of device IDs known to fall
* into that category as provided by Intel in Red Hat bugzilla 1037684.
*/
static const u16 pci_quirk_intel_pch_acs_ids[] = {
/* Ibexpeak PCH */
0x3b42, 0x3b43, 0x3b44, 0x3b45, 0x3b46, 0x3b47, 0x3b48, 0x3b49,
0x3b4a, 0x3b4b, 0x3b4c, 0x3b4d, 0x3b4e, 0x3b4f, 0x3b50, 0x3b51,
/* Cougarpoint PCH */
0x1c10, 0x1c11, 0x1c12, 0x1c13, 0x1c14, 0x1c15, 0x1c16, 0x1c17,
0x1c18, 0x1c19, 0x1c1a, 0x1c1b, 0x1c1c, 0x1c1d, 0x1c1e, 0x1c1f,
/* Pantherpoint PCH */
0x1e10, 0x1e11, 0x1e12, 0x1e13, 0x1e14, 0x1e15, 0x1e16, 0x1e17,
0x1e18, 0x1e19, 0x1e1a, 0x1e1b, 0x1e1c, 0x1e1d, 0x1e1e, 0x1e1f,
/* Lynxpoint-H PCH */
0x8c10, 0x8c11, 0x8c12, 0x8c13, 0x8c14, 0x8c15, 0x8c16, 0x8c17,
0x8c18, 0x8c19, 0x8c1a, 0x8c1b, 0x8c1c, 0x8c1d, 0x8c1e, 0x8c1f,
/* Lynxpoint-LP PCH */
0x9c10, 0x9c11, 0x9c12, 0x9c13, 0x9c14, 0x9c15, 0x9c16, 0x9c17,
0x9c18, 0x9c19, 0x9c1a, 0x9c1b,
/* Wildcat PCH */
0x9c90, 0x9c91, 0x9c92, 0x9c93, 0x9c94, 0x9c95, 0x9c96, 0x9c97,
0x9c98, 0x9c99, 0x9c9a, 0x9c9b,
/* Patsburg (X79) PCH */
0x1d10, 0x1d12, 0x1d14, 0x1d16, 0x1d18, 0x1d1a, 0x1d1c, 0x1d1e,
/* Wellsburg (X99) PCH */
0x8d10, 0x8d11, 0x8d12, 0x8d13, 0x8d14, 0x8d15, 0x8d16, 0x8d17,
0x8d18, 0x8d19, 0x8d1a, 0x8d1b, 0x8d1c, 0x8d1d, 0x8d1e,
/* Lynx Point (9 series) PCH */
0x8c90, 0x8c92, 0x8c94, 0x8c96, 0x8c98, 0x8c9a, 0x8c9c, 0x8c9e,
};
static bool pci_quirk_intel_pch_acs_match(struct pci_dev *dev)
{
int i;
/* Filter out a few obvious non-matches first */
if (!pci_is_pcie(dev) || pci_pcie_type(dev) != PCI_EXP_TYPE_ROOT_PORT)
return false;
for (i = 0; i < ARRAY_SIZE(pci_quirk_intel_pch_acs_ids); i++)
if (pci_quirk_intel_pch_acs_ids[i] == dev->device)
return true;
return false;
}
#define INTEL_PCH_ACS_FLAGS (PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF | PCI_ACS_SV)
static int pci_quirk_intel_pch_acs(struct pci_dev *dev, u16 acs_flags)
{
u16 flags = dev->dev_flags & PCI_DEV_FLAGS_ACS_ENABLED_QUIRK ?
INTEL_PCH_ACS_FLAGS : 0;
if (!pci_quirk_intel_pch_acs_match(dev))
return -ENOTTY;
return acs_flags & ~flags ? 0 : 1;
}
/*
* Sunrise Point PCH root ports implement ACS, but unfortunately as shown in
* the datasheet (Intel 100 Series Chipset Family PCH Datasheet, Vol. 2,
* 12.1.46, 12.1.47)[1] this chipset uses dwords for the ACS capability and
* control registers whereas the PCIe spec packs them into words (Rev 3.0,
* 7.16 ACS Extended Capability). The bit definitions are correct, but the
* control register is at offset 8 instead of 6 and we should probably use
* dword accesses to them. This applies to the following PCI Device IDs, as
* found in volume 1 of the datasheet[2]:
*
* 0xa110-0xa11f Sunrise Point-H PCI Express Root Port #{0-16}
* 0xa167-0xa16a Sunrise Point-H PCI Express Root Port #{17-20}
*
* N.B. This doesn't fix what lspci shows.
*
* [1] http://www.intel.com/content/www/us/en/chipsets/100-series-chipset-datasheet-vol-2.html
* [2] http://www.intel.com/content/www/us/en/chipsets/100-series-chipset-datasheet-vol-1.html
*/
static bool pci_quirk_intel_spt_pch_acs_match(struct pci_dev *dev)
{
return pci_is_pcie(dev) &&
pci_pcie_type(dev) == PCI_EXP_TYPE_ROOT_PORT &&
((dev->device & ~0xf) == 0xa110 ||
(dev->device >= 0xa167 && dev->device <= 0xa16a));
}
#define INTEL_SPT_ACS_CTRL (PCI_ACS_CAP + 4)
static int pci_quirk_intel_spt_pch_acs(struct pci_dev *dev, u16 acs_flags)
{
int pos;
u32 cap, ctrl;
if (!pci_quirk_intel_spt_pch_acs_match(dev))
return -ENOTTY;
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ACS);
if (!pos)
return -ENOTTY;
/* see pci_acs_flags_enabled() */
pci_read_config_dword(dev, pos + PCI_ACS_CAP, &cap);
acs_flags &= (cap | PCI_ACS_EC);
pci_read_config_dword(dev, pos + INTEL_SPT_ACS_CTRL, &ctrl);
return acs_flags & ~ctrl ? 0 : 1;
}
static int pci_quirk_mf_endpoint_acs(struct pci_dev *dev, u16 acs_flags)
{
/*
* SV, TB, and UF are not relevant to multifunction endpoints.
*
* Multifunction devices are only required to implement RR, CR, and DT
* in their ACS capability if they support peer-to-peer transactions.
* Devices matching this quirk have been verified by the vendor to not
* perform peer-to-peer with other functions, allowing us to mask out
* these bits as if they were unimplemented in the ACS capability.
*/
acs_flags &= ~(PCI_ACS_SV | PCI_ACS_TB | PCI_ACS_RR |
PCI_ACS_CR | PCI_ACS_UF | PCI_ACS_DT);
return acs_flags ? 0 : 1;
}
static const struct pci_dev_acs_enabled {
u16 vendor;
u16 device;
int (*acs_enabled)(struct pci_dev *dev, u16 acs_flags);
} pci_dev_acs_enabled[] = {
{ PCI_VENDOR_ID_ATI, 0x4385, pci_quirk_amd_sb_acs },
{ PCI_VENDOR_ID_ATI, 0x439c, pci_quirk_amd_sb_acs },
{ PCI_VENDOR_ID_ATI, 0x4383, pci_quirk_amd_sb_acs },
{ PCI_VENDOR_ID_ATI, 0x439d, pci_quirk_amd_sb_acs },
{ PCI_VENDOR_ID_ATI, 0x4384, pci_quirk_amd_sb_acs },
{ PCI_VENDOR_ID_ATI, 0x4399, pci_quirk_amd_sb_acs },
{ PCI_VENDOR_ID_AMD, 0x780f, pci_quirk_amd_sb_acs },
{ PCI_VENDOR_ID_AMD, 0x7809, pci_quirk_amd_sb_acs },
{ PCI_VENDOR_ID_SOLARFLARE, 0x0903, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_SOLARFLARE, 0x0923, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_SOLARFLARE, 0x0A03, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10C6, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10DB, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10DD, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10E1, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10F1, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10F7, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10F8, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10F9, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10FA, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10FB, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10FC, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1507, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1514, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x151C, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1529, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x152A, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x154D, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x154F, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1551, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1558, pci_quirk_mf_endpoint_acs },
/* 82580 */
{ PCI_VENDOR_ID_INTEL, 0x1509, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x150E, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x150F, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1510, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1511, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1516, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1527, pci_quirk_mf_endpoint_acs },
/* 82576 */
{ PCI_VENDOR_ID_INTEL, 0x10C9, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10E6, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10E7, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10E8, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x150A, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x150D, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1518, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1526, pci_quirk_mf_endpoint_acs },
/* 82575 */
{ PCI_VENDOR_ID_INTEL, 0x10A7, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10A9, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10D6, pci_quirk_mf_endpoint_acs },
/* I350 */
{ PCI_VENDOR_ID_INTEL, 0x1521, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1522, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1523, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1524, pci_quirk_mf_endpoint_acs },
/* 82571 (Quads omitted due to non-ACS switch) */
{ PCI_VENDOR_ID_INTEL, 0x105E, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x105F, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x1060, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x10D9, pci_quirk_mf_endpoint_acs },
/* I219 */
{ PCI_VENDOR_ID_INTEL, 0x15b7, pci_quirk_mf_endpoint_acs },
{ PCI_VENDOR_ID_INTEL, 0x15b8, pci_quirk_mf_endpoint_acs },
/* Intel PCH root ports */
{ PCI_VENDOR_ID_INTEL, PCI_ANY_ID, pci_quirk_intel_pch_acs },
{ PCI_VENDOR_ID_INTEL, PCI_ANY_ID, pci_quirk_intel_spt_pch_acs },
{ 0x19a2, 0x710, pci_quirk_mf_endpoint_acs }, /* Emulex BE3-R */
{ 0x10df, 0x720, pci_quirk_mf_endpoint_acs }, /* Emulex Skyhawk-R */
/* Cavium ThunderX */
{ PCI_VENDOR_ID_CAVIUM, PCI_ANY_ID, pci_quirk_cavium_acs },
{ 0 }
};
int pci_dev_specific_acs_enabled(struct pci_dev *dev, u16 acs_flags)
{
const struct pci_dev_acs_enabled *i;
int ret;
/*
* Allow devices that do not expose standard PCIe ACS capabilities
* or control to indicate their support here. Multi-function express
* devices which do not allow internal peer-to-peer between functions,
* but do not implement PCIe ACS may wish to return true here.
*/
for (i = pci_dev_acs_enabled; i->acs_enabled; i++) {
if ((i->vendor == dev->vendor ||
i->vendor == (u16)PCI_ANY_ID) &&
(i->device == dev->device ||
i->device == (u16)PCI_ANY_ID)) {
ret = i->acs_enabled(dev, acs_flags);
if (ret >= 0)
return ret;
}
}
return -ENOTTY;
}
/* Config space offset of Root Complex Base Address register */
#define INTEL_LPC_RCBA_REG 0xf0
/* 31:14 RCBA address */
#define INTEL_LPC_RCBA_MASK 0xffffc000
/* RCBA Enable */
#define INTEL_LPC_RCBA_ENABLE (1 << 0)
/* Backbone Scratch Pad Register */
#define INTEL_BSPR_REG 0x1104
/* Backbone Peer Non-Posted Disable */
#define INTEL_BSPR_REG_BPNPD (1 << 8)
/* Backbone Peer Posted Disable */
#define INTEL_BSPR_REG_BPPD (1 << 9)
/* Upstream Peer Decode Configuration Register */
#define INTEL_UPDCR_REG 0x1114
/* 5:0 Peer Decode Enable bits */
#define INTEL_UPDCR_REG_MASK 0x3f
static int pci_quirk_enable_intel_lpc_acs(struct pci_dev *dev)
{
u32 rcba, bspr, updcr;
void __iomem *rcba_mem;
/*
* Read the RCBA register from the LPC (D31:F0). PCH root ports
* are D28:F* and therefore get probed before LPC, thus we can't
* use pci_get_slot/pci_read_config_dword here.
*/
pci_bus_read_config_dword(dev->bus, PCI_DEVFN(31, 0),
INTEL_LPC_RCBA_REG, &rcba);
if (!(rcba & INTEL_LPC_RCBA_ENABLE))
return -EINVAL;
rcba_mem = ioremap_nocache(rcba & INTEL_LPC_RCBA_MASK,
PAGE_ALIGN(INTEL_UPDCR_REG));
if (!rcba_mem)
return -ENOMEM;
/*
* The BSPR can disallow peer cycles, but it's set by soft strap and
* therefore read-only. If both posted and non-posted peer cycles are
* disallowed, we're ok. If either are allowed, then we need to use
* the UPDCR to disable peer decodes for each port. This provides the
* PCIe ACS equivalent of PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF
*/
bspr = readl(rcba_mem + INTEL_BSPR_REG);
bspr &= INTEL_BSPR_REG_BPNPD | INTEL_BSPR_REG_BPPD;
if (bspr != (INTEL_BSPR_REG_BPNPD | INTEL_BSPR_REG_BPPD)) {
updcr = readl(rcba_mem + INTEL_UPDCR_REG);
if (updcr & INTEL_UPDCR_REG_MASK) {
dev_info(&dev->dev, "Disabling UPDCR peer decodes\n");
updcr &= ~INTEL_UPDCR_REG_MASK;
writel(updcr, rcba_mem + INTEL_UPDCR_REG);
}
}
iounmap(rcba_mem);
return 0;
}
/* Miscellaneous Port Configuration register */
#define INTEL_MPC_REG 0xd8
/* MPC: Invalid Receive Bus Number Check Enable */
#define INTEL_MPC_REG_IRBNCE (1 << 26)
static void pci_quirk_enable_intel_rp_mpc_acs(struct pci_dev *dev)
{
u32 mpc;
/*
* When enabled, the IRBNCE bit of the MPC register enables the
* equivalent of PCI ACS Source Validation (PCI_ACS_SV), which
* ensures that requester IDs fall within the bus number range
* of the bridge. Enable if not already.
*/
pci_read_config_dword(dev, INTEL_MPC_REG, &mpc);
if (!(mpc & INTEL_MPC_REG_IRBNCE)) {
dev_info(&dev->dev, "Enabling MPC IRBNCE\n");
mpc |= INTEL_MPC_REG_IRBNCE;
pci_write_config_word(dev, INTEL_MPC_REG, mpc);
}
}
static int pci_quirk_enable_intel_pch_acs(struct pci_dev *dev)
{
if (!pci_quirk_intel_pch_acs_match(dev))
return -ENOTTY;
if (pci_quirk_enable_intel_lpc_acs(dev)) {
dev_warn(&dev->dev, "Failed to enable Intel PCH ACS quirk\n");
return 0;
}
pci_quirk_enable_intel_rp_mpc_acs(dev);
dev->dev_flags |= PCI_DEV_FLAGS_ACS_ENABLED_QUIRK;
dev_info(&dev->dev, "Intel PCH root port ACS workaround enabled\n");
return 0;
}
static int pci_quirk_enable_intel_spt_pch_acs(struct pci_dev *dev)
{
int pos;
u32 cap, ctrl;
if (!pci_quirk_intel_spt_pch_acs_match(dev))
return -ENOTTY;
pos = pci_find_ext_capability(dev, PCI_EXT_CAP_ID_ACS);
if (!pos)
return -ENOTTY;
pci_read_config_dword(dev, pos + PCI_ACS_CAP, &cap);
pci_read_config_dword(dev, pos + INTEL_SPT_ACS_CTRL, &ctrl);
ctrl |= (cap & PCI_ACS_SV);
ctrl |= (cap & PCI_ACS_RR);
ctrl |= (cap & PCI_ACS_CR);
ctrl |= (cap & PCI_ACS_UF);
pci_write_config_dword(dev, pos + INTEL_SPT_ACS_CTRL, ctrl);
dev_info(&dev->dev, "Intel SPT PCH root port ACS workaround enabled\n");
return 0;
}
static const struct pci_dev_enable_acs {
u16 vendor;
u16 device;
int (*enable_acs)(struct pci_dev *dev);
} pci_dev_enable_acs[] = {
{ PCI_VENDOR_ID_INTEL, PCI_ANY_ID, pci_quirk_enable_intel_pch_acs },
{ PCI_VENDOR_ID_INTEL, PCI_ANY_ID, pci_quirk_enable_intel_spt_pch_acs },
{ 0 }
};
int pci_dev_specific_enable_acs(struct pci_dev *dev)
{
const struct pci_dev_enable_acs *i;
int ret;
for (i = pci_dev_enable_acs; i->enable_acs; i++) {
if ((i->vendor == dev->vendor ||
i->vendor == (u16)PCI_ANY_ID) &&
(i->device == dev->device ||
i->device == (u16)PCI_ANY_ID)) {
ret = i->enable_acs(dev);
if (ret >= 0)
return ret;
}
}
return -ENOTTY;
}
/*
* The PCI capabilities list for Intel DH895xCC VFs (device id 0x0443) with
* QuickAssist Technology (QAT) is prematurely terminated in hardware. The
* Next Capability pointer in the MSI Capability Structure should point to
* the PCIe Capability Structure but is incorrectly hardwired as 0 terminating
* the list.
*/
static void quirk_intel_qat_vf_cap(struct pci_dev *pdev)
{
int pos, i = 0;
u8 next_cap;
u16 reg16, *cap;
struct pci_cap_saved_state *state;
/* Bail if the hardware bug is fixed */
if (pdev->pcie_cap || pci_find_capability(pdev, PCI_CAP_ID_EXP))
return;
/* Bail if MSI Capability Structure is not found for some reason */
pos = pci_find_capability(pdev, PCI_CAP_ID_MSI);
if (!pos)
return;
/*
* Bail if Next Capability pointer in the MSI Capability Structure
* is not the expected incorrect 0x00.
*/
pci_read_config_byte(pdev, pos + 1, &next_cap);
if (next_cap)
return;
/*
* PCIe Capability Structure is expected to be at 0x50 and should
* terminate the list (Next Capability pointer is 0x00). Verify
* Capability Id and Next Capability pointer is as expected.
* Open-code some of set_pcie_port_type() and pci_cfg_space_size_ext()
* to correctly set kernel data structures which have already been
* set incorrectly due to the hardware bug.
*/
pos = 0x50;
pci_read_config_word(pdev, pos, ®16);
if (reg16 == (0x0000 | PCI_CAP_ID_EXP)) {
u32 status;
#ifndef PCI_EXP_SAVE_REGS
#define PCI_EXP_SAVE_REGS 7
#endif
int size = PCI_EXP_SAVE_REGS * sizeof(u16);
pdev->pcie_cap = pos;
pci_read_config_word(pdev, pos + PCI_EXP_FLAGS, ®16);
pdev->pcie_flags_reg = reg16;
pci_read_config_word(pdev, pos + PCI_EXP_DEVCAP, ®16);
pdev->pcie_mpss = reg16 & PCI_EXP_DEVCAP_PAYLOAD;
pdev->cfg_size = PCI_CFG_SPACE_EXP_SIZE;
if (pci_read_config_dword(pdev, PCI_CFG_SPACE_SIZE, &status) !=
PCIBIOS_SUCCESSFUL || (status == 0xffffffff))
pdev->cfg_size = PCI_CFG_SPACE_SIZE;
if (pci_find_saved_cap(pdev, PCI_CAP_ID_EXP))
return;
/*
* Save PCIE cap
*/
state = kzalloc(sizeof(*state) + size, GFP_KERNEL);
if (!state)
return;
state->cap.cap_nr = PCI_CAP_ID_EXP;
state->cap.cap_extended = 0;
state->cap.size = size;
cap = (u16 *)&state->cap.data[0];
pcie_capability_read_word(pdev, PCI_EXP_DEVCTL, &cap[i++]);
pcie_capability_read_word(pdev, PCI_EXP_LNKCTL, &cap[i++]);
pcie_capability_read_word(pdev, PCI_EXP_SLTCTL, &cap[i++]);
pcie_capability_read_word(pdev, PCI_EXP_RTCTL, &cap[i++]);
pcie_capability_read_word(pdev, PCI_EXP_DEVCTL2, &cap[i++]);
pcie_capability_read_word(pdev, PCI_EXP_LNKCTL2, &cap[i++]);
pcie_capability_read_word(pdev, PCI_EXP_SLTCTL2, &cap[i++]);
hlist_add_head(&state->next, &pdev->saved_cap_space);
}
}
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, 0x443, quirk_intel_qat_vf_cap);
/*
* VMD-enabled root ports will change the source ID for all messages
* to the VMD device. Rather than doing device matching with the source
* ID, the AER driver should traverse the child device tree, reading
* AER registers to find the faulting device.
*/
static void quirk_no_aersid(struct pci_dev *pdev)
{
/* VMD Domain */
if (pdev->bus->sysdata && pci_domain_nr(pdev->bus) >= 0x10000)
pdev->bus->bus_flags |= PCI_BUS_FLAGS_NO_AERSID;
}
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, 0x2030, quirk_no_aersid);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, 0x2031, quirk_no_aersid);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, 0x2032, quirk_no_aersid);
DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, 0x2033, quirk_no_aersid);
| aospan/linux-next-bcm4708-edgecore-ecw7220-l | drivers/pci/quirks.c | C | gpl-2.0 | 164,319 |
package ch.dritz.remedy2redmine;
import java.io.File;
import java.io.IOException;
import ch.dritz.common.Config;
import ch.dritz.remedy2redmine.modules.SyncModule;
/**
* Main class for Remedy2Redmine
* @author D.Ritz
*/
public class Main
{
private static void usage(String msg)
{
if (msg != null)
System.out.println("ERROR: " + msg);
System.out.println("Remedy2Redmine " + Version.getVersion());
System.out.println("Usage: Remedy2Redmine <config.properties> <command> [<command specific args>]");
System.out.println(" <command> : one of (sync)");
System.out.println(" <mode specific args> for each mode:");
System.out.println(" - sync: none");
System.out.println("OR: Remedy2Redmine -version");
System.exit(1);
}
/**
* main() entry point
* @param args
* @throws IOException
*/
public static void main(String[] args)
throws Exception
{
if (args.length == 1 && "-version".equals(args[0])) {
System.out.println("Remedy2Redmine " + Version.getVersion());
return;
}
if (args.length < 2)
usage("Not enough arguments");
File configFile = new File(args[0]);
String command = args[1];
Config config = new Config();
config.loadFromFile(configFile);
if ("sync".equals(command)) {
File syncConfig = new File(configFile.getParentFile(),
config.getString("sync.config", "sync.properties"));
config.loadFromFile(syncConfig);
SyncModule sync = new SyncModule(config);
try {
sync.start();
} finally {
sync.shutdown();
}
} else {
usage("Unknown command");
}
}
}
| dr-itz/redmine_remedy_view | java/src/main/java/ch/dritz/remedy2redmine/Main.java | Java | gpl-2.0 | 1,560 |
<?php
/*------------------------------------------------------------------------
# com_universal_ajaxlivesearch - Universal AJAX Live Search
# ------------------------------------------------------------------------
# author Janos Biro
# copyright Copyright (C) 2011 Offlajn.com. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://www.offlajn.com
-------------------------------------------------------------------------*/
// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
require_once(dirname(__FILE__).DS.'image.php');
class OfflajnImageCaching
{ // BEGIN class OfflajnImageCaching
var $cacheDir;
var $cacheUrl;
function OfflajnImageCaching()
{
$path = JPATH_SITE.DS.'images'.DS.'ajaxsearch'.DS;
if(!is_dir($path)){ mkdir($path);}
$this->cacheDir = $path;
$this->cacheUrl = JURI::root().'images/ajaxsearch/';
}
/*
------------------------------------------------------------------------------
Image methods start
*/
function generateImage($product_full_image, $w, $h, $product_name, $transparent=true){
if( substr( $product_full_image, 0, 4) == "http" ) {
$p = "/".str_replace(array("http","/"),array("http(s{0,1})","\\/"), JURI::base())."/";
$url = preg_replace($p ,JPATH_SITE.DS, $product_full_image);
}else{
$product_full_image = str_replace('%20',' ',$product_full_image);
if (@is_file(JPATH_SITE.DS.$product_full_image)){
$url = JPATH_SITE.DS.$product_full_image;
}elseif(@is_file(IMAGEPATH.'product/'.$product_full_image)){
// VM
$url = IMAGEPATH.'product/'.$product_full_image;
}elseif(@is_file($product_full_image)){
// VM
$url = $product_full_image;
}else{
return;
}
}
$cacheName = $this->generateImageCacheName(array($url, $w, $h));
if(!$this->checkImageCache($cacheName)){
if(!$this->createImage($url, $this->cacheDir.$cacheName, $w, $h, $transparent)){
return '';
}
}
$url = $this->cacheUrl.$cacheName;
return "<img width='".$w."' height='".$h."' alt='".$product_name."' src='".$url."' />";
}
function createImage($in, $out, $w, $h, $transparent){
$img = null;
$img = new OfflajnAJAXImageTool($in);
if($img->res === false){
return false;
}
$img->convertToPng();
if ($transparent) $img->resize($w, $h);
else $img->resize2($w, $h);
$img->write($out);
$img->destroy();
return true;
}
function checkImageCache($cacheName){
return is_file($this->cacheDir.$cacheName);
}
function generateImageCacheName($pieces){
return md5(implode('-', $pieces)).'.png';
}
/*
Image methods end
------------------------------------------------------------------------------
*/
} // END class OfflajnImageCaching
?> | knigherrant/decopatio | components/com_universal_ajax_live_search/helpers/caching.php | PHP | gpl-2.0 | 2,863 |
package com.gilecode.langlocker;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "com.gilecode.langlocker"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
super();
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
* )
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
* )
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
/**
* Returns an image descriptor for the image file at the given plug-in
* relative path
*
* @param path
* the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
}
| amogilev/ide-lang-locker | eclipse-plugin/src/com/gilecode/langlocker/Activator.java | Java | gpl-2.0 | 1,423 |
<?php
/*
+---------------------------------------------------------------------------+
| OpenX v2.8 |
| ========== |
| |
| Copyright (c) 2003-2009 OpenX Limited |
| For contact details, see: http://www.openx.org/ |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by |
| the Free Software Foundation; either version 2 of the License, or |
| (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
| |
| You should have received a copy of the GNU General Public License |
| along with this program; if not, write to the Free Software |
| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
+---------------------------------------------------------------------------+
$Id: BasePublisherService.php 81439 2012-05-07 23:59:14Z chris.nutting $
*/
/**
* @package OpenX
* @author Andriy Petlyovanyy <[email protected]>
*
*/
// Require Publisher Service Implementation
require_once MAX_PATH . '/www/api/v2/xmlrpc/PublisherServiceImpl.php';
/**
* Base Publisher Service
*
*/
class BasePublisherService
{
/**
* Reference to Publisher Service implementation.
*
* @var PublisherServiceImpl $_oPublisherServiceImp
*/
var $_oPublisherServiceImp;
/**
* This method initialises Service implementation object field.
*
*/
function BasePublisherService()
{
$this->_oPublisherServiceImp = new PublisherServiceImpl();
}
}
?> | soeffing/openx_test | www/api/v2/common/BasePublisherService.php | PHP | gpl-2.0 | 2,377 |
/***************************************************************************
qgsgeometryduplicatenodescheck.cpp
---------------------
begin : September 2015
copyright : (C) 2014 by Sandro Mani / Sourcepole AG
email : smani at sourcepole dot ch
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsgeometryduplicatenodescheck.h"
#include "qgsgeometryutils.h"
#include "../utils/qgsfeaturepool.h"
void QgsGeometryDuplicateNodesCheck::collectErrors( QList<QgsGeometryCheckError *> &errors, QStringList &/*messages*/, QAtomicInt *progressCounter, const QgsFeatureIds &ids ) const
{
const QgsFeatureIds &featureIds = ids.isEmpty() ? mFeaturePool->getFeatureIds() : ids;
Q_FOREACH ( QgsFeatureId featureid, featureIds )
{
if ( progressCounter ) progressCounter->fetchAndAddRelaxed( 1 );
QgsFeature feature;
if ( !mFeaturePool->get( featureid, feature ) )
{
continue;
}
QgsGeometry featureGeom = feature.geometry();
QgsAbstractGeometry *geom = featureGeom.geometry();
for ( int iPart = 0, nParts = geom->partCount(); iPart < nParts; ++iPart )
{
for ( int iRing = 0, nRings = geom->ringCount( iPart ); iRing < nRings; ++iRing )
{
int nVerts = QgsGeometryCheckerUtils::polyLineSize( geom, iPart, iRing );
if ( nVerts < 2 )
continue;
for ( int iVert = nVerts - 1, jVert = 0; jVert < nVerts; iVert = jVert++ )
{
QgsPoint pi = geom->vertexAt( QgsVertexId( iPart, iRing, iVert ) );
QgsPoint pj = geom->vertexAt( QgsVertexId( iPart, iRing, jVert ) );
if ( QgsGeometryUtils::sqrDistance2D( pi, pj ) < QgsGeometryCheckPrecision::tolerance() * QgsGeometryCheckPrecision::tolerance() )
{
errors.append( new QgsGeometryCheckError( this, featureid, pj, QgsVertexId( iPart, iRing, jVert ) ) );
}
}
}
}
}
}
void QgsGeometryDuplicateNodesCheck::fixError( QgsGeometryCheckError *error, int method, int /*mergeAttributeIndex*/, Changes &changes ) const
{
QgsFeature feature;
if ( !mFeaturePool->get( error->featureId(), feature ) )
{
error->setObsolete();
return;
}
QgsGeometry featureGeom = feature.geometry();
QgsAbstractGeometry *geom = featureGeom.geometry();
QgsVertexId vidx = error->vidx();
// Check if point still exists
if ( !vidx.isValid( geom ) )
{
error->setObsolete();
return;
}
// Check if error still applies
int nVerts = QgsGeometryCheckerUtils::polyLineSize( geom, vidx.part, vidx.ring );
if ( nVerts == 0 )
{
error->setObsolete();
return;
}
QgsPoint pi = geom->vertexAt( QgsVertexId( vidx.part, vidx.ring, ( vidx.vertex + nVerts - 1 ) % nVerts ) );
QgsPoint pj = geom->vertexAt( error->vidx() );
if ( QgsGeometryUtils::sqrDistance2D( pi, pj ) >= QgsGeometryCheckPrecision::tolerance() * QgsGeometryCheckPrecision::tolerance() )
{
error->setObsolete();
return;
}
// Fix error
if ( method == NoChange )
{
error->setFixed( method );
}
else if ( method == RemoveDuplicates )
{
if ( !QgsGeometryCheckerUtils::canDeleteVertex( geom, vidx.part, vidx.ring ) )
{
error->setFixFailed( tr( "Resulting geometry is degenerate" ) );
}
else if ( !geom->deleteVertex( error->vidx() ) )
{
error->setFixFailed( tr( "Failed to delete vertex" ) );
}
else
{
feature.setGeometry( featureGeom );
mFeaturePool->updateFeature( feature );
error->setFixed( method );
changes[error->featureId()].append( Change( ChangeNode, ChangeRemoved, error->vidx() ) );
}
}
else
{
error->setFixFailed( tr( "Unknown method" ) );
}
}
QStringList QgsGeometryDuplicateNodesCheck::getResolutionMethods() const
{
static QStringList methods = QStringList() << tr( "Delete duplicate node" ) << tr( "No action" );
return methods;
}
| GeoCat/QGIS | src/plugins/geometry_checker/checks/qgsgeometryduplicatenodescheck.cpp | C++ | gpl-2.0 | 4,484 |
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Mecab = require('mecab-async');
var mecab = new Mecab();
var MarkovChain = function () {
function MarkovChain(text) {
_classCallCheck(this, MarkovChain);
this.text = text;
this.result = null;
this.dictionary = {};
this.output = 'output';
}
_createClass(MarkovChain, [{
key: 'start',
value: function start(sentence, callback) {
this.parse(sentence, callback);
}
}, {
key: 'parse',
value: function parse(sentence, callback) {
var _this = this;
mecab.parse(this.text, function (err, result) {
_this.dictionary = _this.makeDic(result);
_this.makeSentence(_this.dictionary, sentence);
callback(_this.output);
});
}
}, {
key: 'makeDic',
value: function makeDic(items) {
var tmp = ['@'];
var dic = {};
for (var i in items) {
var t = items[i];
var word = t[0];
word = word.replace(/\s*/, '');
if (word == '' || word == 'EOS') continue;
tmp.push(word);
if (tmp.length < 3) continue;
if (tmp.length > 3) tmp.splice(0, 1);
this.setWord3(dic, tmp);
if (word == '。') {
tmp = ['@'];
continue;
}
}
return dic;
}
}, {
key: 'setWord3',
value: function setWord3(p, s3) {
var w1 = s3[0];
var w2 = s3[1];
var w3 = s3[2];
if (p[w1] == undefined) p[w1] = {};
if (p[w1][w2] == undefined) p[w1][w2] = {};
if (p[w1][w2][w3] == undefined) p[w1][w2][w3] = 0;
p[w1][w2][w3]++;
}
}, {
key: 'makeSentence',
value: function makeSentence(dic, sentence) {
for (var i = 0; i < sentence; i++) {
var ret = [];
var top = dic['@'];
if (!top) continue;
var w1 = this.choiceWord(top);
var w2 = this.choiceWord(top[w1]);
ret.push(w1);
ret.push(w2);
for (;;) {
var w3 = this.choiceWord(dic[w1][w2]);
ret.push(w3);
if (w3 == '。') break;
w1 = w2, w2 = w3;
}
this.output = ret.join('');
return this.output;
}
}
}, {
key: 'objKeys',
value: function objKeys(obj) {
var r = [];
for (var i in obj) {
r.push(i);
}
return r;
}
}, {
key: 'choiceWord',
value: function choiceWord(obj) {
var ks = this.objKeys(obj);
var i = this.rnd(ks.length);
return ks[i];
}
}, {
key: 'rnd',
value: function rnd(num) {
return Math.floor(Math.random() * num);
}
}]);
return MarkovChain;
}();
module.exports = MarkovChain; | uraway/markov-chain-mecab | lib/index.js | JavaScript | gpl-2.0 | 3,365 |
{% include 'overall_header.html' %}
<h2>{{ lang('ABOUTUS') }}</h2>
<div class="panel aboutus">
<div class="inner">
<div class="content">
{{ ABOUTUS_OUTPUT }}
</div>
{% if TERMS_OF_USE or PRIVACY %}
{% if TERMS_OF_USE and PRIVACY %}
<h2>{{ lang('TERMS_USE') }} {{ lang('ABOUTUS_AND') }} {{ lang('PRIVACY') }}</h2>
<p>{{ lang('DESCRIPTION_PRIVACY_TERMS_OF_USE') }} <a href="{{ U_TERMS_USE }}">{{ lang('TERMS_USE') }}</a> {{ lang('ABOUTUS_AND') }} <a href="{{ U_PRIVACY }}">{{ lang('PRIVACY') }}</a></p>
{% elseif PRIVACY %}
<h2>{{ lang('PRIVACY') }}</h2>
<p>{{ lang('DESCRIPTION_PRIVACY') }} <a href="{{ U_PRIVACY }}">{{ lang('PRIVACY') }}</a></p>
{% elseif TERMS_OF_USE %}
<h2>{{ lang('TERMS_USE') }}</h2>
<p>{{ lang('DESCRIPTION_TERMS_OF_USE') }} <a href="{{ U_TERMS_USE }}">{{ lang('TERMS_USE') }}</a></p>
{% endif %}
{% endif %}
</div>
</div>
{% include 'overall_footer.html' %}
| Crizz0/phpbb3-about-us | styles/prosilver/template/aboutus.html | HTML | gpl-2.0 | 932 |
#include<stdio.h>
int main()
{
int *p,i;
int a[10]={12,23,56,1,65,67,87,34,6,23};
p=a;
for(i=0;i<10;i++)
{
printf("%d ",(p+i));
}
return 0;
}
| shubhmsng/Codes | arptr.c | C | gpl-2.0 | 180 |
package org.iatoki.judgels.jerahmeel.user.item;
public final class UserItem {
private final String userJid;
private final String itemJid;
private final UserItemStatus status;
public UserItem(String userJid, String itemJid, UserItemStatus status) {
this.userJid = userJid;
this.itemJid = itemJid;
this.status = status;
}
public String getUserJid() {
return userJid;
}
public String getItemJid() {
return itemJid;
}
public UserItemStatus getStatus() {
return status;
}
}
| judgels/jerahmeel | app/org/iatoki/judgels/jerahmeel/user/item/UserItem.java | Java | gpl-2.0 | 567 |
We would like to propose a manuscript submission to the *Methods* section of Ecology Letters, discussing the use of Partially Observed Markov Decision Processes (POMDP) in ecological research questions. Markov Decision Process (MDP) methods have a long history in ecology, particularly in natural resource management such as fisheries or forestry, and in behavioral ecology (where they are commonly called SDP problems, referring to the stochastic dynamic programming method used to solve them.) POMDPs have seen limited application owing to the complexity of solving them and the lack of appropriate software to do so. Recent breakthroughs in the robotics & artificial intelligence community have made POMDPs for large problems tractable, opening the door to a wide array of ecological problems previously considered intractable in an optimal control framework.
Our proposed methods paper would present a high quality R package we have developed over several years which leverages a recently developed algorithm for solving POMDP problems. We would illustrate the use of the package on both a classic decision problem from fisheries and in extending a recent Ecology Letters paper of ecosystem services (Dee et al, 2017; which received ESA's Innovation in Sustainability Science award) to account for imperfect observations. We believe that these examples coupled with the user friendly R package would catalyze significant breakthroughs in this critical and timely area of conservation decision making.
Authors qualifications: Carl Boettiger, is a theoretical ecologist & assistant professor at UC Berkeley's department Environmental Science, Policy, and Management. Jeroen Ooms is a well-recognized professional software developer with rOpenSci; several of his packages are downloaded over 100,000 times each week. Milad Memarzadeh is a post-doc in Civil & Environmental engineering at UC Berkeley with a PhD from Carnegie Mellon in POMDP methods.
| boettiger-lab/sarsop | articles/proposal.md | Markdown | gpl-2.0 | 1,961 |
/*
* Read flash partition table from command line
*
* Copyright © 2002 SYSGO Real-Time Solutions GmbH
* Copyright © 2002-2010 David Woodhouse <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* The format for the command line is as follows:
*
* mtdparts=<mtddef>[;<mtddef]
* <mtddef> := <mtd-id>:<partdef>[,<partdef>]
* where <mtd-id> is the name from the "cat /proc/mtd" command
* <partdef> := <size>[@offset][<name>][ro][lk]
* <mtd-id> := unique name used in mapping driver/device (mtd->name)
* <size> := standard linux memsize OR "-" to denote all remaining space
* <name> := '(' NAME ')'
*
* Examples:
*
* 1 NOR Flash, with 1 single writable partition:
* edb7312-nor:-
*
* 1 NOR Flash with 2 partitions, 1 NAND with one
* edb7312-nor:256k(ARMboot)ro,-(root);edb7312-nand:-(home)
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/bootmem.h>
/* error message prefix */
#define ERRP "mtd: "
/* debug macro */
#if 0
#define dbg(x) do { printk("DEBUG-CMDLINE-PART: "); printk x; } while(0)
#else
#define dbg(x)
#endif
/* special size referring to all the remaining space in a partition */
#define SIZE_REMAINING UINT_MAX
#define OFFSET_CONTINUOUS UINT_MAX
struct cmdline_mtd_partition {
struct cmdline_mtd_partition *next;
char *mtd_id;
int num_parts;
struct mtd_partition *parts;
};
/* mtdpart_setup() parses into here */
static struct cmdline_mtd_partition *partitions;
/* the command line passed to mtdpart_setupd() */
static char *cmdline;
static int cmdline_parsed = 0;
/*
* Parse one partition definition for an MTD. Since there can be many
* comma separated partition definitions, this function calls itself
* recursively until no more partition definitions are found. Nice side
* effect: the memory to keep the mtd_partition structs and the names
* is allocated upon the last definition being found. At that point the
* syntax has been verified ok.
*/
static struct mtd_partition * newpart(char *s,
char **retptr,
int *num_parts,
int this_part,
unsigned char **extra_mem_ptr,
int extra_mem_size)
{
struct mtd_partition *parts;
unsigned long size;
unsigned long offset = OFFSET_CONTINUOUS;
char *name;
int name_len;
unsigned char *extra_mem;
char delim;
unsigned int mask_flags;
/* fetch the partition size */
if (*s == '-')
{ /* assign all remaining space to this partition */
size = SIZE_REMAINING;
s++;
}
else
{
size = memparse(s, &s);
if (size < PAGE_SIZE)
{
printk(KERN_ERR ERRP "partition size too small (%lx)\n", size);
return NULL;
}
}
/* fetch partition name and flags */
mask_flags = 0; /* this is going to be a regular partition */
delim = 0;
/* check for offset */
if (*s == '@')
{
s++;
offset = memparse(s, &s);
}
/* now look for name */
if (*s == '(')
{
delim = ')';
}
if (delim)
{
char *p;
name = ++s;
p = strchr(name, delim);
if (!p)
{
printk(KERN_ERR ERRP "no closing %c found in partition name\n", delim);
return NULL;
}
name_len = p - name;
s = p + 1;
}
else
{
name = NULL;
name_len = 13; /* Partition_000 */
}
/* record name length for memory allocation later */
extra_mem_size += name_len + 1;
/* test for options */
if (strncmp(s, "ro", 2) == 0)
{
mask_flags |= MTD_WRITEABLE;
s += 2;
}
/* if lk is found do NOT unlock the MTD partition*/
if (strncmp(s, "lk", 2) == 0)
{
mask_flags |= MTD_POWERUP_LOCK;
s += 2;
}
/* test if more partitions are following */
if (*s == ',')
{
if (size == SIZE_REMAINING)
{
printk(KERN_ERR ERRP "no partitions allowed after a fill-up partition\n");
return NULL;
}
/* more partitions follow, parse them */
parts = newpart(s + 1, &s, num_parts, this_part + 1,
&extra_mem, extra_mem_size);
if (!parts)
return NULL;
}
else
{ /* this is the last partition: allocate space for all */
int alloc_size;
*num_parts = this_part + 1;
alloc_size = *num_parts * sizeof(struct mtd_partition) +
extra_mem_size;
parts = kzalloc(alloc_size, GFP_KERNEL);
if (!parts)
{
printk(KERN_ERR ERRP "out of memory\n");
return NULL;
}
extra_mem = (unsigned char *)(parts + *num_parts);
}
/* enter this partition (offset will be calculated later if it is zero at this point) */
parts[this_part].size = size;
parts[this_part].offset = offset;
parts[this_part].mask_flags = mask_flags;
if (name)
{
strlcpy((char *)extra_mem, name, name_len + 1);
}
else
{
sprintf((char *)extra_mem, "Partition_%03d", this_part);
}
parts[this_part].name = (char *)extra_mem;
extra_mem += name_len + 1;
dbg(("partition %d: name <%s>, offset %llx, size %llx, mask flags %x\n",
this_part,
parts[this_part].name,
parts[this_part].offset,
parts[this_part].size,
parts[this_part].mask_flags));
/* return (updated) pointer to extra_mem memory */
if (extra_mem_ptr)
*extra_mem_ptr = extra_mem;
/* return (updated) pointer command line string */
*retptr = s;
/* return partition table */
return parts;
}
/*
* Parse the command line.
*/
static int mtdpart_setup_real(char *s)
{
cmdline_parsed = 1;
for( ; s != NULL; )
{
struct cmdline_mtd_partition *this_mtd;
struct mtd_partition *parts;
int mtd_id_len;
int num_parts;
char *p, *mtd_id;
mtd_id = s;
/* fetch <mtd-id> */
if (!(p = strchr(s, ':')))
{
printk(KERN_ERR ERRP "no mtd-id\n");
return 0;
}
mtd_id_len = p - mtd_id;
dbg(("parsing <%s>\n", p+1));
/*
* parse one mtd. have it reserve memory for the
* struct cmdline_mtd_partition and the mtd-id string.
*/
parts = newpart(p + 1, /* cmdline */
&s, /* out: updated cmdline ptr */
&num_parts, /* out: number of parts */
0, /* first partition */
(unsigned char**)&this_mtd, /* out: extra mem */
mtd_id_len + 1 + sizeof(*this_mtd) +
sizeof(void*)-1 /*alignment*/);
if(!parts)
{
/*
* An error occurred. We're either:
* a) out of memory, or
* b) in the middle of the partition spec
* Either way, this mtd is hosed and we're
* unlikely to succeed in parsing any more
*/
return 0;
}
/* align this_mtd */
this_mtd = (struct cmdline_mtd_partition *)
ALIGN((unsigned long)this_mtd, sizeof(void*));
/* enter results */
this_mtd->parts = parts;
this_mtd->num_parts = num_parts;
this_mtd->mtd_id = (char*)(this_mtd + 1);
strlcpy(this_mtd->mtd_id, mtd_id, mtd_id_len + 1);
/* link into chain */
this_mtd->next = partitions;
partitions = this_mtd;
dbg(("mtdid=<%s> num_parts=<%d>\n",
this_mtd->mtd_id, this_mtd->num_parts));
/* EOS - we're done */
if (*s == 0)
break;
/* does another spec follow? */
if (*s != ';')
{
printk(KERN_ERR ERRP "bad character after partition (%c)\n", *s);
return 0;
}
s++;
}
return 1;
}
/*
* Main function to be called from the MTD mapping driver/device to
* obtain the partitioning information. At this point the command line
* arguments will actually be parsed and turned to struct mtd_partition
* information. It returns partitions for the requested mtd device, or
* the first one in the chain if a NULL mtd_id is passed in.
*/
static int parse_cmdline_partitions(struct mtd_info *master,
struct mtd_partition **pparts,
unsigned long origin)
{
unsigned long offset;
int i;
struct cmdline_mtd_partition *part;
const char *mtd_id = master->name;
/* parse command line */
if (!cmdline_parsed)
mtdpart_setup_real(cmdline);
for(part = partitions; part; part = part->next)
{
if ((!mtd_id) || (!strcmp(part->mtd_id, mtd_id)))
{
for(i = 0, offset = 0; i < part->num_parts; i++)
{
if (part->parts[i].offset == OFFSET_CONTINUOUS)
part->parts[i].offset = offset;
else
offset = part->parts[i].offset;
if (part->parts[i].size == SIZE_REMAINING)
part->parts[i].size = master->size - offset;
if (offset + part->parts[i].size > master->size)
{
printk(KERN_WARNING ERRP
"%s: partitioning exceeds flash size, truncating\n",
part->mtd_id);
part->parts[i].size = master->size - offset;
part->num_parts = i;
}
offset += part->parts[i].size;
}
*pparts = kmemdup(part->parts,
sizeof(*part->parts) * part->num_parts,
GFP_KERNEL);
if (!*pparts)
return -ENOMEM;
return part->num_parts;
}
}
return 0;
}
/*
* This is the handler for our kernel parameter, called from
* main.c::checksetup(). Note that we can not yet kmalloc() anything,
* so we only save the commandline for later processing.
*
* This function needs to be visible for bootloaders.
*/
static int mtdpart_setup(char *s)
{
cmdline = s;
return 1;
}
__setup("mtdparts=", mtdpart_setup);
static struct mtd_part_parser cmdline_parser = {
.owner = THIS_MODULE,
.parse_fn = parse_cmdline_partitions,
.name = "cmdlinepart",
};
static int __init cmdline_parser_init(void)
{
return register_mtd_parser(&cmdline_parser);
}
module_init(cmdline_parser_init);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Marius Groeger <[email protected]>");
MODULE_DESCRIPTION("Command line configuration of MTD partitions");
| de-wolff/android_kernel_motorola_xt320 | drivers/mtd/cmdlinepart.c | C | gpl-2.0 | 10,218 |
package FusionInventory::Agent::SNMP::MibSupport::Brocade;
use strict;
use warnings;
use parent 'FusionInventory::Agent::SNMP::MibSupportTemplate';
use FusionInventory::Agent::Tools;
use FusionInventory::Agent::Tools::SNMP;
use constant brocade => '.1.3.6.1.4.1.1991' ;
use constant serial => brocade .'.1.1.1.1.2.0' ;
use constant fw_pri => brocade . '.1.1.2.1.11.0' ;
our $mibSupport = [
{
name => "brocade-switch",
sysobjectid => getRegexpOidMatch(brocade)
}
];
sub getSerial {
my ($self) = @_;
return $self->get(serial);
}
sub getFirmware {
my ($self) = @_;
return $self->get(fw_pri);
}
1;
__END__
=head1 NAME
Inventory module for Brocade Switches
=head1 DESCRIPTION
The module enhances Brocade Switches devices support.
| po1vo/fusioninventory-agent | lib/FusionInventory/Agent/SNMP/MibSupport/Brocade.pm | Perl | gpl-2.0 | 801 |
#ifndef SC_BOOST_MPL_BOOL_HPP_INCLUDED
#define SC_BOOST_MPL_BOOL_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Source: /Users/acg/CVSROOT/systemc-2.3/src/sysc/packages/boost/mpl/bool.hpp,v $
// $Date: 2009/10/14 19:11:02 $
// $Revision: 1.2 $
#include <sysc/packages/boost/mpl/bool_fwd.hpp>
#include <sysc/packages/boost/mpl/integral_c_tag.hpp>
#include <sysc/packages/boost/mpl/aux_/config/static_constant.hpp>
SC_BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN
template< bool C_ > struct bool_
{
SC_BOOST_STATIC_CONSTANT(bool, value = C_);
typedef integral_c_tag tag;
typedef bool_ type;
typedef bool value_type;
operator bool() const { return this->value; }
};
#if !defined(SC_BOOST_NO_INCLASS_MEMBER_INITIALIZATION)
template< bool C_ >
bool const bool_<C_>::value;
#endif
SC_BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE
#endif // SC_BOOST_MPL_BOOL_HPP_INCLUDED
| channgo2203/MAG | systemc-2.3.0_modified/src/sysc/packages/boost/mpl/bool.hpp | C++ | gpl-2.0 | 1,115 |
#ifndef TPPROTO_COMMANDPARAMETER_H
#define TPPROTO_COMMANDPARAMETER_H
/* CommandParameter Classes
*
* Copyright (C) 2008 Aaron Mavrinac and the Thousand Parsec Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*! \file
\brief Declares CommandParameter classes and the CommandParamType enum.
*/
#include <string>
#include <stdint.h>
namespace TPProto{
enum CommandParamType{
cpT_Invalid = -1,
cpT_String = 0,
cpT_Integer = 1,
cpT_Max
};
class Buffer;
/*! \brief Baseclass for holding a parameter for a Command.
*/
class CommandParameter{
public:
CommandParameter();
CommandParameter(const CommandParameter &rhs);
virtual ~CommandParameter();
virtual void packBuffer(Buffer* buf) = 0;
virtual bool unpackBuffer(Buffer* buf) = 0;
virtual CommandParameter* clone() = 0;
virtual bool setValueFromString(const std::string &nval) = 0;
std::string getName();
std::string getDescription();
void setName(const std::string &nn);
void setDescription(const std::string &nd);
private:
std::string name;
std::string description;
};
/*! \brief Holds a string CommandParameter.
*/
class StringCommandParameter : public CommandParameter{
public:
StringCommandParameter();
StringCommandParameter(const StringCommandParameter &rhs);
~StringCommandParameter();
void packBuffer(Buffer* buf);
bool unpackBuffer(Buffer* buf);
CommandParameter* clone();
bool setValueFromString(const std::string &nval);
unsigned int getMaxLength();
std::string getString();
void setString(const std::string &nval);
private:
unsigned int maxlength;
std::string value;
};
/*! \brief A CommandParameter that holds an integer.
*/
class IntegerCommandParameter : public CommandParameter{
public:
IntegerCommandParameter();
IntegerCommandParameter(const IntegerCommandParameter &rhs);
~IntegerCommandParameter();
void packBuffer(Buffer* buf);
bool unpackBuffer(Buffer* buf);
CommandParameter* clone();
bool setValueFromString(const std::string &nval);
uint32_t getValue() const;
void setValue(uint32_t nval);
private:
uint32_t value;
};
}
#endif
| thousandparsec/libtpproto-cpp | tpproto/commandparameter.h | C | gpl-2.0 | 3,144 |
require 'test_helper'
class CompetencePeriodTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| azzlo/calyfi | test/models/competence_period_test.rb | Ruby | gpl-2.0 | 130 |
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Test that the file is open for read acces when the applications specify
* the value of O_RDWR.
*
* Step:
* 1. Create a file a shared memory object using shm_open().
* 2. Write in the file referenced by the file descriptor return by
* shm_open().
* 3. Reopen the file with shm_open() and O_RDWR set.
* 4. Read in the file.
* The test pass if it read what it was previously written.
*/
/* ftruncate was formerly an XOPEN extension. We define _XOPEN_SOURCE here to
avoid warning if the implementation does not program ftruncate as a base
interface */
#define _XOPEN_SOURCE 600
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include "posixtest.h"
#define BUF_SIZE 8
#define SHM_NAME "posixtest_14-2"
int main() {
int fd;
char str[BUF_SIZE] = "qwerty";
char *buf;
fd = shm_open(SHM_NAME, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR);
if (fd == -1) {
perror("An error occurs when calling shm_open()");
return PTS_UNRESOLVED;
}
if (ftruncate(fd, BUF_SIZE) != 0) {
perror("An error occurs when calling ftruncate()");
return PTS_UNRESOLVED;
}
buf = mmap(NULL, BUF_SIZE, PROT_WRITE, MAP_SHARED, fd, 0);
if (buf == MAP_FAILED) {
perror("An error occurs when calling mmap()");
return PTS_UNRESOLVED;
}
strcpy(buf, str);
fd = shm_open(SHM_NAME, O_RDWR, S_IRUSR|S_IWUSR);
if (fd == -1) {
perror("An error occurs when calling shm_open()");
return PTS_UNRESOLVED;
}
buf = mmap(NULL, BUF_SIZE, PROT_READ, MAP_SHARED, fd, 0);
if (buf == MAP_FAILED) {
perror("An error occurs when calling mmap()");
return PTS_UNRESOLVED;
}
shm_unlink(SHM_NAME);
if (strcmp(buf, str) == 0) {
printf("Test PASSED\n");
return PTS_PASS;
}
printf("Test FAILED\n");
return PTS_FAIL;
} | anthony-kolesov/arc_ltp | testcases/open_posix_testsuite/conformance/interfaces/shm_open/14-2.c | C | gpl-2.0 | 2,192 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.