code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.05.03 at 03:15:27 PM EDT // package API.amazon.mws.xml.JAXB; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="value"> * &lt;complexType> * &lt;simpleContent> * &lt;extension base="&lt;>String200Type"> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * &lt;/element> * &lt;/sequence> * &lt;attribute name="delete" type="{}BooleanType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) @XmlRootElement(name = "cdrh_classification") public class CdrhClassification { @XmlElement(required = true) protected CdrhClassification.Value value; @XmlAttribute(name = "delete") protected BooleanType delete; /** * Gets the value of the value property. * * @return * possible object is * {@link CdrhClassification.Value } * */ public CdrhClassification.Value getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link CdrhClassification.Value } * */ public void setValue(CdrhClassification.Value value) { this.value = value; } /** * Gets the value of the delete property. * * @return * possible object is * {@link BooleanType } * */ public BooleanType getDelete() { return delete; } /** * Sets the value of the delete property. * * @param value * allowed object is * {@link BooleanType } * */ public void setDelete(BooleanType value) { this.delete = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;simpleContent> * &lt;extension base="&lt;>String200Type"> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "value" }) public static class Value { @XmlValue protected String value; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } } }
VDuda/SyncRunner-Pub
src/API/amazon/mws/xml/JAXB/CdrhClassification.java
Java
mit
3,909
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com> namespace Marius.Html.Hap { /// <summary> /// Represents a base class for fragments in a mixed code document. /// </summary> public abstract class MixedCodeDocumentFragment { #region Fields internal MixedCodeDocument Doc; private string _fragmentText; internal int Index; internal int Length; private int _line; internal int _lineposition; internal MixedCodeDocumentFragmentType _type; #endregion #region Constructors internal MixedCodeDocumentFragment(MixedCodeDocument doc, MixedCodeDocumentFragmentType type) { Doc = doc; _type = type; switch (type) { case MixedCodeDocumentFragmentType.Text: Doc._textfragments.Append(this); break; case MixedCodeDocumentFragmentType.Code: Doc._codefragments.Append(this); break; } Doc._fragments.Append(this); } #endregion #region Properties /// <summary> /// Gets the fragement text. /// </summary> public string FragmentText { get { if (_fragmentText == null) { _fragmentText = Doc._text.Substring(Index, Length); } return FragmentText; } internal set { _fragmentText = value; } } /// <summary> /// Gets the type of fragment. /// </summary> public MixedCodeDocumentFragmentType FragmentType { get { return _type; } } /// <summary> /// Gets the line number of the fragment. /// </summary> public int Line { get { return _line; } internal set { _line = value; } } /// <summary> /// Gets the line position (column) of the fragment. /// </summary> public int LinePosition { get { return _lineposition; } } /// <summary> /// Gets the fragment position in the document's stream. /// </summary> public int StreamPosition { get { return Index; } } #endregion } }
marius-klimantavicius/marius-html
Marius.Html/Hap/MixedCodeDocumentFragment.cs
C#
mit
2,555
import React from 'react' import { User } from '../../lib/accounts/users' import styled from '../../lib/styled' import MdiIcon from '@mdi/react' import { mdiAccount } from '@mdi/js' import { SectionPrimaryButton } from './styled' import { useTranslation } from 'react-i18next' interface UserProps { user: User signout: (user: User) => void } const Container = styled.div` margin-bottom: 8px; ` export default ({ user, signout }: UserProps) => { const { t } = useTranslation() return ( <Container> <MdiIcon path={mdiAccount} size='80px' /> <p>{user.name}</p> <SectionPrimaryButton onClick={() => signout(user)}> {t('general.signOut')} </SectionPrimaryButton> </Container> ) }
Sarah-Seo/Inpad
src/components/PreferencesModal/UserInfo.tsx
TypeScript
mit
731
#include "TextItem.h" #include <QPainter> #include <QFont> #include <QDebug> //////////////////////////////////////////////////////////////// TextItem::TextItem(const QString& text, QGraphicsLayoutItem *parent) : BaseItem(parent) { _text = text; QFont font; font.setPointSize(11); font.setBold(false); setFont(font); } //////////////////////////////////////////////////////////////// TextItem::~TextItem() { } //////////////////////////////////////////////////////////////// void TextItem::setFont(const QFont &font) { _font = font; QFontMetrics fm(_font); } //////////////////////////////////////////////////////////////// QSizeF TextItem::measureSize() const { QFontMetrics fm(_font); const QSizeF& size = fm.size(Qt::TextExpandTabs, _text); // NOTE: flag Qt::TextSingleLine ignores newline characters. return size; } //////////////////////////////////////////////////////////////// void TextItem::draw(QPainter *painter, const QRectF& bounds) { painter->setFont(_font); // TODO: mozno bude treba specialne handlovat novy riadok painter->drawText(bounds, _text); }
AdUki/GraphicEditor
GraphicEditor/Ui/Items/TextItem.cpp
C++
mit
1,137
import {writeFile} from 'fs-promise'; import {get, has, merge, set} from 'lodash/fp'; import flatten from 'flat'; import fs from 'fs'; import path from 'path'; const data = new WeakMap(); const initial = new WeakMap(); export default class Config { constructor(d) { data.set(this, d); initial.set(this, Object.assign({}, d)); } clone() { return Object.assign({}, data.get(this)); } get(keypath) { return get(keypath, data.get(this)); } has(keypath) { return has(keypath, data.get(this)); } inspect() { return data.get(this); } merge(extra) { data.set(this, merge(data.get(this), extra)); } set(keypath, value) { return set(keypath, data.get(this), value); } async save() { const out = this.toString(); return await writeFile(`.boilerizerc`, out); } toJSON() { const keys = Object.keys(flatten(data.get(this), {safe: true})); const init = initial.get(this); let target; try { const filepath = path.join(process.cwd(), `.boilerizerc`); // Using sync here because toJSON can't have async functions in it // eslint-disable-next-line no-sync const raw = fs.readFileSync(filepath, `utf8`); target = JSON.parse(raw); } catch (e) { if (e.code !== `ENOENT`) { console.error(e); throw e; } target = {}; } return keys.reduce((acc, key) => { if (!has(key, init) || has(key, target)) { const val = this.get(key); acc = set(key, val, acc); } return acc; }, target); } toString() { return JSON.stringify(this, null, 2); } }
ianwremmel/boilerize
src/lib/config.js
JavaScript
mit
1,639
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.dfa.report; public class ClassNode extends AbstractReportNode { private String className; public ClassNode(String className) { this.className = className; } public String getClassName() { return className; } public boolean equalsNode(AbstractReportNode arg0) { if (!(arg0 instanceof ClassNode)) { return false; } return ((ClassNode) arg0).getClassName().equals(className); } }
byronka/xenos
utils/pmd-bin-5.2.2/src/pmd-core/src/main/java/net/sourceforge/pmd/lang/dfa/report/ClassNode.java
Java
mit
585
<?php namespace Helpers; /** *This class handles rendering of view files * *@author Geoffrey Oliver <geoffrey.oliver2@gmail.com> *@copyright Copyright (c) 2015 - 2020 Geoffrey Oliver *@link http://libraries.gliver.io *@category Core *@package Core\Helpers\View */ use Drivers\Templates\Implementation; use Exceptions\BaseException; use Drivers\Cache\CacheBase; use Drivers\Registry; class View { /** *This is the constructor class. We make this private to avoid creating instances of *this object * *@param null *@return void */ private function __construct() {} /** *This method stops creation of a copy of this object by making it private * *@param null *@return void * */ private function __clone(){} /** *This method parses the input variables and loads the specified views * *@param string $filePath the string that specifies the view file to load *@param array $data an array with variables to be passed to the view file *@return void This method does not return anything, it directly loads the view file *@throws */ public static function render($filePath, array $data = null) { //this try block is excecuted to enable throwing and catching of errors as appropriate try { //get the variables passed and make them available to the view if ( $data != null) { //loop through the array setting the respective variables foreach ($data as $key => $value) { $$key = $value; } } //get the parsed contents of the template file $contents = self::getContents($filePath); //start the output buffer ob_start(); //evaluate the contents of this view file eval("?>" . $contents . "<?"); //get the evaluated contents $contents = ob_get_contents(); //clean the output buffer ob_end_clean(); //return the evaluated contents echo $contents; //stop further script execution exit(); } catch(BaseException $e) { //echo $e->getMessage(); $e->show(); } catch(Exception $e) { echo $e->getMessage(); } } /** *This method converts the code into valid php code * *@param string $file The name of the view whose contant is to be parsed *@return string $parsedContent The parsed content of the template file */ public static function getContents($filePath) { //compose the file full path $path = Path::view($filePath); //get an instance of the view template class $template = Registry::get('template'); //get the compiled file contents $contents = $template->compiled($path); //return the compiled template file contents return $contents; } }
ggiddy/documentation
system/Helpers/View.php
PHP
mit
3,113
package pl.mmorpg.prototype.server.objects.monsters.properties.builders; import pl.mmorpg.prototype.clientservercommon.packets.monsters.properties.MonsterProperties; public class SnakePropertiesBuilder extends MonsterProperties.Builder { @Override public MonsterProperties build() { experienceGain(100) .hp(100) .strength(5) .level(1); return super.build(); } }
Pankiev/MMORPG_Prototype
Server/core/src/pl/mmorpg/prototype/server/objects/monsters/properties/builders/SnakePropertiesBuilder.java
Java
mit
384
#! python3 """ GUI for Ultrasonic Temperature Controller Copyright (c) 2015 by Stefan Lehmann """ import os import datetime import logging import json import serial from qtpy.QtWidgets import QAction, QDialog, QMainWindow, QMessageBox, \ QDockWidget, QLabel, QFileDialog, QApplication from qtpy.QtGui import QIcon from qtpy.QtCore import QSettings, QCoreApplication, Qt, QThread, \ Signal from serial.serialutil import SerialException from jsonwatch.jsonitem import JsonItem from jsonwatch.jsonnode import JsonNode from jsonwatchqt.logger import LoggingWidget from pyqtconfig.config import QSettingsManager from jsonwatchqt.plotsettings import PlotSettingsWidget from jsonwatchqt.objectexplorer import ObjectExplorer from jsonwatchqt.plotwidget import PlotWidget from jsonwatchqt.serialdialog import SerialDialog, PORT_SETTING, \ BAUDRATE_SETTING from jsonwatchqt.utilities import critical, pixmap from jsonwatchqt.recorder import RecordWidget from jsonwatchqt.csvsettings import CSVSettingsDialog, DECIMAL_SETTING, \ SEPARATOR_SETTING logger = logging.getLogger("jsonwatchqt.mainwindow") WINDOWSTATE_SETTING = "mainwindow/windowstate" GEOMETRY_SETTING = "mainwindow/geometry" FILENAME_SETTING = "mainwindow/filename" def strip(s): return s.strip() def utf8_to_bytearray(x): return bytearray(x, 'utf-8') def bytearray_to_utf8(x): return x.decode('utf-8') def set_default_settings(settings: QSettingsManager): settings.set_defaults({ DECIMAL_SETTING: ',', SEPARATOR_SETTING: ';' }) class SerialWorker(QThread): data_received = Signal(datetime.datetime, str) def __init__(self, ser: serial.Serial, parent=None): super().__init__(parent) self.serial = ser self._quit = False def run(self): while not self._quit: try: if self.serial.isOpen() and self.serial.inWaiting(): self.data_received.emit( datetime.datetime.now(), strip(bytearray_to_utf8(self.serial.readline())) ) except SerialException: pass def quit(self): self._quit = True class MainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.recording_enabled = False self.serial = serial.Serial() self.rootnode = JsonNode('') self._connected = False self._dirty = False self._filename = None # settings self.settings = QSettingsManager() set_default_settings(self.settings) # Controller Settings self.settingsDialog = None # object explorer self.objectexplorer = ObjectExplorer(self.rootnode, self) self.objectexplorer.nodevalue_changed.connect(self.send_serialdata) self.objectexplorer.nodeproperty_changed.connect(self.set_dirty) self.objectexplorerDockWidget = QDockWidget(self.tr("object explorer"), self) self.objectexplorerDockWidget.setObjectName( "objectexplorer_dockwidget") self.objectexplorerDockWidget.setWidget(self.objectexplorer) # plot widget self.plot = PlotWidget(self.rootnode, self.settings, self) # plot settings self.plotsettings = PlotSettingsWidget(self.settings, self.plot, self) self.plotsettingsDockWidget = QDockWidget(self.tr("plot settings"), self) self.plotsettingsDockWidget.setObjectName("plotsettings_dockwidget") self.plotsettingsDockWidget.setWidget(self.plotsettings) # log widget self.loggingWidget = LoggingWidget(self) self.loggingDockWidget = QDockWidget(self.tr("logger"), self) self.loggingDockWidget.setObjectName("logging_dockwidget") self.loggingDockWidget.setWidget(self.loggingWidget) # record widget self.recordWidget = RecordWidget(self.rootnode, self) self.recordDockWidget = QDockWidget(self.tr("data recording"), self) self.recordDockWidget.setObjectName("record_dockwidget") self.recordDockWidget.setWidget(self.recordWidget) # actions and menus self._init_actions() self._init_menus() # statusbar statusbar = self.statusBar() statusbar.setVisible(True) self.connectionstateLabel = QLabel(self.tr("Not connected")) statusbar.addPermanentWidget(self.connectionstateLabel) statusbar.showMessage(self.tr("Ready")) # layout self.setCentralWidget(self.plot) self.addDockWidget(Qt.LeftDockWidgetArea, self.objectexplorerDockWidget) self.addDockWidget(Qt.LeftDockWidgetArea, self.plotsettingsDockWidget) self.addDockWidget(Qt.BottomDockWidgetArea, self.loggingDockWidget) self.addDockWidget(Qt.BottomDockWidgetArea, self.recordDockWidget) self.load_settings() def _init_actions(self): # Serial Dialog self.serialdlgAction = QAction(self.tr("Serial Settings..."), self) self.serialdlgAction.setShortcut("F6") self.serialdlgAction.setIcon(QIcon(pixmap("configure.png"))) self.serialdlgAction.triggered.connect(self.show_serialdlg) # Connect self.connectAction = QAction(self.tr("Connect"), self) self.connectAction.setShortcut("F5") self.connectAction.setIcon(QIcon(pixmap("network-connect-3.png"))) self.connectAction.triggered.connect(self.toggle_connect) # Quit self.quitAction = QAction(self.tr("Quit"), self) self.quitAction.setShortcut("Alt+F4") self.quitAction.setIcon(QIcon(pixmap("window-close-3.png"))) self.quitAction.triggered.connect(self.close) # Save Config as self.saveasAction = QAction(self.tr("Save as..."), self) self.saveasAction.setShortcut("Ctrl+Shift+S") self.saveasAction.setIcon(QIcon(pixmap("document-save-as-5.png"))) self.saveasAction.triggered.connect(self.show_savecfg_dlg) # Save file self.saveAction = QAction(self.tr("Save"), self) self.saveAction.setShortcut("Ctrl+S") self.saveAction.setIcon(QIcon(pixmap("document-save-5.png"))) self.saveAction.triggered.connect(self.save_file) # Load file self.loadAction = QAction(self.tr("Open..."), self) self.loadAction.setShortcut("Ctrl+O") self.loadAction.setIcon(QIcon(pixmap("document-open-7.png"))) self.loadAction.triggered.connect(self.show_opencfg_dlg) # New self.newAction = QAction(self.tr("New"), self) self.newAction.setShortcut("Ctrl+N") self.newAction.setIcon(QIcon(pixmap("document-new-6.png"))) self.newAction.triggered.connect(self.new) # start recording self.startrecordingAction = QAction(self.tr("Start recording"), self) self.startrecordingAction.setShortcut("F9") self.startrecordingAction.setIcon(QIcon(pixmap("media-record-6.png"))) self.startrecordingAction.triggered.connect(self.start_recording) # stop recording self.stoprecordingAction = QAction(self.tr("Stop recording"), self) self.stoprecordingAction.setShortcut("F10") self.stoprecordingAction.setIcon(QIcon(pixmap("media-playback-stop-8.png"))) self.stoprecordingAction.setEnabled(False) self.stoprecordingAction.triggered.connect(self.stop_recording) # clear record self.clearrecordAction = QAction(self.tr("Clear"), self) self.clearrecordAction.setIcon(QIcon(pixmap("editclear.png"))) self.clearrecordAction.triggered.connect(self.clear_record) # export record self.exportcsvAction = QAction(self.tr("Export to csv..."), self) self.exportcsvAction.setIcon(QIcon(pixmap("text_csv.png"))) self.exportcsvAction.triggered.connect(self.export_csv) # show record settings self.recordsettingsAction = QAction(self.tr("Settings..."), self) self.recordsettingsAction.setIcon(QIcon(pixmap("configure.png"))) self.recordsettingsAction.triggered.connect(self.show_recordsettings) # Info self.infoAction = QAction(self.tr("Info"), self) self.infoAction.setShortcut("F1") self.infoAction.triggered.connect(self.show_info) def _init_menus(self): # file menu self.fileMenu = self.menuBar().addMenu(self.tr("File")) self.fileMenu.addAction(self.newAction) self.fileMenu.addAction(self.loadAction) self.fileMenu.addAction(self.saveAction) self.fileMenu.addAction(self.saveasAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.connectAction) self.fileMenu.addAction(self.serialdlgAction) self.fileMenu.addSeparator() self.fileMenu.addAction(self.quitAction) # view menu self.viewMenu = self.menuBar().addMenu(self.tr("View")) self.viewMenu.addAction( self.objectexplorerDockWidget.toggleViewAction()) self.viewMenu.addAction(self.plotsettingsDockWidget.toggleViewAction()) self.viewMenu.addAction(self.loggingDockWidget.toggleViewAction()) self.viewMenu.addAction(self.recordDockWidget.toggleViewAction()) # record menu self.recordMenu = self.menuBar().addMenu(self.tr("Record")) self.recordMenu.addAction(self.startrecordingAction) self.recordMenu.addAction(self.stoprecordingAction) self.recordMenu.addAction(self.exportcsvAction) self.recordMenu.addSeparator() self.recordMenu.addAction(self.clearrecordAction) self.recordMenu.addSeparator() self.recordMenu.addAction(self.recordsettingsAction) # info menu self.menuBar().addAction(self.infoAction) def show_info(self): QMessageBox.about( self, QApplication.applicationName(), "%s %s\n" "Copyright (c) by %s" % ( QCoreApplication.applicationName(), QCoreApplication.applicationVersion(), QCoreApplication.organizationName(), ) ) def load_file(self, filename): old_filename = self.filename if self.filename != filename else None self.filename = filename try: with open(filename, 'rb') as f: try: self.objectexplorer.model().beginResetModel() self.rootnode.load(bytearray_to_utf8(f.read())) self.objectexplorer.model().endResetModel() except ValueError as e: critical(self, "File '%s' is not a valid config file." % filename) logger.error(str(e)) if old_filename is not None: self.load_file(old_filename) else: self.filename = None except FileNotFoundError as e: logger.error(str(e)) self.filename = None self.objectexplorer.refresh() def load_settings(self): settings = QSettings() # window geometry try: self.restoreGeometry(settings.value(GEOMETRY_SETTING)) except: logger.debug("error restoring window geometry") # window state try: self.restoreState(settings.value(WINDOWSTATE_SETTING)) except: logger.debug("error restoring window state") # filename self.filename = settings.value(FILENAME_SETTING) if self.filename is not None: self.load_file(self.filename) def save_settings(self): settings = QSettings() settings.setValue(WINDOWSTATE_SETTING, self.saveState()) settings.setValue(GEOMETRY_SETTING, self.saveGeometry()) settings.setValue(FILENAME_SETTING, self.filename) def closeEvent(self, event): if self.dirty: res = QMessageBox.question( self, QCoreApplication.applicationName(), self.tr("Save changes to file '%s'?" % self.filename if self.filename is not None else "unknown"), QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel ) if res == QMessageBox.Cancel: event.ignore() return elif res == QMessageBox.Yes: self.save_file() self.save_settings() try: self.worker.quit() except AttributeError: pass try: self.serial.close() except (SerialException, AttributeError): pass def new(self): self.objectexplorer.model().beginResetModel() self.rootnode.clear() self.objectexplorer.model().endResetModel() def send_reset(self): jsonstring = json.dumps({"resetpid": 1}) self.serial.write(bytearray(jsonstring, 'utf-8')) def receive_serialdata(self, time, data): self.loggingWidget.log_input(data) try: self.rootnode.from_json(data) except ValueError as e: logger.error(str(e)) # refresh widgets self.objectexplorer.refresh() self.plot.refresh(time) if self.recording_enabled: self.recordWidget.add_data(time, self.rootnode) def send_serialdata(self, node): if isinstance(node, JsonItem): if self.serial.isOpen(): s = node.to_json() self.serial.write(utf8_to_bytearray(s + '\n')) self.loggingWidget.log_output(s.strip()) def show_serialdlg(self): dlg = SerialDialog(self.settings, self) dlg.exec_() def toggle_connect(self): if self.serial.isOpen(): self.disconnect() else: self.connect() def connect(self): # Load port setting port = self.settings.get(PORT_SETTING) baudrate = self.settings.get(BAUDRATE_SETTING) # If no port has been selected before show serial settings dialog if port is None: if self.show_serialdlg() == QDialog.Rejected: return port = self.settings.get(PORT_SETTING) baudrate = self.settings.get(BAUDRATE_SETTING) # Serial connection try: self.serial.port = port self.serial.baudrate = baudrate self.serial.open() except ValueError: QMessageBox.critical( self, QCoreApplication.applicationName(), self.tr("Serial parameters e.g. baudrate, databits are out " "of range.") ) except SerialException: QMessageBox.critical( self, QCoreApplication.applicationName(), self.tr("The device '%s' can not be found or can not be " "configured." % port) ) else: self.worker = SerialWorker(self.serial, self) self.worker.data_received.connect(self.receive_serialdata) self.worker.start() self.connectAction.setText(self.tr("Disconnect")) self.connectAction.setIcon(QIcon(pixmap("network-disconnect-3.png"))) self.serialdlgAction.setEnabled(False) self.connectionstateLabel.setText( self.tr("Connected to %s") % port) self._connected = True self.objectexplorer.refresh() def disconnect(self): self.worker.quit() self.serial.close() self.connectAction.setText(self.tr("Connect")) self.connectAction.setIcon(QIcon(pixmap("network-connect-3.png"))) self.serialdlgAction.setEnabled(True) self.connectionstateLabel.setText(self.tr("Not connected")) self._connected = False self.objectexplorer.refresh() def show_savecfg_dlg(self): filename, _ = QFileDialog.getSaveFileName( self, self.tr("Save configuration file..."), directory=os.path.expanduser("~"), filter="Json file (*.json)" ) if filename: self.filename = filename self.save_file() def save_file(self): if self.filename is not None: config_string = self.rootnode.dump() with open(self.filename, 'w') as f: f.write(config_string) self.dirty = False else: self.show_savecfg_dlg() def show_opencfg_dlg(self): # show file dialog filename, _ = QFileDialog.getOpenFileName( self, self.tr("Open configuration file..."), directory=os.path.expanduser("~"), filter=self.tr("Json file (*.json);;All files (*.*)") ) # load config file if filename: self.load_file(filename) def refresh_window_title(self): s = "%s %s" % (QCoreApplication.applicationName(), QCoreApplication.applicationVersion()) if self.filename is not None: s += " - " + self.filename if self.dirty: s += "*" self.setWindowTitle(s) def start_recording(self): self.recording_enabled = True self.startrecordingAction.setEnabled(False) self.stoprecordingAction.setEnabled(True) def stop_recording(self): self.recording_enabled = False self.startrecordingAction.setEnabled(True) self.stoprecordingAction.setEnabled(False) def export_csv(self): filename, _ = QFileDialog.getSaveFileName( self, QCoreApplication.applicationName(), filter="CSV files(*.csv);;All files (*.*)" ) if filename == "": return # get current dataframe and export to csv df = self.recordWidget.dataframe decimal = self.settings.get(DECIMAL_SETTING) df = df.applymap(lambda x: str(x).replace(".", decimal)) df.to_csv( filename, index_label="time", sep=self.settings.get(SEPARATOR_SETTING) ) def clear_record(self): self.recordWidget.clear() def show_recordsettings(self): dlg = CSVSettingsDialog(self) dlg.exec_() # filename property @property def filename(self): return self._filename @filename.setter def filename(self, value=""): self._filename = value self.refresh_window_title() # dirty property @property def dirty(self): return self._dirty @dirty.setter def dirty(self, value): self._dirty = value self.refresh_window_title() def set_dirty(self): self.dirty = True # connected property @property def connected(self): return self._connected
MrLeeh/jsonwatchqt
jsonwatchqt/mainwindow.py
Python
mit
19,071
using System.Threading; using CodeTiger; using Xunit; namespace UnitTests.CodeTiger { public class LazyTests { public class Create1 { [Fact] public void SetsIsValueCreatedToFalse() { var target = Lazy.Create<object>(); Assert.False(target.IsValueCreated); } [Fact] public void ReturnsDefaultValueOfObject() { var target = Lazy.Create<object>(); Assert.NotNull(target.Value); Assert.Equal(typeof(object), target.Value.GetType()); } [Fact] public void ReturnsDefaultValueOfBoolean() { var target = Lazy.Create<bool>(); Assert.Equal(new bool(), target.Value); } [Fact] public void ReturnsDefaultValueOfDecimal() { var target = Lazy.Create<decimal>(); Assert.Equal(new decimal(), target.Value); } } public class Create1_Boolean { [Theory] [InlineData(false)] [InlineData(true)] public void SetsIsValueCreatedToFalse(bool isThreadSafe) { var target = Lazy.Create<object>(isThreadSafe); Assert.False(target.IsValueCreated); } [Theory] [InlineData(false)] [InlineData(true)] public void ReturnsDefaultValueOfObject(bool isThreadSafe) { var target = Lazy.Create<object>(isThreadSafe); Assert.NotNull(target.Value); Assert.Equal(typeof(object), target.Value.GetType()); } [Theory] [InlineData(false)] [InlineData(true)] public void ReturnsDefaultValueOfBoolean(bool isThreadSafe) { var target = Lazy.Create<bool>(isThreadSafe); Assert.Equal(new bool(), target.Value); } [Theory] [InlineData(false)] [InlineData(true)] public void ReturnsDefaultValueOfDecimal(bool isThreadSafe) { var target = Lazy.Create<decimal>(isThreadSafe); Assert.Equal(new decimal(), target.Value); } } public class Create1_LazyThreadSafetyMode { [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void SetsIsValueCreatedToFalse(LazyThreadSafetyMode mode) { var target = Lazy.Create<object>(mode); Assert.False(target.IsValueCreated); } [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void CreatesTaskWhichReturnsDefaultValueOfObject(LazyThreadSafetyMode mode) { var target = Lazy.Create<object>(mode); Assert.NotNull(target.Value); Assert.Equal(typeof(object), target.Value.GetType()); } [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void CreatesTaskWhichReturnsDefaultValueOfBoolean(LazyThreadSafetyMode mode) { var target = Lazy.Create<bool>(mode); Assert.Equal(new bool(), target.Value); } [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void CreatesTaskWhichReturnsDefaultValueOfDecimal(LazyThreadSafetyMode mode) { var target = Lazy.Create<decimal>(mode); Assert.Equal(new decimal(), target.Value); } } public class Create1_FuncOfTaskOfT1 { [Fact] public void SetsIsValueCreatedToFalse() { object expected = new object(); var target = Lazy.Create(() => expected); Assert.False(target.IsValueCreated); } [Fact] public void SetsValueToProvidedObject() { object expected = new object(); var target = Lazy.Create(() => expected); Assert.Same(expected, target.Value); } } public class Create1_FuncOfTaskOfT1_Boolean { [Theory] [InlineData(false)] [InlineData(true)] public void SetsIsValueCreatedToFalse(bool isThreadSafe) { object expected = new object(); var target = Lazy.Create(() => expected, isThreadSafe); Assert.False(target.IsValueCreated); } [Theory] [InlineData(false)] [InlineData(true)] public void SetsValueToProvidedTask(bool isThreadSafe) { object expected = new object(); var target = Lazy.Create(() => expected, isThreadSafe); Assert.Same(expected, target.Value); } } public class Create1_FuncOfTaskOfT1_LazyThreadSafetyMode { [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void SetsIsValueCreatedToFalse(LazyThreadSafetyMode mode) { object expected = new object(); var target = Lazy.Create(() => expected, mode); Assert.False(target.IsValueCreated); } [Theory] [InlineData(LazyThreadSafetyMode.None)] [InlineData(LazyThreadSafetyMode.PublicationOnly)] [InlineData(LazyThreadSafetyMode.ExecutionAndPublication)] public void SetsValueToProvidedTask(LazyThreadSafetyMode mode) { object expected = new object(); var target = Lazy.Create(() => expected, mode); Assert.Same(expected, target.Value); } } } }
csdahlberg/CodeTigerLib
UnitTests/UnitTests.CodeTiger.Core/LazyTests.cs
C#
mit
6,719
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { sc := bufio.NewScanner(os.Stdin) sc.Split(bufio.ScanWords) n := nextInt(sc) a := nextInt(sc) b := nextInt(sc) answer := 0 for i := 1; i <= n; i++ { sum := 0 for _, s := range fmt.Sprintf("%d", i) { x, _ := strconv.Atoi(string(s)) sum = sum + x } if a <= sum && sum <= b { answer = answer + i } } fmt.Println(answer) } // ---------- func nextString(sc *bufio.Scanner) string { sc.Scan() return sc.Text() } func nextNumber(sc *bufio.Scanner) float64 { sc.Scan() f, err := strconv.ParseFloat(sc.Text(), 32) if err != nil { panic(err) } return f } func nextInt(sc *bufio.Scanner) int { sc.Scan() n, err := strconv.Atoi(sc.Text()) if err != nil { panic(err) } return n } func printArray(xs []int) { fmt.Println(strings.Trim(fmt.Sprint(xs), "[]")) } func debugPrintf(format string, a ...interface{}) { fmt.Fprintf(os.Stderr, format, a...) }
bati11/study-algorithm
at_coder/abc/ABC083B_SomeSums/ABC083B.go
GO
mit
973
export default function _isString(obj) { return toString.call(obj) === '[object String]' }
jrpool/js-utility-underscore
src/objects/_isString.js
JavaScript
mit
93
import Vue from 'vue' import Router from 'vue-router' import index from '../components/index' import project from '../components/project/index' import proAdd from '../components/project/proAdd' import proList from '../components/project/proList' import apiList from '../components/project/apiList' import apiView from '../components/project/apiView' import apiEdit from '../components/project/apiEdit' import apiHistory from '../components/project/apiHistory' import test from '../components/test' import message from '../components/message' import member from '../components/member' import doc from '../components/doc' import set from '../components/set' import userSet from '../components/user/set' import login from '../components/user/login' Vue.use(Router) const router:any = new Router({ mode: 'history', routes: [ { path: '/', name: 'index', component: index }, { path: '/project', name: 'project', component: project, children: [ { path: 'list', name: 'proList', component: proList, meta: { requireLogin: true } }, { path: 'add', name: 'proAdd', component: proAdd, meta: { requireLogin: true } }, { path: ':proId/edit', name: 'proEdit', component: proAdd, meta: { requireLogin: true } }, { path: ':proId/api', name: 'proApiList', component: apiList, children: [ { path: 'add', name: 'apiAdd', component: apiEdit, meta: { requireLogin: true } }, { path: ':apiId/detail', name: 'apiView', component: apiView, meta: { requireLogin: true }, }, { path: ':apiId/edit', name: 'apiEdit', component: apiEdit, meta: { requireLogin: true } }, { path: ':apiId/history', name: 'apiHistory', component: apiHistory, meta: { requireLogin: true } } ] } ] }, { path: '/test', name: 'test', component: test, meta: { requireLogin: true } }, { path: '/message', name: 'message', component: message, meta: { requireLogin: true } }, { path: '/member', name: 'member', component: member, meta: { requireLogin: true } }, { path: '/doc', name: 'doc', component: doc }, { path: '/set', name: 'set', component: set, meta: { requireLogin: true } }, { path: '/user/set', name: 'userSet', component: userSet, meta: { requireLogin: true } }, { path: '/user/login', name: 'login', component: login } ] }) router.beforeEach((to:any, from:any, next:any) => { if (to.matched.some((res:any) => res.meta.requireLogin)) { if (localStorage.getItem('token')) { next() } else { next('/user/login') } } else { next() } }) export default router
studyweb2017/best-api
web/src/service/router.ts
TypeScript
mit
3,538
var class_mock = [ [ "Mock", "class_mock.html#a2b9528f2e7fcf9738201a5ea667c1998", null ], [ "Mock", "class_mock.html#a2b9528f2e7fcf9738201a5ea667c1998", null ], [ "MOCK_METHOD0", "class_mock.html#ae710f23cafb1a2f17772e8805d6312d2", null ], [ "MOCK_METHOD1", "class_mock.html#ada59eea6991953353f332e3ea1e74444", null ], [ "MOCK_METHOD1", "class_mock.html#a2db4d82b6f92b4e462929f651ac4c3b1", null ], [ "MOCK_METHOD1", "class_mock.html#ae73b4ee90bf6d84205d2b1c17f0b8433", null ], [ "MOCK_METHOD1", "class_mock.html#a2cece30a3ea92b34f612f8032fe3a0f9", null ], [ "MOCK_METHOD1", "class_mock.html#ac70c052254fa9816bd759c006062dc47", null ], [ "MOCK_METHOD1", "class_mock.html#ae2379efbc030f1adf8b032be3bdf081d", null ], [ "MOCK_METHOD1", "class_mock.html#a3fd62026610c5d3d3aeaaf2ade3e18aa", null ], [ "MOCK_METHOD1", "class_mock.html#a890668928abcd28d4d39df164e7b6dd8", null ], [ "MOCK_METHOD1", "class_mock.html#a50e2bda4375a59bb89fd5652bd33eb0f", null ] ];
bhargavipatel/808X_VO
docs/html/class_mock.js
JavaScript
mit
1,000
#include "StdAfx.h" #include ".\datawriter.h" using namespace std; DataWriter::DataWriter(const std::string &fileName) { this->fileName = fileName; fileStream = NULL; //Initialize the filestream fileStream = new fstream(fileName.c_str(), ios::out|ios::binary|ios::trunc); } void DataWriter::Write(int data, const size_t size) { if (fileStream) { if (fileStream->is_open()) { int sizeCount = 0; while (data > 0) { fileStream->put(char(data%256)); data /= 256; ++sizeCount; } while (sizeCount < size) //Fill the remaining characters { fileStream->put(char(0)); ++sizeCount; } } } } void DataWriter::Write(const char data) { if (fileStream) { if (fileStream->is_open()) { fileStream->put(data); } } } void DataWriter::Write(const char* data, const size_t size) { if (!data) { std::cout << "Warning: attempted to write null pointer\n"; return; } if (fileStream) { if (fileStream->is_open()) { if (strlen(data) > size) { cout << "Warning: Attempting to write data to area larger than specified size\n"; return; } fileStream->write(data,strlen(data)); if (strlen(data) < size) { for (unsigned int i = 0; i < size - strlen(data); ++i) { fileStream->put(char(0));//The files we're dealing with are little-endian, so fill after the placement of the data } } } } }
AngryLawyer/SiegeUnitConverterCpp
DataWriter.cpp
C++
mit
1,869
namespace mazes.Core.Grids { using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using mazes.Core.Cells; using mazes.Core.Grids.Cartesian; public class WeaveGrid : Grid { private readonly List<UnderCell> _underCells = new List<UnderCell>(); public WeaveGrid(int rows, int cols) : base(rows, cols) { PrepareGrid(); ConfigureCells(); } private void PrepareGrid() { var rows = new List<List<Cell>>(); for (var row = 0; row < Rows; row++) { var newRow = new List<Cell>(); for (var column = 0; column < Columns; column++) { newRow.Add(new OverCell(row, column, this)); } rows.Add(newRow); } _grid = rows; } private void ConfigureCells() { foreach (var cell in Cells.Cast<OverCell>()) { var row = cell.Row; var col = cell.Column; cell.North = (OverCell)this[row - 1, col]; cell.South = (OverCell)this[row + 1, col]; cell.West = (OverCell)this[row, col - 1]; cell.East = (OverCell)this[row, col + 1]; } } public void TunnelUnder(OverCell overCell) { var underCell = new UnderCell(overCell); _underCells.Add(underCell); } public override IEnumerable<Cell> Cells => base.Cells.Union(_underCells); public override Image ToImg(int cellSize = 50, float insetPrc = 0) { return base.ToImg(cellSize, insetPrc == 0 ? 0.1f : insetPrc); } protected override void ToImgWithInset(Graphics g, CartesianCell cell, DrawMode mode, int cellSize, int x, int y, int inset) { if (cell is UnderCell) { var (x1, x2, x3, x4, y1, y2, y3, y4) = CellCoordinatesWithInset(x, y, cellSize, inset); if (cell.VerticalPassage) { g.DrawLine(Pens.Black, x2, y1, x2, y2); g.DrawLine(Pens.Black, x3, y1, x3, y2); g.DrawLine(Pens.Black, x2, y3, x2, y4); g.DrawLine(Pens.Black, x3, y3, x3, y4); } else { g.DrawLine(Pens.Black, x1, y2, x2, y2); g.DrawLine(Pens.Black, x1, y3, x2, y3); g.DrawLine(Pens.Black, x3, y2, x4, y2); g.DrawLine(Pens.Black, x3, y3, x4, y3); } } else { base.ToImgWithInset(g, cell, mode, cellSize, x, y, inset); } } } }
ericrrichards/mazes
mazes/Core/Grids/WeaveGrid.cs
C#
mit
2,678
package stream.flarebot.flarebot.mod.modlog; public enum ModAction { BAN(true, ModlogEvent.USER_BANNED), SOFTBAN(true, ModlogEvent.USER_SOFTBANNED), FORCE_BAN(true, ModlogEvent.USER_BANNED), TEMP_BAN(true, ModlogEvent.USER_TEMP_BANNED), UNBAN(false, ModlogEvent.USER_UNBANNED), KICK(true, ModlogEvent.USER_KICKED), TEMP_MUTE(true, ModlogEvent.USER_TEMP_MUTED), MUTE(true, ModlogEvent.USER_MUTED), UNMUTE(false, ModlogEvent.USER_UNMUTED), WARN(true, ModlogEvent.USER_WARNED); private boolean infraction; private ModlogEvent event; ModAction(boolean infraction, ModlogEvent modlogEvent) { this.infraction = infraction; this.event = modlogEvent; } public boolean isInfraction() { return infraction; } @Override public String toString() { return name().charAt(0) + name().substring(1).toLowerCase().replaceAll("_", " "); } public String getLowercaseName() { return toString().toLowerCase(); } public ModlogEvent getEvent() { return event; } }
FlareBot/FlareBot
src/main/java/stream/flarebot/flarebot/mod/modlog/ModAction.java
Java
mit
1,090
<?php /** * @package Update * @category modules * @author Nazar Mokrynskyi <nazar@mokrynskyi.com> * @copyright Copyright (c) 2013-2014, Nazar Mokrynskyi * @license MIT License, see license.txt */ namespace cs; use h; $Config = Config::instance(); $db = DB::instance(); $Index = Index::instance(); $module_object = $Config->module('Update'); if (!$module_object->version) { $module_object->version = 0; } if (isset($Config->route[0]) && $Config->route[0] == 'process') { $version = (int)$module_object->version; for ($i = 1; file_exists(MFOLDER."/sql/$i.sql") || file_exists(MFOLDER."/php/$i.php"); ++$i) { if ($version < $i) { if (file_exists(MFOLDER."/sql/$i.sql")) { foreach (explode(';', file_get_contents(MFOLDER."/sql/$i.sql")) as $s) { if ($s) { $db->{'0'}()->q($s); } } } if (file_exists(MFOLDER."/php/$i.php")) { include MFOLDER."/php/$i.php"; } $module_object->version = $i; } } $Index->save(true); } $Index->buttons = false; $Index->content( h::{'p.cs-center'}("Current revision: $module_object->version"). h::{'a.cs-button.cs-center'}( 'Update System structure', [ 'href' => 'admin/Update/process' ] ) );
nazar-pc/cherrytea.org-old
components/modules/Update/admin/index.php
PHP
mit
1,229
import PartyBot from 'partybot-http-client'; import React, { PropTypes, Component } from 'react'; import cssModules from 'react-css-modules'; import styles from './index.module.scss'; import Heading from 'grommet/components/Heading'; import Box from 'grommet/components/Box'; import Footer from 'grommet/components/Footer'; import Button from 'grommet/components/Button'; import Form from 'grommet/components/Form'; import FormField from 'grommet/components/FormField'; import FormFields from 'grommet/components/FormFields'; import NumberInput from 'grommet/components/NumberInput'; import CloseIcon from 'grommet/components/icons/base/Close'; import Dropzone from 'react-dropzone'; import Layer from 'grommet/components/Layer'; import Header from 'grommet/components/Header'; import Section from 'grommet/components/Section'; import Paragraph from 'grommet/components/Paragraph'; import request from 'superagent'; import Select from 'react-select'; import { CLOUDINARY_UPLOAD_PRESET, CLOUDINARY_NAME, CLOUDINARY_KEY, CLOUDINARY_SECRET, CLOUDINARY_UPLOAD_URL } from '../../constants'; import Immutable from 'immutable'; import _ from 'underscore'; class ManageTablesPage extends Component { constructor(props) { super(props); this.handleMobile = this.handleMobile.bind(this); this.closeSetup = this.closeSetup.bind(this); this.onDrop = this.onDrop.bind(this); this.addVariant = this.addVariant.bind(this); this.submitSave = this.submitSave.bind(this); this.submitDelete = this.submitDelete.bind(this); this.state = { isMobile: false, tableId: props.params.table_id || null, confirm: false, name: '', variants: [], organisationId: '5800471acb97300011c68cf7', venues: [], venueId: '', events: [], eventId: '', selectedEvents: [], tableTypes: [], tableTypeId: undefined, tags: 'table', image: null, prevImage: null, isNewImage: null, prices: [] }; } componentWillMount() { if (this.state.tableId) { this.setState({variants: []}); } } componentDidMount() { if (typeof window !== 'undefined') { window.addEventListener('resize', this.handleMobile); } let options = { organisationId: this.state.organisationId }; this.getVenues(options); // IF TABLE ID EXISTS if(this.props.params.table_id) { let tOptions = { organisationId: this.state.organisationId, productId: this.props.params.table_id } this.getTable(tOptions); } } componentWillUnmount() { if (typeof window !== 'undefined') { window.removeEventListener('resize', this.handleMobile); } } handleMobile() { const isMobile = window.innerWidth <= 768; this.setState({ isMobile, }); }; getVenues = (options) => { PartyBot.venues.getAllInOrganisation(options, (errors, response, body) => { if(response.statusCode == 200) { if(body.length > 0) { this.setState({venueId: body[0]._id}); let ttOptions = { organisationId: this.state.organisationId, venue_id: this.state.venueId } // this.getEvents(ttOptions); this.getTableTypes(ttOptions); } this.setState({venues: body, events: []}); } }); } getEvents = (options) => { PartyBot.events.getEventsInOrganisation(options, (err, response, body) => { if(!err && response.statusCode == 200) { if(body.length > 0) { this.setState({eventId: body[0]._id}); } body.map((value, index) =>{ this.setState({events: this.state.events.concat({ _event: value._id, name: value.name, selected: false })}); }); } }); } getTableTypes = (options) => { PartyBot.tableTypes.getTableTypesInOrganisation(options, (errors, response, body) => { if(response.statusCode == 200) { if(body.length > 0) { this.setState({tableTypes: body}); let params = { organisationId: this.state.organisationId, venueId: this.state.venueId, tableTypeId: body[0]._id } PartyBot.tableTypes.getTableType(params, (aerr, aresponse, abody) => { let events = abody._events.map((value) => { return value._event_id.map((avalue) => { return { value: avalue._id, label: avalue.name } }); }); this.setState({ tableTypeId: body[0]._id, events: _.flatten(events) }); }); } } }); } getTable = (options) => { PartyBot.products.getProductsInOrganisation(options, (error, response, body) => { if(response.statusCode == 200) { this.setState({ name: body.name, image: { preview: body.image }, prevImage: { preview: body.image }, variants: body.prices.map((value, index) => { return { _event: value._event, price: value.price } }) }); } }); } onVenueChange = (event) => { let id = event.target.value; this.setState({ venueId: id, events: [], variants: []}); let options = { organisationId: this.state.organisationId, venue_id: id }; this.getTableTypes(options); // this.getEvents(options); } onEventChange = (item, index, event) => { let variants = Immutable.List(this.state.variants); let mutated = variants.set(index, { _event: event.target.value, price: item.price}); this.setState( { variants: mutated.toArray() } ); } onPriceChange = (item, index, event) => { let variants = Immutable.List(this.state.variants); let mutated = variants.set(index, { _event: item._event, price: event.target.value}); this.setState( { variants: mutated.toArray() } ); } closeSetup(){ this.setState({ confirm: false }); this.context.router.push('/tables'); } addVariant() { // will create then get? var newArray = this.state.variants.slice(); newArray.push({ _event_id: [], description: "", image: null, imageUrl: "" }); this.setState({variants:newArray}) } removeVariant(index, event){ // delete variant ID let variants = Immutable.List(this.state.variants); let mutated = variants.remove(index); // let selectedEvents = Immutable.List(this.state.selectedEvents); // let mutatedEvents = selectedEvents.remove(index); this.setState({ variants: mutated.toJS(), }); } onEventAdd = (index, selectedEvents) => { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('_event_id', selectedEvents); let newClone = cloned.set(index, anIndex); let selectedEventState = Immutable.List(this.state.selectedEvents); let newSelectedEventState = selectedEventState.set(index, selectedEvents); this.setState({selectedEvents: newSelectedEventState.toJS(), variants: newClone.toJS()}); } setDescrpiption = (index, event) => { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('description', event.target.value); let newClone = cloned.set(index, anIndex); this.setState({variants: newClone.toJS()}); } onDrop = (index, file) => { this.setState({ isBusy: true }); let upload = request.post(CLOUDINARY_UPLOAD_URL) .field('upload_preset', CLOUDINARY_UPLOAD_PRESET) .field('file', file[0]); console.log('dragged'); upload.end((err, response) => { if (err) { } else { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('image', file[0]); anIndex = anIndex.set('imageUrl', response.body.secure_url); let newClone = cloned.set(index, anIndex); this.setState({variants: newClone.toJS(), isBusy: false}); } }); } onTypeChange = (event) => { var id = event.target.value; let params = { organisationId: this.state.organisationId, venueId: this.state.venueId, tableTypeId: id } PartyBot.tableTypes.getTableType(params, (err, response, body) => { let events = body._events.map((value) => { return value._event_id.map((avalue) => { return { value: avalue._id, label: avalue.name } }); }); this.setState({ tableTypeId: id, variants: [], events: _.flatten(events) }); }); } setName = (event) => { this.setState({name: event.target.value}); } getTypeOptions = () => { return this.state.tableTypes.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; }); } getTableVariants = () => { return this.state.variants.map((value, index) => { return ( <Box key={index} separator="all"> <FormField label="Event" htmlFor="events" /> <Select name="events" options={this.state.events.filter((x) => { let a = _.contains(_.uniq(_.flatten(this.state.selectedEvents)), x); return !a; })} value={value._event_id} onChange={this.onEventAdd.bind(this, index)} multi={true} /> <FormField label="Description" htmlFor="tableTypedescription"> <input id="tableTypedescription" type="text" onChange={this.setDescrpiption.bind(this, index)} value={value.description}/> </FormField> <FormField label="Image"> {value.image ? <Box size={{ width: 'large' }} align="center" justify="center"> <div> <img src={value.image.preview} width="200" /> </div> <Box size={{ width: 'large' }}> <Button label="Cancel" onClick={this.onRemoveImage.bind(this)} plain={true} icon={<CloseIcon />}/> </Box> </Box> : <Box align="center" justify="center" size={{ width: 'large' }}> <Dropzone multiple={false} ref={(node) => { this.dropzone = node; }} onDrop={this.onDrop.bind(this, index)} accept='image/*'> Drop image here or click to select image to upload. </Dropzone> </Box> } <Button label="Remove" onClick={this.removeVariant.bind(this, index)} primary={true} float="right"/> </FormField> </Box>) }); // return this.state.variants.map( (item, index) => { // return <div key={index}> // <FormField label="Event" htmlFor="tableName"> // <select id="tableVenue" onChange={this.onEventChange.bind(this, item, index)} value={item._event||this.state.events[0]._event}> // { // this.state.events.map( (value, index) => { // return (<option key={index} value={value._event}>{value.name}</option>) // }) // } // </select> // </FormField> // <FormField label="Price(Php)" htmlFor="tablePrice"> // <input type="number" onChange={this.onPriceChange.bind(this, item, index)} value={item.price}/> // </FormField> // <Footer pad={{"vertical": "small"}}> // <Heading align="center"> // <Button className={styles.eventButton} label="Update" primary={true} onClick={() => {}} /> // <Button className={styles.eventButton} label="Remove" onClick={this.removeVariant.bind(this, index)} /> // </Heading> // </Footer> // </div>; // }); } onDrop(file) { this.setState({ image: file[0], isNewImage: true }); } onRemoveImage = () => { this.setState({ image: null, isNewImage: false }); } handleImageUpload(file, callback) { if(this.state.isNewImage) { let options = { url: CLOUDINARY_UPLOAD_URL, formData: { file: file } }; let upload = request.post(CLOUDINARY_UPLOAD_URL) .field('upload_preset', CLOUDINARY_UPLOAD_PRESET) .field('file', file); upload.end((err, response) => { if (err) { console.error(err); } if (response.body.secure_url !== '') { callback(null, response.body.secure_url) } else { callback(err, ''); } }); } else { callback(null, null); } } submitDelete (event) { event.preventDefault(); let delParams = { organisationId: this.state.organisationId, productId: this.state.tableId }; PartyBot.products.deleteProduct(delParams, (error, response, body) => { if(!error && response.statusCode == 200) { this.setState({ confirm: true }); } else { } }); } submitSave() { event.preventDefault(); this.handleImageUpload(this.state.image, (err, imageLink) => { if(err) { console.log(err); } else { let updateParams = { name: this.state.name, organisationId: this.state.organisationId, productId: this.state.tableId, venueId: this.state.venueId, table_type: this.state.tableTypeId, image: imageLink || this.state.prevImage.preview, prices: this.state.variants }; PartyBot.products.update(updateParams, (errors, response, body) => { if(response.statusCode == 200) { this.setState({ confirm: true }); } }); } }); } submitCreate = () => { event.preventDefault(); console.log(this.state); let params = {}; // this.handleImageUpload(this.state.image, (err, imageLink) => { // if(err) { // console.log(err); // } else { // let createParams = { // name: this.state.name, // organisationId: this.state.organisationId, // venueId: this.state.venueId, // tags: this.state.tags, // table_type: this.state.tableTypeId, // image: imageLink, // prices: this.state.variants // }; // PartyBot.products.create(createParams, (errors, response, body) => { // if(response.statusCode == 200) { // this.setState({ // confirm: true // }); // } // }); // } // }); } render() { const { router, } = this.context; const { isMobile, } = this.state; const { files, variants, } = this.state; return ( <div className={styles.container}> <link rel="stylesheet" href="https://unpkg.com/react-select/dist/react-select.css"/> {this.state.confirm !== false ? <Layer align="center"> <Header> Table successfully created. </Header> <Section> <Button label="Close" onClick={this.closeSetup} plain={true} icon={<CloseIcon />}/> </Section> </Layer> : null } <Box> {this.state.tableId !== null ? <Heading align="center"> Edit Table </Heading> : <Heading align="center"> Add Table </Heading> } </Box> <Box size={{ width: 'large' }} direction="row" justify="center" align="center" wrap={true} margin="small"> <Form> <FormFields> <fieldset> <FormField label="Venue" htmlFor="tableVenue"> <select id="tableVenue" onChange={this.onVenueChange} value={this.state.venueId}> {this.state.venues.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; })} </select> </FormField> <FormField label="Table Type" htmlFor="tableType"> <select id="tableType" onChange={this.onTypeChange} value={this.state.tableTypeId}> {this.state.tableTypes.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; })} </select> </FormField> <FormField label=" Name" htmlFor="tableName"> <input id="tableName" type="text" onChange={this.setName} value={this.state.name}/> </FormField> { //Dynamic Price/Event Component this.getTableVariants() } <Button label="Add Event" primary={true} onClick={this.addVariant} /> </fieldset> </FormFields> <Footer pad={{"vertical": "medium"}}> { this.state.tableId !== null ? <Heading align="center"> <Button label="Save Changes" primary={true} onClick={this.submitSave} /> <Button label="Delete" primary={true} onClick={this.submitDelete} /> </Heading> : <Heading align="center"> <Button label="Create Table" primary={true} onClick={this.submitCreate} /> </Heading> } </Footer> </Form> </Box> </div> ); } } ManageTablesPage.contextTypes = { router: PropTypes.object.isRequired, }; export default cssModules(ManageTablesPage, styles);
JaySmartwave/palace-bot-sw
app/src/pages/ManageTablesPage/index.js
JavaScript
mit
17,890
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Core.Interfaces { public static class IApplicationCommandConstants { /// <summary> /// This application name represents default commands - when there is no /// command for specific application /// </summary> public const string DEFAULT_APPLICATION = "DEFAULT"; } /// <summary> /// Represents simple association that connects application, remote command and feedback to this command. /// If ApplicationName is null - this is a default behaviour. /// </summary> public interface IApplicationCommand { /// <summary> /// Name of the application /// </summary> string ApplicationName { get; } /// <summary> /// Remote command /// </summary> RemoteCommand RemoteCommand { get; } /// <summary> /// Command to be executed /// </summary> ICommand Command { get; } /// <summary> /// Executes associated command /// </summary> void Do(); } }
StanislavUshakov/ArduinoWindowsRemoteControl
Core/Interfaces/IApplicationCommand.cs
C#
mit
1,174
module HealthSeven::V2_3 class QryQ02 < ::HealthSeven::Message attribute :msh, Msh, position: "MSH", require: true attribute :qrd, Qrd, position: "QRD", require: true attribute :qrf, Qrf, position: "QRF" attribute :dsc, Dsc, position: "DSC" end end
niquola/health_seven
lib/health_seven/2.3/messages/qry_q02.rb
Ruby
mit
256
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Amazon.Runtime.Internal.Transform { public static class CustomMarshallTransformations { public static long ConvertDateTimeToEpochMilliseconds(DateTime dateTime) { TimeSpan ts = new TimeSpan(dateTime.ToUniversalTime().Ticks - Amazon.Util.AWSSDKUtils.EPOCH_START.Ticks); return (long)ts.TotalMilliseconds; } } }
Shogan/Unity3D.CharacterCreator
Assets/AWSSDK/src/Core/Amazon.Runtime/Internal/Transform/CustomMarshallTransformations.cs
C#
mit
1,054
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using gView.Framework.IO; using gView.Framework.Data; using gView.Framework.UI; namespace gView.Framework.UI.Dialogs { public partial class FormMetadata : Form { private Metadata _metadata; private object _metadataObject; public FormMetadata(XmlStream xmlStream, object metadataObject) { InitializeComponent(); _metadata = new Metadata(); _metadata.ReadMetadata(xmlStream); _metadataObject = metadataObject; } private void FormMetadata_Load(object sender, EventArgs e) { if (_metadata.Providers == null) return; foreach (IMetadataProvider provider in _metadata.Providers) { if (provider == null) continue; TabPage page = new TabPage(provider.Name); if (provider is IPropertyPage) { Control ctrl = ((IPropertyPage)provider).PropertyPage(null) as Control; if (ctrl != null) { page.Controls.Add(ctrl); ctrl.Dock = DockStyle.Fill; } if (ctrl is IMetadataObjectParameter) ((IMetadataObjectParameter)ctrl).MetadataObject = _metadataObject; } tabControl1.TabPages.Add(page); } } public XmlStream Stream { get { XmlStream stream = new XmlStream("Metadata"); if (_metadata != null) _metadata.WriteMetadata(stream); return stream; } } } }
jugstalt/gViewGisOS
gView.Explorer.UI/Framework/UI/Dialogs/FormMetadata.cs
C#
mit
1,880
namespace EgaViewer_v2 { partial class CustomPictureBox { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion } }
ChainedLupine/BSAVEViewer
EgaViewer_v2/CustomPictureBox.Designer.cs
C#
mit
1,033
namespace StudentClass { public class Course { public Course(string name) : this() { this.Name = name; } public Course() { } public string Name { get; private set; } public override string ToString() { return this.Name; } } }
TomaNikolov/TelerikAcademy
OOP/06.CommonTypeSystem/StudentClass/Course.cs
C#
mit
361
# encoding: UTF-8 module DocuBot::LinkTree; end class DocuBot::LinkTree::Node attr_accessor :title, :link, :page, :parent def initialize( title=nil, link=nil, page=nil ) @title,@link,@page = title,link,page @children = [] end def anchor @link[/#(.+)/,1] end def file @link.sub(/#.+/,'') end def leaf? !@children.any?{ |node| node.page != @page } end # Add a new link underneath a link to its logical parent def add_to_link_hierarchy( title, link, page=nil ) node = DocuBot::LinkTree::Node.new( title, link, page ) parent_link = if node.anchor node.file elsif File.basename(link)=='index.html' File.dirname(File.dirname(link))/'index.html' else (File.dirname(link) / 'index.html') end #puts "Adding #{title.inspect} (#{link}) to hierarchy under #{parent_link}" parent = descendants.find{ |n| n.link==parent_link } || self parent << node end def <<( node ) node.parent = self @children << node end def []( child_index ) @children[child_index] end def children( parent_link=nil, &block ) if parent_link root = find( parent_link ) root ? root.children( &block ) : [] else @children end end def descendants ( @children + @children.map{ |child| child.descendants } ).flatten end def find( link ) # TODO: this is eminently cachable descendants.find{ |node| node.link==link } end def depth # Cached assuming no one is going to shuffle the nodes after placement @depth ||= ancestors.length end def ancestors # Cached assuming no one is going to shuffle the nodes after placement return @ancestors if @ancestors @ancestors = [] node = self @ancestors << node while node = node.parent @ancestors.reverse! end def to_s "#{@title} (#{@link}) - #{@page && @page.title}" end def to_txt( depth=0 ) indent = " "*depth [ indent+to_s, children.map{|kid|kid.to_txt(depth+1)} ].flatten.join("\n") end end class DocuBot::LinkTree::Root < DocuBot::LinkTree::Node undef_method :title undef_method :link undef_method :page attr_reader :bundle def initialize( bundle ) @bundle = bundle @children = [] end def <<( node ) node.parent = nil @children << node end def to_s "(Table of Contents)" end end
Phrogz/docubot
lib/docubot/link_tree.rb
Ruby
mit
2,249
"use strict" const messages = require("..").messages const ruleName = require("..").ruleName const rules = require("../../../rules") const rule = rules[ruleName] testRule(rule, { ruleName, config: ["always"], accept: [ { code: "a { background-size: 0 , 0; }", }, { code: "a { background-size: 0 ,0; }", }, { code: "a::before { content: \"foo,bar,baz\"; }", description: "strings", }, { code: "a { transform: translate(1,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0, 0; }", message: messages.expectedBefore(), line: 1, column: 23, }, { code: "a { background-size: 0 , 0; }", message: messages.expectedBefore(), line: 1, column: 25, }, { code: "a { background-size: 0\n, 0; }", message: messages.expectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\r\n, 0; }", description: "CRLF", message: messages.expectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\t, 0; }", message: messages.expectedBefore(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["never"], accept: [ { code: "a { background-size: 0, 0; }", }, { code: "a { background-size: 0,0; }", }, { code: "a::before { content: \"foo ,bar ,baz\"; }", description: "strings", }, { code: "a { transform: translate(1 ,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0 , 0; }", message: messages.rejectedBefore(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0; }", message: messages.rejectedBefore(), line: 1, column: 25, }, { code: "a { background-size: 0\n, 0; }", message: messages.rejectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\r\n, 0; }", description: "CRLF", message: messages.rejectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\t, 0; }", message: messages.rejectedBefore(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["always-single-line"], accept: [ { code: "a { background-size: 0 , 0; }", }, { code: "a { background-size: 0 ,0; }", }, { code: "a { background-size: 0 ,0;\n}", description: "single-line list, multi-line block", }, { code: "a { background-size: 0 ,0;\r\n}", description: "single-line list, multi-line block with CRLF", }, { code: "a { background-size: 0,\n0; }", description: "ignores multi-line list", }, { code: "a { background-size: 0,\r\n0; }", description: "ignores multi-line list with CRLF", }, { code: "a::before { content: \"foo,bar,baz\"; }", description: "strings", }, { code: "a { transform: translate(1,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0, 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0, 0;\n}", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0, 0;\r\n}", description: "CRLF", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0 , 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 25, }, { code: "a { background-size: 0\t, 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["never-single-line"], accept: [ { code: "a { background-size: 0, 0; }", }, { code: "a { background-size: 0,0; }", }, { code: "a { background-size: 0,0;\n}", description: "single-line list, multi-line block", }, { code: "a { background-size: 0,0;\r\n}", description: "single-line list, multi-line block with CRLF", }, { code: "a { background-size: 0 ,\n0; }", description: "ignores multi-line list", }, { code: "a { background-size: 0 ,\r\n0; }", description: "ignores multi-line list with CRLF", }, { code: "a::before { content: \"foo ,bar ,baz\"; }", description: "strings", }, { code: "a { transform: translate(1 ,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0 , 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0;\n}", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0;\r\n}", description: "CRLF", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 25, }, { code: "a { background-size: 0\t, 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, } ], })
hudochenkov/stylelint
lib/rules/value-list-comma-space-before/__tests__/index.js
JavaScript
mit
5,084
# -*- coding: utf-8 -*- """ """ from datetime import datetime, timedelta import os from flask import request from flask import Flask import pytz import db from utils import get_remote_addr, get_location_data app = Flask(__name__) @app.route('/yo-water/', methods=['POST', 'GET']) def yowater(): payload = request.args if request.args else request.get_json(force=True) username = payload.get('username') reminder = db.reminders.find_one({'username': username}) reply_object = payload.get('reply') if reply_object is None: if db.reminders.find_one({'username': username}) is None: address = get_remote_addr(request) data = get_location_data(address) if not data: return 'Timezone needed' user_data = {'created': datetime.now(pytz.utc), 'username': username} if data.get('time_zone'): user_data.update({'timezone': data.get('time_zone')}) db.reminders.insert(user_data) return 'OK' else: reply_text = reply_object.get('text') if reply_text == u'Can\'t right now 😖': reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=15) else: reminder['step'] += 1 reminder['trigger_date'] = datetime.now(pytz.utc) + timedelta(minutes=60) reminder['last_reply_date'] = datetime.now(pytz.utc) db.reminders.update({'username': username}, reminder) db.replies.insert({'username': username, 'created': datetime.now(pytz.utc), 'reply': reply_text}) return 'OK' if __name__ == "__main__": app.debug = True app.run(host="0.0.0.0", port=int(os.environ.get("PORT", "5000")))
YoApp/yo-water-tracker
server.py
Python
mit
1,851
from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static from django.contrib import admin admin.autodiscover() import views urlpatterns = patterns('', url(r'^pis', views.pis), url(r'^words', views.words, { 'titles': False }), url(r'^projects', views.projects), url(r'^posters', views.posters), url(r'^posterpresenters', views.posterpresenters), url(r'^pigraph', views.pigraph), url(r'^institutions', views.institutions), url(r'^institution/(?P<institutionid>\d+)', views.institution), url(r'^profile/$', views.profile), url(r'^schedule/(?P<email>\S+)', views.schedule), url(r'^ratemeeting/(?P<rmid>\d+)/(?P<email>\S+)', views.ratemeeting), url(r'^submitrating/(?P<rmid>\d+)/(?P<email>\S+)', views.submitrating), url(r'^feedback/(?P<email>\S+)', views.after), url(r'^breakouts', views.breakouts), url(r'^breakout/(?P<bid>\d+)', views.breakout), url(r'^about', views.about), url(r'^buginfo', views.buginfo), url(r'^allrms', views.allrms), url(r'^allratings', views.allratings), url(r'^login', views.login), url(r'^logout', views.logout), url(r'^edit_home_page', views.edit_home_page), url(r'^pi/(?P<userid>\d+)', views.pi), # , name = 'pi'), url(r'^pi/(?P<email>\S+)', views.piEmail), # , name = 'pi'), url(r'^project/(?P<abstractid>\S+)', views.project, name = 'project'), url(r'^scope=(?P<scope>\w+)/(?P<url>.+)$', views.set_scope), url(r'^active=(?P<active>\d)/(?P<url>.+)$', views.set_active), url(r'^admin/', include(admin.site.urls)), (r'', include('django_browserid.urls')), url(r'^$', views.index, name = 'index'), ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
ctames/conference-host
webApp/urls.py
Python
mit
1,850
var test = require('tap').test; var CronExpression = require('../lib/expression'); test('Fields are exposed', function(t){ try { var interval = CronExpression.parse('0 1 2 3 * 1-3,5'); t.ok(interval, 'Interval parsed'); CronExpression.map.forEach(function(field) { interval.fields[field] = []; t.throws(function() { interval.fields[field].push(-1); }, /Cannot add property .*?, object is not extensible/, field + ' is frozen'); delete interval.fields[field]; }); interval.fields.dummy = []; t.same(interval.fields.dummy, undefined, 'Fields is frozen'); t.same(interval.fields.second, [0], 'Second matches'); t.same(interval.fields.minute, [1], 'Minute matches'); t.same(interval.fields.hour, [2], 'Hour matches'); t.same(interval.fields.dayOfMonth, [3], 'Day of month matches'); t.same(interval.fields.month, [1,2,3,4,5,6,7,8,9,10,11,12], 'Month matches'); t.same(interval.fields.dayOfWeek, [1,2,3,5], 'Day of week matches'); } catch (err) { t.error(err, 'Interval parse error'); } t.end(); });
harrisiirak/cron-parser
test/fields.js
JavaScript
mit
1,093
package br.eti.qisolucoes.contactcloud.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/").authenticated() .antMatchers("/theme/**", "/plugins/**", "/page/**", "/", "/usuario/form", "/usuario/salvar").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginProcessingUrl("/login").loginPage("/login").permitAll().defaultSuccessUrl("/agenda/abrir", true) .and() .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { super.configure(auth); auth.userDetailsService(userDetailsService); } }
nosered/contact-cloud
src/main/java/br/eti/qisolucoes/contactcloud/config/SecurityConfig.java
Java
mit
1,557
package de.chandre.admintool.security.dbuser.repo; import java.util.List; import java.util.Set; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import de.chandre.admintool.security.dbuser.domain.ATRole; /** * * @author André * @since 1.1.7 */ @Repository public interface RoleRepository extends JpaRepository<ATRole, String> { ATRole findByName(String name); @Query("SELECT r.name FROM ATRole r") List<String> findAllRoleNames(); List<ATRole> findByNameIn(Set<String> ids); List<ATRole> findByIdIn(Set<String> ids); void deleteByName(String name); }
andrehertwig/admintool
admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/repo/RoleRepository.java
Java
mit
724
#!/usr/bin/env node var listCommand = []; require('./listCommand')(listCommand) var logDetail = (str) => { console.log(' > '+str); } var printHelp = () => { var txtHelp = ""; var h = ' '; var t = ' '; txtHelp += "\n"+h+"Usage : rider [command] \n"; txtHelp += "\n"+h+"Command List : \n"; var maxText = 0; if(listCommand == undefined){ logDetail("not found help detail"); return; } Object.keys(listCommand).forEach((keyName) => { var item = listCommand[keyName]; if(maxText < item.name.length+item.params.length) maxText = item.name.length+item.params.length+4; }); var maxT = Math.ceil(maxText/4); Object.keys(listCommand).forEach((keyName) => { var item = listCommand[keyName]; var x = (item.name.length+item.params.length+4)/4; x = Math.ceil(x); var space = '\t'; for (var i = 0; i < maxT-x-1; i++) { space += '\t'; } var txt = ""; if(item.params.length > 0){ space += '\t'; txt = '\t'+item.name +" [" +item.params+"] " + space +item.desc+"\n"; }else{ txt = '\t'+item.name + space +item.desc+"\n"; } txtHelp +=txt; txtHelp +"\n"; }); console.log(txtHelp); process.exit(0); } var parseParams = (params, cb) => { if(params.length < 3){ return cb(true); } cb(false); } var checkCommand = (cmd) => { var foundCmd = false; Object.keys(listCommand).forEach((keyName) => { if(keyName == cmd){ foundCmd = true; return; } }); return !foundCmd; } var runCommand = (params, cb) => { var opt = params[2]; var objRun = listCommand[opt]; if(objRun != undefined && objRun != null){ objRun.runCommand(params, cb); } } var main = () => { console.log(">> Rider ... "); var params = process.argv; parseParams(params, (err) => { if(err){ printHelp(); return; } var opt = params[2]; if(opt == "-h" || opt == "--help"){ printHelp(); return; } if(checkCommand(opt)){ printHelp(); return; } runCommand(params, () => { process.exit(0); }); }); } // -- call main function -- main();
khajer/rider.js
cli.js
JavaScript
mit
2,029
<?php /* * Arabian language */ $lang = [ 'albums' => 'Альбомы' ];
Speennaker/tanyaprykhodko
application/language/arabian/main_lang.php
PHP
mit
78
import { BaseController } from "./BaseController"; import { Route } from "./BaseController"; import * as loadHtml from "./HtmlLoader"; export class MainController extends BaseController { main = (): void => { loadHtml.load(this.requestData, '/views/index.html', {}); } routes: Route[] = [ new Route("/", this.main) ]; }
Kasperki/NodeBlog
blog/MainController.ts
TypeScript
mit
357
import React from "react"; import $ from "jquery"; import "bootstrap/dist/js/bootstrap.min"; import "jquery-ui/ui/widgets/datepicker"; import { postFulltimeEmployer, postParttimeEmployer, putFullTimeEmployer, putParttimeEmployer } from "../actions/PostData"; import DropDownBtn from "../components/DropDownBtn"; import {parseBirthdayForServer} from "../utils/Utils"; import {connect} from "react-redux"; class ModalEmployer extends React.Component { componentWillReceiveProps = (nextProps) => { if (nextProps.data) { this.setState(nextProps.data); if (nextProps.data.day_salary) { this.setState({ type: 'congNhat' }) } else { this.setState({ type: 'bienChe' }) } } if (nextProps.data == null) { this.setState(this.emptyObject) } } emptyObject = { "salary_level": "", "name": "", "month_salary": "", "phone": "", "birthday": "", "allowance": "", "department_id": this.props.departments.length > 0 ? this.props.departments[0].id : "", day_salary: "", } onClickSave = () => { let data = { "name": this.state.name, "phone": this.state.phone, "birthday": parseBirthdayForServer(this.state.birthday), "department_id": this.state.department_id, } if (this.state.type === "bienChe") { data.salary_level = this.state.salary_level; data.month_salary = this.state.month_salary; data.allowance = this.state.allowance; if (this.props.data) { putFullTimeEmployer(this.props.data.id, data, this.props.fetchEmployers); } else { postFulltimeEmployer(data, this.props.fetchEmployers); } } if (this.state.type === "congNhat") { data.day_salary = this.state.day_salary; if (this.props.data) { putParttimeEmployer(this.props.data.id, data, this.props.fetchEmployers); } else { postParttimeEmployer(data, this.props.fetchEmployers) } } $('#create').modal('toggle'); } constructor(props) { super(props); this.state = Object.assign(this.emptyObject, {type: null}) } onChangeText = (event) => { this.setState({ [event.target.name]: event.target.value }) } clickType = (type) => { this.setState({ type }) } componentDidMount = () => { $('#datepicker').datepicker({ uiLibrary: 'bootstrap4', iconsLibrary: 'fontawesome', onSelect: (dateText) => { this.setState({ birthday: dateText }) }, dateFormat: 'dd/mm/yy' }); } renderExtraForm = () => { if (this.state.type) { switch (this.state.type) { case "bienChe": return <div> <label htmlFor="id">Lương tháng</label> <div className="input-group"> <input onChange={this.onChangeText} name="month_salary" type="text" className="form-control" id="id" aria-describedby="basic-addon3" value={this.state.month_salary}/> </div> <label htmlFor="id">Bậc lương</label> <div className="input-group"> <input onChange={this.onChangeText} name="salary_level" type="text" className="form-control" id="id" aria-describedby="basic-addon3" value={this.state.salary_level}/> </div> <label htmlFor="id">Phụ cấp</label> <div className="input-group"> <input onChange={this.onChangeText} name="allowance" type="text" className="form-control" id="id" aria-describedby="basic-addon3" value={this.state.allowance}/> </div> </div> break; case "congNhat": return <div> <label htmlFor="id">Lương ngày</label> <div className="input-group"> <input name="day_salary" value={this.state.day_salary} onChange={this.onChangeText} type="text" className="form-control" id="id" aria-describedby="basic-addon3"/> </div> </div> break; } } } onSelectDepartment = (item) => { this.setState({ department_id: item.id }) } renderDropDownBtn = () => { if (this.props.departments.length > 0) { return ( <DropDownBtn onChange={this.onSelectDepartment} default data={this.props.departments}></DropDownBtn> ) } } render() { return ( <div className="modal fade" id="create" tabIndex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="exampleModalLabel">Thêm nhân viên</h5> <button type="button" className="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div className="modal-body"> <label htmlFor="name">Tên nhân viên</label> <div className="input-group"> <input onChange={this.onChangeText} value={this.state.name} name="name" type="text" className="form-control" id="name" aria-describedby="basic-addon3"/> </div> <label htmlFor="datepicker">Ngày tháng năm sinh</label> <div className="input-group date" data-provide="datepicker"> <input onClick={this.onChangeText} onChange={this.onChangeText} value={this.state.birthday} name="birthday" type="text" className="form-control" id="datepicker"/> </div> <label htmlFor="phone">Số điện thoại</label> <div className="input-group"> <input onChange={this.onChangeText} value={this.state.phone} name="phone" type="text" className="form-control" id="phone" aria-describedby="basic-addon3"/> </div> <div className="btn-group"> <label htmlFor="name" className="margin-R10">Chọn phòng ban</label> {this.renderDropDownBtn()} </div> <div className="btn-group btn-middle align-middle"> { (() => { if (this.props.data) { if (this.props.data.day_salary === null) { return (<button className="btn btn-primary" id="bien-che">Nhân viên Biên chế </button>) } else { return ( <button className="btn btn-info" id="cong-nhat">Nhân viên Công nhật </button> ) } } else { let arr = []; arr.push(<button onClick={this.clickType.bind(this, "bienChe")} className="btn btn-primary" id="bien-che">Nhân viên Biên chế </button>); arr.push(<button onClick={this.clickType.bind(this, "congNhat")} className="btn btn-info" id="cong-nhat">Nhân viên Công nhật </button>); return arr; } })() } </div> { this.renderExtraForm() } </div> <div className="modal-footer"> <button type="button" className="btn btn-secondary" data-dismiss="modal">Hủy</button> <button onClick={this.onClickSave} type="button" className="btn btn-primary">Lưu</button> </div> </div> </div> </div> ) } } const mapStateToProps = state => { return { departments: state.app.departments } } export default connect(mapStateToProps)(ModalEmployer)
liemnt/quanlynv
quanlynhanvien/src/components/ModalEmployer.js
JavaScript
mit
10,454
require 'spec_helper' describe Character do before do @character = Character.new(name: "Walder Frey", page: 'index.html') end subject { @character} it { should respond_to(:name)} it { should respond_to(:icon)} it { should respond_to(:page)} it { should respond_to(:degrees)} it { should respond_to(:all_relationships)} it { should respond_to(:children)} it { should respond_to(:parents)} it { should respond_to(:relationships)} it { should respond_to(:reverse_relationships)} it { should be_valid} describe "when name is not present" do before {@character.name = nil} it {should_not be_valid} end describe "when page is not present" do before {@character.page = nil} it {should_not be_valid} end describe "character with page already exists" do before do character_with_same_page = @character.dup character_with_same_page.page.upcase! character_with_same_page.save end it { should_not be_valid} end describe "character relationships" do before{ @character.save} let!(:child_character) do FactoryGirl.create(:character) end let!(:relationship) { @character.relationships.build(:child_id => child_character.id)} it "should display for both" do expect(@character.all_relationships.to_a).to eq child_character.all_relationships.to_a end it "should destroy relationships" do relationships = @character.relationships.to_a @character.destroy expect(relationships).not_to be_empty relationships.each do |relationship| expect(Relationship.where(:id => relationship.id)).to be_empty end end end end
thatguyandy27/DegreesOfWalderFrey
degrees_of_frey/spec/models/character_spec.rb
Ruby
mit
1,683
package net.sf.jabref.gui.util; import javafx.concurrent.Task; /** * An object that executes submitted {@link Task}s. This * interface provides a way of decoupling task submission from the * mechanics of how each task will be run, including details of thread * use, scheduling, thread pooling, etc. */ public interface TaskExecutor { /** * Runs the given task. * * @param task the task to run * @param <V> type of return value of the task */ <V> void execute(BackgroundTask<V> task); }
Mr-DLib/jabref
src/main/java/net/sf/jabref/gui/util/TaskExecutor.java
Java
mit
528
package com.mgireesh; public class Solution extends VersionControl { public int firstBadVersion(int n) { int badVersion = 0; int start = 1; int end = n; while (start < end) { int mid = start + (end - start) / 2; if (isBadVersion(mid)) { end = mid; } else { start = mid + 1; } } return start; } }
mgireesh05/leetcode
first-bad-version/src/com/mgireesh/Solution.java
Java
mit
331
<?php namespace Aurex\Framework\Module\Modules\FormDoctrineModule; use Symfony\Bridge\Doctrine\Form\DoctrineOrmExtension, Silex\Provider\TranslationServiceProvider, Aurex\Framework\Module\ModuleInterface, Silex\Provider\SessionServiceProvider, Silex\Provider\FormServiceProvider, Aurex\Framework\Aurex; /** * Class FormDoctrineModule * * @package Aurex\Framework\Module\Modules\FormDoctrineModule */ class FormDoctrineModule implements ModuleInterface { /** * {@inheritDoc} */ public function integrate(Aurex $aurex) { $aurex->register(new FormServiceProvider); $aurex->register(new SessionServiceProvider); $aurex->register(new TranslationServiceProvider, [ 'locale' => 'en' ]); $aurex['form.extensions'] = $aurex->extend('form.extensions', function ($extensions, $app) { $managerRegistry = new FormManagerRegistry(null, [], ['default'], null, null, '\Doctrine\ORM\Proxy\Proxy'); $managerRegistry->setContainer($app); unset($extensions); return [(new DoctrineOrmExtension($managerRegistry))]; }); $aurex->getInjector()->share($aurex['form.factory']); } /** * {@inheritDoc} */ public function usesConfigurationKey() { return null; } }
J7mbo/Aurex
lib/Framework/Module/Modules/FormDoctrineModule/FormDoctrineModule.php
PHP
mit
1,340
define('exports@*', [], function(require, exports, module){ exports.a = 1; });
kaelzhang/neuron
test/mod/exports/*/exports.js
JavaScript
mit
84
package types // ApiVersion custom ENUM for SDK forward compatibility type ApiVersion int const ( ApiV1 ApiVersion = iota ) // EnvironmentType // https://docs.coinapi.io/#endpoints-2 type EnvironmentType int const ( ProdEncrypted EnvironmentType = iota ProdInsecure TestEncrypted TestInsecure ) // MessageType replicates the official incoming message types as (kinda) string enum. // https://docs.coinapi.io/#messages type MessageType string const ( TRADE MessageType = "trade" QUOTE MessageType = "quote" BOOK_L2_FULL MessageType = "book" // Orderbook L2 (Full) BOOK_L2_TOP_5 MessageType = "book5" // Orderbook L2 (5 best Bid / Ask) BOOK_L2_TOP_20 MessageType = "book20" // Orderbook L2 (20 best Bid / Ask) BOOK_L2_TOP_50 MessageType = "book50" // Orderbook L2 (50 best Bid / Ask) BOOK_L3_FULL MessageType = "book_l3" // Orderbook L3 (Full) https://docs.coinapi.io/#orderbook-l3-full-in OHLCV MessageType = "ohlcv" VOLUME MessageType = "volume" HEARTBEAT MessageType = "hearbeat" // DO NOT FIX! it's a typo in the official msg spec! ERROR MessageType = "error" // Otherwise processMessage(.) fails to handle heartbeat messages! EXCHANGERATE MessageType = "exrate" RECONNECT MessageType = "reconnect" ) // ReconnectType defines the reconnect behavior upon receiving a reconnect message // https://docs.coinapi.io/#reconnect-in type ReconnectType int const ( OnConnectionClose ReconnectType = iota OnReconnectMessage )
coinapi/coinapi-sdk
data-api/go-ws/api/types/enums.go
GO
mit
1,517
require 'rubygems' require 'bundler' Bundler.require require 'sinatra' set :public_folder, 'static' get '/' do File.read(File.join('index.html')) end get '/api/' do #content_type :js content_type("application/javascript") response["Content-Type"] = "application/javascript" #require 'config/initializers/beamly.rb' root = ::File.dirname(__FILE__) require ::File.join( root, 'config', 'initializers', 'beamly' ) #require 'config/initializers/beamly' z = Beamly::Epg.new region_id = z.regions.first.id provider_id = z.providers.first.id result = z.catalogues(region_id, provider_id) services = z.epg(result.first.epg_id) today = Date.today.strftime("%Y/%m/%d") schedule = z.schedule(services[8].service_id, today) today_formatted = Date.today.strftime("%Y-%m-%d") headers "Content-Type" => "application/json" json = '[' schedule.each do |item| time_formatted = Time.at(item.start).getlocal.strftime("%Y-%m-%d %H:%M") json += ' { "date": "'+time_formatted+'", "episodes": [ { "show": { "title": "'+item.title+'", "year": 2013, "genres": ["Comedy"], }, "episode":{"images": {"screen": "http://img-a.zeebox.com/940x505/'+item.img+'"}} } ] }, ' end json += ']' formatted_callback = "#{params['callback']}("+json+')' content_type("application/javascript") response["Content-Type"] = "application/javascript" formatted_callback end
TigerWolf/beamly_demo
main.rb
Ruby
mit
1,529
using System.Threading.Tasks; using FluentAssertions; using Histrio.Testing; using Xunit; namespace Histrio.Tests.Cell { public class When_getting_a_value_from_a_cell : GivenWhenThen { [Theory, InlineData(true), InlineData(333), InlineData(new[] {true, true}), InlineData("foo")] public void Then_value_the_cell_is_holding_on_to_is_returned<T>(T expectedValue) { var theater = new Theater(); var taskCompletionSource = new TaskCompletionSource<Reply<T>>(); ; Address customer = null; Address cell = null; Given(() => { cell = theater.CreateActor(new CellBehavior<T>()); var set = new Set<T>(expectedValue); theater.Dispatch(set, cell); customer = theater.CreateActor(new AssertionBehavior<Reply<T>>(taskCompletionSource, 1)); }); When(() => { var get = new Get(customer); theater.Dispatch(get, cell); }); Then(async () => { var actualValue = await taskCompletionSource.Task; actualValue.Content.ShouldBeEquivalentTo(expectedValue); }); } } }
MCGPPeters/Histrio
old/src/Histrio.Tests/Cell/When_getting_a_value_from_a_cell.cs
C#
mit
1,321
using System.Collections; using System.Collections.Generic; using UnityEngine; public class oscilation : MonoBehaviour { public float m_speed = 0.008f; public int m_distance = 45; private int compteur = 0; private int compteur2 = 0; // Use this for initialization void Start () { Vector3 yOrigin = transform.localPosition; /*Vector3 move = new Vector3(0.0f,0.0f,0.0f); Vector3 move2 = new Vector3(0.0f,0.0f,0.0f); move.y = m_speed; move2.y = -m_speed;*/ } // Update is called once per frame void Update () { if (compteur < m_distance) { Vector3 move = new Vector3(0.0f,0.0f,0.0f); move.y = m_speed; transform.localPosition = transform.localPosition + move; compteur++; } else if (compteur2 < m_distance) { Vector3 move2 = new Vector3(0.0f,0.0f,0.0f); move2.y = -m_speed; compteur2++; transform.localPosition = transform.localPosition + move2; } else { compteur = 0; compteur2 = 0; } } }
Wormkil/firstProject
Assets/oscilation.cs
C#
mit
962
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using System.Net; using System.Web; using System.Web.Mvc; using Transit.Models; namespace Transit.Controllers { public class RoutesController : Controller { private ApplicationDbContext db = new ApplicationDbContext(); // GET: Routes public async Task<ActionResult> Index() { var routes = db.Routes.Include(r => r.agency).Include(r => r.type); return View(await routes.ToListAsync()); } // GET: Routes/Details/5 public async Task<ActionResult> Details(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Route route = await db.Routes.FindAsync(id); if (route == null) { return HttpNotFound(); } return View(route); } // GET: Routes/Create public ActionResult Create() { ViewBag.agencyId = new SelectList(db.Agencies, "id", "name"); ViewBag.typeId = new SelectList(db.RouteTypes, "id", "label"); return View(); } // POST: Routes/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Create([Bind(Include = "id,agencyId,label,fullName,description,typeId,url,color,textColor")] Route route) { if (ModelState.IsValid) { db.Routes.Add(route); await db.SaveChangesAsync(); return RedirectToAction("Index"); } ViewBag.agencyId = new SelectList(db.Agencies, "id", "name", route.agencyId); ViewBag.typeId = new SelectList(db.RouteTypes, "id", "label", route.typeId); return View(route); } // GET: Routes/Edit/5 public async Task<ActionResult> Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Route route = await db.Routes.FindAsync(id); if (route == null) { return HttpNotFound(); } ViewBag.agencyId = new SelectList(db.Agencies, "id", "name", route.agencyId); ViewBag.typeId = new SelectList(db.RouteTypes, "id", "label", route.typeId); return View(route); } // POST: Routes/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Edit([Bind(Include = "id,agencyId,label,fullName,description,typeId,url,color,textColor")] Route route) { if (ModelState.IsValid) { db.Entry(route).State = EntityState.Modified; await db.SaveChangesAsync(); return RedirectToAction("Index"); } ViewBag.agencyId = new SelectList(db.Agencies, "id", "name", route.agencyId); ViewBag.typeId = new SelectList(db.RouteTypes, "id", "label", route.typeId); return View(route); } // GET: Routes/Delete/5 public async Task<ActionResult> Delete(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } Route route = await db.Routes.FindAsync(id); if (route == null) { return HttpNotFound(); } return View(route); } // POST: Routes/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<ActionResult> DeleteConfirmed(int id) { Route route = await db.Routes.FindAsync(id); db.Routes.Remove(route); await db.SaveChangesAsync(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } } }
cdchild/TransitApp
Transit/Controllers/RoutesController.cs
C#
mit
4,630
/* * This file is part of LuckPerms, licensed under the MIT License. * * Copyright (c) lucko (Luck) <luck@lucko.me> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.lucko.luckperms.nukkit.inject.server; import me.lucko.luckperms.nukkit.LPNukkitPlugin; import cn.nukkit.Server; import cn.nukkit.permission.Permissible; import cn.nukkit.plugin.PluginManager; import java.lang.reflect.Field; import java.util.Map; import java.util.Objects; import java.util.Set; /** * Injects a {@link LuckPermsSubscriptionMap} into the {@link PluginManager}. */ public class InjectorSubscriptionMap implements Runnable { private static final Field PERM_SUBS_FIELD; static { Field permSubsField = null; try { permSubsField = PluginManager.class.getDeclaredField("permSubs"); permSubsField.setAccessible(true); } catch (Exception e) { // ignore } PERM_SUBS_FIELD = permSubsField; } private final LPNukkitPlugin plugin; public InjectorSubscriptionMap(LPNukkitPlugin plugin) { this.plugin = plugin; } @Override public void run() { try { LuckPermsSubscriptionMap subscriptionMap = inject(); if (subscriptionMap != null) { this.plugin.setSubscriptionMap(subscriptionMap); } } catch (Exception e) { this.plugin.getLogger().severe("Exception occurred whilst injecting LuckPerms Permission Subscription map.", e); } } private LuckPermsSubscriptionMap inject() throws Exception { Objects.requireNonNull(PERM_SUBS_FIELD, "PERM_SUBS_FIELD"); PluginManager pluginManager = this.plugin.getBootstrap().getServer().getPluginManager(); Object map = PERM_SUBS_FIELD.get(pluginManager); if (map instanceof LuckPermsSubscriptionMap) { if (((LuckPermsSubscriptionMap) map).plugin == this.plugin) { return null; } map = ((LuckPermsSubscriptionMap) map).detach(); } //noinspection unchecked Map<String, Set<Permissible>> castedMap = (Map<String, Set<Permissible>>) map; // make a new subscription map & inject it LuckPermsSubscriptionMap newMap = new LuckPermsSubscriptionMap(this.plugin, castedMap); PERM_SUBS_FIELD.set(pluginManager, newMap); return newMap; } public static void uninject() { try { Objects.requireNonNull(PERM_SUBS_FIELD, "PERM_SUBS_FIELD"); PluginManager pluginManager = Server.getInstance().getPluginManager(); Object map = PERM_SUBS_FIELD.get(pluginManager); if (map instanceof LuckPermsSubscriptionMap) { LuckPermsSubscriptionMap lpMap = (LuckPermsSubscriptionMap) map; PERM_SUBS_FIELD.set(pluginManager, lpMap.detach()); } } catch (Exception e) { e.printStackTrace(); } } }
lucko/LuckPerms
nukkit/src/main/java/me/lucko/luckperms/nukkit/inject/server/InjectorSubscriptionMap.java
Java
mit
4,057
jQuery(document).ready(function(){ jQuery('.carousel').carousel() var FPS = 30; var player = $('#player') var pWidth = player.width(); $window = $(window) var wWidth = $window.width(); setInterval(function() { update(); }, 1000/FPS); function update() { if(keydown.space) { player.shoot(); } if(keydown.left) { console.log('go left') player.css('left', '-=10'); } if(keydown.right) { console.log('go right') var x = player.position().left; if(x + pWidth > wWidth) { player.css('left', '0') } else if(x < 0 ) { var p = wWidth + x - pWidth; var t = p + 'px' player.css('left', t) } else { player.css('left', '+=10'); } } } $('') })
ni5ni6/chiptuna.com
js/main.js
JavaScript
mit
739
// Copyright (c) 2015 The original author or authors // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. #if UNITY_EDITOR using SpriterDotNet; using System; using System.IO; using System.Linq; using UnityEditor; using UnityEngine; namespace SpriterDotNetUnity { public class SpriterImporter : AssetPostprocessor { private static readonly string[] ScmlExtensions = new string[] { ".scml" }; private static readonly float DeltaZ = -0.001f; private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath) { foreach (string asset in importedAssets) { if (!IsScml(asset)) continue; CreateSpriter(asset); } foreach (string asset in deletedAssets) { if (!IsScml(asset)) continue; } for (int i = 0; i < movedAssets.Length; i++) { string asset = movedAssets[i]; if (!IsScml(asset)) continue; } } private static bool IsScml(string path) { return ScmlExtensions.Any(path.EndsWith); } private static void CreateSpriter(string path) { string data = File.ReadAllText(path); Spriter spriter = SpriterParser.Parse(data); string rootFolder = Path.GetDirectoryName(path); foreach (SpriterEntity entity in spriter.Entities) { GameObject go = new GameObject(); go.name = entity.Name; SpriterDotNetBehaviour sdnBehaviour = go.AddComponent<SpriterDotNetBehaviour>(); sdnBehaviour.Entity = entity; sdnBehaviour.enabled = true; LoadSprites(sdnBehaviour, spriter, rootFolder); CreateChildren(entity, sdnBehaviour, spriter, go); string prefabPath = rootFolder + "/" + entity.Name + ".prefab"; PrefabUtility.CreatePrefab(prefabPath, go, ReplacePrefabOptions.ConnectToPrefab); GameObject.DestroyImmediate(go); } } private static void CreateChildren(SpriterEntity entity, SpriterDotNetBehaviour sdnBehaviour, Spriter spriter, GameObject parent) { int maxObjects = 0; foreach (SpriterAnimation animation in entity.Animations) { foreach (SpriterMainLineKey mainKey in animation.MainlineKeys) { maxObjects = Math.Max(maxObjects, mainKey.ObjectRefs.Length); } } sdnBehaviour.Children = new GameObject[maxObjects]; sdnBehaviour.Pivots = new GameObject[maxObjects]; for (int i = 0; i < maxObjects; ++i) { GameObject pivot = new GameObject(); GameObject child = new GameObject(); sdnBehaviour.Pivots[i] = pivot; sdnBehaviour.Children[i] = child; pivot.transform.SetParent(parent.transform); child.transform.SetParent(pivot.transform); child.transform.localPosition = new Vector3(0, 0, DeltaZ * i); pivot.name = "pivot " + i; child.name = "child " + i; child.AddComponent<SpriteRenderer>(); } } private static void LoadSprites(SpriterDotNetBehaviour sdnBehaviour, Spriter spriter, string rootFolder) { sdnBehaviour.Folders = new SdnFolder[spriter.Folders.Length]; for (int i = 0; i < spriter.Folders.Length; ++i) { SpriterFolder folder = spriter.Folders[i]; SdnFolder sdnFolder = new SdnFolder(); sdnFolder.Files = new Sprite[folder.Files.Length]; sdnBehaviour.Folders[i] = sdnFolder; for (int j = 0; j < folder.Files.Length; ++j) { SpriterFile file = folder.Files[j]; string spritePath = rootFolder; spritePath += "/"; spritePath += file.Name; Sprite sprite = AssetDatabase.LoadAssetAtPath<Sprite>(spritePath); if (sprite == null) { Debug.LogWarning("Unable to load sprite: " + spritePath); continue; } sdnFolder.Files[j] = sprite; } } } } } #endif
adamholdenyall/SpriterDotNet
SpriterDotNet.Unity/Assets/SpriterDotNet/SpriterImporter.cs
C#
mit
4,693
#!/usr/bin/env python # -*- coding: utf-8 -*- import base64 import json from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from behave import * @step('I share first element in the history list') def step_impl(context): context.execute_steps(u''' given I open History dialog ''') history = context.browser.find_element_by_id("HistoryPopup") entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]') assert len(entries) > 0, "There are no entries in the history" item = entries[0] item.find_elements_by_xpath('.//*[@data-share-item]')[0].click() @then('the json to share is shown with url "{url}" and contains the following headers') def step_impl(context, url): # Wait for modal to appear WebDriverWait(context.browser, 10).until( expected_conditions.visibility_of_element_located( (By.ID, 'ShareRequestForm'))) output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();") snippet = json.loads(output) assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output) for row in context.table: assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key']) assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name]) @step('I click on import request') def step_impl(context): context.execute_steps(u''' given I open History dialog ''') # Click on import context.browser.find_element_by_id('ImportHistory').click() WebDriverWait(context.browser, 10).until( expected_conditions.visibility_of_element_located( (By.ID, 'ImportRequestForm'))) @step('I write a shared request for "{url}"') def step_impl(context, url): req = json.dumps({ "method": "POST", "url": url, "headers": { "Content-Type": "application/json", "X-Test-Header": "shared_request" }, "body": { "type": "form", "content": { "SomeKey": "SomeValue11233", "SomeOtherKey": "SomeOtherValue019", } } }) context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req))) @step('I click on load import request') def step_impl(context): # Import request context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click()
jsargiot/restman
tests/steps/share.py
Python
mit
2,709
import { entryPoint } from '@rpgjs/standalone' import globalConfigClient from './config/client' import globalConfigServer from './config/server' import modules from './modules' document.addEventListener('DOMContentLoaded', function() { entryPoint(modules, { globalConfigClient, globalConfigServer }).start() })
RSamaium/RPG-JS
packages/sample3/src/standalone.ts
TypeScript
mit
338
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Elements part // // Contributor: Lionel Duchateau, kurtnoise@free.fr // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //--------------------------------------------------------------------------- // Pre-compilation #include "MediaInfo/PreComp.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Setup.h" #include <ZenLib/Ztring.h> #include <string> using namespace std; using namespace ZenLib; //--------------------------------------------------------------------------- //*************************************************************************** // Infos //*************************************************************************** //--------------------------------------------------------------------------- #if defined(MEDIAINFO_RIFF_YES) || defined(MEDIAINFO_MK_YES) //--------------------------------------------------------------------------- namespace MediaInfoLib { //--------------------------------------------------------------------------- std::string ExtensibleWave_ChannelMask (int32u ChannelMask) { std::string Text; if ((ChannelMask&0x0007)!=0x0000) Text+="Front:"; if (ChannelMask&0x0001) Text+=" L"; if (ChannelMask&0x0004) Text+=" C"; if (ChannelMask&0x0002) Text+=" R"; if ((ChannelMask&0x0600)!=0x0000) Text+=", Side:"; if (ChannelMask&0x0200) Text+=" L"; if (ChannelMask&0x0400) Text+=" R"; if ((ChannelMask&0x0130)!=0x0000) Text+=", Back:"; if (ChannelMask&0x0010) Text+=" L"; if (ChannelMask&0x0100) Text+=" C"; if (ChannelMask&0x0020) Text+=" R"; if ((ChannelMask&0x0008)!=0x0000) Text+=", LFE"; return Text; } //--------------------------------------------------------------------------- std::string ExtensibleWave_ChannelMask2 (int32u ChannelMask) { std::string Text; int8u Count=0; if (ChannelMask&0x0001) Count++; if (ChannelMask&0x0004) Count++; if (ChannelMask&0x0002) Count++; Text+=Ztring::ToZtring(Count).To_UTF8(); Count=0; if (ChannelMask&0x0200) Count++; if (ChannelMask&0x0400) Count++; Text+="/"+Ztring::ToZtring(Count).To_UTF8(); Count=0; if (ChannelMask&0x0010) Count++; if (ChannelMask&0x0100) Count++; if (ChannelMask&0x0020) Count++; Text+="/"+Ztring::ToZtring(Count).To_UTF8(); Count=0; if (ChannelMask&0x0008) Text+=".1"; return Text; } } //--------------------------------------------------------------------------- #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #ifdef MEDIAINFO_RIFF_YES //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Multiple/File_Riff.h" #if defined(MEDIAINFO_DVDIF_YES) #include "MediaInfo/Multiple/File_DvDif.h" #endif #if defined(MEDIAINFO_OGG_YES) #include "MediaInfo/Multiple/File_Ogg.h" #include "MediaInfo/Multiple/File_Ogg_SubElement.h" #endif #if defined(MEDIAINFO_FFV1_YES) #include "MediaInfo/Video/File_Ffv1.h" #endif #if defined(MEDIAINFO_HUFFYUV_YES) #include "MediaInfo/Video/File_HuffYuv.h" #endif #if defined(MEDIAINFO_MPEG4V_YES) #include "MediaInfo/Video/File_Mpeg4v.h" #endif #if defined(MEDIAINFO_MPEGV_YES) #include "MediaInfo/Video/File_Mpegv.h" #endif #if defined(MEDIAINFO_PRORES_YES) #include "MediaInfo/Video/File_ProRes.h" #endif #if defined(MEDIAINFO_AVC_YES) #include "MediaInfo/Video/File_Avc.h" #endif #if defined(MEDIAINFO_CANOPUS_YES) #include "MediaInfo/Video/File_Canopus.h" #endif #if defined(MEDIAINFO_FRAPS_YES) #include "MediaInfo/Video/File_Fraps.h" #endif #if defined(MEDIAINFO_LAGARITH_YES) #include "MediaInfo/Video/File_Lagarith.h" #endif #if defined(MEDIAINFO_MPEGA_YES) #include "MediaInfo/Audio/File_Mpega.h" #endif #if defined(MEDIAINFO_AAC_YES) #include "MediaInfo/Audio/File_Aac.h" #endif #if defined(MEDIAINFO_AC3_YES) #include "MediaInfo/Audio/File_Ac3.h" #endif #if defined(MEDIAINFO_DTS_YES) #include "MediaInfo/Audio/File_Dts.h" #endif #if defined(MEDIAINFO_JPEG_YES) #include "MediaInfo/Image/File_Jpeg.h" #endif #if defined(MEDIAINFO_SUBRIP_YES) #include "MediaInfo/Text/File_SubRip.h" #endif #if defined(MEDIAINFO_OTHERTEXT_YES) #include "MediaInfo/Text/File_OtherText.h" #endif #if defined(MEDIAINFO_ADPCM_YES) #include "MediaInfo/Audio/File_Adpcm.h" #endif #if defined(MEDIAINFO_PCM_YES) #include "MediaInfo/Audio/File_Pcm.h" #endif #if defined(MEDIAINFO_SMPTEST0337_YES) #include "MediaInfo/Audio/File_SmpteSt0337.h" #endif #if defined(MEDIAINFO_ID3_YES) #include "MediaInfo/Tag/File_Id3.h" #endif #if defined(MEDIAINFO_ID3V2_YES) #include "MediaInfo/Tag/File_Id3v2.h" #endif #if defined(MEDIAINFO_GXF_YES) #if defined(MEDIAINFO_CDP_YES) #include "MediaInfo/Text/File_Cdp.h" #include <cstring> #endif #endif //MEDIAINFO_GXF_YES #include <vector> #include "MediaInfo/MediaInfo_Config_MediaInfo.h" using namespace std; //--------------------------------------------------------------------------- namespace MediaInfoLib { //*************************************************************************** // Const //*************************************************************************** namespace Elements { const int32u FORM=0x464F524D; const int32u LIST=0x4C495354; const int32u ON2_=0x4F4E3220; const int32u RIFF=0x52494646; const int32u RF64=0x52463634; const int32u AIFC=0x41494643; const int32u AIFC_COMM=0x434F4D4D; const int32u AIFC_COMT=0x434F4D54; const int32u AIFC_FVER=0x46564552; const int32u AIFC_SSND=0x53534E44; const int32u AIFF=0x41494646; const int32u AIFF_COMM=0x434F4D4D; const int32u AIFF_COMT=0x434F4D54; const int32u AIFF_SSND=0x53534E44; const int32u AIFF__c__=0x28632920; const int32u AIFF_ANNO=0x414E4E4F; const int32u AIFF_AUTH=0x41555448; const int32u AIFF_NAME=0x4E414D45; const int32u AIFF_ID3_=0x49443320; const int32u AVI_=0x41564920; const int32u AVI__cset=0x63736574; const int32u AVI__Cr8r=0x43723872; const int32u AVI__exif=0x65786966; const int32u AVI__exif_ecor=0x65636F72; const int32u AVI__exif_emdl=0x656D646C; const int32u AVI__exif_emnt=0x656D6E74; const int32u AVI__exif_erel=0x6572656C; const int32u AVI__exif_etim=0x6574696D; const int32u AVI__exif_eucm=0x6575636D; const int32u AVI__exif_ever=0x65766572; const int32u AVI__goog=0x676F6F67; const int32u AVI__goog_GDAT=0x47444154; const int32u AVI__GMET=0x474D4554; const int32u AVI__hdlr=0x6864726C; const int32u AVI__hdlr_avih=0x61766968; const int32u AVI__hdlr_JUNK=0x4A554E4B; const int32u AVI__hdlr_strl=0x7374726C; const int32u AVI__hdlr_strl_indx=0x696E6478; const int32u AVI__hdlr_strl_JUNK=0x4A554E4B; const int32u AVI__hdlr_strl_strd=0x73747264; const int32u AVI__hdlr_strl_strf=0x73747266; const int32u AVI__hdlr_strl_strh=0x73747268; const int32u AVI__hdlr_strl_strh_auds=0x61756473; const int32u AVI__hdlr_strl_strh_iavs=0x69617673; const int32u AVI__hdlr_strl_strh_mids=0x6D696473; const int32u AVI__hdlr_strl_strh_vids=0x76696473; const int32u AVI__hdlr_strl_strh_txts=0x74787473; const int32u AVI__hdlr_strl_strn=0x7374726E; const int32u AVI__hdlr_strl_vprp=0x76707270; const int32u AVI__hdlr_odml=0x6F646D6C; const int32u AVI__hdlr_odml_dmlh=0x646D6C68; const int32u AVI__hdlr_ON2h=0x4F4E3268; const int32u AVI__idx1=0x69647831; const int32u AVI__INFO=0x494E464F; const int32u AVI__INFO_IARL=0x4941524C; const int32u AVI__INFO_IART=0x49415254; const int32u AVI__INFO_IAS1=0x49415331; const int32u AVI__INFO_IAS2=0x49415332; const int32u AVI__INFO_IAS3=0x49415333; const int32u AVI__INFO_IAS4=0x49415334; const int32u AVI__INFO_IAS5=0x49415335; const int32u AVI__INFO_IAS6=0x49415336; const int32u AVI__INFO_IAS7=0x49415337; const int32u AVI__INFO_IAS8=0x49415338; const int32u AVI__INFO_IAS9=0x49415339; const int32u AVI__INFO_ICDS=0x49434453; const int32u AVI__INFO_ICMS=0x49434D53; const int32u AVI__INFO_ICMT=0x49434D54; const int32u AVI__INFO_ICNT=0x49434E54; const int32u AVI__INFO_ICOP=0x49434F50; const int32u AVI__INFO_ICNM=0x49434E4D; const int32u AVI__INFO_ICRD=0x49435244; const int32u AVI__INFO_ICRP=0x49435250; const int32u AVI__INFO_IDIM=0x4944494D; const int32u AVI__INFO_IDIT=0x49444954; const int32u AVI__INFO_IDPI=0x49445049; const int32u AVI__INFO_IDST=0x49445354; const int32u AVI__INFO_IEDT=0x49454454; const int32u AVI__INFO_IENG=0x49454E47; const int32u AVI__INFO_IFRM=0x4946524D; const int32u AVI__INFO_IGNR=0x49474E52; const int32u AVI__INFO_IID3=0x49494433; const int32u AVI__INFO_IKEY=0x494B4559; const int32u AVI__INFO_ILGT=0x494C4754; const int32u AVI__INFO_ILNG=0x494C4E47; const int32u AVI__INFO_ILYC=0x494C5943; const int32u AVI__INFO_IMED=0x494D4544; const int32u AVI__INFO_IMP3=0x494D5033; const int32u AVI__INFO_IMUS=0x494D5553; const int32u AVI__INFO_INAM=0x494E414D; const int32u AVI__INFO_IPLT=0x49504C54; const int32u AVI__INFO_IPDS=0x49504453; const int32u AVI__INFO_IPRD=0x49505244; const int32u AVI__INFO_IPRT=0x49505254; const int32u AVI__INFO_IPRO=0x4950524F; const int32u AVI__INFO_IRTD=0x49525444; const int32u AVI__INFO_ISBJ=0x4953424A; const int32u AVI__INFO_ISGN=0x4953474E; const int32u AVI__INFO_ISTD=0x49535444; const int32u AVI__INFO_ISTR=0x49535452; const int32u AVI__INFO_ISFT=0x49534654; const int32u AVI__INFO_ISHP=0x49534850; const int32u AVI__INFO_ISMP=0x49534D50; const int32u AVI__INFO_ISRC=0x49535243; const int32u AVI__INFO_ISRF=0x49535246; const int32u AVI__INFO_ITCH=0x49544348; const int32u AVI__INFO_IWEB=0x49574542; const int32u AVI__INFO_IWRI=0x49575249; const int32u AVI__INFO_JUNK=0x4A554E4B; const int32u AVI__JUNK=0x4A554E4B; const int32u AVI__MD5_=0x4D443520; const int32u AVI__movi=0x6D6F7669; const int32u AVI__movi_rec_=0x72656320; const int32u AVI__movi_xxxx_____=0x00005F5F; const int32u AVI__movi_xxxx___db=0x00006462; const int32u AVI__movi_xxxx___dc=0x00006463; const int32u AVI__movi_xxxx___sb=0x00007362; const int32u AVI__movi_xxxx___tx=0x00007478; const int32u AVI__movi_xxxx___wb=0x00007762; const int32u AVI__PrmA=0x50726D41; const int32u AVI__Tdat=0x54646174; const int32u AVI__Tdat_rn_A=0x726E5F41; const int32u AVI__Tdat_rn_O=0x726E5F4F; const int32u AVI__Tdat_tc_A=0x74635F41; const int32u AVI__Tdat_tc_O=0x74635F4F; const int32u AVIX=0x41564958; const int32u AVIX_idx1=0x69647831; const int32u AVIX_movi=0x6D6F7669; const int32u AVIX_movi_rec_=0x72656320; const int32u CADP=0x43414450; const int32u CDDA=0x43444441; const int32u CDDA_fmt_=0x666D7420; const int32u CMJP=0x434D4A50; const int32u CMP4=0x434D5034; const int32u IDVX=0x49445658; const int32u INDX=0x494E4458; const int32u JUNK=0x4A554E4B; const int32u menu=0x6D656E75; const int32u MThd=0x4D546864; const int32u MTrk=0x4D54726B; const int32u PAL_=0x50414C20; const int32u QLCM=0x514C434D; const int32u QLCM_fmt_=0x666D7420; const int32u rcrd=0x72637264; const int32u rcrd_desc=0x64657363; const int32u rcrd_fld_=0x666C6420; const int32u rcrd_fld__anc_=0x616E6320; const int32u rcrd_fld__anc__pos_=0x706F7320; const int32u rcrd_fld__anc__pyld=0x70796C64; const int32u rcrd_fld__finf=0x66696E66; const int32u RDIB=0x52444942; const int32u RMID=0x524D4944; const int32u RMMP=0x524D4D50; const int32u RMP3=0x524D5033; const int32u RMP3_data=0x64617461; const int32u RMP3_INFO=0x494E464F; const int32u RMP3_INFO_IID3=0x49494433; const int32u RMP3_INFO_ILYC=0x494C5943; const int32u RMP3_INFO_IMP3=0x494D5033; const int32u RMP3_INFO_JUNK=0x4A554E4B; const int32u SMV0=0x534D5630; const int32u SMV0_xxxx=0x534D563A; const int32u WAVE=0x57415645; const int32u WAVE__pmx=0x20786D70; const int32u WAVE_aXML=0x61584D4C; const int32u WAVE_bext=0x62657874; const int32u WAVE_cue_=0x63756520; const int32u WAVE_data=0x64617461; const int32u WAVE_ds64=0x64733634; const int32u WAVE_fact=0x66616374; const int32u WAVE_fmt_=0x666D7420; const int32u WAVE_ID3_=0x49443320; const int32u WAVE_id3_=0x69643320; const int32u WAVE_INFO=0x494E464F; const int32u WAVE_iXML=0x69584D4C; const int32u wave=0x77617665; const int32u wave_data=0x64617461; const int32u wave_fmt_=0x666D7420; const int32u W3DI=0x57334449; #define UUID(NAME, PART1, PART2, PART3, PART4, PART5) \ const int64u NAME =0x##PART3##PART2##PART1##ULL; \ const int64u NAME##2=0x##PART4##PART5##ULL; \ UUID(QLCM_QCELP1, 5E7F6D41, B115, 11D0, BA91, 00805FB4B97E) UUID(QLCM_QCELP2, 5E7F6D42, B115, 11D0, BA91, 00805FB4B97E) UUID(QLCM_EVRC, E689D48D, 9076, 46B5, 91EF, 736A5100CEB4) UUID(QLCM_SMV, 8D7C2B75, A797, ED49, 985E, D53C8CC75F84) } //*************************************************************************** // Format //*************************************************************************** //--------------------------------------------------------------------------- void File_Riff::Data_Parse() { //Alignement specific Element_Size-=Alignement_ExtraByte; DATA_BEGIN LIST(AIFC) ATOM_BEGIN ATOM(AIFC_COMM) ATOM(AIFC_COMT) ATOM(AIFC_FVER) ATOM(AIFC_SSND) ATOM_DEFAULT(AIFC_xxxx) ATOM_END_DEFAULT LIST(AIFF) ATOM_BEGIN ATOM(AIFF_COMM) ATOM(AIFF_COMT) ATOM(AIFF_ID3_) LIST_SKIP(AIFF_SSND) ATOM_DEFAULT(AIFF_xxxx) ATOM_END_DEFAULT LIST(AVI_) ATOM_BEGIN ATOM(AVI__Cr8r); ATOM(AVI__cset) LIST(AVI__exif) ATOM_DEFAULT_ALONE(AVI__exif_xxxx) LIST(AVI__goog) ATOM_BEGIN ATOM(AVI__goog_GDAT) ATOM_END ATOM(AVI__GMET) LIST(AVI__hdlr) ATOM_BEGIN ATOM(AVI__hdlr_avih) ATOM(AVI__hdlr_JUNK) LIST(AVI__hdlr_strl) ATOM_BEGIN ATOM(AVI__hdlr_strl_indx) ATOM(AVI__hdlr_strl_JUNK) ATOM(AVI__hdlr_strl_strd) ATOM(AVI__hdlr_strl_strf) ATOM(AVI__hdlr_strl_strh) ATOM(AVI__hdlr_strl_strn) ATOM(AVI__hdlr_strl_vprp) ATOM_END LIST(AVI__hdlr_odml) ATOM_BEGIN ATOM(AVI__hdlr_odml_dmlh) ATOM_END ATOM(AVI__hdlr_ON2h) LIST(AVI__INFO) ATOM_BEGIN ATOM(AVI__INFO_IID3) ATOM(AVI__INFO_ILYC) ATOM(AVI__INFO_IMP3) ATOM(AVI__INFO_JUNK) ATOM_DEFAULT(AVI__INFO_xxxx) ATOM_END_DEFAULT ATOM_DEFAULT(AVI__hdlr_xxxx) ATOM_END_DEFAULT ATOM(AVI__idx1) LIST(AVI__INFO) ATOM_BEGIN ATOM(AVI__INFO_IID3) ATOM(AVI__INFO_ILYC) ATOM(AVI__INFO_IMP3) ATOM(AVI__INFO_JUNK) ATOM_DEFAULT(AVI__INFO_xxxx) ATOM_END_DEFAULT ATOM(AVI__JUNK) ATOM(AVI__MD5_) LIST(AVI__movi) ATOM_BEGIN LIST(AVI__movi_rec_) ATOM_DEFAULT_ALONE(AVI__movi_xxxx) ATOM_DEFAULT(AVI__movi_xxxx) ATOM_END_DEFAULT ATOM(AVI__PrmA); LIST(AVI__Tdat) ATOM_BEGIN ATOM(AVI__Tdat_rn_A) ATOM(AVI__Tdat_rn_O) ATOM(AVI__Tdat_tc_A) ATOM(AVI__Tdat_tc_O) ATOM_END ATOM_DEFAULT(AVI__xxxx) ATOM_END_DEFAULT LIST(AVIX) //OpenDML ATOM_BEGIN ATOM(AVIX_idx1) LIST(AVIX_movi) ATOM_BEGIN LIST(AVIX_movi_rec_) ATOM_DEFAULT_ALONE(AVIX_movi_xxxx) ATOM_DEFAULT(AVIX_movi_xxxx) ATOM_END_DEFAULT ATOM_END ATOM_PARTIAL(CADP) LIST(CDDA) ATOM_BEGIN ATOM(CDDA_fmt_) ATOM_END ATOM_PARTIAL(CMJP) ATOM(CMP4) ATOM(IDVX) LIST(INDX) ATOM_DEFAULT_ALONE(INDX_xxxx) LIST_SKIP(JUNK) LIST_SKIP(menu) ATOM(MThd) LIST_SKIP(MTrk) LIST_SKIP(PAL_) LIST(QLCM) ATOM_BEGIN ATOM(QLCM_fmt_) ATOM_END #if defined(MEDIAINFO_GXF_YES) LIST(rcrd) ATOM_BEGIN ATOM(rcrd_desc) LIST(rcrd_fld_) ATOM_BEGIN LIST(rcrd_fld__anc_) ATOM_BEGIN ATOM(rcrd_fld__anc__pos_) ATOM(rcrd_fld__anc__pyld) ATOM_END ATOM(rcrd_fld__finf) ATOM_END ATOM_END #endif //defined(MEDIAINFO_GXF_YES) LIST_SKIP(RDIB) LIST_SKIP(RMID) LIST_SKIP(RMMP) LIST(RMP3) ATOM_BEGIN LIST(RMP3_data) break; LIST(RMP3_INFO) ATOM_BEGIN ATOM(RMP3_INFO_IID3) ATOM(RMP3_INFO_ILYC) ATOM(RMP3_INFO_IMP3) ATOM(RMP3_INFO_JUNK) ATOM_DEFAULT(RMP3_INFO_xxxx) ATOM_END_DEFAULT ATOM_END ATOM(SMV0) ATOM(SMV0_xxxx) ATOM(W3DI) LIST(WAVE) ATOM_BEGIN ATOM(WAVE__pmx) ATOM(WAVE_aXML) ATOM(WAVE_bext) LIST(WAVE_data) break; ATOM(WAVE_cue_) ATOM(WAVE_ds64) ATOM(WAVE_fact) ATOM(WAVE_fmt_) ATOM(WAVE_ID3_) ATOM(WAVE_id3_) LIST(WAVE_INFO) ATOM_DEFAULT_ALONE(WAVE_INFO_xxxx) ATOM(WAVE_iXML) ATOM_END LIST(wave) ATOM_BEGIN LIST(wave_data) break; ATOM(wave_fmt_) ATOM_END DATA_END if (Alignement_ExtraByte) { Element_Size+=Alignement_ExtraByte; if (Element_Offset+Alignement_ExtraByte==Element_Size) Skip_XX(Alignement_ExtraByte, "Alignement"); } } //*************************************************************************** // Elements //*************************************************************************** //--------------------------------------------------------------------------- void File_Riff::AIFC() { Data_Accept("AIFF Compressed"); Element_Name("AIFF Compressed"); //Filling Fill(Stream_General, 0, General_Format, "AIFF"); Stream_Prepare(Stream_Audio); Kind=Kind_Aiff; #if MEDIAINFO_EVENTS StreamIDs_Width[0]=0; #endif //MEDIAINFO_EVENTS } //--------------------------------------------------------------------------- void File_Riff::AIFC_COMM() { AIFF_COMM(); } //--------------------------------------------------------------------------- void File_Riff::AIFC_COMT() { AIFF_COMT(); } //--------------------------------------------------------------------------- void File_Riff::AIFC_FVER() { Element_Name("Format Version"); //Parsing Skip_B4( "Version"); } //--------------------------------------------------------------------------- void File_Riff::AIFC_SSND() { AIFF_SSND(); } //--------------------------------------------------------------------------- void File_Riff::AIFC_xxxx() { AIFF_xxxx(); } //--------------------------------------------------------------------------- void File_Riff::AIFF() { Data_Accept("AIFF"); Element_Name("AIFF"); //Filling Fill(Stream_General, 0, General_Format, "AIFF"); Stream_Prepare(Stream_Audio); Kind=Kind_Aiff; #if MEDIAINFO_EVENTS StreamIDs_Width[0]=0; #endif //MEDIAINFO_EVENTS } //--------------------------------------------------------------------------- void File_Riff::AIFF_COMM() { Element_Name("Common"); int32u numSampleFrames; int16u numChannels, sampleSize; float80 sampleRate; //Parsing Get_B2 (numChannels, "numChannels"); Get_B4 (numSampleFrames, "numSampleFrames"); Get_B2 (sampleSize, "sampleSize"); Get_BF10(sampleRate, "sampleRate"); if (Data_Remain()) //AIFC { int32u compressionType; Get_C4 (compressionType, "compressionType"); Skip_PA( "compressionName"); //Filling CodecID_Fill(Ztring().From_CC4(compressionType), Stream_Audio, StreamPos_Last, InfoCodecID_Format_Mpeg4); Fill(Stream_Audio, StreamPos_Last, Audio_Codec, Ztring().From_CC4(compressionType)); } else { //Filling Fill(Stream_Audio, StreamPos_Last, Audio_Format, "PCM"); Fill(Stream_Audio, StreamPos_Last, Audio_Codec, "PCM"); } //Filling Fill(Stream_Audio, StreamPos_Last, Audio_Channel_s_, numChannels); Fill(Stream_Audio, StreamPos_Last, Audio_BitDepth, sampleSize); if (sampleRate) Fill(Stream_Audio, StreamPos_Last, Audio_Duration, numSampleFrames/sampleRate*1000); Fill(Stream_Audio, StreamPos_Last, Audio_SamplingRate, sampleRate, 0); //Compute the current codec ID Element_Code=(int64u)-1; Stream_ID=(int32u)-1; stream_Count=1; //Specific cases #if defined(MEDIAINFO_SMPTEST0337_YES) if (Retrieve(Stream_Audio, 0, Audio_CodecID).empty() && numChannels==2 && sampleSize<=32 && sampleRate==48000) //Some SMPTE ST 337 streams are hidden in PCM stream { File_SmpteSt0337* Parser=new File_SmpteSt0337; Parser->Endianness='B'; Parser->Container_Bits=(int8u)sampleSize; Parser->ShouldContinueParsing=true; #if MEDIAINFO_DEMUX if (Config->Demux_Unpacketize_Get()) { Parser->Demux_Level=2; //Container Parser->Demux_UnpacketizeContainer=true; Demux_Level=4; //Intermediate } #endif //MEDIAINFO_DEMUX Stream[Stream_ID].Parsers.push_back(Parser); } #endif stream& StreamItem = Stream[Stream_ID]; #if defined(MEDIAINFO_PCM_YES) File_Pcm* Parser=new File_Pcm; Parser->Codec=Retrieve(Stream_Audio, StreamPos_Last, Audio_CodecID); if (Parser->Codec.empty() || Parser->Codec==__T("NONE")) Parser->Endianness='B'; Parser->BitDepth=(int8u)sampleSize; #if MEDIAINFO_DEMUX if (Demux_Rate) Parser->Frame_Count_Valid = float64_int64s(Demux_Rate); if (Config->Demux_Unpacketize_Get()) { Parser->Demux_Level=2; //Container Parser->Demux_UnpacketizeContainer=true; Demux_Level=4; //Intermediate } #else //MEDIAINFO_DEMUX Parser->Frame_Count_Valid=(int64u)-1; //Disabling it, waiting for SMPTE ST 337 parser reject #endif //MEDIAINFO_DEMUX StreamItem.Parsers.push_back(Parser); StreamItem.IsPcm=true; StreamItem.StreamKind=Stream_Audio; #endif #if MEDIAINFO_DEMUX BlockAlign=numChannels*sampleSize/8; AvgBytesPerSec=(int32u)float64_int64s(BlockAlign*(float64)sampleRate); #endif //MEDIAINFO_DEMUX Element_Code=(int64u)-1; Open_Buffer_Init_All(); } //--------------------------------------------------------------------------- void File_Riff::AIFF_COMT() { //Parsing int16u numComments; Get_B2(numComments, "numComments"); for (int16u Pos=0; Pos<=numComments; Pos++) { Ztring text; int16u count; Element_Begin1("Comment"); Skip_B4( "timeStamp"); Skip_B4( "marker"); Get_B2 (count, "count"); count+=count%1; //always even Get_Local(count, text, "text"); Element_End0(); //Filling Fill(Stream_General, 0, General_Comment, text); } } //--------------------------------------------------------------------------- void File_Riff::AIFF_SSND() { WAVE_data(); } //--------------------------------------------------------------------------- void File_Riff::AIFF_SSND_Continue() { WAVE_data_Continue(); } //--------------------------------------------------------------------------- void File_Riff::AIFF_xxxx() { #define ELEMENT_CASE(_ELEMENT, _NAME) \ case Elements::_ELEMENT : Element_Name(_NAME); Name=_NAME; break; //Known? std::string Name; switch(Element_Code) { ELEMENT_CASE(AIFF__c__, "Copyright"); ELEMENT_CASE(AIFF_ANNO, "Comment"); ELEMENT_CASE(AIFF_AUTH, "Performer"); ELEMENT_CASE(AIFF_NAME, "Title"); default : Skip_XX(Element_Size, "Unknown"); return; } //Parsing Ztring text; Get_Local(Element_Size, text, "text"); //Filling Fill(Stream_General, 0, Name.c_str(), text); } //--------------------------------------------------------------------------- void File_Riff::AVI_() { Element_Name("AVI"); //Test if there is only one AVI chunk if (Status[IsAccepted]) { Element_Info1("Problem: 2 AVI chunks, this is not normal"); Skip_XX(Element_TotalSize_Get(), "Data"); return; } Data_Accept("AVI"); //Filling Fill(Stream_General, 0, General_Format, "AVI"); Kind=Kind_Avi; //Configuration Buffer_MaximumSize=64*1024*1024; //Some big frames are possible (e.g YUV 4:2:2 10 bits 1080p) } //--------------------------------------------------------------------------- void File_Riff::AVI__Cr8r() { Element_Name("Adobe Premiere Cr8r"); //Parsing Skip_C4( "FourCC"); Skip_B4( "Size"); Skip_XX(Element_Size-Element_Offset, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::AVI__cset() { Element_Name("Regional settings"); //Parsing Skip_L2( "CodePage"); //TODO: take a look about IBM/MS RIFF/MCI Specification 1.0 Skip_L2( "CountryCode"); Skip_L2( "LanguageCode"); Skip_L2( "Dialect"); } //--------------------------------------------------------------------------- void File_Riff::AVI__exif() { Element_Name("Exif (Exchangeable Image File Format)"); } //--------------------------------------------------------------------------- void File_Riff::AVI__exif_xxxx() { Element_Name("Value"); //Parsing Ztring Value; Get_Local(Element_Size, Value, "Value"); //Filling switch (Element_Code) { case Elements::AVI__exif_ecor : Fill(Stream_General, 0, "Make", Value); break; case Elements::AVI__exif_emdl : Fill(Stream_General, 0, "Model", Value); break; case Elements::AVI__exif_emnt : Fill(Stream_General, 0, "MakerNotes", Value); break; case Elements::AVI__exif_erel : Fill(Stream_General, 0, "RelatedImageFile", Value); break; case Elements::AVI__exif_etim : Fill(Stream_General, 0, "Written_Date", Value); break; case Elements::AVI__exif_eucm : Fill(Stream_General, 0, General_Comment, Value); break; case Elements::AVI__exif_ever : break; //Exif version default: Fill(Stream_General, 0, Ztring().From_CC4((int32u)Element_Code).To_Local().c_str(), Value); } } //--------------------------------------------------------------------------- void File_Riff::AVI__goog() { Element_Name("Google specific"); //Filling Fill(Stream_General, 0, General_Format, "Google Video", Unlimited, false, true); } //--------------------------------------------------------------------------- void File_Riff::AVI__goog_GDAT() { Element_Name("Google datas"); } //--------------------------------------------------------------------------- // Google Metadata // void File_Riff::AVI__GMET() { Element_Name("Google Metadatas"); //Parsing Ztring Value; Value.From_Local((const char*)(Buffer+Buffer_Offset+0), (size_t)Element_Size); ZtringListList List; List.Separator_Set(0, __T("\n")); List.Separator_Set(1, __T(":")); List.Max_Set(1, 2); List.Write(Value); //Details #if MEDIAINFO_TRACE if (Config_Trace_Level) { //for (size_t Pos=0; Pos<List.size(); Pos++) // Details_Add_Info(Pos, List(Pos, 0).To_Local().c_str(), List(Pos, 1)); } #endif //MEDIAINFO_TRACE //Filling for (size_t Pos=0; Pos<List.size(); Pos++) { if (List(Pos, 0)==__T("title")) Fill(Stream_General, 0, General_Title, List(Pos, 1)); if (List(Pos, 0)==__T("description")) Fill(Stream_General, 0, General_Title_More, List(Pos, 1)); if (List(Pos, 0)==__T("url")) Fill(Stream_General, 0, General_Title_Url, List(Pos, 1)); if (List(Pos, 0)==__T("docid")) Fill(Stream_General, 0, General_UniqueID, List(Pos, 1)); } } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr() { Element_Name("AVI Header"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_avih() { Element_Name("File header"); //Parsing int32u MicrosecPerFrame, Flags; Get_L4 (MicrosecPerFrame, "MicrosecPerFrame"); Skip_L4( "MaxBytesPerSec"); Skip_L4( "PaddingGranularity"); Get_L4 (Flags, "Flags"); Skip_Flags(Flags, 4, "HasIndex"); Skip_Flags(Flags, 5, "MustUseIndex"); Skip_Flags(Flags, 8, "IsInterleaved"); Skip_Flags(Flags, 9, "UseCKTypeToFindKeyFrames"); Skip_Flags(Flags, 11, "TrustCKType"); Skip_Flags(Flags, 16, "WasCaptureFile"); Skip_Flags(Flags, 17, "Copyrighted"); Get_L4 (avih_TotalFrame, "TotalFrames"); Skip_L4( "InitialFrames"); Skip_L4( "StreamsCount"); Skip_L4( "SuggestedBufferSize"); Skip_L4( "Width"); Skip_L4( "Height"); Skip_L4( "Reserved"); Skip_L4( "Reserved"); Skip_L4( "Reserved"); Skip_L4( "Reserved"); if(Element_Offset<Element_Size) Skip_XX(Element_Size-Element_Offset, "Unknown"); //Filling if (MicrosecPerFrame>0) avih_FrameRate=1000000.0/MicrosecPerFrame; } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_JUNK() { Element_Name("Garbage"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_odml() { Element_Name("OpenDML"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_odml_dmlh() { Element_Name("OpenDML Header"); //Parsing Get_L4(dmlh_TotalFrame, "GrandFrames"); if (Element_Offset<Element_Size) Skip_XX(Element_Size-Element_Offset, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_ON2h() { Element_Name("On2 header"); //Parsing Skip_XX(Element_Size, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl() { Element_Name("Stream info"); Element_Info1(stream_Count); //Clean up StreamKind_Last=Stream_Max; StreamPos_Last=(size_t)-1; //Compute the current codec ID Stream_ID=(('0'+stream_Count/10)*0x01000000 +('0'+stream_Count )*0x00010000); stream_Count++; } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_indx() { Element_Name("Index"); int32u Entry_Count, ChunkId; int16u LongsPerEntry; int8u IndexType, IndexSubType; Get_L2 (LongsPerEntry, "LongsPerEntry"); //Size of each entry in aIndex array Get_L1 (IndexSubType, "IndexSubType"); Get_L1 (IndexType, "IndexType"); Get_L4 (Entry_Count, "EntriesInUse"); //Index of first unused member in aIndex array Get_C4 (ChunkId, "ChunkId"); //FCC of what is indexed //Depends of size of structure... switch (IndexType) { case 0x01 : //AVI_INDEX_OF_CHUNKS switch (IndexSubType) { case 0x00 : AVI__hdlr_strl_indx_StandardIndex(Entry_Count, ChunkId); break; case 0x01 : AVI__hdlr_strl_indx_FieldIndex(Entry_Count, ChunkId); break; //AVI_INDEX_2FIELD default: Skip_XX(Element_Size-Element_Offset, "Unknown"); } break; case 0x0 : //AVI_INDEX_OF_INDEXES switch (IndexSubType) { case 0x00 : case 0x01 : AVI__hdlr_strl_indx_SuperIndex(Entry_Count, ChunkId); break; //AVI_INDEX_2FIELD default: Skip_XX(Element_Size-Element_Offset, "Unknown"); } break; default: Skip_XX(Element_Size-Element_Offset, "Unknown"); } } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_indx_StandardIndex(int32u Entry_Count, int32u ChunkId) { Element_Name("Standard Index"); //Parsing int64u BaseOffset, StreamSize=0; Get_L8 (BaseOffset, "BaseOffset"); Skip_L4( "Reserved3"); for (int32u Pos=0; Pos<Entry_Count; Pos++) { //Is too slow /* Element_Begin1("Index"); int32u Offset, Size; Get_L4 (Offset, "Offset"); //BaseOffset + this is absolute file offset Get_L4 (Size, "Size"); //Bit 31 is set if this is NOT a keyframe Element_Info1(Size&0x7FFFFFFF); if (Size) Element_Info1("KeyFrame"); Element_End0(); */ //Faster method if (Element_Offset+8>Element_Size) break; //Malformed index int32u Offset=LittleEndian2int32u(Buffer+Buffer_Offset+(size_t)Element_Offset ); int32u Size =LittleEndian2int32u(Buffer+Buffer_Offset+(size_t)Element_Offset+4)&0x7FFFFFFF; Element_Offset+=8; //Stream Position and size if (Pos<300 || MediaInfoLib::Config.ParseSpeed_Get()==1.00) { Stream_Structure[BaseOffset+Offset-8].Name=ChunkId&0xFFFF0000; Stream_Structure[BaseOffset+Offset-8].Size=Size; } StreamSize+=(Size&0x7FFFFFFF); Stream[ChunkId&0xFFFF0000].PacketCount++; //Interleaved if (Pos== 0 && (ChunkId&0xFFFF0000)==0x30300000 && Interleaved0_1 ==0) Interleaved0_1 =BaseOffset+Offset-8; if (Pos==Entry_Count/10 && (ChunkId&0xFFFF0000)==0x30300000 && Interleaved0_10==0) Interleaved0_10=BaseOffset+Offset-8; if (Pos== 0 && (ChunkId&0xFFFF0000)==0x30310000 && Interleaved1_1 ==0) Interleaved1_1 =BaseOffset+Offset-8; if (Pos==Entry_Count/10 && (ChunkId&0xFFFF0000)==0x30310000 && Interleaved1_10==0) Interleaved1_10=BaseOffset+Offset-8; } Stream[ChunkId&0xFFFF0000].StreamSize+=StreamSize; if (Element_Offset<Element_Size) Skip_XX(Element_Size-Element_Offset, "Garbage"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_indx_FieldIndex(int32u Entry_Count, int32u) { Element_Name("Field Index"); //Parsing Skip_L8( "Offset"); Skip_L4( "Reserved2"); for (int32u Pos=0; Pos<Entry_Count; Pos++) { Element_Begin1("Index"); Skip_L4( "Offset"); //BaseOffset + this is absolute file offset Skip_L4( "Size"); //Bit 31 is set if this is NOT a keyframe Skip_L4( "OffsetField2"); //Offset to second field Element_End0(); } } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_indx_SuperIndex(int32u Entry_Count, int32u ChunkId) { Element_Name("Index of Indexes"); //Parsing int64u Offset; Skip_L4( "Reserved0"); Skip_L4( "Reserved1"); Skip_L4( "Reserved2"); stream& StreamItem = Stream[Stream_ID]; for (int32u Pos=0; Pos<Entry_Count; Pos++) { int32u Duration; Element_Begin1("Index of Indexes"); Get_L8 (Offset, "Offset"); Skip_L4( "Size"); //Size of index chunk at this offset Get_L4 (Duration, "Duration"); //time span in stream ticks Index_Pos[Offset]=ChunkId; StreamItem.indx_Duration+=Duration; Element_End0(); } //We needn't anymore Old version NeedOldIndex=false; } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_JUNK() { Element_Name("Garbage"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strd() { Element_Name("Stream datas"); //Parsing Skip_XX(Element_Size, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf() { Element_Name("Stream format"); //Parse depending of kind of stream stream& StreamItem = Stream[Stream_ID]; switch (StreamItem.fccType) { case Elements::AVI__hdlr_strl_strh_auds : AVI__hdlr_strl_strf_auds(); break; case Elements::AVI__hdlr_strl_strh_iavs : AVI__hdlr_strl_strf_iavs(); break; case Elements::AVI__hdlr_strl_strh_mids : AVI__hdlr_strl_strf_mids(); break; case Elements::AVI__hdlr_strl_strh_txts : AVI__hdlr_strl_strf_txts(); break; case Elements::AVI__hdlr_strl_strh_vids : AVI__hdlr_strl_strf_vids(); break; default : Element_Info1("Unknown"); } //Registering stream StreamItem.StreamKind=StreamKind_Last; StreamItem.StreamPos=StreamPos_Last; } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_auds() { Element_Info1("Audio"); //Parsing #if !MEDIAINFO_DEMUX int32u AvgBytesPerSec; #endif //!MEDIAINFO_DEMUX int16u FormatTag, Channels; BitsPerSample=0; Get_L2 (FormatTag, "FormatTag"); Get_L2 (Channels, "Channels"); Get_L4 (SamplesPerSec, "SamplesPerSec"); Get_L4 (AvgBytesPerSec, "AvgBytesPerSec"); #if MEDIAINFO_DEMUX Get_L2 (BlockAlign, "BlockAlign"); #else //MEDIAINFO_DEMUX Skip_L2( "BlockAlign"); #endif //MEDIAINFO_DEMUX if (Element_Offset+2<=Element_Size) Get_L2 (BitsPerSample, "BitsPerSample"); if (FormatTag==1) //Only for PCM { //Coherancy if (BitsPerSample && SamplesPerSec*BitsPerSample*Channels/8==AvgBytesPerSec*8) AvgBytesPerSec*=8; //Found in one file. TODO: Provide information to end user about such error //Computing of missing value if (!BitsPerSample && AvgBytesPerSec && SamplesPerSec && Channels) BitsPerSample=(int16u)(AvgBytesPerSec*8/SamplesPerSec/Channels); } //Filling Stream_Prepare(Stream_Audio); stream& StreamItem = Stream[Stream_ID]; StreamItem.Compression=FormatTag; Ztring Codec; Codec.From_Number(FormatTag, 16); Codec.MakeUpperCase(); CodecID_Fill(Codec, Stream_Audio, StreamPos_Last, InfoCodecID_Format_Riff); Fill(Stream_Audio, StreamPos_Last, Audio_Codec, Codec); //May be replaced by codec parser Fill(Stream_Audio, StreamPos_Last, Audio_Codec_CC, Codec); if (Channels) Fill(Stream_Audio, StreamPos_Last, Audio_Channel_s_, (Channels!=5 || FormatTag==0xFFFE)?Channels:6); if (SamplesPerSec) Fill(Stream_Audio, StreamPos_Last, Audio_SamplingRate, SamplesPerSec); if (AvgBytesPerSec) Fill(Stream_Audio, StreamPos_Last, Audio_BitRate, AvgBytesPerSec*8); if (BitsPerSample) Fill(Stream_Audio, StreamPos_Last, Audio_BitDepth, BitsPerSample); StreamItem.AvgBytesPerSec=AvgBytesPerSec; //Saving bitrate for each stream if (SamplesPerSec && TimeReference!=(int64u)-1) { Fill(Stream_Audio, 0, Audio_Delay, float64_int64s(((float64)TimeReference)*1000/SamplesPerSec)); Fill(Stream_Audio, 0, Audio_Delay_Source, "Container (bext)"); } //Specific cases #if defined(MEDIAINFO_DTS_YES) || defined(MEDIAINFO_SMPTEST0337_YES) if (FormatTag==0x1 && Retrieve(Stream_General, 0, General_Format)==__T("Wave")) //Some DTS or SMPTE ST 337 streams are coded "1" { #if defined(MEDIAINFO_DTS_YES) { File_Dts* Parser=new File_Dts; Parser->Frame_Count_Valid=2; Parser->ShouldContinueParsing=true; #if MEDIAINFO_DEMUX if (Config->Demux_Unpacketize_Get() && Retrieve(Stream_General, 0, General_Format)==__T("Wave")) { Parser->Demux_Level=2; //Container Parser->Demux_UnpacketizeContainer=true; Demux_Level=4; //Intermediate } #endif //MEDIAINFO_DEMUX StreamItem.Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_SMPTEST0337_YES) { File_SmpteSt0337* Parser=new File_SmpteSt0337; Parser->Container_Bits=(int8u)BitsPerSample; Parser->Aligned=true; Parser->ShouldContinueParsing=true; #if MEDIAINFO_DEMUX if (Config->Demux_Unpacketize_Get() && Retrieve(Stream_General, 0, General_Format)==__T("Wave")) { Parser->Demux_Level=2; //Container Parser->Demux_UnpacketizeContainer=true; Demux_Level=4; //Intermediate } #endif //MEDIAINFO_DEMUX StreamItem.Parsers.push_back(Parser); } #endif } #endif //Creating the parser if (0); #if defined(MEDIAINFO_MPEGA_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("MPEG Audio")) { File_Mpega* Parser=new File_Mpega; Parser->CalculateDelay=true; Parser->ShouldContinueParsing=true; StreamItem.Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_AC3_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("AC-3")) { File_Ac3* Parser=new File_Ac3; Parser->Frame_Count_Valid=2; Parser->CalculateDelay=true; Parser->ShouldContinueParsing=true; StreamItem.Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_DTS_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("DTS")) { File_Dts* Parser=new File_Dts; Parser->Frame_Count_Valid=2; Parser->ShouldContinueParsing=true; StreamItem.Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_AAC_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("AAC")) { File_Aac* Parser=new File_Aac; Parser->Mode=File_Aac::Mode_ADTS; Parser->Frame_Count_Valid=1; Parser->ShouldContinueParsing=true; StreamItem.Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_PCM_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("PCM")) { File_Pcm* Parser=new File_Pcm; Parser->Codec=Codec; Parser->Endianness='L'; Parser->BitDepth=(int8u)BitsPerSample; #if MEDIAINFO_DEMUX if (Demux_Rate) Parser->Frame_Count_Valid = float64_int64s(Demux_Rate); if (Config->Demux_Unpacketize_Get() && Retrieve(Stream_General, 0, General_Format)==__T("Wave")) { Parser->Demux_Level=2; //Container Parser->Demux_UnpacketizeContainer=true; Demux_Level=4; //Intermediate } #else //MEDIAINFO_DEMUX Parser->Frame_Count_Valid=(int64u)-1; //Disabling it, waiting for SMPTE ST 337 parser reject #endif //MEDIAINFO_DEMUX stream& StreamItem = Stream[Stream_ID]; StreamItem.Parsers.push_back(Parser); StreamItem.IsPcm=true; } #endif #if defined(MEDIAINFO_ADPCM_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("ADPCM")) { //Creating the parser File_Adpcm MI; MI.Codec=Codec; //Parsing Open_Buffer_Init(&MI); Open_Buffer_Continue(&MI, 0); //Filling Finish(&MI); Merge(MI, StreamKind_Last, 0, StreamPos_Last); } #endif #if defined(MEDIAINFO_OGG_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("Vorbis") && FormatTag!=0x566F) //0x566F has config in this chunk { File_Ogg* Parser=new File_Ogg; Parser->ShouldContinueParsing=true; StreamItem.Parsers.push_back(Parser); } #endif Open_Buffer_Init_All(); //Options if (Element_Offset+2>Element_Size) return; //No options //Parsing int16u Option_Size; Get_L2 (Option_Size, "cbSize"); //Filling if (Option_Size>0) { if (0); else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Codec)==__T("MPEG Audio")) { if (Option_Size==12) AVI__hdlr_strl_strf_auds_Mpega(); else Skip_XX(Option_Size, "MPEG Audio - Uknown"); } else if (Codec==__T("AAC") || Codec==__T("FF") || Codec==__T("8180")) AVI__hdlr_strl_strf_auds_Aac(); else if (FormatTag==0x566F) //Vorbis with Config in this chunk AVI__hdlr_strl_strf_auds_Vorbis(); else if (FormatTag==0x6750) //Vorbis with Config in this chunk AVI__hdlr_strl_strf_auds_Vorbis2(); else if (FormatTag==0xFFFE) //Extensible Wave AVI__hdlr_strl_strf_auds_ExtensibleWave(); else if (Element_Offset+Option_Size<=Element_Size) Skip_XX(Option_Size, "Unknown"); else if (Element_Offset!=Element_Size) Skip_XX(Element_Size-Element_Offset, "Error"); } } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_auds_Mpega() { //Parsing Element_Begin1("MPEG Audio options"); Skip_L2( "ID"); Skip_L4( "Flags"); Skip_L2( "BlockSize"); Skip_L2( "FramesPerBlock"); Skip_L2( "CodecDelay"); Element_End0(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_auds_Aac() { //Parsing Element_Begin1("AAC options"); #if defined(MEDIAINFO_AAC_YES) File_Aac* MI=new File_Aac(); MI->Mode=File_Aac::Mode_AudioSpecificConfig; Open_Buffer_Init(MI); Open_Buffer_Continue(MI); Finish(MI); Merge(*MI, StreamKind_Last, 0, StreamPos_Last); delete MI; //MI=NULL; #else //MEDIAINFO_MPEG4_YES Skip_XX(Element_Size-Element_Offset, "(AudioSpecificConfig)"); #endif Element_End0(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_auds_Vorbis() { //Parsing Element_Begin1("Vorbis options"); #if defined(MEDIAINFO_OGG_YES) File_Ogg_SubElement MI; Open_Buffer_Init(&MI); Element_Begin1("Element sizes"); //All elements parsing, except last one std::vector<size_t> Elements_Size; size_t Elements_TotalSize=0; int8u Elements_Count; Get_L1(Elements_Count, "Element count"); Elements_Size.resize(Elements_Count+1); //+1 for the last block for (int8u Pos=0; Pos<Elements_Count; Pos++) { int8u Size; Get_L1(Size, "Size"); Elements_Size[Pos]=Size; Elements_TotalSize+=Size; } Element_End0(); if (Element_Offset+Elements_TotalSize>Element_Size) return; //Adding the last block Elements_Size[Elements_Count]=(size_t)(Element_Size-(Element_Offset+Elements_TotalSize)); Elements_Count++; //Parsing blocks for (int8u Pos=0; Pos<Elements_Count; Pos++) { Open_Buffer_Continue(&MI, Elements_Size[Pos]); Open_Buffer_Continue(&MI, 0); Element_Offset+=Elements_Size[Pos]; } //Finalizing Finish(&MI); Merge(MI, StreamKind_Last, 0, StreamPos_Last); Clear(Stream_Audio, StreamPos_Last, Audio_BitDepth); //Resolution is not valid for Vorbis Element_Show(); #else //MEDIAINFO_MPEG4_YES Skip_XX(Element_Size-Element_Offset, "(Vorbis headers)"); #endif Element_End0(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_auds_Vorbis2() { //Parsing Skip_XX(8, "Vorbis Unknown"); Element_Begin1("Vorbis options"); #if defined(MEDIAINFO_OGG_YES) stream& StreamItem = Stream[Stream_ID]; Open_Buffer_Continue(StreamItem.Parsers[0]); Open_Buffer_Continue(StreamItem.Parsers[0], 0); Finish(StreamItem.Parsers[0]); Merge(*StreamItem.Parsers[0], StreamKind_Last, 0, StreamPos_Last); Element_Show(); #else //MEDIAINFO_MPEG4_YES Skip_XX(Element_Size-Element_Offset, "(Vorbis headers)"); #endif Element_End0(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_auds_ExtensibleWave() { //Parsing int128u SubFormat; int32u ChannelMask; Skip_L2( "ValidBitsPerSample / SamplesPerBlock"); Get_L4 (ChannelMask, "ChannelMask"); Get_GUID(SubFormat, "SubFormat"); FILLING_BEGIN(); if ((SubFormat.hi&0xFFFFFFFFFFFF0000LL)==0x0010000000000000LL && SubFormat.lo==0x800000AA00389B71LL) { CodecID_Fill(Ztring().From_Number((int16u)SubFormat.hi, 16), Stream_Audio, StreamPos_Last, InfoCodecID_Format_Riff); Fill(Stream_Audio, StreamPos_Last, Audio_CodecID, Ztring().From_GUID(SubFormat), true); Fill(Stream_Audio, StreamPos_Last, Audio_Codec, MediaInfoLib::Config.Codec_Get(Ztring().From_Number((int16u)SubFormat.hi, 16)), true); //Creating the parser if (0); #if defined(MEDIAINFO_PCM_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Audio, InfoCodecID_Format_Riff, Ztring().From_Number((int16u)SubFormat.hi, 16))==__T("PCM")) { //Creating the parser File_Pcm* Parser=new File_Pcm; Parser->Codec=Ztring().From_GUID(SubFormat); Parser->Endianness='L'; Parser->Sign='S'; Parser->BitDepth=(int8u)BitsPerSample; #if MEDIAINFO_DEMUX if (Config->Demux_Unpacketize_Get() && Retrieve(Stream_General, 0, General_Format)==__T("Wave")) { Parser->Demux_Level=2; //Container Parser->Demux_UnpacketizeContainer=true; Demux_Level=4; //Intermediate } #endif //MEDIAINFO_DEMUX stream& StreamItem = Stream[Stream_ID]; StreamItem.Parsers.push_back(Parser); StreamItem.IsPcm=true; } #endif Open_Buffer_Init_All(); } else { CodecID_Fill(Ztring().From_GUID(SubFormat), Stream_Audio, StreamPos_Last, InfoCodecID_Format_Riff); } Fill(Stream_Audio, StreamPos_Last, Audio_ChannelPositions, ExtensibleWave_ChannelMask(ChannelMask)); Fill(Stream_Audio, StreamPos_Last, Audio_ChannelPositions_String2, ExtensibleWave_ChannelMask2(ChannelMask)); FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_iavs() { //Standard video header before Iavs? if (Element_Size==72) { Element_Begin0(); AVI__hdlr_strl_strf_vids(); Element_End0(); } Element_Info1("Interleaved Audio/Video"); #ifdef MEDIAINFO_DVDIF_YES if (Element_Size<8*4) return; //Parsing DV_FromHeader=new File_DvDif(); Open_Buffer_Init(DV_FromHeader); //DVAAuxSrc ((File_DvDif*)DV_FromHeader)->AuxToAnalyze=0x50; //Audio source Open_Buffer_Continue(DV_FromHeader, 4); //DVAAuxCtl ((File_DvDif*)DV_FromHeader)->AuxToAnalyze=0x51; //Audio control Open_Buffer_Continue(DV_FromHeader, Buffer+Buffer_Offset+(size_t)Element_Offset, 4); Element_Offset+=4; //DVAAuxSrc1 Skip_L4( "DVAAuxSrc1"); //DVAAuxCtl1 Skip_L4( "DVAAuxCtl1"); //DVVAuxSrc ((File_DvDif*)DV_FromHeader)->AuxToAnalyze=0x60; //Video source Open_Buffer_Continue(DV_FromHeader, 4); //DVAAuxCtl ((File_DvDif*)DV_FromHeader)->AuxToAnalyze=0x61; //Video control Open_Buffer_Continue(DV_FromHeader, 4); //Reserved if (Element_Offset<Element_Size) { Skip_L4( "DVReserved"); Skip_L4( "DVReserved"); } Finish(DV_FromHeader); Stream_Prepare(Stream_Video); stream& StreamItem = Stream[Stream_ID]; StreamItem.Parsers.push_back(new File_DvDif); Open_Buffer_Init(StreamItem.Parsers[0]); #else //MEDIAINFO_DVDIF_YES //Parsing Skip_L4( "DVAAuxSrc"); Skip_L4( "DVAAuxCtl"); Skip_L4( "DVAAuxSrc1"); Skip_L4( "DVAAuxCtl1"); Skip_L4( "DVVAuxSrc"); Skip_L4( "DVVAuxCtl"); Skip_L4( "DVReserved"); Skip_L4( "DVReserved"); //Filling Ztring Codec; Codec.From_CC4(Stream[Stream_ID].fccHandler); Stream_Prepare(Stream_Video); float32 FrameRate=Retrieve(Stream_Video, StreamPos_Last, Video_FrameRate).To_float32(); Fill(Stream_Video, StreamPos_Last, Video_Codec, Codec); //May be replaced by codec parser Fill(Stream_Video, StreamPos_Last, Video_Codec_CC, Codec); if (Codec==__T("dvsd") || Codec==__T("dvsl")) { Fill(Stream_Video, StreamPos_Last, Video_Width, 720); if (FrameRate==25.000) Fill(Stream_Video, StreamPos_Last, Video_Height, 576); else if (FrameRate==29.970) Fill(Stream_Video, StreamPos_Last, Video_Height, 480); Fill(Stream_Video, StreamPos_Last, Video_DisplayAspectRatio, 4.0/3, 3, true); } else if (Codec==__T("dvhd")) { Fill(Stream_Video, StreamPos_Last, Video_Width, 1440); if (FrameRate==25.000) Fill(Stream_Video, StreamPos_Last, Video_Height, 1152); else if (FrameRate==30.000) Fill(Stream_Video, StreamPos_Last, Video_Height, 960); Fill(Stream_Video, StreamPos_Last, Video_DisplayAspectRatio, 4.0/3, 3, true); } Stream_Prepare(Stream_Audio); CodecID_Fill(Codec, Stream_Audio, StreamPos_Last, InfoCodecID_Format_Riff); Fill(Stream_Audio, StreamPos_Last, Audio_Codec, Codec); //May be replaced by codec parser Fill(Stream_Audio, StreamPos_Last, Audio_Codec_CC, Codec); #endif //MEDIAINFO_DVDIF_YES } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_mids() { Element_Info1("Midi"); //Filling Stream_Prepare(Stream_Audio); Fill(Stream_Audio, StreamPos_Last, Audio_Format, "MIDI"); Fill(Stream_Audio, StreamPos_Last, Audio_Codec, "Midi"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_txts() { Element_Info1("Text"); //Parsing Ztring Format; if (Element_Size) { Get_Local(10, Format, "Format"); Skip_XX(22, "Unknown"); } FILLING_BEGIN_PRECISE(); Stream_Prepare(Stream_Text); if (Element_Size==0) { //Creating the parser stream& StreamItem = Stream[Stream_ID]; #if defined(MEDIAINFO_SUBRIP_YES) StreamItem.Parsers.push_back(new File_SubRip); #endif #if defined(MEDIAINFO_OTHERTEXT_YES) StreamItem.Parsers.push_back(new File_OtherText); //For SSA #endif Open_Buffer_Init_All(); } else { Fill(Stream_Text, StreamPos_Last, Text_Format, Format); } FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_vids() { Element_Info1("Video"); //Parsing int32u Compression, Width, Height; int16u Resolution; Skip_L4( "Size"); Get_L4 (Width, "Width"); Get_L4 (Height, "Height"); Skip_L2( "Planes"); Get_L2 (Resolution, "BitCount"); //Do not use it Get_C4 (Compression, "Compression"); Skip_L4( "SizeImage"); Skip_L4( "XPelsPerMeter"); Skip_L4( "YPelsPerMeter"); Skip_L4( "ClrUsed"); Skip_L4( "ClrImportant"); //Filling Stream[Stream_ID].Compression=Compression; if (Compression==CC4("DXSB")) { //Divx.com hack for subtitle, this is a text stream in a DivX Format Fill(Stream_General, 0, General_Format, "DivX", Unlimited, true, true); Stream_Prepare(Stream_Text); } else Stream_Prepare(Stream_Video); //Filling CodecID_Fill(Ztring().From_CC4(Compression), StreamKind_Last, StreamPos_Last, InfoCodecID_Format_Riff); Fill(StreamKind_Last, StreamPos_Last, Fill_Parameter(StreamKind_Last, Generic_Codec), Ztring().From_CC4(Compression).To_Local().c_str()); //FormatTag, may be replaced by codec parser Fill(StreamKind_Last, StreamPos_Last, Fill_Parameter(StreamKind_Last, Generic_Codec_CC), Ztring().From_CC4(Compression).To_Local().c_str()); //FormatTag Fill(StreamKind_Last, StreamPos_Last, "Width", Width, 10, true); Fill(StreamKind_Last, StreamPos_Last, "Height", Height>=0x80000000?(-((int32s)Height)):Height, 10, true); // AVI can use negative height for raw to signal that it's coded top-down, not bottom-up if (Resolution==32 && Compression==0x74736363) //tscc Fill(StreamKind_Last, StreamPos_Last, "BitDepth", 8); else if (Compression==0x44495633) //DIV3 Fill(StreamKind_Last, StreamPos_Last, "BitDepth", 8); else if (MediaInfoLib::Config.CodecID_Get(StreamKind_Last, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression)).find(__T("Canopus"))!=std::string::npos) //Canopus codecs Fill(StreamKind_Last, StreamPos_Last, "BitDepth", Resolution/3); else if (Compression==0x44585342) //DXSB Fill(StreamKind_Last, StreamPos_Last, "BitDepth", Resolution); else if (MediaInfoLib::Config.CodecID_Get(StreamKind_Last, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_ColorSpace).find(__T("RGBA"))!=std::string::npos) //RGB codecs Fill(StreamKind_Last, StreamPos_Last, "BitDepth", Resolution/4); else if (Compression==0x00000000 //RGB || MediaInfoLib::Config.CodecID_Get(StreamKind_Last, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_ColorSpace).find(__T("RGB"))!=std::string::npos) //RGB codecs { if (Resolution==32) { Fill(StreamKind_Last, StreamPos_Last, Fill_Parameter(StreamKind_Last, Generic_Format), "RGBA", Unlimited, true, true); Fill(StreamKind_Last, StreamPos_Last, "BitDepth", Resolution/4); //With Alpha } else Fill(StreamKind_Last, StreamPos_Last, "BitDepth", Resolution<=16?8:(Resolution/3)); //indexed or normal } else if (Compression==0x56503632 //VP62 || MediaInfoLib::Config.CodecID_Get(StreamKind_Last, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_Format)==__T("H.263") //H.263 || MediaInfoLib::Config.CodecID_Get(StreamKind_Last, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_Format)==__T("VC-1")) //VC-1 Fill(StreamKind_Last, StreamPos_Last, "BitDepth", Resolution/3); Stream[Stream_ID].StreamKind=StreamKind_Last; //Creating the parser if (0); #if defined(MEDIAINFO_FFV1_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_Format)==__T("FFV1")) { File_Ffv1* Parser=new File_Ffv1; Parser->Width=Width; Parser->Height=Height; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_HUFFYUV_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_Format)==__T("HuffYUV")) { File_HuffYuv* Parser=new File_HuffYuv; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_MPEGV_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_Format)==__T("MPEG Video")) { File_Mpegv* Parser=new File_Mpegv; Parser->FrameIsAlwaysComplete=true; Parser->TimeCodeIsNotTrustable=true; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_MPEG4V_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("MPEG-4 Visual")) { File_Mpeg4v* Parser=new File_Mpeg4v; Stream[Stream_ID].Specific_IsMpeg4v=true; Parser->FrameIsAlwaysComplete=true; if (MediaInfoLib::Config.ParseSpeed_Get()>=0.5) Parser->ShouldContinueParsing=true; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_PRORES_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression), InfoCodecID_Format)==__T("ProRes")) { File_ProRes* Parser=new File_ProRes; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_AVC_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("AVC")) { File_Avc* Parser=new File_Avc; Parser->FrameIsAlwaysComplete=true; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_CANOPUS_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("Canopus HQ")) { File_Canopus* Parser=new File_Canopus; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_JPEG_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("JPEG")) { File_Jpeg* Parser=new File_Jpeg; Parser->StreamKind=Stream_Video; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_DVDIF_YES) else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("DV")) { File_DvDif* Parser=new File_DvDif; Parser->IgnoreAudio=true; Stream[Stream_ID].Parsers.push_back(Parser); } #endif #if defined(MEDIAINFO_FRAPS_YES) else if (Compression==0x46505331) //"FPS1" { File_Fraps* Parser=new File_Fraps; Stream[Stream_ID].Parsers.push_back(Parser); } #endif else if (Compression==0x48465955) //"HFUY" { switch (Resolution) { case 16 : Fill(Stream_Video, StreamPos_Last, Video_ColorSpace, "YUV"); Fill(Stream_Video, StreamPos_Last, Video_ChromaSubsampling, "4:2:2"); Fill(Stream_Video, StreamPos_Last, Video_BitDepth, 8); break; case 24 : Fill(Stream_Video, StreamPos_Last, Video_ColorSpace, "RGB"); Fill(Stream_Video, StreamPos_Last, Video_BitDepth, 8); break; case 32 : Fill(Stream_Video, StreamPos_Last, Video_ColorSpace, "RGBA"); Fill(Stream_Video, StreamPos_Last, Video_BitDepth, 8); break; default : ; } } #if defined(MEDIAINFO_LAGARITH_YES) else if (Compression==0x4C414753) //"LAGS" { File_Lagarith* Parser=new File_Lagarith; Stream[Stream_ID].Parsers.push_back(Parser); } #endif Open_Buffer_Init_All(); //Options if (Element_Offset>=Element_Size) return; //No options //Filling if (0); else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("AVC")) AVI__hdlr_strl_strf_vids_Avc(); else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("FFV1")) AVI__hdlr_strl_strf_vids_Ffv1(); else if (MediaInfoLib::Config.CodecID_Get(Stream_Video, InfoCodecID_Format_Riff, Ztring().From_CC4(Compression))==__T("HuffYUV")) AVI__hdlr_strl_strf_vids_HuffYUV(Resolution, Height); else Skip_XX(Element_Size-Element_Offset, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_vids_Avc() { //Parsing Element_Begin1("AVC options"); #if defined(MEDIAINFO_AVC_YES) //Can be sized block or with 000001 stream& StreamItem = Stream[Stream_ID]; File_Avc* Parser=(File_Avc*)StreamItem.Parsers[0]; Parser->MustParse_SPS_PPS=false; Parser->SizedBlocks=false; Parser->MustSynchronize=true; int64u Element_Offset_Save=Element_Offset; Open_Buffer_Continue(Parser); if (!Parser->Status[IsAccepted]) { Element_Offset=Element_Offset_Save; delete StreamItem.Parsers[0]; StreamItem.Parsers[0]=new File_Avc; Parser=(File_Avc*)StreamItem.Parsers[0]; Open_Buffer_Init(Parser); Parser->FrameIsAlwaysComplete=true; Parser->MustParse_SPS_PPS=true; Parser->SizedBlocks=true; Parser->MustSynchronize=false; Open_Buffer_Continue(Parser); Element_Show(); } #else //MEDIAINFO_AVC_YES Skip_XX(Element_Size-Element_Offset, "(AVC headers)"); #endif Element_End0(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_vids_Ffv1() { //Parsing Element_Begin1("FFV1 options"); #if defined(MEDIAINFO_FFV1_YES) File_Ffv1* Parser=(File_Ffv1*)Stream[Stream_ID].Parsers[0]; Open_Buffer_OutOfBand(Parser); #else //MEDIAINFO_FFV1_YES Skip_XX(Element_Size-Element_Offset, "(FFV1 headers)"); #endif Element_End0(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strf_vids_HuffYUV(int16u BitCount, int32u Height) { //Parsing Element_Begin1("HuffYUV options"); #if defined(MEDIAINFO_HUFFYUV_YES) File_HuffYuv* Parser=(File_HuffYuv*)Stream[Stream_ID].Parsers[0]; Parser->IsOutOfBandData=true; Parser->BitCount=BitCount; Parser->Height=Height; Open_Buffer_Continue(Parser); #else //MEDIAINFO_HUFFYUV_YES Skip_XX(Element_Size-Element_Offset, "(HuffYUV headers)"); #endif Element_End0(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strh() { Element_Name("Stream header"); //Parsing int32u fccType, fccHandler, Scale, Rate, Start, Length; int16u Left, Top, Right, Bottom; Get_C4 (fccType, "fccType"); switch (fccType) { case Elements::AVI__hdlr_strl_strh_auds : Get_L4 (fccHandler, "fccHandler"); break; default: Get_C4 (fccHandler, "fccHandler"); } Skip_L4( "Flags"); Skip_L2( "Priority"); Skip_L2( "Language"); Skip_L4( "InitialFrames"); Get_L4 (Scale, "Scale"); Get_L4 (Rate, "Rate"); //Rate/Scale is stream tick rate in ticks/sec Get_L4 (Start, "Start"); Get_L4 (Length, "Length"); Skip_L4( "SuggestedBufferSize"); Skip_L4( "Quality"); Skip_L4( "SampleSize"); Get_L2 (Left, "Frame_Left"); Get_L2 (Top, "Frame_Top"); Get_L2 (Right, "Frame_Right"); Get_L2 (Bottom, "Frame_Bottom"); if(Element_Offset<Element_Size) Skip_XX(Element_Size-Element_Offset, "Unknown"); //Filling float32 FrameRate=0; if (Rate>0 && Scale>0) { //FrameRate (without known value detection) FrameRate=((float32)Rate)/Scale; if (FrameRate>1) { float32 Rest=FrameRate-(int32u)FrameRate; if (Rest<0.01) FrameRate-=Rest; else if (Rest>0.99) FrameRate+=1-Rest; else { float32 Rest1001=FrameRate*1001/1000-(int32u)(FrameRate*1001/1000); if (Rest1001<0.001) FrameRate=(float32)((int32u)(FrameRate*1001/1000))*1000/1001; if (Rest1001>0.999) FrameRate=(float32)((int32u)(FrameRate*1001/1000)+1)*1000/1001; } } //Duration if (FrameRate) { int64u Duration=float32_int64s((1000*(float32)Length)/FrameRate); if (avih_TotalFrame>0 //avih_TotalFrame is here because some files have a wrong Audio Duration if TotalFrame==0 (which is a bug, of course!) && (avih_FrameRate==0 || Duration<((float32)avih_TotalFrame)/avih_FrameRate*1000*1.10) //Some file have a nearly perfect header, except that the value is false, trying to detect it (false if 10% more than 1st video) && (avih_FrameRate==0 || Duration>((float32)avih_TotalFrame)/avih_FrameRate*1000*0.90)) //Some file have a nearly perfect header, except that the value is false, trying to detect it (false if 10% less than 1st video) { Fill(StreamKind_Last, StreamPos_Last, "Duration", Duration); } } } switch (fccType) { case Elements::AVI__hdlr_strl_strh_vids : if (FrameRate>0) Fill(Stream_Video, StreamPos_Last, Video_FrameRate, FrameRate, 3); if (Right-Left>0) Fill(Stream_Video, StreamPos_Last, Video_Width, Right-Left, 10, true); if (Bottom-Top>0) Fill(Stream_Video, StreamPos_Last, Video_Height, Bottom-Top, 10, true); break; case Elements::AVI__hdlr_strl_strh_txts : if (Right-Left>0) Fill(Stream_Text, StreamPos_Last, Text_Width, Right-Left, 10, true); if (Bottom-Top>0) Fill(Stream_Text, StreamPos_Last, Text_Height, Bottom-Top, 10, true); break; default: ; } stream& StreamItem = Stream[Stream_ID]; StreamItem.fccType=fccType; StreamItem.fccHandler=fccHandler; StreamItem.Scale=Scale; StreamItem.Rate=Rate; StreamItem.Start=Start; StreamItem.Length=Length; } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_strn() { Element_Name("Stream name"); //Parsing Ztring Title; Get_Local(Element_Size, Title, "StreamName"); //Filling Fill(StreamKind_Last, StreamPos_Last, "Title", Title); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_strl_vprp() { Element_Name("Video properties"); //Parsing int32u FieldPerFrame; int16u FrameAspectRatio_H, FrameAspectRatio_W; Skip_L4( "VideoFormatToken"); Skip_L4( "VideoStandard"); Skip_L4( "VerticalRefreshRate"); Skip_L4( "HTotalInT"); Skip_L4( "VTotalInLines"); Get_L2 (FrameAspectRatio_H, "FrameAspectRatio Height"); Get_L2 (FrameAspectRatio_W, "FrameAspectRatio Width"); Skip_L4( "FrameWidthInPixels"); Skip_L4( "FrameHeightInLines"); Get_L4 (FieldPerFrame, "FieldPerFrame"); vector<int32u> VideoYValidStartLines; for (int32u Pos=0; Pos<FieldPerFrame; Pos++) { Element_Begin1("Field"); int32u VideoYValidStartLine; Skip_L4( "CompressedBMHeight"); Skip_L4( "CompressedBMWidth"); Skip_L4( "ValidBMHeight"); Skip_L4( "ValidBMWidth"); Skip_L4( "ValidBMXOffset"); Skip_L4( "ValidBMYOffset"); Skip_L4( "VideoXOffsetInT"); Get_L4 (VideoYValidStartLine, "VideoYValidStartLine"); VideoYValidStartLines.push_back(VideoYValidStartLine); Element_End0(); } if(Element_Offset<Element_Size) Skip_XX(Element_Size-Element_Offset, "Unknown"); FILLING_BEGIN(); if (FrameAspectRatio_H && FrameAspectRatio_W) Fill(Stream_Video, 0, Video_DisplayAspectRatio, ((float32)FrameAspectRatio_W)/FrameAspectRatio_H, 3); switch (FieldPerFrame) { case 1 : Fill(Stream_Video, 0, Video_ScanType, "Progressive"); break; case 2 : Fill(Stream_Video, 0, Video_ScanType, "Interlaced"); if (VideoYValidStartLines.size()==2 && VideoYValidStartLines[0]<VideoYValidStartLines[1]) Fill(Stream_Video, 0, Video_ScanOrder, "TFF"); if (VideoYValidStartLines.size()==2 && VideoYValidStartLines[0]>VideoYValidStartLines[1]) Fill(Stream_Video, 0, Video_ScanOrder, "BFF"); default: ; } FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::AVI__hdlr_xxxx() { AVI__INFO_xxxx(); } //--------------------------------------------------------------------------- void File_Riff::AVI__idx1() { Element_Name("Index (old)"); //Tests if (!NeedOldIndex || Idx1_Offset==(int64u)-1) { Skip_XX(Element_Size, "Data"); return; } //Testing malformed index (index is based on start of the file, wrong) if (16<=Element_Size && Idx1_Offset+4==LittleEndian2int32u(Buffer+Buffer_Offset+(size_t)Element_Offset+ 8)) Idx1_Offset=0; //Fixing base of movi atom, the index think it is the start of the file //Parsing while (Element_Offset+16<=Element_Size) { //Is too slow /* int32u ChunkID, Offset, Size; Element_Begin1("Index"); Get_C4 (ChunkID, "ChunkID"); //Bit 31 is set if this is NOT a keyframe Info_L4(Flags, "Flags"); Skip_Flags(Flags, 0, "NoTime"); Skip_Flags(Flags, 1, "Lastpart"); Skip_Flags(Flags, 2, "Firstpart"); Skip_Flags(Flags, 3, "Midpart"); Skip_Flags(Flags, 4, "KeyFrame"); Get_L4 (Offset, "Offset"); //qwBaseOffset + this is absolute file offset Get_L4 (Size, "Size"); //Bit 31 is set if this is NOT a keyframe Element_Info1(Ztring().From_CC4(ChunkID)); Element_Info1(Size); //Stream Pos and Size int32u StreamID=(ChunkID&0xFFFF0000); Stream[StreamID].StreamSize+=Size; Stream[StreamID].PacketCount++; Stream_Structure[Idx1_Offset+Offset].Name=StreamID; Stream_Structure[Idx1_Offset+Offset].Size=Size; Element_End0(); */ //Faster method int32u StreamID=BigEndian2int32u (Buffer+Buffer_Offset+(size_t)Element_Offset )&0xFFFF0000; int32u Offset =LittleEndian2int32u(Buffer+Buffer_Offset+(size_t)Element_Offset+ 8); int32u Size =LittleEndian2int32u(Buffer+Buffer_Offset+(size_t)Element_Offset+12); stream& Stream_Item=Stream[StreamID]; Stream_Item.StreamSize+=Size; Stream_Item.PacketCount++; stream_structure& Stream_Structure_Item=Stream_Structure[Idx1_Offset+Offset]; Stream_Structure_Item.Name=StreamID; Stream_Structure_Item.Size=Size; Element_Offset+=16; } //Interleaved size_t Pos0=0; size_t Pos1=0; for (std::map<int64u, stream_structure>::iterator Temp=Stream_Structure.begin(); Temp!=Stream_Structure.end(); ++Temp) { switch (Temp->second.Name) { case 0x30300000 : if (Interleaved0_1==0) Interleaved0_1=Temp->first; if (Interleaved0_10==0) { Pos0++; if (Pos0>1) Interleaved0_10=Temp->first; } break; case 0x30310000 : if (Interleaved1_1==0) Interleaved1_1=Temp->first; if (Interleaved1_10==0) { Pos1++; if (Pos1>1) Interleaved1_10=Temp->first; } break; default:; } } } //--------------------------------------------------------------------------- void File_Riff::AVI__INFO() { Element_Name("Tags"); } //--------------------------------------------------------------------------- void File_Riff::AVI__INFO_IID3() { Element_Name("ID3 Tag"); //Parsing #if defined(MEDIAINFO_ID3_YES) File_Id3 MI; Open_Buffer_Init(&MI); Open_Buffer_Continue(&MI); Finish(&MI); Merge(MI, Stream_General, 0, 0); #endif } //--------------------------------------------------------------------------- void File_Riff::AVI__INFO_ILYC() { Element_Name("Lyrics"); } //--------------------------------------------------------------------------- void File_Riff::AVI__INFO_IMP3() { Element_Name("MP3 Information"); } //--------------------------------------------------------------------------- void File_Riff::AVI__INFO_JUNK() { Element_Name("Garbage"); } //--------------------------------------------------------------------------- // List of information atoms // Name X bytes, Pos=0 // void File_Riff::AVI__INFO_xxxx() { //Parsing Ztring Value; Get_Local(Element_Size, Value, "Value"); //Filling stream_t StreamKind=Stream_General; size_t StreamPos=0; size_t Parameter=(size_t)-1; switch (Element_Code) { case 0x00000000 : Parameter=General_Comment; break; case Elements::AVI__INFO_IARL : Parameter=General_Archival_Location; break; case Elements::AVI__INFO_IART : Parameter=General_Director; break; case Elements::AVI__INFO_IAS1 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=0; break; case Elements::AVI__INFO_IAS2 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=1; break; case Elements::AVI__INFO_IAS3 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=2; break; case Elements::AVI__INFO_IAS4 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=3; break; case Elements::AVI__INFO_IAS5 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=4; break; case Elements::AVI__INFO_IAS6 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=5; break; case Elements::AVI__INFO_IAS7 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=6; break; case Elements::AVI__INFO_IAS8 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=7; break; case Elements::AVI__INFO_IAS9 : Parameter=Audio_Language; StreamKind=Stream_Audio; StreamPos=8; break; case Elements::AVI__INFO_ICDS : Parameter=General_CostumeDesigner; break; case Elements::AVI__INFO_ICMS : Parameter=General_CommissionedBy; break; case Elements::AVI__INFO_ICMT : Parameter=General_Comment; break; case Elements::AVI__INFO_ICNM : Parameter=General_DirectorOfPhotography; break; case Elements::AVI__INFO_ICNT : Parameter=General_Movie_Country; break; case Elements::AVI__INFO_ICOP : Parameter=General_Copyright; break; case Elements::AVI__INFO_ICRD : Parameter=General_Recorded_Date; Value.Date_From_String(Value.To_Local().c_str()); break; case Elements::AVI__INFO_ICRP : Parameter=General_Cropped; break; case Elements::AVI__INFO_IDIM : Parameter=General_Dimensions; break; case Elements::AVI__INFO_IDIT : Parameter=General_Mastered_Date; Value.Date_From_String(Value.To_Local().c_str()); break; case Elements::AVI__INFO_IDPI : Parameter=General_DotsPerInch; break; case Elements::AVI__INFO_IDST : Parameter=General_DistributedBy; break; case Elements::AVI__INFO_IEDT : Parameter=General_EditedBy; break; case Elements::AVI__INFO_IENG : Parameter=General_EncodedBy; break; case Elements::AVI__INFO_IGNR : Parameter=General_Genre; break; case Elements::AVI__INFO_IFRM : Parameter=General_Part_Position_Total; break; case Elements::AVI__INFO_IKEY : Parameter=General_Keywords; break; case Elements::AVI__INFO_ILGT : Parameter=General_Lightness; break; case Elements::AVI__INFO_ILNG : Parameter=Audio_Language; StreamKind=Stream_Audio; break; case Elements::AVI__INFO_IMED : Parameter=General_OriginalSourceMedium; break; case Elements::AVI__INFO_IMUS : Parameter=General_MusicBy; break; case Elements::AVI__INFO_INAM : Parameter=General_Title; break; case Elements::AVI__INFO_IPDS : Parameter=General_ProductionDesigner; break; case Elements::AVI__INFO_IPLT : Parameter=General_OriginalSourceForm_NumColors; break; case Elements::AVI__INFO_IPRD : Parameter=General_OriginalSourceForm_Name; break; case Elements::AVI__INFO_IPRO : Parameter=General_Producer; break; case Elements::AVI__INFO_IPRT : Parameter=General_Part_Position; break; case Elements::AVI__INFO_IRTD : Parameter=General_LawRating; break; case Elements::AVI__INFO_ISBJ : Parameter=General_Subject; break; case Elements::AVI__INFO_ISFT : Parameter=General_Encoded_Application; break; case Elements::AVI__INFO_ISGN : Parameter=General_Genre; break; case Elements::AVI__INFO_ISHP : Parameter=General_OriginalSourceForm_Sharpness; break; case Elements::AVI__INFO_ISRC : Parameter=General_OriginalSourceForm_DistributedBy; break; case Elements::AVI__INFO_ISRF : Parameter=General_OriginalSourceForm; break; case Elements::AVI__INFO_ISTD : Parameter=General_ProductionStudio; break; case Elements::AVI__INFO_ISTR : Parameter=General_Performer; break; case Elements::AVI__INFO_ITCH : Parameter=General_EncodedBy; break; case Elements::AVI__INFO_IWEB : Parameter=General_Movie_Url; break; case Elements::AVI__INFO_IWRI : Parameter=General_WrittenBy; break; default : ; } Element_Name(MediaInfoLib::Config.Info_Get(StreamKind, Parameter, Info_Name)); Element_Info1(Value); switch (Element_Code) { case Elements::AVI__INFO_ISMP : INFO_ISMP=Value; break; case Elements::AVI__INFO_IGNR : { Ztring ISGN=Retrieve(Stream_General, 0, General_Genre); Clear(Stream_General, 0, General_Genre); Fill(StreamKind, StreamPos, General_Genre, Value); if (!ISGN.empty()) Fill(StreamKind, StreamPos, General_Genre, ISGN); } break; default : if (!Value.empty()) { if (Parameter!=(size_t)-1) Fill(StreamKind, StreamPos, Parameter, Value); else Fill(StreamKind, StreamPos, Ztring().From_CC4((int32u)Element_Code).To_Local().c_str(), Value, true); } } } //--------------------------------------------------------------------------- void File_Riff::AVI__JUNK() { Element_Name("Garbage"); //Library defined size for padding, often used to store library name if (Element_Size<8) { Skip_XX(Element_Size, "Junk"); return; } //Detect DivX files if (CC5(Buffer+Buffer_Offset)==CC5("DivX ")) { Fill(Stream_General, 0, General_Format, "DivX", Unlimited, true, true); } //MPlayer else if (CC8(Buffer+Buffer_Offset)==CC8("[= MPlay") && Retrieve(Stream_General, 0, General_Encoded_Library).empty()) Fill(Stream_General, 0, General_Encoded_Library, "MPlayer"); //Scenalyzer else if (CC8(Buffer+Buffer_Offset)==CC8("scenalyz") && Retrieve(Stream_General, 0, General_Encoded_Library).empty()) Fill(Stream_General, 0, General_Encoded_Library, "Scenalyzer"); //FFMpeg broken files detection else if (CC8(Buffer+Buffer_Offset)==CC8("odmldmlh")) dmlh_TotalFrame=0; //this is not normal to have this string in a JUNK block!!! and in files tested, in this case TotalFrame is broken too //VirtualDubMod else if (CC8(Buffer+Buffer_Offset)==CC8("INFOISFT")) { int32u Size=LittleEndian2int32u(Buffer+Buffer_Offset+8); if (Size>Element_Size-12) Size=(int32u)Element_Size-12; Fill(Stream_General, 0, General_Encoded_Library, (const char*)(Buffer+Buffer_Offset+12), Size); } else if (CC8(Buffer+Buffer_Offset)==CC8("INFOIENG")) { int32u Size=LittleEndian2int32u(Buffer+Buffer_Offset+8); if (Size>Element_Size-12) Size=(int32u)Element_Size-12; Fill(Stream_General, 0, General_Encoded_Library, (const char*)(Buffer+Buffer_Offset+12), Size); } //Other libraries? else if (CC1(Buffer+Buffer_Offset)>=CC1("A") && CC1(Buffer+Buffer_Offset)<=CC1("z") && Retrieve(Stream_General, 0, General_Encoded_Library).empty()) Fill(Stream_General, 0, General_Encoded_Library, (const char*)(Buffer+Buffer_Offset), (size_t)Element_Size); Skip_XX(Element_Size, "Data"); } //--------------------------------------------------------------------------- void File_Riff::AVI__MD5_() { //Parsing while (Element_Offset<Element_Size) { int128u MD5Stored; Get_L16 (MD5Stored, "MD5"); Ztring MD5_PerItem; MD5_PerItem.From_Number(MD5Stored, 16); while (MD5_PerItem.size()<32) MD5_PerItem.insert(MD5_PerItem.begin(), '0'); //Padding with 0, this must be a 32-byte string MD5_PerItem.MakeLowerCase(); MD5s.push_back(MD5_PerItem); } } //--------------------------------------------------------------------------- void File_Riff::AVI__movi() { Element_Name("Datas"); //Only the first time, no need in AVIX if (movi_Size==0) { Idx1_Offset=File_Offset+Buffer_Offset-4; BookMark_Set(); //Remenbering this place, for stream parsing in phase 2 //For each stream std::map<int32u, stream>::iterator Temp=Stream.begin(); while (Temp!=Stream.end()) { if ((Temp->second.Parsers.empty() || Temp->second.Parsers[0]==NULL) && Temp->second.fccType!=Elements::AVI__hdlr_strl_strh_txts) { Temp->second.SearchingPayload=false; stream_Count--; } ++Temp; } } //Probing rec (with index, this is not always tested in the flow if (Element_Size<12) { Element_WaitForMoreData(); return; } if (CC4(Buffer+Buffer_Offset+8)==0x72656320) //"rec " rec__Present=true; //Filling if (!SecondPass) movi_Size+=Element_TotalSize_Get(); //We must parse moov? if (NeedOldIndex || (stream_Count==0 && Index_Pos.empty())) { //Jumping #if MEDIAINFO_TRACE if (Trace_Activated) Param("Data", Ztring("(")+Ztring::ToZtring(Element_TotalSize_Get())+Ztring(" bytes)")); #endif //MEDIAINFO_TRACE Element_Offset=Element_TotalSize_Get(); //Not using Skip_XX() because we want to skip data we don't have, and Skip_XX() does a test on size of buffer return; } //Jump to next useful data AVI__movi_StreamJump(); } //--------------------------------------------------------------------------- void File_Riff::AVI__movi_rec_() { Element_Name("Syncronisation"); rec__Present=true; } //--------------------------------------------------------------------------- void File_Riff::AVI__movi_rec__xxxx() { AVI__movi_xxxx(); } //--------------------------------------------------------------------------- void File_Riff::AVI__movi_xxxx() { if (Element_Code==Elements::AVI__JUNK) { Skip_XX(Element_Size, "Junk"); AVI__movi_StreamJump(); return; } if (Element_Code!=(int64u)-1) Stream_ID=(int32u)(Element_Code&0xFFFF0000); else Stream_ID=(int32u)-1; if (Stream_ID==0x69780000) //ix.. { //AVI Standard Index Chunk AVI__hdlr_strl_indx(); Stream_ID=(int32u)(Element_Code&0x0000FFFF)<<16; AVI__movi_StreamJump(); return; } if ((Element_Code&0x0000FFFF)==0x00006978) //..ix (Out of specs, but found in a Adobe After Effects CS4 DV file { //AVI Standard Index Chunk AVI__hdlr_strl_indx(); Stream_ID=(int32u)(Element_Code&0xFFFF0000); AVI__movi_StreamJump(); return; } stream& StreamItem = Stream[Stream_ID]; #if MEDIAINFO_DEMUX if (StreamItem.Rate) //AVI { int64u Element_Code_Old=Element_Code; Element_Code=((Element_Code_Old>>24)&0xF)*10+((Element_Code_Old>>16)&0xF); Frame_Count_NotParsedIncluded= StreamItem.PacketPos; FrameInfo.DTS=Frame_Count_NotParsedIncluded*1000000000* StreamItem.Scale/ StreamItem.Rate; Demux(Buffer+Buffer_Offset, (size_t)Element_Size, ContentType_MainStream); Element_Code=Element_Code_Old; Frame_Count_NotParsedIncluded=(int64u)-1; } else //WAV { //TODO } #endif //MEDIAINFO_DEMUX StreamItem.PacketPos++; //Finished? if (!StreamItem.SearchingPayload) { Element_DoNotShow(); AVI__movi_StreamJump(); return; } #if MEDIAINFO_TRACE if (Config_Trace_Level) { switch (Element_Code&0x0000FFFF) //2 last bytes { case Elements::AVI__movi_xxxx_____ : Element_Info1("DV"); break; case Elements::AVI__movi_xxxx___db : case Elements::AVI__movi_xxxx___dc : Element_Info1("Video"); break; case Elements::AVI__movi_xxxx___sb : case Elements::AVI__movi_xxxx___tx : Element_Info1("Text"); break; case Elements::AVI__movi_xxxx___wb : Element_Info1("Audio"); break; default : Element_Info1("Unknown"); break; } Element_Info1(Stream[Stream_ID].PacketPos); } #endif //MEDIAINFO_TRACE //Some specific stuff switch (Element_Code&0x0000FFFF) //2 last bytes { case Elements::AVI__movi_xxxx___tx : AVI__movi_xxxx___tx(); break; default : ; } //Parsing for (size_t Pos=0; Pos<StreamItem.Parsers.size(); Pos++) if (StreamItem.Parsers[Pos]) { if (FrameInfo.PTS!=(int64u)-1) StreamItem.Parsers[Pos]->FrameInfo.PTS=FrameInfo.PTS; if (FrameInfo.DTS!=(int64u)-1) StreamItem.Parsers[Pos]->FrameInfo.DTS=FrameInfo.DTS; Open_Buffer_Continue(StreamItem.Parsers[Pos], Buffer+Buffer_Offset+(size_t)Element_Offset, (size_t)(Element_Size-Element_Offset)); Element_Show(); if (StreamItem.Parsers.size()==1 && StreamItem.Parsers[Pos]->Buffer_Size>0) StreamItem.ChunksAreComplete=false; if (StreamItem.Parsers.size()>1) { if (!StreamItem.Parsers[Pos]->Status[IsAccepted] && StreamItem.Parsers[Pos]->Status[IsFinished]) { delete *(StreamItem.Parsers.begin()+Pos); StreamItem.Parsers.erase(StreamItem.Parsers.begin()+Pos); Pos--; } else if (StreamItem.Parsers.size()>1 && StreamItem.Parsers[Pos]->Status[IsAccepted]) { File__Analyze* Parser= StreamItem.Parsers[Pos]; for (size_t Pos2=0; Pos2<StreamItem.Parsers.size(); Pos2++) { if (Pos2!=Pos) delete *(StreamItem.Parsers.begin()+Pos2); } StreamItem.Parsers.clear(); StreamItem.Parsers.push_back(Parser); Pos=0; } } #if MEDIAINFO_DEMUX if (Config->Demux_EventWasSent) { Demux_Parser= StreamItem.Parsers[Pos]; return; } #endif //MEDIAINFO_DEMUX } Element_Offset=Element_Size; //Some specific stuff switch (Element_Code&0x0000FFFF) //2 last bytes { case Elements::AVI__movi_xxxx_____ : case Elements::AVI__movi_xxxx___db : case Elements::AVI__movi_xxxx___dc : AVI__movi_xxxx___dc(); break; case Elements::AVI__movi_xxxx___wb : AVI__movi_xxxx___wb(); break; default : ; } //We must always parse moov? AVI__movi_StreamJump(); Element_Show(); } //--------------------------------------------------------------------------- void File_Riff::AVI__movi_xxxx___dc() { //Finish (if requested) stream& StreamItem = Stream[Stream_ID]; if (StreamItem.Parsers.empty() || StreamItem.Parsers[0]->Status[IsFinished] || (StreamItem.PacketPos>=300 && MediaInfoLib::Config.ParseSpeed_Get()<1.00)) { StreamItem.SearchingPayload=false; stream_Count--; return; } } //--------------------------------------------------------------------------- void File_Riff::AVI__movi_xxxx___tx() { //Parsing int32u Name_Size; Ztring Value; int32u GAB2; Peek_B4(GAB2); if (GAB2==0x47414232 && Element_Size>=17) { Skip_C4( "GAB2"); Skip_L1( "Zero"); Skip_L2( "CodePage"); //2=Unicode Get_L4 (Name_Size, "Name_Size"); Skip_UTF16L(Name_Size, "Name"); Skip_L2( "Four"); Skip_L4( "File_Size"); if (Element_Offset>Element_Size) Element_Offset=Element_Size; //Problem } //Skip it Stream[Stream_ID].SearchingPayload=false; stream_Count--; } //--------------------------------------------------------------------------- void File_Riff::AVI__movi_xxxx___wb() { //Finish (if requested) stream& StreamItem = Stream[Stream_ID]; if (StreamItem.PacketPos>=4 //For having the chunk alignement && (StreamItem.Parsers.empty() || StreamItem.Parsers[0]->Status[IsFinished] || (StreamItem.PacketPos>=300 && MediaInfoLib::Config.ParseSpeed_Get()<1.00))) { StreamItem.SearchingPayload=false; stream_Count--; } } //--------------------------------------------------------------------------- void File_Riff::AVI__movi_StreamJump() { //Jump to next useful data if (!Index_Pos.empty()) { if (Index_Pos.begin()->first<=File_Offset+Buffer_Offset && Element_Code!=Elements::AVI__movi) Index_Pos.erase(Index_Pos.begin()); int64u ToJump=File_Size; if (!Index_Pos.empty()) ToJump=Index_Pos.begin()->first; if (ToJump>File_Size) ToJump=File_Size; if (ToJump>=File_Offset+Buffer_Offset+Element_TotalSize_Get(Element_Level-2)) //We want always Element movi { #if MEDIAINFO_HASH if (Config->File_Hash_Get().to_ulong() && SecondPass) Hash_ParseUpTo=File_Offset+Buffer_Offset+Element_TotalSize_Get(Element_Level-2); else #endif //MEDIAINFO_HASH GoTo(File_Offset+Buffer_Offset+Element_TotalSize_Get(Element_Level-2), "AVI"); //Not in this chunk } else if (ToJump!=File_Offset+Buffer_Offset+(Element_Code==Elements::AVI__movi?0:Element_Size)) { #if MEDIAINFO_HASH if (Config->File_Hash_Get().to_ulong() && SecondPass) Hash_ParseUpTo=File_Offset+Buffer_Offset+Element_TotalSize_Get(Element_Level-2); else #endif //MEDIAINFO_HASH GoTo(ToJump, "AVI"); //Not just after } } else if (stream_Count==0) { //Jumping Element_Show(); if (rec__Present) Element_End0(); Info("movi, Jumping to end of chunk"); if (SecondPass) { std::map<int32u, stream>::iterator Temp=Stream.begin(); while (Temp!=Stream.end()) { for (size_t Pos=0; Pos<Temp->second.Parsers.size(); ++Pos) { Temp->second.Parsers[Pos]->Fill(); Temp->second.Parsers[Pos]->Open_Buffer_Unsynch(); } ++Temp; } Finish("AVI"); //The rest is already parsed } else GoTo(File_Offset+Buffer_Offset+Element_TotalSize_Get(), "AVI"); } else if (Stream_Structure_Temp!=Stream_Structure.end()) { do Stream_Structure_Temp++; while (Stream_Structure_Temp!=Stream_Structure.end() && !(Stream[(int32u)Stream_Structure_Temp->second.Name].SearchingPayload && Config->ParseSpeed<1.0)); if (Stream_Structure_Temp!=Stream_Structure.end()) { int64u ToJump=Stream_Structure_Temp->first; if (ToJump>=File_Offset+Buffer_Offset+Element_TotalSize_Get(Element_Level-2)) { #if MEDIAINFO_HASH if (Config->File_Hash_Get().to_ulong() && SecondPass) Hash_ParseUpTo=File_Offset+Buffer_Offset+Element_TotalSize_Get(Element_Level-2); else #endif //MEDIAINFO_HASH GoTo(File_Offset+Buffer_Offset+Element_TotalSize_Get(Element_Level-2), "AVI"); //Not in this chunk } else if (ToJump!=File_Offset+Buffer_Offset+Element_Size) { #if MEDIAINFO_HASH if (Config->File_Hash_Get().to_ulong() && SecondPass) Hash_ParseUpTo=ToJump; else #endif //MEDIAINFO_HASH GoTo(ToJump, "AVI"); //Not just after } } else Finish("AVI"); } } //--------------------------------------------------------------------------- void File_Riff::AVI__PrmA() { Element_Name("Adobe Premiere PrmA"); //Parsing int32u FourCC, Size; Get_C4 (FourCC, "FourCC"); Get_B4 (Size, "Size"); switch (FourCC) { case 0x50415266: if (Size==20) { int32u PAR_X, PAR_Y; Skip_B4( "Unknown"); Get_B4 (PAR_X, "PAR_X"); Get_B4 (PAR_Y, "PAR_Y"); if (PAR_Y) PAR=((float64)PAR_X)/PAR_Y; } else Skip_XX(Element_Size-Element_Offset, "Unknown"); break; default: for (int32u Pos=8; Pos<Size; Pos++) Skip_B4( "Unknown"); } } //--------------------------------------------------------------------------- void File_Riff::AVI__Tdat() { Element_Name("Adobe Premiere Tdat"); } //--------------------------------------------------------------------------- void File_Riff::AVI__Tdat_tc_A() { Element_Name("tc_A"); //Parsing Ztring Value; Get_Local(Element_Size, Value, "Unknown"); if (Value.find_first_not_of(__T("0123456789:;"))==string::npos) Tdat_tc_A=Value; } //--------------------------------------------------------------------------- void File_Riff::AVI__Tdat_tc_O() { Element_Name("tc_O"); //Parsing Ztring Value; Get_Local(Element_Size, Value, "Unknown"); if (Value.find_first_not_of(__T("0123456789:;"))==string::npos) Tdat_tc_O=Value; } //--------------------------------------------------------------------------- void File_Riff::AVI__Tdat_rn_A() { Element_Name("rn_A"); //Parsing Skip_Local(Element_Size, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::AVI__Tdat_rn_O() { Element_Name("rn_O"); //Parsing Skip_Local(Element_Size, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::AVI__xxxx() { Stream_ID=(int32u)(Element_Code&0xFFFF0000); if (Stream_ID==0x69780000) //ix.. { //AVI Standard Index Chunk AVI__hdlr_strl_indx(); Stream_ID=(int32u)(Element_Code&0x0000FFFF)<<16; AVI__movi_StreamJump(); return; } if ((Element_Code&0x0000FFFF)==0x00006978) //..ix (Out of specs, but found in a Adobe After Effects CS4 DV file { //AVI Standard Index Chunk AVI__hdlr_strl_indx(); Stream_ID=(int32u)(Element_Code&0xFFFF0000); AVI__movi_StreamJump(); return; } } //--------------------------------------------------------------------------- void File_Riff::AVIX() { //Filling Fill(Stream_General, 0, General_Format_Profile, "OpenDML", Unlimited, true, true); } //--------------------------------------------------------------------------- void File_Riff::AVIX_idx1() { AVI__idx1(); } //--------------------------------------------------------------------------- void File_Riff::AVIX_movi() { AVI__movi(); } //--------------------------------------------------------------------------- void File_Riff::AVIX_movi_rec_() { AVI__movi_rec_(); } //--------------------------------------------------------------------------- void File_Riff::AVIX_movi_rec__xxxx() { AVIX_movi_xxxx(); } //--------------------------------------------------------------------------- void File_Riff::AVIX_movi_xxxx() { AVI__movi_xxxx(); } //--------------------------------------------------------------------------- void File_Riff::CADP() { Element_Name("CMP4 - ADPCM"); //Testing if we have enough data if (Element_Size<4) { Element_WaitForMoreData(); return; } //Parsing int32u Codec; Get_C4 (Codec, "Codec"); #if MEDIAINFO_TRACE if (Trace_Activated) Param("Data", Ztring("(")+Ztring::ToZtring(Element_TotalSize_Get()-Element_Offset)+Ztring(" bytes)")); #endif //MEDIAINFO_TRACE Element_Offset=Element_TotalSize_Get(); //Not using Skip_XX() because we want to skip data we don't have, and Skip_XX() does a test on size of buffer FILLING_BEGIN(); Stream_Prepare(Stream_Audio); if (Codec==0x41647063) //Adpc Fill(Stream_Audio, StreamPos_Last, Audio_Format, "ADPCM"); Fill(Stream_Audio, StreamPos_Last, Audio_StreamSize, Element_TotalSize_Get()); FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::CDDA() { Element_Name("Compact Disc for Digital Audio"); //Filling Accept("CDDA"); } //--------------------------------------------------------------------------- void File_Riff::CDDA_fmt_() { //Specs: http://fr.wikipedia.org/wiki/Compact_Disc_Audio_track //Specs: http://www.moon-soft.com/program/FORMAT/sound/cda.htm Element_Name("Stream format"); //Parsing int32u id; int16u Version, tracknb=1; int8u TPositionF=0, TPositionS=0, TPositionM=0, TDurationF=0, TDurationS=0, TDurationM=0; Get_L2 (Version, "Version"); // Always 1 if (Version!=1) { //Not supported Skip_XX(Element_Size-2, "Data"); return; } Get_L2 (tracknb, "Number"); // Start at 1 Get_L4 (id, "id"); Skip_L4( "offset"); // in frames //Priority of FSM format Skip_L4( "Duration"); // in frames //Priority of FSM format Get_L1 (TPositionF, "Track_PositionF"); // in frames Get_L1 (TPositionS, "Track_PositionS"); // in seconds Get_L1 (TPositionM, "Track_PositionM"); // in minutes Skip_L1( "empty"); Get_L1 (TDurationF, "Track_DurationF"); // in frames Get_L1 (TDurationS, "Track_DurationS"); // in seconds Get_L1 (TDurationM, "Track_DurationM"); // in minutes Skip_L1( "empty"); FILLING_BEGIN(); int32u TPosition=TPositionM*60*75+TPositionS*75+TPositionF; int32u TDuration=TDurationM*60*75+TDurationS*75+TDurationF; Fill(Stream_General, 0, General_Track_Position, tracknb); Fill(Stream_General, 0, General_Format, "CDDA"); Fill(Stream_General, 0, General_Format_Info, "Compact Disc for Digital Audio"); Fill(Stream_General, 0, General_UniqueID, id); Fill(Stream_General, 0, General_FileSize, File_Size+TDuration*2352, 10, true); Stream_Prepare(Stream_Audio); Fill(Stream_Audio, 0, Audio_Format, "PCM"); Fill(Stream_Audio, 0, Audio_Format_Settings_Endianness, "Little"); Fill(Stream_Audio, 0, Audio_BitDepth, 16); Fill(Stream_Audio, 0, Audio_Channel_s_, 2); Fill(Stream_Audio, 0, Audio_SamplingRate, 44100); Fill(Stream_Audio, 0, Audio_FrameRate, (float)75); Fill(Stream_Audio, 0, Audio_BitRate, 1411200); Fill(Stream_Audio, 0, Audio_Compression_Mode, "Lossless"); Fill(Stream_Audio, 0, Audio_FrameCount, TDuration); Fill(Stream_Audio, 0, Audio_Duration, float32_int32s(((float32)TDuration)*1000/75)); Fill(Stream_Audio, 0, Audio_Delay, float32_int32s(((float32)TPosition)*1000/75)); //No more need data Finish("CDDA"); FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::CMJP() { Element_Name("CMP4 - JPEG"); //Parsing #ifdef MEDIAINFO_JPEG_YES Stream_ID=0; File_Jpeg* Parser=new File_Jpeg; Open_Buffer_Init(Parser); Parser->StreamKind=Stream_Video; Open_Buffer_Continue(Parser); Element_Offset=Element_TotalSize_Get(); //Not using Skip_XX() because we want to skip data we don't have, and Skip_XX() does a test on size of buffer FILLING_BEGIN(); Stream_Prepare(Stream_Video); Fill(Stream_Video, StreamPos_Last, Video_StreamSize, Element_TotalSize_Get()); Finish(Parser); Merge(*Parser, StreamKind_Last, 0, StreamPos_Last); FILLING_END(); Stream[Stream_ID].Parsers.push_back(Parser); #else Element_Offset=Element_TotalSize_Get(); //Not using Skip_XX() because we want to skip data we don't have, and Skip_XX() does a test on size of buffer FILLING_BEGIN(); Stream_Prepare(Stream_Video); Fill(Stream_Video, StreamPos_Last, Video_Format, "JPEG"); Fill(Stream_Video, StreamPos_Last, Video_StreamSize, Element_TotalSize_Get()); FILLING_END(); #endif } //--------------------------------------------------------------------------- void File_Riff::CMP4() { Accept("CMP4"); Element_Name("CMP4 - Header"); //Parsing Ztring Title; Get_Local(Element_Size, Title, "Title"); FILLING_BEGIN(); Fill(Stream_General, 0, General_Format, "CMP4"); Fill(Stream_General, 0, "Title", Title); FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::IDVX() { Element_Name("Tags"); } //--------------------------------------------------------------------------- void File_Riff::INDX() { Element_Name("Index (from which spec?)"); } //--------------------------------------------------------------------------- void File_Riff::INDX_xxxx() { Stream_ID=(int32u)(Element_Code&0xFFFF0000); if (Stream_ID==0x69780000) //ix.. { //Index int32u Entry_Count, ChunkId; int16u LongsPerEntry; int8u IndexType, IndexSubType; Get_L2 (LongsPerEntry, "LongsPerEntry"); //Size of each entry in aIndex array Get_L1 (IndexSubType, "IndexSubType"); Get_L1 (IndexType, "IndexType"); Get_L4 (Entry_Count, "EntriesInUse"); //Index of first unused member in aIndex array Get_C4 (ChunkId, "ChunkId"); //FCC of what is indexed Skip_L4( "Unknown"); Skip_L4( "Unknown"); Skip_L4( "Unknown"); for (int32u Pos=0; Pos<Entry_Count; Pos++) { Skip_L8( "Offset"); Skip_L4( "Size"); Skip_L4( "Frame number?"); Skip_L4( "Frame number?"); Skip_L4( "Zero"); } } //Currently, we do not use the index //TODO: use the index Stream_Structure.clear(); } //--------------------------------------------------------------------------- void File_Riff::JUNK() { Element_Name("Junk"); //Parse #if MEDIAINFO_TRACE if (Trace_Activated) Param("Junk", Ztring("(")+Ztring::ToZtring(Element_TotalSize_Get())+Ztring(" bytes)")); #endif //MEDIAINFO_TRACE Element_Offset=Element_TotalSize_Get(); //Not using Skip_XX() because we want to skip data we don't have, and Skip_XX() does a test on size of buffer } //--------------------------------------------------------------------------- void File_Riff::menu() { Element_Name("DivX Menu"); //Filling Stream_Prepare(Stream_Menu); Fill(Stream_Menu, StreamPos_Last, Menu_Format, "DivX Menu"); Fill(Stream_Menu, StreamPos_Last, Menu_Codec, "DivX"); } //--------------------------------------------------------------------------- void File_Riff::MThd() { Element_Name("MIDI header"); //Parsing Skip_B2( "format"); Skip_B2( "ntrks"); Skip_B2( "division"); FILLING_BEGIN_PRECISE(); Accept("MIDI"); Fill(Stream_General, 0, General_Format, "MIDI"); FILLING_ELSE(); Reject("MIDI"); FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::MTrk() { Element_Name("MIDI Track"); //Parsing #if MEDIAINFO_TRACE if (Trace_Activated) Param("Data", Ztring("(")+Ztring::ToZtring(Element_TotalSize_Get())+Ztring(" bytes)")); #endif //MEDIAINFO_TRACE Element_Offset=Element_TotalSize_Get(); //Not using Skip_XX() because we want to skip data we don't have, and Skip_XX() does a test on size of buffer FILLING_BEGIN(); Stream_Prepare(Stream_Audio); Fill(Stream_Audio, StreamPos_Last, Audio_Format, "MIDI"); Fill(Stream_Audio, StreamPos_Last, Audio_Codec, "Midi"); Finish("MIDI"); FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::PAL_() { Data_Accept("RIFF Palette"); Element_Name("RIFF Palette"); //Filling Fill(Stream_General, 0, General_Format, "RIFF Palette"); } //--------------------------------------------------------------------------- void File_Riff::QLCM() { Data_Accept("QLCM"); Element_Name("QLCM"); //Filling Fill(Stream_General, 0, General_Format, "QLCM"); } //--------------------------------------------------------------------------- void File_Riff::QLCM_fmt_() { //Parsing Ztring codec_name; int128u codec_guid; int32u num_rates; int16u codec_version, average_bps, packet_size, block_size, sampling_rate, sample_size; int8u major, minor; Get_L1 (major, "major"); Get_L1 (minor, "minor"); Get_GUID(codec_guid, "codec-guid"); Get_L2 (codec_version, "codec-version"); Get_Local(80, codec_name, "codec-name"); Get_L2 (average_bps, "average-bps"); Get_L2 (packet_size, "packet-size"); Get_L2 (block_size, "block-size"); Get_L2 (sampling_rate, "sampling-rate"); Get_L2 (sample_size, "sample-size"); Element_Begin1("rate-map-table"); Get_L4 (num_rates, "num-rates"); for (int32u rate=0; rate<num_rates; rate++) { Skip_L2( "rate-size"); Skip_L2( "rate-octet"); } Element_End0(); Skip_L4( "Reserved"); Skip_L4( "Reserved"); Skip_L4( "Reserved"); Skip_L4( "Reserved"); if (Element_Offset<Element_Size) Skip_L4( "Reserved"); //Some files don't have the 5th reserved dword FILLING_BEGIN_PRECISE(); Stream_Prepare (Stream_Audio); switch (codec_guid.hi) { case Elements::QLCM_QCELP1 : case Elements::QLCM_QCELP2 : Fill(Stream_Audio, 0, Audio_Format, "QCELP"); Fill(Stream_Audio, 0, Audio_Codec, "QCELP"); break; case Elements::QLCM_EVRC : Fill(Stream_Audio, 0, Audio_Format, "EVRC"); Fill(Stream_Audio, 0, Audio_Codec, "EVRC"); break; case Elements::QLCM_SMV : Fill(Stream_Audio, 0, Audio_Format, "SMV"); Fill(Stream_Audio, 0, Audio_Codec, "SMV"); break; default : ; } Fill(Stream_Audio, 0, Audio_BitRate, average_bps); Fill(Stream_Audio, 0, Audio_SamplingRate, sampling_rate); Fill(Stream_Audio, 0, Audio_BitDepth, sample_size); Fill(Stream_Audio, 0, Audio_Channel_s_, 1); FILLING_END(); } #if defined(MEDIAINFO_GXF_YES) //--------------------------------------------------------------------------- void File_Riff::rcrd() { Data_Accept("Ancillary media packets"); Element_Name("Ancillary media packets"); //Filling if (Retrieve(Stream_General, 0, General_Format).empty()) Fill(Stream_General, 0, General_Format, "Ancillary media packets"); //GXF, RDD14-2007 //Clearing old data if (Ancillary) { (*Ancillary)->FrameInfo.DTS=FrameInfo.DTS; Open_Buffer_Continue(*Ancillary, Buffer, 0); } } //--------------------------------------------------------------------------- void File_Riff::rcrd_desc() { Element_Name("Ancillary media packet description"); //Parsing int32u Version; Get_L4 (Version, "Version"); if (Version==2) { Skip_L4( "Number of fields"); Skip_L4( "Length of the ancillary data field descriptions"); Skip_L4( "Byte size of the complete ancillary media packet"); Skip_L4( "Format of the video"); } else Skip_XX(Element_Size-Element_Offset, "Unknown"); } //--------------------------------------------------------------------------- void File_Riff::rcrd_fld_() { Element_Name("Ancillary data field description"); } //--------------------------------------------------------------------------- void File_Riff::rcrd_fld__anc_() { Element_Name("Ancillary data sample description"); rcrd_fld__anc__pos__LineNumber=(int32u)-1; } //--------------------------------------------------------------------------- void File_Riff::rcrd_fld__anc__pos_() { Element_Name("Ancillary data sample description"); //Parsing Get_L4 (rcrd_fld__anc__pos__LineNumber, "Video line number"); Skip_L4( "Ancillary video color difference or luma space"); Skip_L4( "Ancillary video space"); } //--------------------------------------------------------------------------- void File_Riff::rcrd_fld__anc__pyld() { Element_Name("Ancillary data sample payload"); if (Ancillary) { (*Ancillary)->FrameInfo.DTS=FrameInfo.DTS; (*Ancillary)->LineNumber=rcrd_fld__anc__pos__LineNumber; Open_Buffer_Continue(*Ancillary); } } //--------------------------------------------------------------------------- void File_Riff::rcrd_fld__finf() { Element_Name("Data field description"); //Parsing Skip_L4( "Video field identifier"); } #endif //MEDIAINFO_GXF_YES //--------------------------------------------------------------------------- void File_Riff::RDIB() { Data_Accept("RIFF DIB"); Element_Name("RIFF DIB"); //Filling Fill(Stream_General, 0, General_Format, "RIFF DIB"); } //--------------------------------------------------------------------------- void File_Riff::RMID() { Data_Accept("RIFF MIDI"); Element_Name("RIFF MIDI"); //Filling Fill(Stream_General, 0, General_Format, "RIFF MIDI"); } //--------------------------------------------------------------------------- void File_Riff::RMMP() { Data_Accept("RIFF MMP"); Element_Name("RIFF MMP"); //Filling Fill(Stream_General, 0, General_Format, "RIFF MMP"); } //--------------------------------------------------------------------------- void File_Riff::RMP3() { Data_Accept("RMP3"); Element_Name("RMP3"); //Filling Fill(Stream_General, 0, General_Format, "RMP3"); Kind=Kind_Rmp3; } //--------------------------------------------------------------------------- void File_Riff::RMP3_data() { Element_Name("Raw datas"); Fill(Stream_Audio, 0, Audio_StreamSize, Buffer_DataToParse_End-Buffer_DataToParse_Begin); Stream_Prepare(Stream_Audio); //Creating parser #if defined(MEDIAINFO_MPEGA_YES) File_Mpega* Parser=new File_Mpega; Parser->CalculateDelay=true; Parser->ShouldContinueParsing=true; Open_Buffer_Init(Parser); stream& StreamItem=Stream[(int32u)-1]; StreamItem.StreamKind=Stream_Audio; StreamItem.StreamPos=0; StreamItem.Parsers.push_back(Parser); #else //MEDIAINFO_MPEG4_YES Fill(Stream_Audio, 0, Audio_Format, "MPEG Audio"); Skip_XX(Buffer_DataToParse_End-Buffer_DataToParse_Begin, "Data"); #endif } //--------------------------------------------------------------------------- void File_Riff::RMP3_data_Continue() { #if MEDIAINFO_DEMUX if (Element_Size) { Demux_random_access=true; Demux(Buffer+Buffer_Offset, (size_t)Element_Size, ContentType_MainStream); } #endif //MEDIAINFO_DEMUX Element_Code=(int64u)-1; AVI__movi_xxxx(); } //--------------------------------------------------------------------------- void File_Riff::SMV0() { Accept("SMV"); //Parsing int8u Version; Skip_C1( "Identifier (continuing)"); Get_C1 (Version, "Version"); Skip_C3( "Identifier (continuing)"); if (Version=='1') { int32u Width, Height, FrameRate, BlockSize, FrameCount; Get_B3 (Width, "Width"); Get_B3 (Height, "Height"); Skip_B3( "0x000010"); Skip_B3( "0x000001"); Get_B3 (BlockSize, "Block size"); Get_B3 (FrameRate, "Frame rate"); Get_B3 (FrameCount, "Frame count"); Skip_B3( "0x000000"); Skip_B3( "0x000000"); Skip_B3( "0x000000"); Skip_B3( "0x010101"); Skip_B3( "0x010101"); Skip_B3( "0x010101"); Skip_B3( "0x010101"); //Filling Fill(Stream_General, 0, General_Format_Profile, "SMV v1"); Stream_Prepare(Stream_Video); Fill(Stream_Video, 0, Video_MuxingMode, "SMV v1"); Fill(Stream_Video, 0, Video_Width, Width); Fill(Stream_Video, 0, Video_Height, Height); Fill(Stream_Video, 0, Video_FrameRate, (float)FrameRate); Fill(Stream_Video, 0, Video_FrameCount, FrameCount); Finish("SMV"); } else if (Version=='2') { int32u Width, Height, FrameRate; Get_L3 (Width, "Width"); Get_L3 (Height, "Height"); Skip_L3( "0x000010"); Skip_L3( "0x000001"); Get_L3 (SMV_BlockSize, "Block size"); Get_L3 (FrameRate, "Frame rate"); Get_L3 (SMV_FrameCount, "Frame count"); Skip_L3( "0x000001"); Skip_L3( "0x000000"); Skip_L3( "Frame rate"); Skip_L3( "0x010101"); Skip_L3( "0x010101"); Skip_L3( "0x010101"); Skip_L3( "0x010101"); //Filling SMV_BlockSize+=3; SMV_FrameCount++; Fill(Stream_General, 0, General_Format_Profile, "SMV v2"); Stream_Prepare(Stream_Video); Fill(Stream_Video, 0, Video_Format, "JPEG"); Fill(Stream_Video, 0, Video_Codec, "JPEG"); Fill(Stream_Video, 0, Video_MuxingMode, "SMV v2"); Fill(Stream_Video, 0, Video_Width, Width); Fill(Stream_Video, 0, Video_Height, Height); Fill(Stream_Video, 0, Video_FrameRate, FrameRate); Fill(Stream_Video, 0, Video_FrameCount, SMV_FrameCount); Fill(Stream_Video, 0, Video_StreamSize, SMV_BlockSize*SMV_FrameCount); } else Finish("SMV"); } //--------------------------------------------------------------------------- void File_Riff::SMV0_xxxx() { //Parsing int32u Size; Get_L3 (Size, "Size"); #if defined(MEDIAINFO_JPEG_YES) //Creating the parser File_Jpeg MI; Open_Buffer_Init(&MI); //Parsing Open_Buffer_Continue(&MI, Size); //Filling Finish(&MI); Merge(MI, Stream_Video, 0, StreamPos_Last); //Positioning Element_Offset+=Size; #else //Parsing Skip_XX(Size, "JPEG data"); #endif Skip_XX(Element_Size-Element_Offset, "Padding"); //Filling #if MEDIAINFO_HASH if (Config->File_Hash_Get().to_ulong()) Element_Offset=Element_Size+(SMV_FrameCount-1)*SMV_BlockSize; #endif //MEDIAINFO_HASH Data_GoTo(File_Offset+Buffer_Offset+(size_t)Element_Size+(SMV_FrameCount-1)*SMV_BlockSize, "SMV"); SMV_BlockSize=0; } //--------------------------------------------------------------------------- void File_Riff::WAVE() { Data_Accept("Wave"); Element_Name("Wave"); //Filling Fill(Stream_General, 0, General_Format, "Wave"); Kind=Kind_Wave; #if MEDIAINFO_EVENTS StreamIDs_Width[0]=0; #endif //MEDIAINFO_EVENTS } //--------------------------------------------------------------------------- void File_Riff::WAVE__pmx() { Element_Name("XMP"); //Parsing Ztring XML_Data; Get_Local(Element_Size, XML_Data, "XML data"); } //--------------------------------------------------------------------------- void File_Riff::WAVE_aXML() { Element_Name("aXML"); //Parsing Skip_Local(Element_Size, "XML data"); } //--------------------------------------------------------------------------- void File_Riff::WAVE_bext() { Element_Name("Broadcast extension"); //Parsing Ztring Description, Originator, OriginatorReference, OriginationDate, OriginationTime, History; int16u Version; Get_Local(256, Description, "Description"); Get_Local( 32, Originator, "Originator"); Get_Local( 32, OriginatorReference, "OriginatorReference"); Get_Local( 10, OriginationDate, "OriginationDate"); Get_Local( 8, OriginationTime, "OriginationTime"); Get_L8 ( TimeReference, "TimeReference"); //To be divided by SamplesPerSec Get_L2 ( Version, "Version"); if (Version==1) Skip_UUID( "UMID"); Skip_XX (602-Element_Offset, "Reserved"); if (Element_Offset<Element_Size) Get_Local(Element_Size-Element_Offset, History, "History"); FILLING_BEGIN(); Fill(Stream_General, 0, General_Description, Description); Fill(Stream_General, 0, General_Producer, Originator); Fill(Stream_General, 0, "Producer_Reference", OriginatorReference); Fill(Stream_General, 0, General_Encoded_Date, OriginationDate+__T(' ')+OriginationTime); Fill(Stream_General, 0, General_Encoded_Library_Settings, History); if (SamplesPerSec && TimeReference!=(int64u)-1) { Fill(Stream_Audio, 0, Audio_Delay, float64_int64s(((float64)TimeReference)*1000/SamplesPerSec)); Fill(Stream_Audio, 0, Audio_Delay_Source, "Container (bext)"); } FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::WAVE_cue_() { Element_Name("Cue points"); //Parsing int32u numCuePoints; Get_L4(numCuePoints, "numCuePoints"); for (int32u Pos=0; Pos<numCuePoints; Pos++) { Element_Begin1("Cue point"); Skip_L4( "ID"); Skip_L4( "Position"); Skip_C4( "DataChunkID"); Skip_L4( "ChunkStart"); Skip_L4( "BlockStart"); Skip_L4( "SampleOffset"); Element_End0(); } } //--------------------------------------------------------------------------- void File_Riff::WAVE_data() { Element_Name("Raw datas"); if (Buffer_DataToParse_End-Buffer_DataToParse_Begin<100) { Skip_XX(Buffer_DataToParse_End-Buffer_Offset, "Unknown"); return; //This is maybe embeded in another container, and there is only the header (What is the junk?) } FILLING_BEGIN(); Fill(Stream_Audio, 0, Audio_StreamSize, Buffer_DataToParse_End-Buffer_DataToParse_Begin); FILLING_END(); //Parsing Element_Code=(int64u)-1; FILLING_BEGIN(); int64u Duration=Retrieve(Stream_Audio, 0, Audio_Duration).To_int64u(); int64u BitRate=Retrieve(Stream_Audio, 0, Audio_BitRate).To_int64u(); if (Duration) { int64u BitRate_New=(Buffer_DataToParse_End-Buffer_DataToParse_Begin)*8*1000/Duration; if (BitRate_New<BitRate*0.95 || BitRate_New>BitRate*1.05) Fill(Stream_Audio, 0, Audio_BitRate, BitRate_New, 10, true); //Correcting the bitrate, it was false in the header } else if (BitRate) { if (IsSub) //Retrieving "data" real size, in case of truncated files and/or wave header in another container Duration=((int64u)LittleEndian2int32u(Buffer+Buffer_Offset-4))*8*1000/BitRate; //TODO: RF64 is not handled else Duration=(Buffer_DataToParse_End-Buffer_DataToParse_Begin)*8*1000/BitRate; Fill(Stream_General, 0, General_Duration, Duration, 10, true); Fill(Stream_Audio, 0, Audio_Duration, Duration, 10, true); } FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::WAVE_data_Continue() { #if MEDIAINFO_DEMUX Element_Code=(int64u)-1; if (AvgBytesPerSec && Demux_Rate) { FrameInfo.DTS=float64_int64s((File_Offset+Buffer_Offset-Buffer_DataToParse_Begin)*1000000000.0/AvgBytesPerSec); FrameInfo.PTS=FrameInfo.DTS; Frame_Count_NotParsedIncluded=float64_int64s(((float64)FrameInfo.DTS)/1000000000.0*Demux_Rate); } Demux_random_access=true; Demux(Buffer+Buffer_Offset, (size_t)Element_Size, ContentType_MainStream); Frame_Count_NotParsedIncluded=(int64u)-1; #endif //MEDIAINFO_DEMUX Element_Code=(int64u)-1; AVI__movi_xxxx(); } //--------------------------------------------------------------------------- void File_Riff::WAVE_ds64() { Element_Name("DataSize64"); //Parsing int32u tableLength; Skip_L8( "riffSize"); //Is directly read from the header parser Get_L8 (WAVE_data_Size, "dataSize"); Get_L8 (WAVE_fact_samplesCount, "sampleCount"); Get_L4 (tableLength, "tableLength"); for (int32u Pos=0; Pos<tableLength; Pos++) Skip_L8( "table[]"); } //--------------------------------------------------------------------------- void File_Riff::WAVE_fact() { Element_Name("Sample count"); //Parsing int64u SamplesCount64; int32u SamplesCount; Get_L4 (SamplesCount, "SamplesCount"); SamplesCount64=SamplesCount; if (SamplesCount64==0xFFFFFFFF) SamplesCount64=WAVE_fact_samplesCount; FILLING_BEGIN(); int32u SamplingRate=Retrieve(Stream_Audio, 0, Audio_SamplingRate).To_int32u(); if (SamplingRate) { //Calculating int64u Duration=(SamplesCount64*1000)/SamplingRate; //Coherency test bool IsOK=true; if (File_Size!=(int64u)-1) { int64u BitRate=Retrieve(Stream_Audio, 0, Audio_BitRate).To_int64u(); if (BitRate) { int64u Duration_FromBitRate = File_Size * 8 * 1000 / BitRate; if (Duration_FromBitRate > Duration*1.10 || Duration_FromBitRate < Duration*0.9) IsOK = false; } } //Filling if (IsOK) Fill(Stream_Audio, 0, Audio_Duration, Duration); } FILLING_END(); } //--------------------------------------------------------------------------- void File_Riff::WAVE_fmt_() { //Compute the current codec ID Element_Code=(int64u)-1; Stream_ID=(int32u)-1; stream_Count=1; Stream[(int32u)-1].fccType=Elements::AVI__hdlr_strl_strh_auds; AVI__hdlr_strl_strf(); } //--------------------------------------------------------------------------- void File_Riff::WAVE_ID3_() { Element_Name("ID3v2 tags"); //Parsing #if defined(MEDIAINFO_ID3V2_YES) File_Id3v2 MI; Open_Buffer_Init(&MI); Open_Buffer_Continue(&MI); Finish(&MI); Merge(MI, Stream_General, 0, 0); #endif } //--------------------------------------------------------------------------- void File_Riff::WAVE_iXML() { Element_Name("iXML"); //Parsing Skip_Local(Element_Size, "XML data"); } //--------------------------------------------------------------------------- void File_Riff::wave() { Data_Accept("Wave64"); Element_Name("Wave64"); //Filling Fill(Stream_General, 0, General_Format, "Wave64"); } //--------------------------------------------------------------------------- void File_Riff::W3DI() { Element_Name("IDVX tags (Out of specs!)"); //Parsing int32u Size=(int32u)Element_Size; Ztring Title, Artist, Album, Unknown, Genre, Comment; int32u TrackPos; Get_Local(Size, Title, "Title"); Element_Offset=(int32u)Title.size(); Size-=(int32u)Title.size(); if (Size==0) return; Skip_L1( "Zero"); Size--; //NULL char Get_Local(Size, Artist, "Artist"); Element_Offset=(int32u)Title.size()+1+(int32u)Artist.size(); Size-=(int32u)Artist.size(); if (Size==0) return; Skip_L1( "Zero"); Size--; //NULL char Get_Local(Size, Album, "Album"); Element_Offset=(int32u)Title.size()+1+(int32u)Artist.size()+1+(int32u)Album.size(); Size-=(int32u)Album.size(); if (Size==0) return; Skip_L1( "Zero"); Size--; //NULL char Get_Local(Size, Unknown, "Unknown"); Element_Offset=(int32u)Title.size()+1+(int32u)Artist.size()+1+(int32u)Album.size()+1+(int32u)Unknown.size(); Size-=(int32u)Unknown.size(); if (Size==0) return; Skip_L1( "Zero"); Size--; //NULL char Get_Local(Size, Genre, "Genre"); Element_Offset=(int32u)Title.size()+1+(int32u)Artist.size()+1+(int32u)Album.size()+1+(int32u)Unknown.size()+1+(int32u)Genre.size(); Size-=(int32u)Genre.size(); if (Size==0) return; Skip_L1( "Zero"); Size--; //NULL char Get_Local(Size, Comment, "Comment"); Element_Offset=(int32u)Title.size()+1+(int32u)Artist.size()+1+(int32u)Album.size()+1+(int32u)Unknown.size()+1+(int32u)Genre.size()+1+(int32u)Comment.size(); Size-=(int32u)Comment.size(); if (Size==0) return; Skip_L1( "Zero"); Size--; //NULL char Get_L4 (TrackPos, "Track_Position"); if(Element_Offset+8<Element_Size) Skip_XX(Element_Size-Element_Offset, "Unknown"); Element_Begin1("Footer"); Skip_L4( "Size"); Skip_C4( "Name"); Element_End0(); //Filling Fill(Stream_General, 0, General_Track, Title); Fill(Stream_General, 0, General_Performer, Artist); Fill(Stream_General, 0, General_Album, Album); Fill(Stream_General, 0, "Unknown", Unknown); Fill(Stream_General, 0, General_Genre, Genre); Fill(Stream_General, 0, General_Comment, Comment); Fill(Stream_General, 0, General_Track_Position, TrackPos); } void File_Riff::Open_Buffer_Init_All() { stream& StreamItem = Stream[Stream_ID]; for (size_t Pos = 0; Pos<StreamItem.Parsers.size(); Pos++) Open_Buffer_Init(StreamItem.Parsers[Pos]); } //*************************************************************************** // C++ //*************************************************************************** } //NameSpace #endif //MEDIAINFO_RIFF_YES
pavel-pimenov/sandbox
mediainfo/MediaInfoLib/Source/MediaInfo/Multiple/File_Riff_Elements.cpp
C++
mit
147,762
package cwr; import java.util.ArrayList; public class RobotBite { //0 = time [state] //1 = x [state] //2 = y [state] //3 = energy [state] //4 = bearing radians [relative position] //5 = distance [relative position] //6 = heading radians [travel] //7 = velocity [travel] String name; long cTime; double cx; double cy; cwruBase origin; double cEnergy; double cBearing_radians; double cDistance; double cHeading_radians; double cVelocity; ArrayList<Projection> projec; //forward projections for x public RobotBite(String name, long time, cwruBase self, double energy, double bearing_radians, double distance, double heading_radians, double velocity) { this.name = name; cTime = time; origin = self; cEnergy = energy; cBearing_radians = bearing_radians; double myBearing = self.getHeadingRadians(); //System.out.println("I'm going "+self.getHeadingRadians()); double adjust_bearing = (bearing_radians+myBearing)%(2*Math.PI); //System.out.println("input bearing "+(bearing_radians)); //System.out.println("adjust bearing "+(adjust_bearing)); //System.out.println("math bearing"+(-adjust_bearing+Math.PI/2)); cDistance = distance; cHeading_radians = heading_radians; //System.out.println("location heading "+heading_radians); cVelocity = velocity; double myX = self.getX(); double myY = self.getY(); double math_bearing = (-adjust_bearing+Math.PI/2)%(2*Math.PI); //double math_heading = (-heading_radians+Math.PI/2)%(2*Math.PI); /* * 0 * 90 * -90 180 0 90 * -90 * 180 */ double dX = distance*Math.cos(math_bearing); //System.out.println("location dx:" + dX); double dY = distance*Math.sin(math_bearing); //System.out.println("location dy:" + dY); cx = myX+dX; cy = myY+dY; } public void attachProjection(ArrayList<Projection> projList) { projec = projList; } }
buckbaskin/RoboCodeGit
old_src/cwr/RobotBite.java
Java
mit
1,934
export default function closest(n, arr) { let i let ndx let diff let best = Infinity let low = 0 let high = arr.length - 1 while (low <= high) { // eslint-disable-next-line no-bitwise i = low + ((high - low) >> 1) diff = arr[i] - n if (diff < 0) { low = i + 1 } else if (diff > 0) { high = i - 1 } diff = Math.abs(diff) if (diff < best) { best = diff ndx = i } if (arr[i] === n) break } return arr[ndx] }
octopitus/rn-sliding-up-panel
libs/closest.js
JavaScript
mit
493
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClearScript.Installer.Demo { public class Class1 { } }
eswann/ClearScript.Installer
src/ClearScript.Installer.Demo/Class1.cs
C#
mit
197
/** * 斐波那契数列 */ export default function fibonacci(n){ if(n <= 2){ return 1; } let n1 = 1, n2 = 1, sn = 0; for(let i = 0; i < n - 2; i ++){ sn = n1 + n2; n1 = n2; n2 = sn; } return sn; }
lomocc/react-boilerplate
src/utils/fibonacci.js
JavaScript
mit
230
import * as UTILS from '@utils'; const app = new WHS.App([ ...UTILS.appModules({ position: new THREE.Vector3(0, 40, 70) }) ]); const halfMat = { transparent: true, opacity: 0.5 }; const box = new WHS.Box({ geometry: { width: 30, height: 2, depth: 2 }, modules: [ new PHYSICS.BoxModule({ mass: 0 }) ], material: new THREE.MeshPhongMaterial({ color: UTILS.$colors.mesh, ...halfMat }), position: { y: 40 } }); const box2 = new WHS.Box({ geometry: { width: 30, height: 1, depth: 20 }, modules: [ new PHYSICS.BoxModule({ mass: 10, damping: 0.1 }) ], material: new THREE.MeshPhongMaterial({ color: UTILS.$colors.softbody, ...halfMat }), position: { y: 38, z: 12 } }); const pointer = new WHS.Sphere({ modules: [ new PHYSICS.SphereModule() ], material: new THREE.MeshPhongMaterial({ color: UTILS.$colors.mesh }) }); console.log(pointer); pointer.position.set(0, 60, -8); pointer.addTo(app); box.addTo(app); box2.addTo(app).then(() => { const constraint = new PHYSICS.DOFConstraint(box2, box, new THREE.Vector3(0, 38, 1) ); app.addConstraint(constraint); constraint.enableAngularMotor(10, 20); }); UTILS.addPlane(app, 250); UTILS.addBasicLights(app); app.start();
WhitestormJS/whs.js
examples/physics/Constraints/DofConstraint/script.js
JavaScript
mit
1,332
package unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.common.exceptions.CantRegisterDebitException; import com.bitdubai.fermat_api.layer.dmp_basic_wallet.bitcoin_wallet.interfaces.BitcoinWalletTransactionRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.Database; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord; import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTransaction; import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException; import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException; import com.bitdubai.fermat_pip_api.layer.pip_platform_service.error_manager.ErrorManager; import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletBasicWalletAvailableBalance; import com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.BitcoinWalletDatabaseConstants; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import java.util.List; import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockBitcoinWalletTransactionRecord; import unit.com.bitdubai.fermat_dmp_plugin.layer.basic_wallet.bitcoin_wallet.developer.bitdubai.version_1.structure.mocks.MockDatabaseTableRecord; import static com.googlecode.catchexception.CatchException.catchException; import static com.googlecode.catchexception.CatchException.caughtException; import static org.fest.assertions.api.Assertions.assertThat; import static org.fest.assertions.api.Assertions.fail; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; /** * Created by jorgegonzalez on 2015.07.14.. */ @RunWith(MockitoJUnitRunner.class) public class DebitTest { @Mock private ErrorManager mockErrorManager; @Mock private PluginDatabaseSystem mockPluginDatabaseSystem; @Mock private Database mockDatabase; @Mock private DatabaseTable mockWalletTable; @Mock private DatabaseTable mockBalanceTable; @Mock private DatabaseTransaction mockTransaction; private List<DatabaseTableRecord> mockRecords; private DatabaseTableRecord mockBalanceRecord; private DatabaseTableRecord mockWalletRecord; private BitcoinWalletTransactionRecord mockTransactionRecord; private BitcoinWalletBasicWalletAvailableBalance testBalance; @Before public void setUpMocks(){ mockTransactionRecord = new MockBitcoinWalletTransactionRecord(); mockBalanceRecord = new MockDatabaseTableRecord(); mockWalletRecord = new MockDatabaseTableRecord(); mockRecords = new ArrayList<>(); mockRecords.add(mockBalanceRecord); setUpMockitoRules(); } public void setUpMockitoRules(){ when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_TABLE_NAME)).thenReturn(mockWalletTable); when(mockDatabase.getTable(BitcoinWalletDatabaseConstants.BITCOIN_WALLET_BALANCE_TABLE_NAME)).thenReturn(mockBalanceTable); when(mockBalanceTable.getRecords()).thenReturn(mockRecords); when(mockWalletTable.getEmptyRecord()).thenReturn(mockWalletRecord); when(mockDatabase.newTransaction()).thenReturn(mockTransaction); } @Before public void setUpAvailableBalance(){ testBalance = new BitcoinWalletBasicWalletAvailableBalance(mockDatabase); } @Test public void Debit_SuccesfullyInvoked_ReturnsAvailableBalance() throws Exception{ catchException(testBalance).debit(mockTransactionRecord); assertThat(caughtException()).isNull(); } @Test public void Debit_OpenDatabaseCantOpenDatabase_ReturnsAvailableBalance() throws Exception{ doThrow(new CantOpenDatabaseException("MOCK", null, null, null)).when(mockDatabase).openDatabase(); catchException(testBalance).debit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterDebitException.class); } @Test public void Debit_OpenDatabaseDatabaseNotFound_Throws() throws Exception{ doThrow(new DatabaseNotFoundException("MOCK", null, null, null)).when(mockDatabase).openDatabase(); catchException(testBalance).debit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterDebitException.class); } @Test public void Debit_DaoCantCalculateBalanceException_ReturnsAvailableBalance() throws Exception{ doThrow(new CantLoadTableToMemoryException("MOCK", null, null, null)).when(mockWalletTable).loadToMemory(); catchException(testBalance).debit(mockTransactionRecord); assertThat(caughtException()) .isNotNull() .isInstanceOf(CantRegisterDebitException.class); } }
fvasquezjatar/fermat-unused
DMP/plugin/basic_wallet/fermat-dmp-plugin-basic-wallet-bitcoin-wallet-bitdubai/src/test/java/unit/com/bitdubai/fermat_dmp_plugin/layer/basic_wallet/bitcoin_wallet/developer/bitdubai/version_1/structure/BitcoinWalletBasicWalletAvailableBalance/DebitTest.java
Java
mit
5,573
// ****************************************************************** // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE CODE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH // THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE. // // ****************************************************************** using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Windows.Foundation; namespace Microsoft.Toolkit.Uwp.Services.OAuth { /// <summary> /// OAuth Uri extensions. /// </summary> internal static class OAuthUriExtensions { /// <summary> /// Get query parameters from Uri. /// </summary> /// <param name="uri">Uri to process.</param> /// <returns>Dictionary of query parameters.</returns> public static IDictionary<string, string> GetQueryParams(this Uri uri) { return new WwwFormUrlDecoder(uri.Query).ToDictionary(decoderEntry => decoderEntry.Name, decoderEntry => decoderEntry.Value); } /// <summary> /// Get absolute Uri. /// </summary> /// <param name="uri">Uri to process.</param> /// <returns>Uri without query string.</returns> public static string AbsoluteWithoutQuery(this Uri uri) { if (string.IsNullOrEmpty(uri.Query)) { return uri.AbsoluteUri; } return uri.AbsoluteUri.Replace(uri.Query, string.Empty); } /// <summary> /// Normalize the Uri into string. /// </summary> /// <param name="uri">Uri to process.</param> /// <returns>Normalized string.</returns> public static string Normalize(this Uri uri) { var result = new StringBuilder(string.Format(CultureInfo.InvariantCulture, "{0}://{1}", uri.Scheme, uri.Host)); if (!((uri.Scheme == "http" && uri.Port == 80) || (uri.Scheme == "https" && uri.Port == 443))) { result.Append(string.Concat(":", uri.Port)); } result.Append(uri.AbsolutePath); return result.ToString(); } } }
phmatray/UWPCommunityToolkit
Microsoft.Toolkit.Uwp.Services/OAuth/OAuthUriExtensions.cs
C#
mit
2,612
/* gopm (Go Package Manager) Copyright (c) 2012 cailei (dancercl@gmail.com) The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package main import ( "fmt" "github.com/cailei/gopm_index/gopm/index" "github.com/hailiang/gosocks" "io" "io/ioutil" "log" "net/http" "net/url" "os" ) type Agent struct { client *http.Client } func newAgent() *Agent { client := http.DefaultClient // check if using a proxy proxy_addr := os.Getenv("GOPM_PROXY") if proxy_addr != "" { fmt.Printf("NOTE: Using socks5 proxy: %v\n", proxy_addr) proxy := socks.DialSocksProxy(socks.SOCKS5, proxy_addr) transport := &http.Transport{Dial: proxy} client = &http.Client{Transport: transport} } return &Agent{client} } func (agent *Agent) getFullIndexReader() io.Reader { request := remote_db_host + "/all" return agent._get_body_reader(request) } func (agent *Agent) uploadPackage(meta index.PackageMeta) { request := fmt.Sprintf("%v/publish", remote_db_host) // marshal PackageMeta to json json, err := meta.ToJson() if err != nil { log.Fatalln(err) } // create a POST request response, err := http.PostForm(request, url.Values{"pkg": {string(json)}}) if err != nil { log.Fatalln(err) } body, err := ioutil.ReadAll(response.Body) defer response.Body.Close() if err != nil { log.Fatalln(err) } if len(body) > 0 { fmt.Println(string(body)) } // check response if response.StatusCode != 200 { log.Fatalln(response.Status) } } func (agent *Agent) _get_body_reader(request string) io.ReadCloser { // GET the index content response, err := agent.client.Get(request) if err != nil { log.Fatalln(err) } // check response if response.StatusCode != 200 { body, err := ioutil.ReadAll(response.Body) if err != nil { log.Fatalln(err) } if len(body) > 0 { fmt.Println(string(body)) } log.Fatalln(response.Status) } return response.Body }
cailei/gopm
gopm/agent.go
GO
mit
3,137
package org.usfirst.frc.team6135.robot.subsystems; import java.awt.geom.Arc2D.Double; import org.usfirst.frc.team6135.robot.RobotMap; import org.usfirst.frc.team6135.robot.commands.teleopDrive; import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.wpilibj.ADXRS450_Gyro; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SerialPort; import edu.wpi.first.wpilibj.VictorSP; import edu.wpi.first.wpilibj.command.Subsystem; public class Drive extends Subsystem { //Constants private static final boolean rReverse = true; private static final boolean lReverse = false; private static final double kA=0.03; //Objects private VictorSP leftDrive = null; private VictorSP rightDrive = null; public ADXRS450_Gyro gyro=null; public AHRS ahrs=null; public RobotDrive robotDrive=null; //Constructors public Drive() { gyro=RobotMap.gyro; ahrs=new AHRS(SerialPort.Port.kUSB1); robotDrive=new RobotDrive(RobotMap.leftDriveVictor,RobotMap.rightDriveVictor); leftDrive = RobotMap.leftDriveVictor; rightDrive = RobotMap.rightDriveVictor; leftDrive.set(0); rightDrive.set(0); leftDrive.setInverted(lReverse); rightDrive.setInverted(rReverse); ahrs.reset(); } //Direct object access methods public void setMotors(double l, double r) {//sets motor speeds accounting for directions of motors leftDrive.set(l); rightDrive.set(r); } public void setLeft(double d) { leftDrive.set(d); } public void setRight(double d) { rightDrive.set(d); } //Teleop Driving methods private static final double accBoundX = 0.7; //The speed after which the drive starts to accelerate over time private static final int accLoopX = 15; //The number of loops for the bot to accelerate to max speed private int accLoopCountX = 0; public double accCalcX(double input) {//applies a delay for motors to reach full speed for larger joystick inputs if(input > accBoundX && accLoopCountX < accLoopX) {//positive inputs return accBoundX + (input - accBoundX) * (accLoopCountX++ / (double) accLoopX); } else if(input < -accBoundX && accLoopCountX < accLoopX) {//negative inputs return -accBoundX + (input + accBoundX) * (accLoopCountX++ / (double) accLoopX); } else if(Math.abs(input) <= accBoundX) { accLoopCountX = 0; } return input; } private static final double accBoundY = 0.7; //The speed after which the drive starts to accelerate over time private static final int accLoopY = 15; //The number of loops for the bot to accelerate to max speed private int accLoopCountY = 0; public double accCalcY(double input) {//applies a delay for motors to reach full speed for larger joystick inputs if(input > accBoundY && accLoopCountY < accLoopY) {//positive inputs return accBoundY + (input - accBoundY) * (accLoopCountY++ / (double) accLoopY); } else if(input < -accBoundY && accLoopCountY < accLoopY) {//negative inputs return -accBoundY + (input + accBoundY) * (accLoopCountY++ / (double) accLoopY); } else if(Math.abs(input) <= accBoundY) { accLoopCountY = 0; } return input; } private static final double accBoundZ = 0.7; //The speed after which the drive starts to accelerate over time private static final int accLoopZ = 15; //The number of loops for the bot to accelerate to max speed private int accLoopCountZ = 0; public double accCalcZ(double input) {//applies a delay for motors to reach full speed for larger joystick inputs if(input > accBoundZ && accLoopCountZ < accLoopZ) {//positive inputs return accBoundZ + (input - accBoundZ) * (accLoopCountZ++ / (double) accLoopZ); } else if(input < -accBoundZ && accLoopCountZ < accLoopZ) {//negative inputs return -accBoundZ + (input + accBoundZ) * (accLoopCountZ++ / (double) accLoopZ); } else if(Math.abs(input) <= accBoundZ) { accLoopCountZ = 0; } return input; } public double sensitivityCalc(double input) {//Squares magnitude of input to reduce magnitude of smaller joystick inputs if (input >= 0.0) { return (input * input); } else { return -(input * input); } } public void reverse() { leftDrive.setInverted(!leftDrive.getInverted()); rightDrive.setInverted(!rightDrive.getInverted()); VictorSP temp1 = leftDrive; VictorSP temp2 = rightDrive; rightDrive = temp1; leftDrive = temp2; } public double getGyroAngle() { return gyro.getAngle(); } public double getNAVXAngle() { return ahrs.getAngle(); } public void driveStraight() { robotDrive.drive(0.6, -gyro.getAngle()*kA); } @Override protected void initDefaultCommand() { setDefaultCommand(new teleopDrive()); } }
Arctos6135/frc-2017
src/org/usfirst/frc/team6135/robot/subsystems/Drive.java
Java
mit
4,676
module Shopping class LineItem < ActiveRecord::Base extend Shopping::AttributeAccessibleHelper belongs_to :cart belongs_to :source, polymorphic: true validate :unique_source_and_cart, on: :create validate :unpurchased_cart validates :quantity, allow_nil: true, numericality: {only_integer: true, greater_than: -1} validates :cart_id, presence: true validates :source_id, presence: true validates :source_type, presence: true attr_accessible :cart_id, :source, :source_id, :source_type, :quantity, :list_price, :sale_price, :options before_create :set_prices, :set_name def unique_source_and_cart other = Shopping::LineItem.where(source_id: self.source_id, source_type: self.source_type, cart_id: self.cart_id) if other.count > 0 self.errors.add(:source, "A line item with identical source and cart exists, update quantity instead (id=#{other.first.id})") end end def unpurchased_cart if cart && cart.purchased? changes.keys.each do |k| self.errors.add(k, "Cannot change `#{k}', cart is purchased") end end end def set_name self.source_name ||= source.try(:name) end def set_prices self.list_price ||= source.try(:price) self.sale_price ||= source.try(:price) end end end
barkbox/shopping
app/models/shopping/line_item.rb
Ruby
mit
1,352
using System; namespace KeyWatcher.Reactive { internal sealed class ObservingKeyWatcher : IObserver<char> { private readonly string id; internal ObservingKeyWatcher(string id) => this.id = id; public void OnCompleted() => Console.Out.WriteLine($"{this.id} - {nameof(this.OnCompleted)}"); public void OnError(Exception error) => Console.Out.WriteLine($"{this.id} - {nameof(this.OnError)} - {error.Message}"); public void OnNext(char value) => Console.Out.WriteLine($"{this.id} - {nameof(this.OnNext)} - {value}"); } }
rockfordlhotka/DistributedComputingDemo
src/KeyWatcher - Core/KeyWatcher.Reactive/ObservingKeyWatcher.cs
C#
mit
552
from baroque.entities.event import Event class EventCounter: """A counter of events.""" def __init__(self): self.events_count = 0 self.events_count_by_type = dict() def increment_counting(self, event): """Counts an event Args: event (:obj:`baroque.entities.event.Event`): the event to be counted """ assert isinstance(event, Event) self.events_count += 1 t = type(event.type) if t in self.events_count_by_type: self.events_count_by_type[t] += 1 else: self.events_count_by_type[t] = 1 def count_all(self): """Tells how many events have been counted globally Returns: int """ return self.events_count def count(self, eventtype): """Tells how many events have been counted of the specified type Args: eventtype (:obj:`baroque.entities.eventtype.EventType`): the type of events to be counted Returns: int """ return self.events_count_by_type.get(type(eventtype), 0)
baroquehq/baroque
baroque/datastructures/counters.py
Python
mit
1,120
import React from 'react' import { PlanItineraryContainer } from './index' const PlanMapRoute = () => { return ( <div> <PlanItineraryContainer /> </div> ) } export default PlanMapRoute
in-depth/indepth-demo
src/shared/views/plans/planItinerary/PlanItineraryRoute.js
JavaScript
mit
206
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Collections.Immutable; using OpenIddict.Abstractions; using OpenIddict.Server; using static OpenIddict.Server.OpenIddictServerEvents; namespace Squidex.Areas.IdentityServer.Config { public sealed class AlwaysAddTokenHandler : IOpenIddictServerHandler<ProcessSignInContext> { public ValueTask HandleAsync(ProcessSignInContext context) { if (context == null) { return default; } if (!string.IsNullOrWhiteSpace(context.Response.AccessToken)) { var scopes = context.AccessTokenPrincipal?.GetScopes() ?? ImmutableArray<string>.Empty; context.Response.Scope = string.Join(" ", scopes); } return default; } } }
Squidex/squidex
backend/src/Squidex/Areas/IdentityServer/Config/AlwaysAddTokenHandler.cs
C#
mit
1,160
using System.Diagnostics.CodeAnalysis; namespace Npoi.Mapper { /// <summary> /// Information for one row that read from file. /// </summary> /// <typeparam name="TTarget">The target mapping type for a row.</typeparam> [SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Global")] public class RowInfo<TTarget> : IRowInfo { #region Properties /// <summary> /// Row number. /// </summary> public int RowNumber { get; set; } /// <summary> /// Constructed value object from the row. /// </summary> public TTarget Value { get; set; } /// <summary> /// Column index of the first error. /// </summary> public int ErrorColumnIndex { get; set; } /// <summary> /// Error message for the first error. /// </summary> public string ErrorMessage { get; set; } #endregion #region Constructors /// <summary> /// Initialize a new RowData object. /// </summary> /// <param name="rowNumber">The row number</param> /// <param name="value">Constructed value object from the row</param> /// <param name="errorColumnIndex">Column index of the first error cell</param> /// <param name="errorMessage">The error message</param> public RowInfo(int rowNumber, TTarget value, int errorColumnIndex, string errorMessage) { RowNumber = rowNumber; Value = value; ErrorColumnIndex = errorColumnIndex; ErrorMessage = errorMessage; } #endregion } }
donnytian/Npoi.Mapper
Npoi.Mapper/src/Npoi.Mapper/RowInfo.cs
C#
mit
1,652
const path = require('path'); module.exports = { lazyLoad: true, pick: { posts(markdownData) { return { meta: markdownData.meta, description: markdownData.description, }; }, }, plugins: [path.join(__dirname, '..', 'node_modules', 'bisheng-plugin-description')], routes: [{ path: '/', component: './template/Archive', }, { path: '/posts/:post', dataPath: '/:post', component: './template/Post', }, { path: '/tags', component: './template/TagCloud', }], };
benjycui/bisheng
packages/bisheng-theme-one/src/index.js
JavaScript
mit
536
<?php namespace WindowsAzure\DistributionBundle\Deployment; /** * @author Stéphane Escandell <stephane.escandell@gmail.com> */ interface CustomIteratorInterface { /** * @param array $dirs * @param array $subdirs */ public function getIterator(array $dirs, array $subdirs); }
beberlei/AzureDistributionBundle
Deployment/CustomIteratorInterface.php
PHP
mit
302
import numpy as np class Surface(object): def __init__(self, image, edge_points3d, edge_points2d): """ Constructor for a surface defined by a texture image and 4 boundary points. Choose the first point as the origin of the surface's coordinate system. :param image: image array :param edge_points3d: array of 3d coordinates of 4 corner points in clockwise direction :param edge_points2d: array of 2d coordinates of 4 corner points in clockwise direction """ assert len(edge_points3d) == 4 and len(edge_points2d) == 4 self.image = image self.edge_points3d = edge_points3d self.edge_points2d = np.float32(edge_points2d) # This is required for using cv2's getPerspectiveTransform self.normal = self._get_normal_vector() def top_left_corner3d(self): return self.edge_points3d[0] def top_right_corner3d(self): return self.edge_points3d[1] def bottom_right_corner3d(self): return self.edge_points3d[2] def bottom_left_corner3d(self): return self.edge_points3d[3] def distance_to_point(self, point): point_to_surface = point - self.top_left_corner3d() distance_to_surface = self.normal.dot(point_to_surface) return distance_to_surface def _get_normal_vector(self): """ :return: the normal vector of the surface. It determined the front side of the surface and it's not necessarily a unit vector """ p0 = self.edge_points3d[0] p1 = self.edge_points3d[1] p3 = self.edge_points3d[3] v1 = p3 - p0 v2 = p1 - p0 normal = np.cross(v1, v2) norm = np.linalg.norm(normal) return normal / norm class Polyhedron(object): def __init__(self, surfaces): self.surfaces = surfaces class Space(object): def __init__(self, models=None): self.models = models or [] def add_model(self, model): assert isinstance(model, Polyhedron) self.models.append(model) class Line2D(object): def __init__(self, point1, point2): """ Using the line equation a*x + b*y + c = 0 with b >= 0 :param point1: starting point :param point2: ending point :return: a Line object """ assert len(point1) == 2 and len(point2) == 2 self.a = point2[1] - point1[1] self.b = point1[0] - point2[0] self.c = point1[1] * point2[0] - point1[0] * point2[1] if self.b < 0: self.a = -self.a self.b = -self.b self.c = -self.c def is_point_on_left(self, point): return self.a * point[0] + self.b * point[1] + self.c > 0 def is_point_on_right(self, point): return self.a * point[0] + self.b * point[1] + self.c < 0 def is_point_on_line(self, point): return self.a * point[0] + self.b * point[1] + self.c == 0 def get_y_from_x(self, x): if self.b == 0: return 0.0 return 1.0 * (-self.c - self.a * x) / self.b def get_x_from_y(self, y): if self.a == 0: return 0.0 return 1.0 * (-self.c - self.b * y) / self.a
yangshun/cs4243-project
app/surface.py
Python
mit
3,220
import { fullSrc } from '../element/element'; import { pixels } from '../math/unit'; import { Clone } from './clone'; import { Container } from './container'; import { Image } from './image'; import { Overlay } from './overlay'; import { Wrapper } from './wrapper'; export class ZoomDOM { static useExisting(element: HTMLImageElement, parent: HTMLElement, grandparent: HTMLElement): ZoomDOM { let overlay = Overlay.create(); let wrapper = new Wrapper(grandparent); let container = new Container(parent); let image = new Image(element); let src = fullSrc(element); if (src === element.src) { return new ZoomDOM(overlay, wrapper, container, image); } else { return new ZoomDOM(overlay, wrapper, container, image, new Clone(container.clone())); } } static create(element: HTMLImageElement): ZoomDOM { let overlay = Overlay.create(); let wrapper = Wrapper.create(); let container = Container.create(); let image = new Image(element); let src = fullSrc(element); if (src === element.src) { return new ZoomDOM(overlay, wrapper, container, image); } else { return new ZoomDOM(overlay, wrapper, container, image, Clone.create(src)); } } readonly overlay: Overlay; readonly wrapper: Wrapper; readonly container: Container; readonly image: Image; readonly clone?: Clone; constructor(overlay: Overlay, wrapper: Wrapper, container: Container, image: Image, clone?: Clone) { this.overlay = overlay; this.wrapper = wrapper; this.container = container; this.image = image; this.clone = clone; } appendContainerToWrapper(): void { this.wrapper.element.appendChild(this.container.element); } replaceImageWithWrapper(): void { let parent = this.image.element.parentElement as HTMLElement; parent.replaceChild(this.wrapper.element, this.image.element); } appendImageToContainer(): void { this.container.element.appendChild(this.image.element); } appendCloneToContainer(): void { if (this.clone !== undefined) { this.container.element.appendChild(this.clone.element); } } replaceImageWithClone(): void { if (this.clone !== undefined) { this.clone.show(); this.image.hide(); } } replaceCloneWithImage(): void { if (this.clone !== undefined) { this.image.show(); this.clone.hide(); } } fixWrapperHeight(): void { this.wrapper.element.style.height = pixels(this.image.element.height); } collapsed(): void { this.overlay.removeFrom(document.body); this.image.deactivate(); this.wrapper.finishCollapsing(); } /** * Called at the end of an expansion to check if the clone loaded before our expansion finished. If it did, and is * still not visible, we can now show it to the client. */ showCloneIfLoaded(): void { if (this.clone !== undefined && this.clone.isLoaded() && this.clone.isHidden()) { this.replaceImageWithClone(); } } }
MikeBull94/zoom.ts
src/dom/zoom-dom.ts
TypeScript
mit
3,272
"use strict"; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var qs = require("querystring"); var partial = require("lodash.partial"); var endpoints = require("./stats-endpoints"); var dicts = require("./dicts"); var translateKeys = require("./util/translate-keys"); var transport = require("./get-json"); var translate = partial(translateKeys, dicts.jsToNbaMap); var stats = Object.create({ setTransport: function setTransport(_transport) { transport = _transport; }, getTransport: function getTransport() { return transport; } }); Object.keys(endpoints).forEach(function (key) { stats[key] = makeStatsMethod(endpoints[key]); }); function makeStatsMethod(endpoint) { return function statsMethod(query, callback) { if (typeof query === "function") { callback = query; query = {}; } if (typeof callback !== "function") { throw new TypeError("Must pass a callback function."); } var params = _extends({}, endpoint.defaults, translate(query)); transport(endpoint.url, params, function (err, response) { if (err) return callback(err); if (response == null) return callback(); // response is something like "GameID is required" if (typeof response === "string") return callback(new Error(response)); if (endpoint.transform) return callback(null, endpoint.transform(response)); callback(null, response); }); }; } module.exports = stats;
weixiyen/nba
lib/stats.js
JavaScript
mit
1,662
<?php /* TwigBundle:Exception:exception.json.twig */ class __TwigTemplate_8d9b12e119daada0de361618d51aaa01 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 if (isset($context["exception"])) { $_exception_ = $context["exception"]; } else { $_exception_ = null; } echo twig_jsonencode_filter($this->getAttribute($_exception_, "toarray")); echo " "; } public function getTemplateName() { return "TwigBundle:Exception:exception.json.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 47 => 8, 30 => 4, 27 => 3, 22 => 4, 117 => 22, 112 => 21, 109 => 20, 104 => 19, 96 => 18, 84 => 14, 80 => 12, 68 => 9, 44 => 7, 26 => 4, 23 => 3, 20 => 2, 17 => 1, 92 => 39, 86 => 6, 79 => 40, 57 => 22, 46 => 7, 37 => 8, 33 => 7, 29 => 6, 24 => 4, 19 => 1, 144 => 54, 138 => 50, 130 => 46, 124 => 24, 121 => 41, 115 => 40, 111 => 38, 108 => 37, 99 => 32, 94 => 29, 91 => 17, 88 => 16, 85 => 26, 77 => 39, 74 => 20, 71 => 19, 65 => 16, 62 => 15, 58 => 8, 54 => 11, 51 => 10, 42 => 9, 38 => 8, 35 => 5, 31 => 4, 28 => 3,); } }
waltertschwe/kids-reading-network
app/cache/prod/twig/8d/9b/12e119daada0de361618d51aaa01.php
PHP
mit
1,455
<div id="menu-logo-wrapper" class="animated slideInDown"> <div class="main-menu"> <div class="pull-left"> <div class="toggle-menu-container"> <div class="toggle-menu"> <a href="javascript:void(0)"> <span class="nav-bar"></span> <span class="nav-bar"></span> <span class="nav-bar"></span> </a> </div> </div> <div class="main-nav-wrapper"> <ul class="main-nav"> <li><a href="<?php echo View::url('/'); ?>#about">About</a></li> <li><a href="<?php echo View::url('/'); ?>#flavours">Flavours</a></li> <li><a href="<?php echo View::url('/'); ?>#news">News</a></li> <li><a href="<?php echo View::url('/'); ?>#locate">Locate</a></li> <li><a href="<?php echo View::url('/'); ?>#wholesale">Wholesale</a></li> </ul> </div> </div> <a href="<?php echo View::url('/'); ?>" class="logo pull-right"><img src="<?= $view->getThemePath() ?>/images/logos/main-logo.png" alt=""></a> </div> </div>
zawzawzaw/scoop
application/themes/scooptherapy/elements/menu.php
PHP
mit
988
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.vmwarecloudsimple.models; import com.azure.resourcemanager.vmwarecloudsimple.fluent.models.CustomizationPolicyInner; /** An immutable client-side representation of CustomizationPolicy. */ public interface CustomizationPolicy { /** * Gets the id property: Customization policy azure id. * * @return the id value. */ String id(); /** * Gets the location property: Azure region. * * @return the location value. */ String location(); /** * Gets the name property: Customization policy name. * * @return the name value. */ String name(); /** * Gets the type property: The type property. * * @return the type value. */ String type(); /** * Gets the description property: Policy description. * * @return the description value. */ String description(); /** * Gets the privateCloudId property: The Private cloud id. * * @return the privateCloudId value. */ String privateCloudId(); /** * Gets the specification property: Detailed customization policy specification. * * @return the specification value. */ CustomizationSpecification specification(); /** * Gets the typePropertiesType property: The type of customization (Linux or Windows). * * @return the typePropertiesType value. */ CustomizationPolicyPropertiesType typePropertiesType(); /** * Gets the version property: Policy version. * * @return the version value. */ String version(); /** * Gets the inner com.azure.resourcemanager.vmwarecloudsimple.fluent.models.CustomizationPolicyInner object. * * @return the inner object. */ CustomizationPolicyInner innerModel(); }
Azure/azure-sdk-for-java
sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/src/main/java/com/azure/resourcemanager/vmwarecloudsimple/models/CustomizationPolicy.java
Java
mit
2,001
import React from 'react'; import ErrorIcon from './ErrorIcon'; export const symbols = { 'ErrorIcon -> with filled': <ErrorIcon filled={true} />, 'ErrorIcon -> without filled': <ErrorIcon filled={false} /> };
seekinternational/seek-asia-style-guide
react/ErrorIcon/ErrorIcon.iconSketch.js
JavaScript
mit
214
<!DOCTYPE HTML> <?php include '../inc/draft_config.php'; ?><!-- Use relative path to find config file --> <html lang=""> <head> <base href="<?php echo BASE_URL; ?>"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>Project Draft — 404</title> <meta name="robots" content="noindex, nofollow"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <?php include INC_PATH . 'pages_resources.php'; ?> <link rel="icon" sizes="16x16" href="assets/favicon-16.png"> <link rel="icon" sizes="32x32" href="assets/favicon-32.png"> <link rel="icon" sizes="48x48" href="assets/favicon-48.png"> <link rel="icon" sizes="64x64" href="assets/favicon-64.png"> <link rel="icon" sizes="128x128" href="assets/favicon-128.png"> <link rel="icon" sizes="192x192" href="assets/favicon-192.png"> </head> <body class="error-404"> <?php $page = 'error-404'; include INC_PATH . 'pages_overhead.php'; ?> <!-- Example 404 content (markup based on Bootstrap 3 framework) --> <div class="container"> <div class="row"> <div class="col-md-12"> <h1>Error 404 <br>Page not found!</h1> <p>Oops! Seems like the page you are looking for no longer exists. <br>You may go <a href='javascript:history.back(1)'>back</a> or <a href='<?php echo BASE_URL; ?>'>start over</a>.</p> <hr> <p class="small text-muted">Rename and edit <code>htaccess</code> file to activate custom error pages.</p> </div> </div> </div> <!-- END of example content --> <?php include INC_PATH . 'pages_scripts.php'; ?> </body> </html>
Kiriniy/Project_Draft
dist/assets/errors/404.php
PHP
mit
1,764
package commands import ( "compress/gzip" "errors" "fmt" "io" "os" "path/filepath" "strings" core "github.com/ipfs/go-ipfs/core" cmdenv "github.com/ipfs/go-ipfs/core/commands/cmdenv" e "github.com/ipfs/go-ipfs/core/commands/e" tar "gx/ipfs/QmQine7gvHncNevKtG9QXxf3nXcwSj6aDDmMm52mHofEEp/tar-utils" uarchive "gx/ipfs/QmSMJ4rZbCJaih3y82Ebq7BZqK6vU2FHsKcWKQiE1DPTpS/go-unixfs/archive" "gx/ipfs/QmWGm4AbZEbnmdgVTza52MSNpEmBdFVqzmAysRbjrRyGbH/go-ipfs-cmds" path "gx/ipfs/QmWqh9oob7ZHQRwU5CdTqpnC8ip8BEkFNrwXRxeNo5Y7vA/go-path" "gx/ipfs/QmYWB8oH6o7qftxoyqTTZhzLrhKCVT7NYahECQTwTtqbgj/pb" dag "gx/ipfs/Qmb2UEG2TAeVrEJSjqsZF7Y2he7wRDkrdt6c3bECxwZf4k/go-merkledag" "gx/ipfs/Qmde5VP1qUkyQXKCfmEUA7bP64V2HAptbJ7phuPp7jXWwg/go-ipfs-cmdkit" ) var ErrInvalidCompressionLevel = errors.New("compression level must be between 1 and 9") const ( outputOptionName = "output" archiveOptionName = "archive" compressOptionName = "compress" compressionLevelOptionName = "compression-level" ) var GetCmd = &cmds.Command{ Helptext: cmdkit.HelpText{ Tagline: "Download IPFS objects.", ShortDescription: ` Stores to disk the data contained an IPFS or IPNS object(s) at the given path. By default, the output will be stored at './<ipfs-path>', but an alternate path can be specified with '--output=<path>' or '-o=<path>'. To output a TAR archive instead of unpacked files, use '--archive' or '-a'. To compress the output with GZIP compression, use '--compress' or '-C'. You may also specify the level of compression by specifying '-l=<1-9>'. `, }, Arguments: []cmdkit.Argument{ cmdkit.StringArg("ipfs-path", true, false, "The path to the IPFS object(s) to be outputted.").EnableStdin(), }, Options: []cmdkit.Option{ cmdkit.StringOption(outputOptionName, "o", "The path where the output should be stored."), cmdkit.BoolOption(archiveOptionName, "a", "Output a TAR archive."), cmdkit.BoolOption(compressOptionName, "C", "Compress the output with GZIP compression."), cmdkit.IntOption(compressionLevelOptionName, "l", "The level of compression (1-9)."), }, PreRun: func(req *cmds.Request, env cmds.Environment) error { _, err := getCompressOptions(req) return err }, Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error { cmplvl, err := getCompressOptions(req) if err != nil { return err } node, err := cmdenv.GetNode(env) if err != nil { return err } p := path.Path(req.Arguments[0]) ctx := req.Context dn, err := core.Resolve(ctx, node.Namesys, node.Resolver, p) if err != nil { return err } switch dn := dn.(type) { case *dag.ProtoNode: size, err := dn.Size() if err != nil { return err } res.SetLength(size) case *dag.RawNode: res.SetLength(uint64(len(dn.RawData()))) default: return err } archive, _ := req.Options[archiveOptionName].(bool) reader, err := uarchive.DagArchive(ctx, dn, p.String(), node.DAG, archive, cmplvl) if err != nil { return err } return res.Emit(reader) }, PostRun: cmds.PostRunMap{ cmds.CLI: func(res cmds.Response, re cmds.ResponseEmitter) error { req := res.Request() v, err := res.Next() if err != nil { return err } outReader, ok := v.(io.Reader) if !ok { return e.New(e.TypeErr(outReader, v)) } outPath := getOutPath(req) cmplvl, err := getCompressOptions(req) if err != nil { return err } archive, _ := req.Options[archiveOptionName].(bool) gw := getWriter{ Out: os.Stdout, Err: os.Stderr, Archive: archive, Compression: cmplvl, Size: int64(res.Length()), } return gw.Write(outReader, outPath) }, }, } type clearlineReader struct { io.Reader out io.Writer } func (r *clearlineReader) Read(p []byte) (n int, err error) { n, err = r.Reader.Read(p) if err == io.EOF { // callback fmt.Fprintf(r.out, "\033[2K\r") // clear progress bar line on EOF } return } func progressBarForReader(out io.Writer, r io.Reader, l int64) (*pb.ProgressBar, io.Reader) { bar := makeProgressBar(out, l) barR := bar.NewProxyReader(r) return bar, &clearlineReader{barR, out} } func makeProgressBar(out io.Writer, l int64) *pb.ProgressBar { // setup bar reader // TODO: get total length of files bar := pb.New64(l).SetUnits(pb.U_BYTES) bar.Output = out // the progress bar lib doesn't give us a way to get the width of the output, // so as a hack we just use a callback to measure the output, then git rid of it bar.Callback = func(line string) { terminalWidth := len(line) bar.Callback = nil log.Infof("terminal width: %v\n", terminalWidth) } return bar } func getOutPath(req *cmds.Request) string { outPath, _ := req.Options[outputOptionName].(string) if outPath == "" { trimmed := strings.TrimRight(req.Arguments[0], "/") _, outPath = filepath.Split(trimmed) outPath = filepath.Clean(outPath) } return outPath } type getWriter struct { Out io.Writer // for output to user Err io.Writer // for progress bar output Archive bool Compression int Size int64 } func (gw *getWriter) Write(r io.Reader, fpath string) error { if gw.Archive || gw.Compression != gzip.NoCompression { return gw.writeArchive(r, fpath) } return gw.writeExtracted(r, fpath) } func (gw *getWriter) writeArchive(r io.Reader, fpath string) error { // adjust file name if tar if gw.Archive { if !strings.HasSuffix(fpath, ".tar") && !strings.HasSuffix(fpath, ".tar.gz") { fpath += ".tar" } } // adjust file name if gz if gw.Compression != gzip.NoCompression { if !strings.HasSuffix(fpath, ".gz") { fpath += ".gz" } } // create file file, err := os.Create(fpath) if err != nil { return err } defer file.Close() fmt.Fprintf(gw.Out, "Saving archive to %s\n", fpath) bar, barR := progressBarForReader(gw.Err, r, gw.Size) bar.Start() defer bar.Finish() _, err = io.Copy(file, barR) return err } func (gw *getWriter) writeExtracted(r io.Reader, fpath string) error { fmt.Fprintf(gw.Out, "Saving file(s) to %s\n", fpath) bar := makeProgressBar(gw.Err, gw.Size) bar.Start() defer bar.Finish() defer bar.Set64(gw.Size) extractor := &tar.Extractor{Path: fpath, Progress: bar.Add64} return extractor.Extract(r) } func getCompressOptions(req *cmds.Request) (int, error) { cmprs, _ := req.Options[compressOptionName].(bool) cmplvl, cmplvlFound := req.Options[compressionLevelOptionName].(int) switch { case !cmprs: return gzip.NoCompression, nil case cmprs && !cmplvlFound: return gzip.DefaultCompression, nil case cmprs && (cmplvl < 1 || cmplvl > 9): return gzip.NoCompression, ErrInvalidCompressionLevel } return cmplvl, nil }
chriscool/go-ipfs
core/commands/get.go
GO
mit
6,703
package org.reasm.m68k.assembly.internal; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import org.reasm.Value; import org.reasm.ValueToBooleanVisitor; /** * The <code>WHILE</code> directive. * * @author Francis Gagné */ @Immutable class WhileDirective extends Mnemonic { @Nonnull static final WhileDirective WHILE = new WhileDirective(); private WhileDirective() { } @Override void assemble(M68KAssemblyContext context) { context.sizeNotAllowed(); final Object blockState = context.getParentBlock(); if (!(blockState instanceof WhileBlockState)) { throw new AssertionError(); } final WhileBlockState whileBlockState = (WhileBlockState) blockState; // The WHILE directive is assembled on every iteration. // Parse the condition operand on the first iteration only. if (!whileBlockState.parsedCondition) { if (context.requireNumberOfOperands(1)) { whileBlockState.conditionExpression = parseExpressionOperand(context, 0); } whileBlockState.parsedCondition = true; } final Value condition; if (whileBlockState.conditionExpression != null) { condition = whileBlockState.conditionExpression.evaluate(context.getEvaluationContext()); } else { condition = null; } final Boolean result = Value.accept(condition, ValueToBooleanVisitor.INSTANCE); if (!(result != null && result.booleanValue())) { // Skip the block body and stop the iteration. whileBlockState.iterator.next(); whileBlockState.hasNextIteration = false; } } }
reasm/reasm-m68k
src/main/java/org/reasm/m68k/assembly/internal/WhileDirective.java
Java
mit
1,747
/* * This file is part of FlexibleLogin * * The MIT License (MIT) * * Copyright (c) 2015-2018 contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.games647.flexiblelogin.listener.prevent; import com.flowpowered.math.vector.Vector3i; import com.github.games647.flexiblelogin.FlexibleLogin; import com.github.games647.flexiblelogin.PomData; import com.github.games647.flexiblelogin.config.Settings; import com.google.inject.Inject; import java.util.List; import java.util.Optional; import org.spongepowered.api.command.CommandManager; import org.spongepowered.api.command.CommandMapping; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.block.InteractBlockEvent; import org.spongepowered.api.event.command.SendCommandEvent; import org.spongepowered.api.event.entity.DamageEntityEvent; import org.spongepowered.api.event.entity.InteractEntityEvent; import org.spongepowered.api.event.entity.MoveEntityEvent; import org.spongepowered.api.event.filter.Getter; import org.spongepowered.api.event.filter.cause.First; import org.spongepowered.api.event.filter.cause.Root; import org.spongepowered.api.event.filter.type.Exclude; import org.spongepowered.api.event.item.inventory.ChangeInventoryEvent; import org.spongepowered.api.event.item.inventory.ClickInventoryEvent; import org.spongepowered.api.event.item.inventory.ClickInventoryEvent.NumberPress; import org.spongepowered.api.event.item.inventory.DropItemEvent; import org.spongepowered.api.event.item.inventory.InteractInventoryEvent; import org.spongepowered.api.event.item.inventory.InteractItemEvent; import org.spongepowered.api.event.item.inventory.UseItemStackEvent; import org.spongepowered.api.event.message.MessageChannelEvent; public class PreventListener extends AbstractPreventListener { private final CommandManager commandManager; @Inject PreventListener(FlexibleLogin plugin, Settings settings, CommandManager commandManager) { super(plugin, settings); this.commandManager = commandManager; } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerMove(MoveEntityEvent playerMoveEvent, @First Player player) { if (playerMoveEvent instanceof MoveEntityEvent.Teleport) { return; } Vector3i oldLocation = playerMoveEvent.getFromTransform().getPosition().toInt(); Vector3i newLocation = playerMoveEvent.getToTransform().getPosition().toInt(); if (oldLocation.getX() != newLocation.getX() || oldLocation.getZ() != newLocation.getZ()) { checkLoginStatus(playerMoveEvent, player); } } @Listener(order = Order.FIRST, beforeModifications = true) public void onChat(MessageChannelEvent.Chat chatEvent, @First Player player) { checkLoginStatus(chatEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onCommand(SendCommandEvent commandEvent, @First Player player) { String command = commandEvent.getCommand(); Optional<? extends CommandMapping> commandOpt = commandManager.get(command); if (commandOpt.isPresent()) { CommandMapping mapping = commandOpt.get(); command = mapping.getPrimaryAlias(); //do not blacklist our own commands if (commandManager.getOwner(mapping) .map(pc -> pc.getId().equals(PomData.ARTIFACT_ID)) .orElse(false)) { return; } } commandEvent.setResult(CommandResult.empty()); if (settings.getGeneral().isCommandOnlyProtection()) { List<String> protectedCommands = settings.getGeneral().getProtectedCommands(); if (protectedCommands.contains(command) && !plugin.getDatabase().isLoggedIn(player)) { player.sendMessage(settings.getText().getProtectedCommand()); commandEvent.setCancelled(true); } } else { checkLoginStatus(commandEvent, player); } } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerItemDrop(DropItemEvent dropItemEvent, @First Player player) { checkLoginStatus(dropItemEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerItemPickup(ChangeInventoryEvent.Pickup pickupItemEvent, @Root Player player) { checkLoginStatus(pickupItemEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onItemConsume(UseItemStackEvent.Start itemConsumeEvent, @First Player player) { checkLoginStatus(itemConsumeEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onItemInteract(InteractItemEvent interactItemEvent, @First Player player) { checkLoginStatus(interactItemEvent, player); } // Ignore number press events, because Sponge before this commit // https://github.com/SpongePowered/SpongeForge/commit/f0605fb0bd62ca2f958425378776608c41f16cca // has a duplicate bug. Using this exclude we can ignore it, but still cancel the movement of the item // it appears to be fixed using SpongeForge 4005 (fixed) and 4004 with this change @Exclude(NumberPress.class) @Listener(order = Order.FIRST, beforeModifications = true) public void onInventoryChange(ChangeInventoryEvent changeInventoryEvent, @First Player player) { checkLoginStatus(changeInventoryEvent, player); } @Exclude(NumberPress.class) @Listener(order = Order.FIRST, beforeModifications = true) public void onInventoryInteract(InteractInventoryEvent interactInventoryEvent, @First Player player) { checkLoginStatus(interactInventoryEvent, player); } @Exclude(NumberPress.class) @Listener(order = Order.FIRST, beforeModifications = true) public void onInventoryClick(ClickInventoryEvent clickInventoryEvent, @First Player player) { checkLoginStatus(clickInventoryEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onBlockInteract(InteractBlockEvent interactBlockEvent, @First Player player) { checkLoginStatus(interactBlockEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerInteractEntity(InteractEntityEvent interactEntityEvent, @First Player player) { checkLoginStatus(interactEntityEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onPlayerDamage(DamageEntityEvent damageEntityEvent, @First Player player) { //player is damage source checkLoginStatus(damageEntityEvent, player); } @Listener(order = Order.FIRST, beforeModifications = true) public void onDamagePlayer(DamageEntityEvent damageEntityEvent, @Getter("getTargetEntity") Player player) { //player is damage target checkLoginStatus(damageEntityEvent, player); } }
games647/FlexibleLogin
src/main/java/com/github/games647/flexiblelogin/listener/prevent/PreventListener.java
Java
mit
8,213
# coding: utf-8 """ ORCID Member No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: Latest Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class ContributorOrcid(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, uri=None, path=None, host=None): """ ContributorOrcid - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'uri': 'str', 'path': 'str', 'host': 'str' } self.attribute_map = { 'uri': 'uri', 'path': 'path', 'host': 'host' } self._uri = uri self._path = path self._host = host @property def uri(self): """ Gets the uri of this ContributorOrcid. :return: The uri of this ContributorOrcid. :rtype: str """ return self._uri @uri.setter def uri(self, uri): """ Sets the uri of this ContributorOrcid. :param uri: The uri of this ContributorOrcid. :type: str """ self._uri = uri @property def path(self): """ Gets the path of this ContributorOrcid. :return: The path of this ContributorOrcid. :rtype: str """ return self._path @path.setter def path(self, path): """ Sets the path of this ContributorOrcid. :param path: The path of this ContributorOrcid. :type: str """ self._path = path @property def host(self): """ Gets the host of this ContributorOrcid. :return: The host of this ContributorOrcid. :rtype: str """ return self._host @host.setter def host(self, host): """ Sets the host of this ContributorOrcid. :param host: The host of this ContributorOrcid. :type: str """ self._host = host def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, ContributorOrcid): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
orcid_api/models/contributor_orcid.py
Python
mit
3,922
package com.contexthub.storageapp; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.SearchView; import android.view.Menu; import android.view.MenuItem; import com.chaione.contexthub.sdk.model.VaultDocument; import com.contexthub.storageapp.fragments.AboutFragment; import com.contexthub.storageapp.fragments.EditVaultItemFragment; import com.contexthub.storageapp.fragments.VaultItemListFragment; import com.contexthub.storageapp.models.Person; public class MainActivity extends ActionBarActivity implements VaultItemListFragment.Listener, FragmentManager.OnBackStackChangedListener { private MenuItem menuSearch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(savedInstanceState == null) { getSupportFragmentManager().beginTransaction() .replace(android.R.id.content, new VaultItemListFragment()) .commit(); getSupportFragmentManager().addOnBackStackChangedListener(this); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); setupSearchView(menu.findItem(R.id.action_search)); return true; } private void setupSearchView(final MenuItem menuSearch) { this.menuSearch = menuSearch; SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuSearch); SearchView.SearchAutoComplete searchAutoComplete = (SearchView.SearchAutoComplete) searchView.findViewById(R.id.search_src_text); searchAutoComplete.setHint(R.string.search_hint); searchView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { menuSearch.collapseActionView(); getSupportFragmentManager().beginTransaction() .addToBackStack(null) .replace(android.R.id.content, VaultItemListFragment.newInstance(query)) .commit(); return true; } @Override public boolean onQueryTextChange(String query) { return false; } }); } @Override public boolean onPrepareOptionsMenu(Menu menu) { boolean isMainFragment = getSupportFragmentManager().getBackStackEntryCount() <= 0; menu.findItem(R.id.action_search).setVisible(isMainFragment); menu.findItem(R.id.action_add).setVisible(isMainFragment); menu.findItem(R.id.action_about).setVisible(isMainFragment); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { menuSearch.collapseActionView(); switch(item.getItemId()) { case R.id.action_add: launchEditVaultItemFragment(null); return true; case R.id.action_about: getSupportFragmentManager().beginTransaction() .addToBackStack(null) .replace(android.R.id.content, new AboutFragment()) .commit(); return true; default: return super.onOptionsItemSelected(item); } } private void launchEditVaultItemFragment(VaultDocument<Person> document) { EditVaultItemFragment fragment = document == null ? new EditVaultItemFragment() : EditVaultItemFragment.newInstance(document); getSupportFragmentManager().beginTransaction() .addToBackStack(null) .replace(android.R.id.content, fragment) .commit(); } @Override public void onItemClick(VaultDocument<Person> document) { menuSearch.collapseActionView(); launchEditVaultItemFragment(document); } @Override public void onBackStackChanged() { supportInvalidateOptionsMenu(); } }
contexthub/storage-android
StorageApp/app/src/main/java/com/contexthub/storageapp/MainActivity.java
Java
mit
4,259
<?php /** * @author Victor Demin <mail@vdemin.com> * @copyright (c) 2015, Victor Demin <mail@vdemin.com> */ namespace GlenDemon\ZabbixApi\Repository; use \GlenDemon\ZabbixApi\Entity\HostGroup; /** * HostGroup repository. */ class HostGroupRepository extends AbstractRepository { /** * Finds an object by its primary key / identifier. * * @param mixed $id The identifier. * * @return HostGroup The object. */ public function find($id) { return parent::find($id); } /** * Finds all objects in the repository. * * @return HostGroup[] The objects. */ public function findAll() { return parent::findAll(); } /** * @inherit */ protected function getRawData(array $params) { return $this->api->hostgroupGet($params); } /** * Finds a single object by a set of criteria. * * @param array $criteria The criteria. * * @return HostGroup|null The object. */ public function findOneBy(array $criteria) { return parent::findOneBy($criteria); } }
glendemon/zabbix-api
src/Repository/HostGroupRepository.php
PHP
mit
1,128
// 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.lslboost.org/LICENSE_1_0.txt) // // Preprocessed version of "lslboost/mpl/list/list10_c.hpp" header // -- DO NOT modify by hand! namespace lslboost { namespace mpl { template< typename T , T C0 > struct list1_c : l_item< long_<1> , integral_c< T,C0 > , l_end > { typedef list1_c type; typedef T value_type; }; template< typename T , T C0, T C1 > struct list2_c : l_item< long_<2> , integral_c< T,C0 > , list1_c< T,C1 > > { typedef list2_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2 > struct list3_c : l_item< long_<3> , integral_c< T,C0 > , list2_c< T,C1,C2 > > { typedef list3_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3 > struct list4_c : l_item< long_<4> , integral_c< T,C0 > , list3_c< T,C1,C2,C3 > > { typedef list4_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4 > struct list5_c : l_item< long_<5> , integral_c< T,C0 > , list4_c< T,C1,C2,C3,C4 > > { typedef list5_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5 > struct list6_c : l_item< long_<6> , integral_c< T,C0 > , list5_c< T,C1,C2,C3,C4,C5 > > { typedef list6_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6 > struct list7_c : l_item< long_<7> , integral_c< T,C0 > , list6_c< T,C1,C2,C3,C4,C5,C6 > > { typedef list7_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7 > struct list8_c : l_item< long_<8> , integral_c< T,C0 > , list7_c< T,C1,C2,C3,C4,C5,C6,C7 > > { typedef list8_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8 > struct list9_c : l_item< long_<9> , integral_c< T,C0 > , list8_c< T,C1,C2,C3,C4,C5,C6,C7,C8 > > { typedef list9_c type; typedef T value_type; }; template< typename T , T C0, T C1, T C2, T C3, T C4, T C5, T C6, T C7, T C8, T C9 > struct list10_c : l_item< long_<10> , integral_c< T,C0 > , list9_c< T,C1,C2,C3,C4,C5,C6,C7,C8,C9 > > { typedef list10_c type; typedef T value_type; }; }}
gazzlab/LSL-gazzlab-branch
liblsl/external/lslboost/mpl/list/aux_/preprocessed/plain/list10_c.hpp
C++
mit
2,868
module CardHelper def card_element_properties(node, options = {}) { class: dom_class(node, :card), itemscope: '', itemtype: 'http://schema.org/Thing', itemid: node.uuid, itemtype: node.class.schema_path }.merge(options) end def cardtec_header(node) content_tag(:span, node.uuid, itemprop: :uuid) << content_tag(:span, node.ident, itemprop: :ident) << content_tag(:span, node.class.name, itemprop: :class_name) << content_tag(:span, node.path, itemprop: :path) << content_tag(:span, node.created_at, itemprop: :created_at) << content_tag(:span, node.updated_at, itemprop: :updated_at) end end
dinge/dinghub
app/helpers/card_helper.rb
Ruby
mit
705
/* * The MIT License * * Copyright 2014 Jon Arney, Ensor Robotics. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.ensor.robots.roboclawdriver; /** * * @author jona */ class CommandReadMainBatteryVoltage extends CommandReadBatteryVoltage { protected CommandReadMainBatteryVoltage(RoboClaw aRoboClaw) { super(aRoboClaw); } @Override protected byte getCommandByte() { return (byte)24; } @Override protected void onResponse(double voltage) { mRoboClaw.setMainBatteryVoltage(voltage); } }
jarney/snackbot
src/main/java/org/ensor/robots/roboclawdriver/CommandReadMainBatteryVoltage.java
Java
mit
1,602
package org.kalnee.trivor.insights.web.rest; import com.codahale.metrics.annotation.Timed; import org.kalnee.trivor.insights.domain.insights.Insights; import org.kalnee.trivor.insights.service.InsightService; import org.kalnee.trivor.nlp.domain.ChunkFrequency; import org.kalnee.trivor.nlp.domain.PhrasalVerbUsage; import org.kalnee.trivor.nlp.domain.SentenceFrequency; import org.kalnee.trivor.nlp.domain.WordUsage; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; import java.util.Set; @RestController @RequestMapping(value = "/api/insights") public class InsightsResource { private final InsightService insightService; public InsightsResource(InsightService insightService) { this.insightService = insightService; } @GetMapping public ResponseEntity<Page<Insights>> findByInsightAndImdb(@RequestParam("imdbId") String imdbId, Pageable pageable) { return ResponseEntity.ok().body(insightService.findByImdbId(imdbId, pageable)); } @GetMapping("/summary") @Timed public ResponseEntity<Map<String, Object>> getInsightsSummary(@RequestParam("imdbId") String imdbId) { return ResponseEntity.ok().body(insightService.getInsightsSummary(imdbId)); } @GetMapping("/sentences/frequency") @Timed public ResponseEntity<List<SentenceFrequency>> findSentencesFrequency(@RequestParam("imdbId") String imdbId, @RequestParam(value = "limit", required = false) Integer limit) { return ResponseEntity.ok().body( insightService.findSentencesFrequencyByImdbId(imdbId, limit) ); } @GetMapping("/chunks/frequency") @Timed public ResponseEntity<List<ChunkFrequency>> findChunksFrequency(@RequestParam("imdbId") String imdbId, @RequestParam(value = "limit", required = false) Integer limit) { return ResponseEntity.ok().body( insightService.findChunksFrequencyByImdbId(imdbId, limit) ); } @GetMapping("/phrasal-verbs/usage") @Timed public ResponseEntity<List<PhrasalVerbUsage>> findPhrasalVerbsUsageByImdbId(@RequestParam("imdbId") String imdbId) { return ResponseEntity.ok().body(insightService.findPhrasalVerbsUsageByImdbId(imdbId)); } @GetMapping("/vocabulary/{vocabulary}/frequency") @Timed public ResponseEntity<Map<String, Integer>> findVocabularyFrequencyByImdbId( @PathVariable("vocabulary") String vocabulary, @RequestParam("imdbId") String imdbId, @RequestParam(value = "limit", required = false) Integer limit) { return ResponseEntity.ok().body(insightService.findVocabularyFrequencyByImdbId(vocabulary, imdbId, limit)); } @GetMapping("/vocabulary/{vocabulary}/usage") @Timed public ResponseEntity<List<WordUsage>> findVocabularyUsageByImdbAndSeasonAndEpisode( @PathVariable("vocabulary") String vocabulary, @RequestParam("imdbId") String imdbId, @RequestParam(value = "season", required = false) Integer season, @RequestParam(value = "episode", required = false) Integer episode) { return ResponseEntity.ok().body( insightService.findVocabularyUsageByImdbAndSeasonAndEpisode(vocabulary, imdbId, season, episode) ); } @GetMapping("/{insight}/genres/{genre}") @Timed public ResponseEntity<List<Insights>> findInsightsByGenre( @PathVariable("genre") String genre) { return ResponseEntity.ok().body(insightService.findInsightsByInsightAndGenre(genre)); } @GetMapping("/{insight}/keywords/{keyword}") @Timed public ResponseEntity<List<Insights>> findInsightsByKeyword( @PathVariable("keyword") String keyword) { return ResponseEntity.ok().body(insightService.findInsightsByInsightAndKeyword(keyword)); } }
kalnee/trivor
insights/src/main/java/org/kalnee/trivor/insights/web/rest/InsightsResource.java
Java
mit
4,162
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GlobalSuppressions.cs"> // Copyright (c) 2017. All rights reserved. Licensed under the MIT license. See LICENSE file in // the project root for full license information. // </copyright> // -------------------------------------------------------------------------------------------------------------------- // This file is used by Code Analysis to maintain SuppressMessage attributes that are applied to this // project. Project-level suppressions either have no target or are given a specific target and // scoped to a namespace, type, member, etc. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0002:Simplify Member Access", Justification = "This is an auto-generated file.", Scope = "member", Target = "~P:Spritely.Foundations.WebApi.Messages.ResourceManager")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Spritely.Foundations.WebApi.WriteLog.Invoke(System.String)", Scope = "member", Target = "Spritely.Foundations.WebApi.BasicWebApiLogPolicy.#.cctor()", Justification = "Colon is used as a separator for log file output - overkill to move this into resources.")]
spritely/Foundations.WebApi
Foundations.WebApi/GlobalSuppressions.cs
C#
mit
1,356
<?php # MetInfo Enterprise Content Management System # Copyright (C) MetInfo Co.,Ltd (http://www.metinfo.cn). All rights reserved. require_once '../login/login_check.php'; if($action=='modify'){ $shortcut=array(); $query="select * from $met_language where value='$name' and lang='$lang'"; $lang_shortcut=$db->get_one($query); $shortcut['name']=$lang_shortcut?'lang_'.$lang_shortcut['name']:urlencode($name); $shortcut['url']=$url; $shortcut['bigclass']=$bigclass; $shortcut['field']=$field; $shortcut['type']='2'; $shortcut['list_order']=$list_order; $shortcut['protect']='0'; $shortcut['hidden']='0'; foreach($shortcut_list as $key=>$val){ $shortcut_list[$key][name]=$shortcut_list[$key][lang]; } $shortcut_list[]=$shortcut; change_met_cookie('metinfo_admin_shortcut',$shortcut_list); save_met_cookie(); $query="update $met_admin_table set admin_shortcut='".json_encode($shortcut_list)."' where admin_id='$metinfo_admin_name'"; $db->query($query); echo '<script type="text/javascript">parent.window.location.reload();</script>'; die(); //metsave('../system/shortcut.php?anyid='.$anyid.'&lang='.$lang.'&cs='.$cs); }else{ $query="select * from $met_app where download=1"; $app=$db->get_all($query); $css_url="../templates/".$met_skin."/css"; $img_url="../templates/".$met_skin."/images"; include template('system/shortcut_editor'); footer(); } # This program is an open source system, commercial use, please consciously to purchase commercial license. # Copyright (C) MetInfo Co., Ltd. (http://www.metinfo.cn). All rights reserved. ?>
maicong/OpenAPI
MetInfo5.2/admin/system/shortcut_editor.php
PHP
mit
1,564
/* * The MIT License (MIT) * * Copyright (c) 2015 maldicion069 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ 'use strict'; exports.init = function(req, res){ //res.write("joder\n"); //res.write(req.csrfToken()); //res.end(); req.app.db.models.Experiment.find({}) .select("tableList name uploadedBy dateDevelopment id name neuronType") // Hay que sacar también nombre y tipo D= .exec(function(err, exps) { if(err) { res.send("Error"); } else { console.log(exps); res.render('account/experiments/compare/stage1', { code: req.csrfToken(), experiments: exps }); } }); }; /** * Esta función sirve para que, dado * */ exports.second = function(req, res) { console.log("BODY: " + req.body.fcbklist_value); if(req.body.fcbklist_value.length < 2) { res.redirect("/account/experiments/compare/"); } else { //res.send(req.body); var orArray = []; req.body.fcbklist_value.forEach(function(idExp) { orArray.push({_id: idExp}); }); console.log(orArray); req.app.db.models.Experiment.find({$or: orArray}) .select("tableList name createdBy dateDevelopment id") //.populate("tableList", "id") .populate("createdBy", "username") .exec(function(err, exps) { console.log(err); console.log(JSON.stringify(exps)); res.render("account/experiments/compare/stage2", { experiments: exps, code: req.csrfToken() }); }); } //["54514c6a4650426d2a9bf056","5451853c745acc0a412abf68"] // Con esta lista de ids, lo que hacemos es sacar: // 1. Cada experimento con: // name uploadedBy dateDevelopment id // y el identificador de cada tabla del experimento. // 2. Con esos datos, montamos algo guay con radio button. }; /** * En este método recibimos los id's de los experimentos * y la tabla seleccionada * Por cada tabla, sacamos las columnas comunes entre ellas e * imprimimos los gráficos de una vez */ exports.third = function(req, res) { var peticiones = req.body.tab; console.log(peticiones); var arr = []; /*var mapMatch = { "a": null, "b": null, "c": null, "Datos2": null }*/ var params = req.app.utility.variables; var tabs = []; var headersPaths = []; var data = {}; // To save the return to view var Set = req.app.utility.Set; var commons = new Set(); var async = require('async'); async.series([ // First read data from database and save function(callback){ console.log("ejecuto 1"); async.each(peticiones, function(tabid, call) { console.log(tabid); req.app.db.models.TableExperiment.findById(tabid).populate("assignedTo", "name neuronType createdBy dateDevelopment description").exec(function(err, tab) { var username = ""; async.series({ first: function(call2) { console.log("Paso 1"); console.log("Jodeeer, " + tab.assignedTo.createdBy); /*console.log(tab); async.each(tab, function(tab_, call3) { console.log("Buscamos username " + tab_); req.app.db.models.User.findById(tab_.createdBy._id).select("username").exec(function(err, user) { console.log("USER : " + user); tab.createdBy = user.username; call3(); }); });*/ req.app.db.models.User.findById(tab.assignedTo.createdBy).select("username").exec(function(err, user) { console.log("USER : " + user); tab["username"] = user.username; username = user.username; //tab.username = user.username; call2(); }); }, second: function(call2) { console.log("Paso 2"); // TODO: Controlar "err" var tab_ = {}; tab_.assignedTo = { _id: tab.assignedTo._id, username: username, createdBy: tab.assignedTo.createdBy, name: tab.assignedTo.name, neuronType: tab.assignedTo.neuronType, dateDevelopment: tab.assignedTo.dateDevelopment, description: tab.assignedTo.description }; tab_.id = tab._id; tab_.matrix = tab.matrix; tab_.headers = tab.headers; /* assignedTo: { _id: 545bde715e4a5d4a4089ad21, createdBy: 545bde535e4a5d4a4089ad1f, name: 'Mi physiological', neuronType: 'PHYSIOLOGICAL' }, _id: 545bde715e4a5d4a4089ad52, __v: 0, matrix: */ console.log("SECOND : " + tab_); // Añadimos la tabla al sistema //console.log("Añado " + tab); tabs.push(tab_); // Recorro las cabeceras y genero un mapa con k(header) y v(position) var mapMatch = {}; console.log(tab.headers); tab.headers.forEach(function(header, pos) { if(params.contains(header)) { mapMatch[header] = pos; } }); //console.log("Añado " + JSON.stringify(mapMatch)); headersPaths.push(mapMatch); // Guardamos el mapeo call2(); } }, function(err, results) { call(); }); }); }, function(err) { callback(); }); }, // Filter columns that I use to compare table's experiment function(callback) { console.log("Tengo : " + tabs.length); console.log("Tengo : " + headersPaths.length); // Guardamos todos los valores de "params" en "data" data.headers = {}; params.get().forEach(function(value) { data.headers[value] = [];//undefined; }); console.log(JSON.stringify(data)); // Creamos el attr "exps" dentro de "data" data.exps = []; // Ahora por cada experimento, cargamos los datos correspondientes headersPaths.forEach(function(headerPath, index) { console.log("--------- Empezamos a recorrer con header " + headerPath + " ---------"); var posHeader = 0; Object.keys(headerPath).forEach(function(key) { console.log(key + " <=> " + headerPath[key]); //tabs.forEach(function(tab, ii) { tabs[index].matrix.forEach(function(matrix, area) { //console.log("Header: " + key + "\tNº Tab: " + ii + "\tArea: " + area); data.headers[key][area] = data.headers[key][area] || [0]; // Si existe se queda igual, si no, se añade array data.headers[key][area].push(matrix.data[posHeader]); }); //}); /*var infoData = []; tabs[index].matrix.forEach(function(matrix, area) { infoData.push(matrix.data[posHeader]); }); //console.log(infoData); console.log("Inserta del index " + posHeader); data.headers[key].push(infoData);*/ posHeader++; }); // Volcamos la información del experimento asociado a cada tabla data.exps.push(tabs[index].assignedTo); }); console.log("----------------------"); console.log("----------------------"); //console.log(data); console.log("----------------------"); console.log("----------------------"); /*async.each(arr, function(tab, call) { tab.headers.forEach(function(header, position) { //if(mapMatch[header] != undefined) { if(header in tab.mapMatch) { tab.mapMatch[header] = position; } }); // Remove all columns that not contains in mapMatch //tab.mapMatch.forEach(function(position) { //}); call(); });*/ callback(); } ], // finish callback function(err, results){ console.log("FIN: " + arr.length); console.log(params.intersect(commons)); //res.send(data); /*var ret = { data: data }; res.send(ret);*/ console.log("----------------------"); console.log("----------------------"); console.log("----------------------"); console.log("----------------------"); console.log(JSON.stringify(data)); res.render("account/experiments/compare/stage3", { data: data, code: req.csrfToken(), id: 0 }); }); }; // TODO: No funciona bien T.T /*exports.downloadHTML = function(req, res) { phantom = require('phantom') phantom.create(function(ph){ ph.createPage(function(page) { page.open("http://www.google.com", function(status) { page.render('google.pdf', function(){ console.log('Page Rendered'); ph.exit(); }); }); }); }); };*/
maldicion069/HBPWebNodeJs
views/account/experiments/compare/stages.js
JavaScript
mit
9,900
import QUnit from 'qunit'; import { registerDeprecationHandler } from '@ember/debug'; let isRegistered = false; let deprecations = new Set(); let expectedDeprecations = new Set(); // Ignore deprecations that are not caused by our own code, and which we cannot fix easily. const ignoredDeprecations = [ // @todo remove when we can land https://github.com/emberjs/ember-render-modifiers/pull/33 here /Versions of modifier manager capabilities prior to 3\.22 have been deprecated/, /Usage of the Ember Global is deprecated./, /import .* directly from/, /Use of `assign` has been deprecated/, ]; export default function setupNoDeprecations({ beforeEach, afterEach }) { beforeEach(function () { deprecations.clear(); expectedDeprecations.clear(); if (!isRegistered) { registerDeprecationHandler((message, options, next) => { if (!ignoredDeprecations.some((regex) => message.match(regex))) { deprecations.add(message); } next(message, options); }); isRegistered = true; } }); afterEach(function (assert) { // guard in if instead of using assert.equal(), to not make assert.expect() fail if (deprecations.size > expectedDeprecations.size) { assert.ok( false, `Expected ${expectedDeprecations.size} deprecations, found: ${[...deprecations] .map((msg) => `"${msg}"`) .join(', ')}` ); } }); QUnit.assert.deprecations = function (count) { if (count === undefined) { this.ok(deprecations.size, 'Expected deprecations during test.'); } else { this.equal(deprecations.size, count, `Expected ${count} deprecation(s) during test.`); } deprecations.forEach((d) => expectedDeprecations.add(d)); }; QUnit.assert.deprecationsInclude = function (expected) { let found = [...deprecations].find((deprecation) => deprecation.includes(expected)); this.pushResult({ result: !!found, actual: deprecations, message: `expected to find \`${expected}\` deprecation. Found ${[...deprecations] .map((d) => `"${d}"`) .join(', ')}`, }); if (found) { expectedDeprecations.add(found); } }; }
kaliber5/ember-bootstrap
tests/helpers/setup-no-deprecations.js
JavaScript
mit
2,205
/* The MIT License (MIT) Copyright (c) 2014 Manni Wood Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.manniwood.cl4pg.v1.exceptions; public class Cl4pgConfFileException extends Cl4pgException { private static final long serialVersionUID = 1L; public Cl4pgConfFileException() { super(); } public Cl4pgConfFileException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public Cl4pgConfFileException(String message, Throwable cause) { super(message, cause); } public Cl4pgConfFileException(String message) { super(message); } public Cl4pgConfFileException(Throwable cause) { super(cause); } }
manniwood/cl4pg
src/main/java/com/manniwood/cl4pg/v1/exceptions/Cl4pgConfFileException.java
Java
mit
1,781
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("10.TraverseDirectoryXDocument")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("10.TraverseDirectoryXDocument")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0db1c3e2-162a-4e14-b304-0f69cce18d90")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
emilti/Telerik-Academy-My-Courses
DataBases/03.Processing Xml/Processing XML/10.TraverseDirectoryXDocument/Properties/AssemblyInfo.cs
C#
mit
1,434
package com.cosium.spring.data.jpa.entity.graph.repository.support; import com.google.common.base.MoreObjects; import org.springframework.core.ResolvableType; import org.springframework.data.jpa.repository.query.JpaEntityGraph; import static java.util.Objects.requireNonNull; /** * Wrapper class allowing to hold a {@link JpaEntityGraph} with its associated domain class. Created * on 23/11/16. * * @author Reda.Housni-Alaoui */ class EntityGraphBean { private final JpaEntityGraph jpaEntityGraph; private final Class<?> domainClass; private final ResolvableType repositoryMethodReturnType; private final boolean optional; private final boolean primary; private final boolean valid; public EntityGraphBean( JpaEntityGraph jpaEntityGraph, Class<?> domainClass, ResolvableType repositoryMethodReturnType, boolean optional, boolean primary) { this.jpaEntityGraph = requireNonNull(jpaEntityGraph); this.domainClass = requireNonNull(domainClass); this.repositoryMethodReturnType = requireNonNull(repositoryMethodReturnType); this.optional = optional; this.primary = primary; this.valid = computeValidity(); } private boolean computeValidity() { Class<?> resolvedReturnType = repositoryMethodReturnType.resolve(); if (Void.TYPE.equals(resolvedReturnType) || domainClass.isAssignableFrom(resolvedReturnType)) { return true; } for (Class genericType : repositoryMethodReturnType.resolveGenerics()) { if (domainClass.isAssignableFrom(genericType)) { return true; } } return false; } /** @return The jpa entity graph */ public JpaEntityGraph getJpaEntityGraph() { return jpaEntityGraph; } /** @return The jpa entity class */ public Class<?> getDomainClass() { return domainClass; } /** @return True if this entity graph is not mandatory */ public boolean isOptional() { return optional; } /** @return True if this EntityGraph seems valid */ public boolean isValid() { return valid; } /** * @return True if this EntityGraph is a primary one. Default EntityGraph is an example of non * primary EntityGraph. */ public boolean isPrimary() { return primary; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("jpaEntityGraph", jpaEntityGraph) .add("domainClass", domainClass) .add("repositoryMethodReturnType", repositoryMethodReturnType) .add("optional", optional) .toString(); } }
Cosium/spring-data-jpa-entity-graph
core/src/main/java/com/cosium/spring/data/jpa/entity/graph/repository/support/EntityGraphBean.java
Java
mit
2,555
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Page', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('title', models.CharField(unique=True, max_length=150)), ('slug', models.SlugField(unique=True, max_length=150)), ('posted', models.DateTimeField(auto_now_add=True, db_index=True)), ], options={ }, bases=(models.Model,), ), ]
vollov/i18n-django-api
page/migrations/0001_initial.py
Python
mit
723
<?php namespace App\Service; class Message { public function get() { if (isset($_SESSION['message'])) { $array = explode(',', $_SESSION['message']); unset($_SESSION['message']); return $array; } return ''; } public function set($message, $type = null) { $_SESSION['message'] = implode(',', [$message, $type]); } }
QA-Games/QA-tools
app/Service/Message.php
PHP
mit
421
package mqttpubsub import ( "encoding/json" "fmt" "sync" "time" log "github.com/Sirupsen/logrus" "github.com/brocaar/loraserver/api/gw" "github.com/brocaar/lorawan" "github.com/eclipse/paho.mqtt.golang" ) // Backend implements a MQTT pub-sub backend. type Backend struct { conn mqtt.Client txPacketChan chan gw.TXPacketBytes gateways map[lorawan.EUI64]struct{} mutex sync.RWMutex } // NewBackend creates a new Backend. func NewBackend(server, username, password string) (*Backend, error) { b := Backend{ txPacketChan: make(chan gw.TXPacketBytes), gateways: make(map[lorawan.EUI64]struct{}), } opts := mqtt.NewClientOptions() opts.AddBroker(server) opts.SetUsername(username) opts.SetPassword(password) opts.SetOnConnectHandler(b.onConnected) opts.SetConnectionLostHandler(b.onConnectionLost) log.WithField("server", server).Info("backend: connecting to mqtt broker") b.conn = mqtt.NewClient(opts) if token := b.conn.Connect(); token.Wait() && token.Error() != nil { return nil, token.Error() } return &b, nil } // Close closes the backend. func (b *Backend) Close() { b.conn.Disconnect(250) // wait 250 milisec to complete pending actions } // TXPacketChan returns the TXPacketBytes channel. func (b *Backend) TXPacketChan() chan gw.TXPacketBytes { return b.txPacketChan } // SubscribeGatewayTX subscribes the backend to the gateway TXPacketBytes // topic (packets the gateway needs to transmit). func (b *Backend) SubscribeGatewayTX(mac lorawan.EUI64) error { defer b.mutex.Unlock() b.mutex.Lock() topic := fmt.Sprintf("gateway/%s/tx", mac.String()) log.WithField("topic", topic).Info("backend: subscribing to topic") if token := b.conn.Subscribe(topic, 0, b.txPacketHandler); token.Wait() && token.Error() != nil { return token.Error() } b.gateways[mac] = struct{}{} return nil } // UnSubscribeGatewayTX unsubscribes the backend from the gateway TXPacketBytes // topic. func (b *Backend) UnSubscribeGatewayTX(mac lorawan.EUI64) error { defer b.mutex.Unlock() b.mutex.Lock() topic := fmt.Sprintf("gateway/%s/tx", mac.String()) log.WithField("topic", topic).Info("backend: unsubscribing from topic") if token := b.conn.Unsubscribe(topic); token.Wait() && token.Error() != nil { return token.Error() } delete(b.gateways, mac) return nil } // PublishGatewayRX publishes a RX packet to the MQTT broker. func (b *Backend) PublishGatewayRX(mac lorawan.EUI64, rxPacket gw.RXPacketBytes) error { topic := fmt.Sprintf("gateway/%s/rx", mac.String()) return b.publish(topic, rxPacket) } // PublishGatewayStats publishes a GatewayStatsPacket to the MQTT broker. func (b *Backend) PublishGatewayStats(mac lorawan.EUI64, stats gw.GatewayStatsPacket) error { topic := fmt.Sprintf("gateway/%s/stats", mac.String()) return b.publish(topic, stats) } func (b *Backend) publish(topic string, v interface{}) error { bytes, err := json.Marshal(v) if err != nil { return err } log.WithField("topic", topic).Info("backend: publishing packet") if token := b.conn.Publish(topic, 0, false, bytes); token.Wait() && token.Error() != nil { return token.Error() } return nil } func (b *Backend) txPacketHandler(c mqtt.Client, msg mqtt.Message) { log.WithField("topic", msg.Topic()).Info("backend: packet received") var txPacket gw.TXPacketBytes if err := json.Unmarshal(msg.Payload(), &txPacket); err != nil { log.Errorf("backend: decode tx packet error: %s", err) return } b.txPacketChan <- txPacket } func (b *Backend) onConnected(c mqtt.Client) { defer b.mutex.RUnlock() b.mutex.RLock() log.Info("backend: connected to mqtt broker") if len(b.gateways) > 0 { for { log.WithField("topic_count", len(b.gateways)).Info("backend: re-registering to gateway topics") topics := make(map[string]byte) for k := range b.gateways { topics[fmt.Sprintf("gateway/%s/tx", k)] = 0 } if token := b.conn.SubscribeMultiple(topics, b.txPacketHandler); token.Wait() && token.Error() != nil { log.WithField("topic_count", len(topics)).Errorf("backend: subscribe multiple failed: %s", token.Error()) time.Sleep(time.Second) continue } return } } } func (b *Backend) onConnectionLost(c mqtt.Client, reason error) { log.Errorf("backend: mqtt connection error: %s", reason) }
kumara0093/loraserver
backend/mqttpubsub/backend.go
GO
mit
4,289
package stage2; public class DecafError { int numErrors; DecafError(){ } public static String errorPos(Position p){ return "(L: " + p.startLine + ", Col: " + p.startCol + ") -- (L: " + p.endLine + ", Col: " + p.endCol + ")"; } public void error(String s, Position p) { System.out.println("Error found at location "+ errorPos(p) + ":\n"+s); } public boolean haveErrors() { return (numErrors>0); } }
bigfatnoob/Decaf
src/stage2/DecafError.java
Java
mit
471
"use strict"; define("ace/mode/asciidoc_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function (require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var AsciidocHighlightRules = function AsciidocHighlightRules() { var identifierRe = "[a-zA-Z\xA1-\uFFFF]+\\b"; this.$rules = { "start": [{ token: "empty", regex: /$/ }, { token: "literal", regex: /^\.{4,}\s*$/, next: "listingBlock" }, { token: "literal", regex: /^-{4,}\s*$/, next: "literalBlock" }, { token: "string", regex: /^\+{4,}\s*$/, next: "passthroughBlock" }, { token: "keyword", regex: /^={4,}\s*$/ }, { token: "text", regex: /^\s*$/ }, { token: "empty", regex: "", next: "dissallowDelimitedBlock" }], "dissallowDelimitedBlock": [{ include: "paragraphEnd" }, { token: "comment", regex: '^//.+$' }, { token: "keyword", regex: "^(?:NOTE|TIP|IMPORTANT|WARNING|CAUTION):" }, { include: "listStart" }, { token: "literal", regex: /^\s+.+$/, next: "indentedBlock" }, { token: "empty", regex: "", next: "text" }], "paragraphEnd": [{ token: "doc.comment", regex: /^\/{4,}\s*$/, next: "commentBlock" }, { token: "tableBlock", regex: /^\s*[|!]=+\s*$/, next: "tableBlock" }, { token: "keyword", regex: /^(?:--|''')\s*$/, next: "start" }, { token: "option", regex: /^\[.*\]\s*$/, next: "start" }, { token: "pageBreak", regex: /^>{3,}$/, next: "start" }, { token: "literal", regex: /^\.{4,}\s*$/, next: "listingBlock" }, { token: "titleUnderline", regex: /^(?:={2,}|-{2,}|~{2,}|\^{2,}|\+{2,})\s*$/, next: "start" }, { token: "singleLineTitle", regex: /^={1,5}\s+\S.*$/, next: "start" }, { token: "otherBlock", regex: /^(?:\*{2,}|_{2,})\s*$/, next: "start" }, { token: "optionalTitle", regex: /^\.[^.\s].+$/, next: "start" }], "listStart": [{ token: "keyword", regex: /^\s*(?:\d+\.|[a-zA-Z]\.|[ixvmIXVM]+\)|\*{1,5}|-|\.{1,5})\s/, next: "listText" }, { token: "meta.tag", regex: /^.+(?::{2,4}|;;)(?: |$)/, next: "listText" }, { token: "support.function.list.callout", regex: /^(?:<\d+>|\d+>|>) /, next: "text" }, { token: "keyword", regex: /^\+\s*$/, next: "start" }], "text": [{ token: ["link", "variable.language"], regex: /((?:https?:\/\/|ftp:\/\/|file:\/\/|mailto:|callto:)[^\s\[]+)(\[.*?\])/ }, { token: "link", regex: /(?:https?:\/\/|ftp:\/\/|file:\/\/|mailto:|callto:)[^\s\[]+/ }, { token: "link", regex: /\b[\w\.\/\-]+@[\w\.\/\-]+\b/ }, { include: "macros" }, { include: "paragraphEnd" }, { token: "literal", regex: /\+{3,}/, next: "smallPassthrough" }, { token: "escape", regex: /\((?:C|TM|R)\)|\.{3}|->|<-|=>|<=|&#(?:\d+|x[a-fA-F\d]+);|(?: |^)--(?=\s+\S)/ }, { token: "escape", regex: /\\[_*'`+#]|\\{2}[_*'`+#]{2}/ }, { token: "keyword", regex: /\s\+$/ }, { token: "text", regex: identifierRe }, { token: ["keyword", "string", "keyword"], regex: /(<<[\w\d\-$]+,)(.*?)(>>|$)/ }, { token: "keyword", regex: /<<[\w\d\-$]+,?|>>/ }, { token: "constant.character", regex: /\({2,3}.*?\){2,3}/ }, { token: "keyword", regex: /\[\[.+?\]\]/ }, { token: "support", regex: /^\[{3}[\w\d =\-]+\]{3}/ }, { include: "quotes" }, { token: "empty", regex: /^\s*$/, next: "start" }], "listText": [{ include: "listStart" }, { include: "text" }], "indentedBlock": [{ token: "literal", regex: /^[\s\w].+$/, next: "indentedBlock" }, { token: "literal", regex: "", next: "start" }], "listingBlock": [{ token: "literal", regex: /^\.{4,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "constant.numeric", regex: '<\\d+>' }, { token: "literal", regex: '[^<]+' }, { token: "literal", regex: '<' }], "literalBlock": [{ token: "literal", regex: /^-{4,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "constant.numeric", regex: '<\\d+>' }, { token: "literal", regex: '[^<]+' }, { token: "literal", regex: '<' }], "passthroughBlock": [{ token: "literal", regex: /^\+{4,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "literal", regex: identifierRe + "|\\d+" }, { include: "macros" }, { token: "literal", regex: "." }], "smallPassthrough": [{ token: "literal", regex: /[+]{3,}/, next: "dissallowDelimitedBlock" }, { token: "literal", regex: /^\s*$/, next: "dissallowDelimitedBlock" }, { token: "literal", regex: identifierRe + "|\\d+" }, { include: "macros" }], "commentBlock": [{ token: "doc.comment", regex: /^\/{4,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "doc.comment", regex: '^.*$' }], "tableBlock": [{ token: "tableBlock", regex: /^\s*\|={3,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "tableBlock", regex: /^\s*!={3,}\s*$/, next: "innerTableBlock" }, { token: "tableBlock", regex: /\|/ }, { include: "text", noEscape: true }], "innerTableBlock": [{ token: "tableBlock", regex: /^\s*!={3,}\s*$/, next: "tableBlock" }, { token: "tableBlock", regex: /^\s*|={3,}\s*$/, next: "dissallowDelimitedBlock" }, { token: "tableBlock", regex: /\!/ }], "macros": [{ token: "macro", regex: /{[\w\-$]+}/ }, { token: ["text", "string", "text", "constant.character", "text"], regex: /({)([\w\-$]+)(:)?(.+)?(})/ }, { token: ["text", "markup.list.macro", "keyword", "string"], regex: /(\w+)(footnote(?:ref)?::?)([^\s\[]+)?(\[.*?\])?/ }, { token: ["markup.list.macro", "keyword", "string"], regex: /([a-zA-Z\-][\w\.\/\-]*::?)([^\s\[]+)(\[.*?\])?/ }, { token: ["markup.list.macro", "keyword"], regex: /([a-zA-Z\-][\w\.\/\-]+::?)(\[.*?\])/ }, { token: "keyword", regex: /^:.+?:(?= |$)/ }], "quotes": [{ token: "string.italic", regex: /__[^_\s].*?__/ }, { token: "string.italic", regex: quoteRule("_") }, { token: "keyword.bold", regex: /\*\*[^*\s].*?\*\*/ }, { token: "keyword.bold", regex: quoteRule("\\*") }, { token: "literal", regex: quoteRule("\\+") }, { token: "literal", regex: /\+\+[^+\s].*?\+\+/ }, { token: "literal", regex: /\$\$.+?\$\$/ }, { token: "literal", regex: quoteRule("`") }, { token: "keyword", regex: quoteRule("^") }, { token: "keyword", regex: quoteRule("~") }, { token: "keyword", regex: /##?/ }, { token: "keyword", regex: /(?:\B|^)``|\b''/ }] }; function quoteRule(ch) { var prefix = /\w/.test(ch) ? "\\b" : "(?:\\B|^)"; return prefix + ch + "[^" + ch + "].*?" + ch + "(?![\\w*])"; } var tokenMap = { macro: "constant.character", tableBlock: "doc.comment", titleUnderline: "markup.heading", singleLineTitle: "markup.heading", pageBreak: "string", option: "string.regexp", otherBlock: "markup.list", literal: "support.function", optionalTitle: "constant.numeric", escape: "constant.language.escape", link: "markup.underline.list" }; for (var state in this.$rules) { var stateRules = this.$rules[state]; for (var i = stateRules.length; i--;) { var rule = stateRules[i]; if (rule.include || typeof rule == "string") { var args = [i, 1].concat(this.$rules[rule.include || rule]); if (rule.noEscape) { args = args.filter(function (x) { return !x.next; }); } stateRules.splice.apply(stateRules, args); } else if (rule.token in tokenMap) { rule.token = tokenMap[rule.token]; } } } }; oop.inherits(AsciidocHighlightRules, TextHighlightRules); exports.AsciidocHighlightRules = AsciidocHighlightRules; }); define("ace/mode/folding/asciidoc", ["require", "exports", "module", "ace/lib/oop", "ace/mode/folding/fold_mode", "ace/range"], function (require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function () {}; oop.inherits(FoldMode, BaseFoldMode); (function () { this.foldingStartMarker = /^(?:\|={10,}|[\.\/=\-~^+]{4,}\s*$|={1,5} )/; this.singleLineHeadingRe = /^={1,5}(?=\s+\S)/; this.getFoldWidget = function (session, foldStyle, row) { var line = session.getLine(row); if (!this.foldingStartMarker.test(line)) return ""; if (line[0] == "=") { if (this.singleLineHeadingRe.test(line)) return "start"; if (session.getLine(row - 1).length != session.getLine(row).length) return ""; return "start"; } if (session.bgTokenizer.getState(row) == "dissallowDelimitedBlock") return "end"; return "start"; }; this.getFoldWidgetRange = function (session, foldStyle, row) { var line = session.getLine(row); var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; if (!line.match(this.foldingStartMarker)) return; var token; function getTokenType(row) { token = session.getTokens(row)[0]; return token && token.type; } var levels = ["=", "-", "~", "^", "+"]; var heading = "markup.heading"; var singleLineHeadingRe = this.singleLineHeadingRe; function getLevel() { var match = token.value.match(singleLineHeadingRe); if (match) return match[0].length; var level = levels.indexOf(token.value[0]) + 1; if (level == 1) { if (session.getLine(row - 1).length != session.getLine(row).length) return Infinity; } return level; } if (getTokenType(row) == heading) { var startHeadingLevel = getLevel(); while (++row < maxRow) { if (getTokenType(row) != heading) continue; var level = getLevel(); if (level <= startHeadingLevel) break; } var isSingleLineHeading = token && token.value.match(this.singleLineHeadingRe); endRow = isSingleLineHeading ? row - 1 : row - 2; if (endRow > startRow) { while (endRow > startRow && (!getTokenType(endRow) || token.value[0] == "[")) { endRow--; } } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } } else { var state = session.bgTokenizer.getState(row); if (state == "dissallowDelimitedBlock") { while (row-- > 0) { if (session.bgTokenizer.getState(row).lastIndexOf("Block") == -1) break; } endRow = row + 1; if (endRow < startRow) { var endColumn = session.getLine(row).length; return new Range(endRow, 5, startRow, startColumn - 5); } } else { while (++row < maxRow) { if (session.bgTokenizer.getState(row) == "dissallowDelimitedBlock") break; } endRow = row; if (endRow > startRow) { var endColumn = session.getLine(row).length; return new Range(startRow, 5, endRow, endColumn - 5); } } } }; }).call(FoldMode.prototype); }); define("ace/mode/asciidoc", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/mode/asciidoc_highlight_rules", "ace/mode/folding/asciidoc"], function (require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var AsciidocHighlightRules = require("./asciidoc_highlight_rules").AsciidocHighlightRules; var AsciidocFoldMode = require("./folding/asciidoc").FoldMode; var Mode = function Mode() { this.HighlightRules = AsciidocHighlightRules; this.foldingRules = new AsciidocFoldMode(); }; oop.inherits(Mode, TextMode); (function () { this.type = "text"; this.getNextLineIndent = function (state, line, tab) { if (state == "listblock") { var match = /^((?:.+)?)([-+*][ ]+)/.exec(line); if (match) { return new Array(match[1].length + 1).join(" ") + match[2]; } else { return ""; } } else { return this.$getIndent(line); } }; this.$id = "ace/mode/asciidoc"; }).call(Mode.prototype); exports.Mode = Mode; });
IonicaBizau/arc-assembler
clients/ace-builds/src/mode-asciidoc.js
JavaScript
mit
13,207
/* * * Copyright (c) 2013 - 2014 INT - National Institute of Technology & COPPE - Alberto Luiz Coimbra Institute - Graduate School and Research in Engineering. * See the file license.txt for copyright permission. * */ package cargaDoSistema; import modelo.TipoUsuario; import modelo.Usuario; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import service.TipoUsuarioAppService; import service.UsuarioAppService; import service.controleTransacao.FabricaDeAppService; import service.exception.AplicacaoException; import util.JPAUtil; /** * Classe responsável pela inclusão de Tipos de Usuário e de Usuário. * É usada na carga do sistema e deve ser a primeira a ser executada. * Está criando um usuário para cada tipo. (dma) * * @author marques * */ public class CargaUsuario { // Services public TipoUsuarioAppService tipoUsuarioService; public UsuarioAppService usuarioService; @BeforeClass public void setupClass(){ try { tipoUsuarioService = FabricaDeAppService.getAppService(TipoUsuarioAppService.class); usuarioService = FabricaDeAppService.getAppService(UsuarioAppService.class); } catch (Exception e) { e.printStackTrace(); } } @Test public void incluirTiposDeUsuario() { TipoUsuario tipoUsuarioAdmin = new TipoUsuario(); TipoUsuario tipoUsuarioAluno = new TipoUsuario(); TipoUsuario tipoUsuarioGestor = new TipoUsuario(); TipoUsuario tipoUsuarioEngenheiro = new TipoUsuario(); tipoUsuarioAdmin.setTipoUsuario(TipoUsuario.ADMINISTRADOR); tipoUsuarioAdmin.setDescricao("O usuário ADMINISTRADOR pode realizar qualquer operação no Sistema."); tipoUsuarioAluno.setTipoUsuario(TipoUsuario.ALUNO); tipoUsuarioAluno.setDescricao("O usuário ALUNO pode realizar apenas consultas e impressão de relatórios nas telas " + "relativas ao Horizonte de Planejamento (HP,Periodo PMP, Periodo PAP) e não acessa " + "Administração e Eng. Conhecimento"); tipoUsuarioGestor.setTipoUsuario(TipoUsuario.GESTOR); tipoUsuarioGestor.setDescricao("O usuário GESTOR pode realizar qualquer operação no Sistema, porém não possui acesso" + "as áreas de Administração e Engenharia de Conhecimento."); tipoUsuarioEngenheiro.setTipoUsuario(TipoUsuario.ENGENHEIRO_DE_CONHECIMENTO); tipoUsuarioEngenheiro.setDescricao("O usuário ENGENHEIRO pode realizar a parte de Logica Fuzzy (Engenharia de Conhecimento)" + "no Sistema. Porém, não possui acesso a área Administrativa."); tipoUsuarioService.inclui(tipoUsuarioAdmin); tipoUsuarioService.inclui(tipoUsuarioAluno); tipoUsuarioService.inclui(tipoUsuarioGestor); tipoUsuarioService.inclui(tipoUsuarioEngenheiro); Usuario usuarioAdmin = new Usuario(); Usuario usuarioAluno = new Usuario(); Usuario usuarioGestor = new Usuario(); Usuario usuarioEngenheiro = new Usuario(); usuarioAdmin.setNome("Administrador"); usuarioAdmin.setLogin("dgep"); usuarioAdmin.setSenha("admgesplan2@@8"); usuarioAdmin.setTipoUsuario(tipoUsuarioAdmin); usuarioAluno.setNome("Alberto da Silva"); usuarioAluno.setLogin("alberto"); usuarioAluno.setSenha("alberto"); usuarioAluno.setTipoUsuario(tipoUsuarioAluno); usuarioEngenheiro.setNome("Bernadete da Silva"); usuarioEngenheiro.setLogin("bernadete"); usuarioEngenheiro.setSenha("bernadete"); usuarioEngenheiro.setTipoUsuario(tipoUsuarioEngenheiro); usuarioGestor.setNome("Carlos da Silva"); usuarioGestor.setLogin("carlos"); usuarioGestor.setSenha("carlos"); usuarioGestor.setTipoUsuario(tipoUsuarioGestor); try { usuarioService.inclui(usuarioAdmin, usuarioAdmin.getSenha()); usuarioService.inclui(usuarioEngenheiro, usuarioEngenheiro.getSenha()); usuarioService.inclui(usuarioGestor, usuarioGestor.getSenha()); usuarioService.inclui(usuarioAluno, usuarioAluno.getSenha()); } catch (AplicacaoException e) { //e.printStackTrace(); System.out.println("Erro na inclusao do usuario: "+ e.getMessage()); } } }
dayse/gesplan
test/cargaDoSistema/CargaUsuario.java
Java
mit
4,187