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 |
|---|---|---|---|---|---|
# coding: utf-8
class Photo
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::BaseModel
field :image
belongs_to :user
ACCESSABLE_ATTRS = [:image]
# 封面图
mount_uploader :image, PhotoUploader
end
| alanlong9278/ruby-china-message | app/models/photo.rb | Ruby | gpl-2.0 | 257 |
<?php
/**
* CSS typography
*
* @package Elgg.Core
* @subpackage UI
*/
?>
/* ***************************************
Typography
*************************************** */
body {
font-size: 80%;
line-height: 1.4em;
font-family: "Lucida Grande", Arial, Tahoma, Verdana, sans-serif;
}
a {
color: #446;
}
a:hover,
a.selected { <?php //@todo remove .selected ?>
color: #555555;
text-decoration: underline;
}
p {
margin-bottom: 15px;
}
p:last-child {
margin-bottom: 0;
}
pre, code {
font-family: Monaco, "Courier New", Courier, monospace;
font-size: 12px;
background:#EBF5FF;
color:#000000;
overflow:auto;
overflow-x: auto; /* Use horizontal scroller if needed; for Firefox 2, not needed in Firefox 3 */
white-space: pre-wrap;
word-wrap: break-word; /* IE 5.5-7 */
}
pre {
padding:3px 15px;
margin:0px 0 15px 0;
line-height:1.3em;
}
code {
padding:2px 3px;
}
.elgg-monospace {
font-family: Monaco, "Courier New", Courier, monospace;
}
blockquote {
line-height: 1.3em;
padding:3px 15px;
margin:0px 0 15px 0;
background:#EBF5FF;
border:none;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
h1, h2, h3, h4, h5, h6 {
font-weight: bold;
color: #566;
}
h1 { font-size: 1.8em; }
h2 { font-size: 1.5em; line-height: 1.1em; padding-bottom:5px}
h3 { font-size: 1.2em; }
h4 { font-size: 1.0em; }
h5 { font-size: 0.9em; }
h6 { font-size: 0.8em; }
.elgg-heading-site, .elgg-heading-site:hover {
font-size: 2em;
line-height: 1.4em;
color: white;
font-style: italic;
font-family: Georgia, times, serif;
text-shadow: 1px 2px 4px #333333;
text-decoration: none;
}
.elgg-heading-main {
float: left;
max-width: 530px;
margin-right: 10px;
}
.elgg-heading-basic {
color: #455;
font-size: 1.2em;
font-weight: bold;
}
.elgg-subtext {
color: #666666;
font-size: 85%;
line-height: 1.2em;
font-style: italic;
}
.elgg-text-help {
display: block;
font-size: 85%;
font-style: italic;
}
.elgg-quiet {
color: #666;
}
.elgg-loud {
color: #0054A7;
}
/* ***************************************
USER INPUT DISPLAY RESET
*************************************** */
.elgg-output {
margin-top: 10px;
}
.elgg-output dt { font-weight: bold }
.elgg-output dd { margin: 0 0 1em 1em }
.elgg-output ul, .elgg-output ol {
margin: 0 1.5em 1.5em 0;
padding-left: 1.5em;
}
.elgg-output ul {
list-style-type: disc;
}
.elgg-output ol {
list-style-type: decimal;
}
.elgg-output table {
border: 1px solid #ccc;
}
.elgg-output table td {
border: 1px solid #ccc;
padding: 3px 5px;
}
.elgg-output img {
max-width: 100%;
} | weSPOT/wespot_iwe | mod/elastic/views/default/css/elements/typography.php | PHP | gpl-2.0 | 2,583 |
<?php
/** List with all available otw sitebars
*
*
*/
global $_wp_column_headers;
$_wp_column_headers['toplevel_page_otw-sbm'] = array(
'id' => __( 'Sidebar ID' ),
'title' => __( 'Title' ),
'description' => __( 'Description' )
);
$otw_sidebar_list = get_option( 'otw_sidebars' );
$message = '';
$massages = array();
$messages[1] = 'Sidebar saved.';
$messages[2] = 'Sidebar deleted.';
$messages[3] = 'Sidebar activated.';
$messages[4] = 'Sidebar deactivated.';
if( isset( $_GET['message'] ) && isset( $messages[ $_GET['message'] ] ) ){
$message .= $messages[ $_GET['message'] ];
}
$filtered_otw_sidebar_list = array();
if( is_array( $otw_sidebar_list ) && count( $otw_sidebar_list ) ){
foreach( $otw_sidebar_list as $sidebar_key => $sidebar_item ){
if( $sidebar_item['replace'] == '' ){
$filtered_otw_sidebar_list[ $sidebar_key ] = $sidebar_item;
}
}
}
?>
<div class="updated"><p>Check out the <a href="http://otwthemes.com/online-documentation-widgetize-pages-light/?utm_source=wp.org&utm_medium=admin&utm_content=docs&utm_campaign=wpl">Online documentation</a> for this plugin<br /><br /> Upgrade to the full version of <a href="http://codecanyon.net/item/sidebar-widget-manager-for-wordpress/2287447?ref=OTWthemes">Sidebar and Widget Manager</a> | <a href="http://otwthemes.com/demos/1ts/?item=Sidebar%20Widget%20Manager&utm_source=wp.org&utm_medium=admin&utm_content=upgrade&utm_campaign=wpl">Demo site</a><br /><br />
<a href="http://otwthemes.com/widgetizing-pages-in-wordpress-can-be-even-easier-and-faster?utm_source=wp.org&utm_medium=admin&utm_content=site&utm_campaign=wpl">Create responsive layouts in minutes, drag & drop interface, feature rich.</a></p></div>
<?php if ( $message ) : ?>
<div id="message" class="updated"><p><?php echo $message; ?></p></div>
<?php endif; ?>
<div class="wrap">
<div id="icon-edit" class="icon32"><br/></div>
<h2>
<?php _e('Available Custom Sidebars') ?>
<a class="button add-new-h2" href="<?php echo admin_url( 'admin.php?page=otw-wpl-add'); ?>">Add New</a>
</h2>
<form class="search-form" action="" method="get">
</form>
<br class="clear" />
<?php if( is_array( $filtered_otw_sidebar_list ) && count( $filtered_otw_sidebar_list ) ){?>
<table class="widefat fixed" cellspacing="0">
<thead>
<tr>
<?php foreach( $_wp_column_headers['toplevel_page_otw-sbm'] as $key => $name ){?>
<th><?php echo $name?></th>
<?php }?>
</tr>
</thead>
<tfoot>
<tr>
<?php foreach( $_wp_column_headers['toplevel_page_otw-sbm'] as $key => $name ){?>
<th><?php echo $name?></th>
<?php }?>
</tr>
</tfoot>
<tbody>
<?php foreach( $filtered_otw_sidebar_list as $sidebar_item ){?>
<tr>
<?php foreach( $_wp_column_headers['toplevel_page_otw-sbm'] as $column_name => $column_title ){
$edit_link = admin_url( 'admin.php?page=otw-wpl&action=edit&sidebar='.$sidebar_item['id'] );
$delete_link = admin_url( 'admin.php?page=otw-wpl-action&sidebar='.$sidebar_item['id'].'&action=delete' );
switch($column_name) {
case 'cb':
echo '<th scope="row" class="check-column"><input type="checkbox" name="itemcheck[]" value="'. esc_attr($sidebar_item['id']) .'" /></th>';
break;
case 'id':
echo '<td><strong><a href="'.$edit_link.'" title="'.esc_attr(sprintf(__('Edit “%s”'), $sidebar_item['id'])).'">'.$sidebar_item['id'].'</a></strong><br />';
echo '<div class="row-actions">';
echo '<a href="'.$edit_link.'">' . __('Edit') . '</a>';
echo ' | <a href="'.$delete_link.'">' . __('Delete'). '</a>';
echo '</div>';
echo '</td>';
break;
case 'title':
echo '<td>'.$sidebar_item['title'].'</td>';
break;
case 'description':
echo '<td>'.$sidebar_item['description'].'</td>';
break;
}
}?>
</tr>
<?php }?>
</tbody>
</table>
<div class="updated einfo"><p><?php _e( 'Create as many sidebars as you need. Then add them in your pages/posts/template files. Here is how you can add sidebars:<br /><br /> - page/post bellow content using the Grid Manager metabox when you edit your page<br /> - page/post content - select the sidebar you want to insert from the Insert Sidebar ShortCode button in your page/post editor.<br /> - page/post content - copy the shortcode and paste it in the editor of a page/post.<br /> - any page template using the do_shortcode WP function.<br /><br />Use the Sidebar ID to build your shortcodes.<br />Example: [otw_is sidebar=otw-sidebar-1] ' );?></p></div>
<?php }else{ ?>
<p><?php _e('No custom sidebars found.')?></p>
<?php } ?>
</div>
| rm913/lamaze-dc | wp-content/plugins/widgetize-pages-light/include/otw_list_sidebars.php | PHP | gpl-2.0 | 4,748 |
package speiger.src.api.common.recipes.squezingCompressor.parts;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;
import speiger.src.api.common.recipes.squezingCompressor.EnumRecipeType;
import speiger.src.api.common.recipes.util.RecipeHardness;
import speiger.src.api.common.recipes.util.Result;
public class SqueezerRecipe implements INormalRecipe
{
ItemStack recipeInput;
Result[] result;
public SqueezerRecipe(ItemStack par1, Result...par2)
{
recipeInput = par1;
result = par2;
}
@Override
public ItemStack getItemInput()
{
return recipeInput;
}
@Override
public FluidStack[] getFluidInput()
{
return null;
}
@Override
public Result[] getResults()
{
return result;
}
@Override
public boolean matches(ItemStack input, FluidTank first, FluidTank second, World world)
{
if(recipeInput.isItemEqual(input) && input.stackSize >= recipeInput.stackSize)
{
return true;
}
return false;
}
@Override
public EnumRecipeType getRecipeType()
{
return EnumRecipeType.Sqeezing;
}
@Override
public void runResult(ItemStack input, FluidTank first, FluidTank second, World world)
{
input.stackSize -= recipeInput.stackSize;
}
@Override
public RecipeHardness getComplexity()
{
return RecipeHardness.Extrem_Easy;
}
}
| TinyModularThings/TinyModularThings | src/speiger/src/api/common/recipes/squezingCompressor/parts/SqueezerRecipe.java | Java | gpl-2.0 | 1,458 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_newsfeeds
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\Component\Newsfeeds\Administrator\View\Newsfeeds;
\defined('_JEXEC') or die;
use Joomla\CMS\Factory;
use Joomla\CMS\Helper\ContentHelper;
use Joomla\CMS\Language\Multilanguage;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\View\GenericDataException;
use Joomla\CMS\MVC\View\HtmlView as BaseHtmlView;
use Joomla\CMS\Toolbar\Toolbar;
use Joomla\CMS\Toolbar\ToolbarHelper;
/**
* View class for a list of newsfeeds.
*
* @since 1.6
*/
class HtmlView extends BaseHtmlView
{
/**
* The list of newsfeeds
*
* @var \JObject
* @since 1.6
*/
protected $items;
/**
* The pagination object
*
* @var \Joomla\CMS\Pagination\Pagination
* @since 1.6
*/
protected $pagination;
/**
* The model state
*
* @var \JObject
* @since 1.6
*/
protected $state;
/**
* Execute and display a template script.
*
* @param string $tpl The name of the template file to parse; automatically searches through the template paths.
*
* @return mixed A string if successful, otherwise an Error object.
*
* @since 1.6
*/
public function display($tpl = null)
{
$this->items = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->state = $this->get('State');
$this->filterForm = $this->get('FilterForm');
$this->activeFilters = $this->get('ActiveFilters');
// Check for errors.
if (count($errors = $this->get('Errors')))
{
throw new GenericDataException(implode("\n", $errors), 500);
}
// We don't need toolbar in the modal layout.
if ($this->getLayout() !== 'modal')
{
$this->addToolbar();
// We do not need to filter by language when multilingual is disabled
if (!Multilanguage::isEnabled())
{
unset($this->activeFilters['language']);
$this->filterForm->removeField('language', 'filter');
}
}
else
{
// In article associations modal we need to remove language filter if forcing a language.
// We also need to change the category filter to show show categories with All or the forced language.
if ($forcedLanguage = Factory::getApplication()->input->get('forcedLanguage', '', 'CMD'))
{
// If the language is forced we can't allow to select the language, so transform the language selector filter into a hidden field.
$languageXml = new \SimpleXMLElement('<field name="language" type="hidden" default="' . $forcedLanguage . '" />');
$this->filterForm->setField($languageXml, 'filter', true);
// Also, unset the active language filter so the search tools is not open by default with this filter.
unset($this->activeFilters['language']);
// One last changes needed is to change the category filter to just show categories with All language or with the forced language.
$this->filterForm->setFieldAttribute('category_id', 'language', '*,' . $forcedLanguage, 'filter');
}
}
parent::display($tpl);
}
/**
* Add the page title and toolbar.
*
* @return void
*
* @since 1.6
*/
protected function addToolbar()
{
$state = $this->get('State');
$canDo = ContentHelper::getActions('com_newsfeeds', 'category', $state->get('filter.category_id'));
$user = Factory::getUser();
// Get the toolbar object instance
$toolbar = Toolbar::getInstance('toolbar');
ToolbarHelper::title(Text::_('COM_NEWSFEEDS_MANAGER_NEWSFEEDS'), 'rss newsfeeds');
if (count($user->getAuthorisedCategories('com_newsfeeds', 'core.create')) > 0)
{
$toolbar->addNew('newsfeed.add');
}
if ($canDo->get('core.edit.state') || $user->authorise('core.admin'))
{
$dropdown = $toolbar->dropdownButton('status-group')
->text('JTOOLBAR_CHANGE_STATUS')
->toggleSplit(false)
->icon('fas fa-ellipsis-h')
->buttonClass('btn btn-action')
->listCheck(true);
$childBar = $dropdown->getChildToolbar();
$childBar->publish('newsfeeds.publish')->listCheck(true);
$childBar->unpublish('newsfeeds.unpublish')->listCheck(true);
$childBar->archive('newsfeeds.archive')->listCheck(true);
if ($user->authorise('core.admin'))
{
$childBar->checkin('newsfeeds.checkin')->listCheck(true);
}
if (!$this->state->get('filter.published') == -2)
{
$childBar->trash('newsfeeds.trash')->listCheck(true);
}
// Add a batch button
if ($user->authorise('core.create', 'com_newsfeeds')
&& $user->authorise('core.edit', 'com_newsfeeds')
&& $user->authorise('core.edit.state', 'com_newsfeeds'))
{
$childBar->popupButton('batch')
->text('JTOOLBAR_BATCH')
->selector('collapseModal')
->listCheck(true);
}
if ($state->get('filter.published') == -2 && $canDo->get('core.delete'))
{
$childBar->delete('newsfeeds.delete')
->text('JTOOLBAR_EMPTY_TRASH')
->message('JGLOBAL_CONFIRM_DELETE')
->listCheck(true);
}
}
if ($user->authorise('core.admin', 'com_newsfeeds') || $user->authorise('core.options', 'com_newsfeeds'))
{
$toolbar->preferences('com_newsfeeds');
}
$toolbar->help('JHELP_COMPONENTS_NEWSFEEDS_FEEDS');
}
}
| twister65/joomla-cms | administrator/components/com_newsfeeds/src/View/Newsfeeds/HtmlView.php | PHP | gpl-2.0 | 5,288 |
<?php
/**
* @package hubzero-cms
* @copyright Copyright (c) 2005-2020 The Regents of the University of California.
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Components\Members\Admin;
if (!\User::authorise('core.manage', 'com_members'))
{
return \App::abort(403, \Lang::txt('JERROR_ALERTNOAUTHOR'));
}
// Include scripts
require_once dirname(__DIR__) . DS . 'models' . DS . 'member.php';
require_once dirname(__DIR__) . DS . 'helpers' . DS . 'admin.php';
$controllerName = \Request::getCmd('controller', 'members');
if (!file_exists(__DIR__ . DS . 'controllers' . DS . $controllerName . '.php'))
{
$controllerName = 'members';
}
// Build sub-menu
require_once __DIR__ . DS . 'helpers' . DS . 'members.php';
\MembersHelper::addSubmenu($controllerName);
// Instantiate controller
require_once __DIR__ . DS . 'controllers' . DS . $controllerName . '.php';
$controllerName = __NAMESPACE__ . '\\Controllers\\' . ucfirst($controllerName);
$controller = new $controllerName();
$controller->execute();
| hubzero/hubzero-cms | core/components/com_members/admin/members.php | PHP | gpl-2.0 | 1,035 |
PUMP_SELECTOR.CoordSlicer = function( parameters ) {
var image = parameters.image;
var coord = parameters.coord;
var name = parameters.name;
var obj = {};
if( image === undefined) {
//PUMPER.debug("PUMPER::CoordSlicer() - Cannot slice image, image missing.");
return undefined;
}else if (coord === undefined) {
//PUMPER.debug("PUMPER::CoordSlicer() - Warn: No coordinate data given. Returning image.");
return obj[name] = obj;
}else{
var coords = coord.split("\n");
coords.clean("");
for(var i=0;i<coords.length;i++) {
var coordinate = coords[i].split(" ");
obj[coordinate[0]] = PUMP_SELECTOR.CropImage(image,coordinate[1],coordinate[2],coordinate[3],coordinate[4]);
}
return obj;
}
};
| racerxdl/f2rank | jsselector/coord.js | JavaScript | gpl-2.0 | 823 |
package gof.structure.proxy;
public class ProxySubject extends Subject {
private RealSubject realSubject;
public ProxySubject(){
}
/* (non-Javadoc)
* @see gof.structure.proxy.Subject#request()
*
* Subject subject = new ProxySubject();
* subject.request();
*/
@Override
public void request() {
preRequest();
if(realSubject == null){
realSubject = new RealSubject();
}
realSubject.request();
postRequest();
}
private void preRequest(){
}
private void postRequest(){
}
}
| expleeve/GoF23 | src/gof/structure/proxy/ProxySubject.java | Java | gpl-2.0 | 560 |
# encoding: utf8
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
fields = [(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True),), ('name', models.CharField(max_length=255),), ('email', models.EmailField(max_length=75),), ('message', models.TextField(),), ('date', models.DateField(auto_now=True),)],
bases = (models.Model,),
options = {},
name = 'Contact',
),
migrations.CreateModel(
fields = [(u'id', models.AutoField(verbose_name=u'ID', serialize=False, auto_created=True, primary_key=True),), ('date', models.DateTimeField(),), ('title', models.CharField(max_length=255),), ('code', models.CharField(max_length=255),), ('summary', models.TextField(),)],
bases = (models.Model,),
options = {},
name = 'Commits',
),
]
| Nimmard/james-olson.com | main/migrations/0001_initial.py | Python | gpl-2.0 | 1,003 |
<?php
/**
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
namespace eZ\Publish\Core\Search\Legacy\Content\Location\Gateway\CriterionHandler;
use eZ\Publish\Core\Search\Legacy\Content\Common\Gateway\CriterionHandler;
use eZ\Publish\Core\Search\Legacy\Content\Common\Gateway\CriteriaConverter;
use eZ\Publish\API\Repository\Values\Content\Query\Criterion;
use eZ\Publish\Core\Persistence\Database\SelectQuery;
/**
* Visits the Ancestor criterion.
*/
class Ancestor extends CriterionHandler
{
/**
* Check if this criterion handler accepts to handle the given criterion.
*
* @param \eZ\Publish\API\Repository\Values\Content\Query\Criterion $criterion
*
* @return bool
*/
public function accept(Criterion $criterion)
{
return $criterion instanceof Criterion\Ancestor;
}
/**
* Generate query expression for a Criterion this handler accepts.
*
* accept() must be called before calling this method.
*
* @param \eZ\Publish\Core\Search\Legacy\Content\Common\Gateway\CriteriaConverter $converter
* @param \eZ\Publish\Core\Persistence\Database\SelectQuery $query
* @param \eZ\Publish\API\Repository\Values\Content\Query\Criterion $criterion
* @param array $languageSettings
*
* @return \eZ\Publish\Core\Persistence\Database\Expression
*/
public function handle(
CriteriaConverter $converter,
SelectQuery $query,
Criterion $criterion,
array $languageSettings
) {
$idSet = [];
foreach ($criterion->value as $value) {
foreach (explode('/', trim($value, '/')) as $id) {
$idSet[$id] = true;
}
}
return $query->expr->in(
$this->dbHandler->quoteColumn('node_id', 'ezcontentobject_tree'),
array_keys($idSet)
);
}
}
| ezsystems/ezpublish-kernel | eZ/Publish/Core/Search/Legacy/Content/Location/Gateway/CriterionHandler/Ancestor.php | PHP | gpl-2.0 | 1,991 |
using System;
using System.Collections.Generic;
using System.Management;
using System.Security.Principal;
using Microsoft.Win32;
using PowerPointLabs.ActionFramework.Common.Log;
namespace PowerPointLabs.Utils
{
/// <summary>
/// A class that allows watching of Registry Key values.
/// </summary>
class RegistryWatcher<T> where T : IEquatable<T>
{
private readonly string path;
private readonly string key;
private readonly List<T> defaultKey;
private ManagementEventWatcher watcher;
// returns true if the key started as defaultKey and is not modified, else false
public bool IsDefaultKey { get; private set; }
public event EventHandler<T> ValueChanged;
public RegistryWatcher(string path, string key, List<T> defaultKey)
{
this.path = path;
this.key = key;
this.defaultKey = defaultKey;
this.IsDefaultKey = true;
RegisterKeyChanged();
try
{
GetKeyAndUpdateKeyStatus();
}
catch (Exception)
{
// There is a possibility no registry entries have been created yet
}
}
/// <summary>
/// Fires the event manually
/// </summary>
public void Fire()
{
Notify();
}
public void Start()
{
watcher.Start();
}
public void Stop()
{
watcher.Stop();
}
public void SetValue(object o)
{
WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
Registry.SetValue(String.Format("{0}\\{1}", currentUser.User.Value, path), key, o);
}
private void RegisterKeyChanged()
{
WindowsIdentity currentUser = WindowsIdentity.GetCurrent();
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM RegistryValueChangeEvent WHERE " +
"Hive = 'HKEY_USERS'" +
String.Format(@"AND KeyPath = '{0}\\{1}' AND ValueName='{2}'", currentUser.User.Value, path, key));
watcher = new ManagementEventWatcher(query);
watcher.EventArrived += (object sender, EventArrivedEventArgs e) => { Notify(); };
}
private T GetKeyAndUpdateKeyStatus()
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(path))
{
object objectValue;
if (key == null || (objectValue = key.GetValue(this.key)) == null)
{
throw new Exceptions.AssumptionFailedException("Key is null");
}
T result = (T)objectValue;
IsDefaultKey &= defaultKey == null || defaultKey.Contains(result);
return result;
}
}
private void Notify()
{
try
{
T key = GetKeyAndUpdateKeyStatus();
if (IsDefaultKey)
{
return;
}
ValueChanged?.Invoke(this, key);
}
catch (Exception e)
{
Logger.LogException(e, nameof(Notify));
}
}
}
}
| PowerPointLabs/PowerPointLabs | PowerPointLabs/PowerPointLabs/Utils/RegistryWatcher.cs | C# | gpl-2.0 | 3,325 |
<?php
/**********************************************************
* Lidiun PHP Framework 4.0 - (http://www.lidiun.com)
*
* @Created in 26/08/2013
* @Author Dyon Enedi <dyonenedi@hotmail.com>
* @Modify in 04/08/2014
* @By Dyon Enedi <dyonenedi@hotmail.com>
* @Contributor Gabriela A. Ayres Garcia <gabriela.ayres.garcia@gmail.com>
* @Contributor Rodolfo Bulati <rbulati@gmail.com>
* @License: free
*
**********************************************************/
class Panel
{
public function __construct() {
}
} | dyonenedi/lidiun_history | LidiunFramework_5.0/app/repository/render/panel.php | PHP | gpl-2.0 | 550 |
<?php
$files = elgg_extract("files", $vars, array());
$folder = elgg_extract("folder", $vars);
$folder_content = elgg_view("file_tools/breadcrumb", array("entity" => $folder));
if(!($sub_folders = file_tools_get_sub_folders($folder))){
$sub_folders = array();
}
$entities = array_merge($sub_folders, $files) ;
if(!empty($entities)) {
$params = array(
"full_view" => false,
"pagination" => false
);
elgg_push_context("file_tools_selector");
$files_content = elgg_view_entity_list($entities, $params);
elgg_pop_context();
}
if(empty($files_content)){
$files_content = elgg_echo("file_tools:list:files:none");
} else {
$files_content .= "<div class='clearfix'>";
if(elgg_get_page_owner_entity()->canEdit()) {
$files_content .= '<a id="file_tools_action_bulk_delete" href="javascript:void(0);">' . elgg_echo("file_tools:list:delete_selected") . '</a> | ';
}
$files_content .= "<a id='file_tools_action_bulk_download' href='javascript:void(0);'>" . elgg_echo("file_tools:list:download_selected") . "</a>";
$files_content .= "<a id='file_tools_select_all' class='float-alt' href='javascript:void(0);'>";
$files_content .= "<span>" . elgg_echo("file_tools:list:select_all") . "</span>";
$files_content .= "<span class='hidden'>" . elgg_echo("file_tools:list:deselect_all") . "</span>";
$files_content .= "</a>";
$files_content .= "</div>";
}
$files_content .= elgg_view("graphics/ajax_loader");
?>
<div id="file_tools_list_files">
<div id="file_tools_list_files_overlay"></div>
<?php
echo $folder_content;
echo $files_content;
?>
</div>
<?php
$page_owner = elgg_get_page_owner_entity();
if($page_owner->canEdit() || (elgg_instanceof($page_owner, "group") && $page_owner->isMember())) { ?>
<script type="text/javascript">
$(function(){
$("#file_tools_list_files .file-tools-file").draggable({
revert: "invalid",
opacity: 0.8,
appendTo: "body",
helper: "clone",
start: function(event, ui) {
$(this).css("visibility", "hidden");
$(ui.helper).width($(this).width());
},
stop: function(event, ui) {
$(this).css("visibility", "visible");
}
});
$("#file_tools_list_files .file-tools-folder").droppable({
accept: "#file_tools_list_files .file-tools-file",
drop: function(event, ui){
droppable = $(this);
draggable = ui.draggable;
drop_id = droppable.parent().attr("id").split("-").pop();
drag_id = draggable.parent().attr("id").split("-").pop();
elgg.file_tools.move_file(drag_id, drop_id, draggable);
}
});
});
</script>
<?php
} | nachopavon/redprofesional | mod/file_tools/views/default/file_tools/list/files.php | PHP | gpl-2.0 | 2,690 |
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* Customers Controller
*
* @property \App\Model\Table\CustomersTable $Customers
*/
class CustomersController extends AppController
{
/**
* Index method
*
* @return void
*/
public function index()
{
$this->set('customers', $this->paginate($this->Customers));
$this->set('_serialize', ['customers']);
}
/**
* View method
*
* @param string|null $id Customer id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$customer = $this->Customers->get($id, [
'contain' => ['Orders']
]);
$this->set('customer', $customer);
$this->set('_serialize', ['customer']);
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$customer = $this->Customers->newEntity();
if ($this->request->is('post')) {
$customer = $this->Customers->patchEntity($customer, $this->request->data);
if ($this->Customers->save($customer)) {
$this->Flash->success('The customer has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The customer could not be saved. Please, try again.');
}
}
$this->set(compact('customer'));
$this->set('_serialize', ['customer']);
}
/**
* Edit method
*
* @param string|null $id Customer id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$customer = $this->Customers->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$customer = $this->Customers->patchEntity($customer, $this->request->data);
if ($this->Customers->save($customer)) {
$this->Flash->success('The customer has been saved.');
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error('The customer could not be saved. Please, try again.');
}
}
$this->set(compact('customer'));
$this->set('_serialize', ['customer']);
}
/**
* Delete method
*
* @param string|null $id Customer id.
* @return void Redirects to index.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$customer = $this->Customers->get($id);
if ($this->Customers->delete($customer)) {
$this->Flash->success('The customer has been deleted.');
} else {
$this->Flash->error('The customer could not be deleted. Please, try again.');
}
return $this->redirect(['action' => 'index']);
}
}
| thinkingwise/cakephp3crm | src/Controller/CustomersController.php | PHP | gpl-2.0 | 3,197 |
# force floating point division. Can still use integer with //
from __future__ import division
# This file is used for importing the common utilities classes.
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append("../../../../../")
from EnergyLandscapes.Lifetime_Dudko2008.Python.TestExamples.Util import \
Example_Data
def PlotFit(data,BaseName):
fig = Example_Data.PlotHistograms(data)
fig.savefig(BaseName + "_Histogram.png")
fig = Example_Data.PlotLifetimesAndFit(data)
fig.savefig(BaseName + "_Lifetimes.png")
def run():
"""
"""
# figure 1 from dudko 2008
data = Example_Data.Dudko2008Fig1_Probabilities()
PlotFit(data,"../Out/Dudko2008_Fig1")
# figure 2 frm dudko 2008
data = Example_Data.Dudko2008Fig2_Probabilities()
PlotFit(data,"../Out/Dudko2008_Fig2")
if __name__ == "__main__":
run()
| prheenan/BioModel | EnergyLandscapes/Lifetime_Dudko2008/Python/TestExamples/Examples/Example_Dudko_Fit.py | Python | gpl-2.0 | 889 |
// Wildebeest Migration Framework
// Copyright © 2013 - 2018, Matheson Ventures Pte Ltd
//
// This file is part of Wildebeest
//
// Wildebeest is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License v2 as published by the Free
// Software Foundation.
//
// Wildebeest is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
// A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with
// Wildebeest. If not, see http://www.gnu.org/licenses/gpl-2.0.html
package co.mv.wb.plugin.generaldatabase.dom;
import co.mv.wb.Asserts;
import co.mv.wb.InvalidReferenceException;
import co.mv.wb.LoaderFault;
import co.mv.wb.ModelExtensions;
import co.mv.wb.PluginBuildException;
import co.mv.wb.Resource;
import co.mv.wb.fixture.Fixtures;
import co.mv.wb.impl.ResourceTypeServiceBuilder;
import co.mv.wb.plugin.base.dom.DomPlugins;
import co.mv.wb.plugin.base.dom.DomResourceLoader;
import co.mv.wb.plugin.generaldatabase.AnsiSqlCreateDatabaseMigration;
import co.mv.wb.plugin.generaldatabase.AnsiSqlDropDatabaseMigration;
import co.mv.wb.plugin.generaldatabase.AnsiSqlTableDoesNotExistAssertion;
import co.mv.wb.plugin.generaldatabase.AnsiSqlTableExistsAssertion;
import co.mv.wb.plugin.postgresql.PostgreSqlConstants;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.util.Optional;
import java.util.UUID;
/**
* Unit tests for the DOM persistence services for ANSI SQL plugins.
*
* @since 4.0
*/
public class AnsiSqlDomServiceUnitTests
{
@Test
public void ansiSqlCreateDatabaseMigrationLoadFromValidDocument() throws
LoaderFault,
PluginBuildException,
InvalidReferenceException
{
// Setup
UUID migrationId = UUID.randomUUID();
UUID toStateId = UUID.randomUUID();
String xml = Fixtures
.resourceXmlBuilder()
.resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo")
.migration("AnsiSqlCreateDatabase", migrationId, null, toStateId.toString())
.render();
DomResourceLoader loader = DomPlugins.resourceLoader(
ResourceTypeServiceBuilder
.create()
.withFactoryResourceTypes()
.build(),
xml);
// Execute
Resource resource = loader.load(new File("."));
// Verify
Assert.assertNotNull("resource", resource);
Assert.assertEquals("resource.migrations.size", 1, resource.getMigrations().size());
AnsiSqlCreateDatabaseMigration mT = ModelExtensions.as(
resource.getMigrations().get(0),
AnsiSqlCreateDatabaseMigration.class);
Assert.assertNotNull(
"resourceWithPlugin.resource.migrations[0] expected to be of type AnsiSqlCreateDatabaseMigration",
mT);
Assert.assertEquals(
"resourceWithPlugin.resource.migrations[0].id",
migrationId,
mT.getMigrationId());
Assert.assertEquals(
"resourceWithPlugin.resource.migrations[0].fromStateId",
Optional.empty(),
mT.getFromState());
Assert.assertEquals(
"resourceWithPlugin.resource.migrations[0].toStateId",
Optional.of(toStateId.toString()),
mT.getToState());
}
@Test
public void ansiSqlDropDatabaseMigrationLoadFromValidDocument() throws
LoaderFault,
PluginBuildException,
InvalidReferenceException
{
// Setup
UUID migrationId = UUID.randomUUID();
String toState = UUID.randomUUID().toString();
String xml = Fixtures
.resourceXmlBuilder()
.resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo")
.migration("AnsiSqlDropDatabase", migrationId, null, toState.toString())
.render();
DomResourceLoader loader = DomPlugins.resourceLoader(
ResourceTypeServiceBuilder
.create()
.withFactoryResourceTypes()
.build(),
xml);
// Execute
Resource resource = loader.load(new File("."));
// Verify
Assert.assertNotNull("resource", resource);
Assert.assertEquals("resource.migrations.size", 1, resource.getMigrations().size());
AnsiSqlDropDatabaseMigration mT = ModelExtensions.as(
resource.getMigrations().get(0),
AnsiSqlDropDatabaseMigration.class);
Assert.assertNotNull("resource.migrations[0] expected to be of type AnsiSqlDropDatabaseMigration", mT);
Assert.assertEquals(
"resource.migrations[0].id",
migrationId,
mT.getMigrationId());
Assert.assertEquals(
"resource.migrations[0].fromState",
Optional.empty(),
mT.getFromState());
Assert.assertEquals(
"resource.migrations[0].toState",
Optional.of(toState),
mT.getToState());
}
@Test
public void ansiSqlTableExistsAssertionLoadFromValidDocument() throws
LoaderFault,
PluginBuildException,
InvalidReferenceException
{
// Setup
UUID assertionId = UUID.randomUUID();
String xml = Fixtures
.resourceXmlBuilder()
.resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo")
.state(UUID.randomUUID(), null)
.assertion("AnsiSqlTableExists", assertionId)
.appendInnerXml("<schemaName>sch</schemaName>")
.appendInnerXml("<tableName>tbl</tableName>")
.build();
DomResourceLoader loader = DomPlugins.resourceLoader(
ResourceTypeServiceBuilder
.create()
.withFactoryResourceTypes()
.build(),
xml);
// Execute
Resource resource = loader.load(new File("."));
// Verify
Assert.assertNotNull("resource", resource);
Assert.assertEquals("resource.states.size", 1, resource.getStates().size());
Assert.assertEquals(
"resource.states[0].assertions.size",
1,
resource.getStates().get(0).getAssertions().size());
AnsiSqlTableExistsAssertion assertionT = ModelExtensions.as(
resource.getStates().get(0).getAssertions().get(0),
AnsiSqlTableExistsAssertion.class);
Assert.assertNotNull("Expected to be an AnsiSqlTableExistsAssertion", assertionT);
Asserts.assertAnsiSqlTableExistsAssertion(
assertionId,
"sch",
"tbl",
assertionT,
"resource.states[0].assertions[0]");
}
@Test
public void ansiSqlTableDoesNotExistAssertionLoadFromValidDocument() throws
LoaderFault,
PluginBuildException,
InvalidReferenceException
{
// Setup
UUID assertionId = UUID.randomUUID();
String xml = Fixtures
.resourceXmlBuilder()
.resource(PostgreSqlConstants.PostgreSqlDatabase.getUri(), UUID.randomUUID(), "Foo")
.state(UUID.randomUUID(), null)
.assertion("AnsiSqlTableDoesNotExist", assertionId)
.appendInnerXml("<schemaName>sch</schemaName>")
.appendInnerXml("<tableName>tbl</tableName>")
.build();
DomResourceLoader loader = DomPlugins.resourceLoader(
ResourceTypeServiceBuilder
.create()
.withFactoryResourceTypes()
.build(),
xml);
// Execute
Resource resource = loader.load(new File("."));
// Verify
Assert.assertNotNull("resource", resource);
Assert.assertEquals("resource.states.size", 1, resource.getStates().size());
Assert.assertEquals(
"resource.states[0].assertions.size",
1,
resource.getStates().get(0).getAssertions().size());
AnsiSqlTableDoesNotExistAssertion assertionT = ModelExtensions.as(
resource.getStates().get(0).getAssertions().get(0),
AnsiSqlTableDoesNotExistAssertion.class);
Assert.assertNotNull("Expected to be an AnsiSqlTableDoesNotExistAssertion", assertionT);
Asserts.assertAnsiSqlTableDoesNotExistAssertion(
assertionId,
"sch",
"tbl",
assertionT,
"resource.states[0].assertions[0]");
}
}
| zendigitalstudios/wildebeest | MV.Wildebeest.Core/source/test/java/co/mv/wb/plugin/generaldatabase/dom/AnsiSqlDomServiceUnitTests.java | Java | gpl-2.0 | 7,441 |
#include <string.h>
#include <sys/time.h>
#include <sys/resource.h>
///////////////////////////////////////
// Function: trim - Remove "\n" //
///////////////////////////////////////
int trim(char *line) {
int end_pos = strlen(line) - 1;
if (line[end_pos] == '\n') {
line[end_pos] = '\0';
return 1;
}
return 0;
}
///////////////////////////////////////////////////////
// Function: get_time_cpu - Get CPU time //
///////////////////////////////////////////////////////
long get_time_cpu() {
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
return ru.ru_utime.tv_sec;
}
///////////////////////////////////////////////////////
// Function: get_time - Get time //
///////////////////////////////////////////////////////
long get_time() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec;
}
/////////////////////////////////////////
// Function: count_digit - count digit //
/////////////////////////////////////////
int count_digit(long num) {
int digit = 1;
int quotient;
quotient = int(num / 10);
while (quotient != 0) {
digit ++;
quotient = int(quotient / 10);
}
return digit;
}
//////////////////////////////////////////////////////
// Function: revcomp - convert to reverse complement//
//////////////////////////////////////////////////////
void revcomp(char* str) {
int i, len;
char c;
len = strlen(str);
for(i=0; i<len/2; i++) {
c = str[i];
str[i] = str[len-i-1];
str[len-i-1] = c;
}
for(i=0; i<len; i++) {
if (str[i] == 'A') {
str[i] = 'T';
} else if (str[i] == 'T') {
str[i] = 'A';
} else if (str[i] == 'G') {
str[i] = 'C';
} else if (str[i] == 'C') {
str[i] = 'G';
}
}
} | pfaucon/PBSIM-PacBio-Simulator | src/helpers.cpp | C++ | gpl-2.0 | 1,764 |
<?php namespace Jenssegers\Mongodb\Relations;
use MongoId;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\Collection as BaseCollection;
use Jenssegers\Mongodb\Eloquent\Collection;
abstract class EmbedsOneOrMany extends Relation {
/**
* The local key of the parent model.
*
* @var string
*/
protected $localKey;
/**
* The foreign key of the parent model.
*
* @var string
*/
protected $foreignKey;
/**
* The "name" of the relationship.
*
* @var string
*/
protected $relation;
/**
* Create a new embeds many relationship instance.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Illuminate\Database\Eloquent\Model $parent
* @param string $localKey
* @param string $foreignKey
* @param string $relation
* @return void
*/
public function __construct(Builder $query, Model $parent, Model $related, $localKey, $foreignKey, $relation)
{
$this->query = $query;
$this->parent = $parent;
$this->related = $related;
$this->localKey = $localKey;
$this->foreignKey = $foreignKey;
$this->relation = $relation;
// If this is a nested relation, we need to get the parent query instead.
if ($parentRelation = $this->getParentRelation())
{
$this->query = $parentRelation->getQuery();
}
$this->addConstraints();
}
/**
* Set the base constraints on the relation query.
*
* @return void
*/
public function addConstraints()
{
if (static::$constraints)
{
$this->query->where($this->getQualifiedParentKeyName(), '=', $this->getParentKey());
}
}
/**
* Set the constraints for an eager load of the relation.
*
* @param array $models
* @return void
*/
public function addEagerConstraints(array $models)
{
// There are no eager loading constraints.
}
/**
* Initialize the relation on a set of models.
*
* @param array $models
* @param string $relation
* @return void
*/
public function initRelation(array $models, $relation)
{
foreach ($models as $model)
{
$model->setParentRelation($this);
$model->setRelation($relation, $this->related->newCollection());
}
return $models;
}
/**
* Match the eagerly loaded results to their parents.
*
* @param array $models
* @param \Illuminate\Database\Eloquent\Collection $results
* @param string $relation
* @return array
*/
public function match(array $models, BaseCollection $results, $relation)
{
foreach ($models as $model)
{
$results = $model->$relation()->getResults();
$model->setParentRelation($this);
$model->setRelation($relation, $results);
}
return $models;
}
/**
* Shorthand to get the results of the relationship.
*
* @return Jenssegers\Mongodb\Eloquent\Collection
*/
public function get()
{
return $this->getResults();
}
/**
* Get the number of embedded models.
*
* @return int
*/
public function count()
{
return count($this->getEmbedded());
}
/**
* Attach a model instance to the parent model.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @return \Illuminate\Database\Eloquent\Model
*/
public function save(Model $model)
{
$model->setParentRelation($this);
return $model->save() ? $model : false;
}
/**
* Attach an array of models to the parent instance.
*
* @param array $models
* @return array
*/
public function saveMany(array $models)
{
array_walk($models, array($this, 'save'));
return $models;
}
/**
* Create a new instance of the related model.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model
*/
public function create(array $attributes)
{
// Here we will set the raw attributes to avoid hitting the "fill" method so
// that we do not have to worry about a mass accessor rules blocking sets
// on the models. Otherwise, some of these attributes will not get set.
$instance = $this->related->newInstance($attributes);
$instance->setParentRelation($this);
$instance->save();
return $instance;
}
/**
* Create an array of new instances of the related model.
*
* @param array $records
* @return array
*/
public function createMany(array $records)
{
$instances = array();
foreach ($records as $record)
{
$instances[] = $this->create($record);
}
return $instances;
}
/**
* Transform single ID, single Model or array of Models into an array of IDs
*
* @param mixed $ids
* @return array
*/
protected function getIdsArrayFrom($ids)
{
if ( ! is_array($ids)) $ids = array($ids);
foreach ($ids as &$id)
{
if ($id instanceof Model) $id = $id->getKey();
}
return $ids;
}
/**
* Get the embedded records array.
*
* @return array
*/
protected function getEmbedded()
{
// Get raw attributes to skip relations and accessors.
$attributes = $this->parent->getAttributes();
return isset($attributes[$this->localKey]) ? $attributes[$this->localKey] : null;
}
/**
* Set the embedded records array.
*
* @param array $records
* @return \Illuminate\Database\Eloquent\Model
*/
protected function setEmbedded($records)
{
$attributes = $this->parent->getAttributes();
$attributes[$this->localKey] = $records;
// Set raw attributes to skip mutators.
$this->parent->setRawAttributes($attributes);
// Set the relation on the parent.
return $this->parent->setRelation($this->relation, $this->getResults());
}
/**
* Get the foreign key value for the relation.
*
* @param mixed $id
* @return mixed
*/
protected function getForeignKeyValue($id)
{
if ($id instanceof Model)
{
$id = $id->getKey();
}
// Convert the id to MongoId if necessary.
return $this->getBaseQuery()->convertKey($id);
}
/**
* Convert an array of records to a Collection.
*
* @param array $records
* @return Jenssegers\Mongodb\Eloquent\Collection
*/
protected function toCollection(array $records = array())
{
$models = array();
foreach ($records as $attributes)
{
$models[] = $this->toModel($attributes);
}
if (count($models) > 0)
{
$models = $this->eagerLoadRelations($models);
}
return new Collection($models);
}
/**
* Create a related model instanced.
*
* @param array $attributes
* @return \Illuminate\Database\Eloquent\Model
*/
protected function toModel($attributes = array())
{
if (is_null($attributes)) return null;
$model = $this->related->newFromBuilder((array) $attributes);
$model->setParentRelation($this);
$model->setRelation($this->foreignKey, $this->parent);
// If you remove this, you will get segmentation faults!
$model->setHidden(array_merge($model->getHidden(), array($this->foreignKey)));
return $model;
}
/**
* Get the relation instance of the parent.
*
* @return Illuminate\Database\Eloquent\Relations\Relation
*/
protected function getParentRelation()
{
return $this->parent->getParentRelation();
}
/**
* Get the underlying query for the relation.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function getQuery()
{
// Because we are sharing this relation instance to models, we need
// to make sure we use separate query instances.
return clone $this->query;
}
/**
* Get the base query builder driving the Eloquent builder.
*
* @return \Illuminate\Database\Query\Builder
*/
public function getBaseQuery()
{
// Because we are sharing this relation instance to models, we need
// to make sure we use separate query instances.
return clone $this->query->getQuery();
}
/**
* Check if this relation is nested in another relation.
*
* @return boolean
*/
protected function isNested()
{
return $this->getParentRelation() != null;
}
/**
* Get the fully qualified local key name.
*
* @return string
*/
protected function getPathHierarchy($glue = '.')
{
if ($parentRelation = $this->getParentRelation())
{
return $parentRelation->getPathHierarchy($glue) . $glue . $this->localKey;
}
return $this->localKey;
}
/**
* Get the parent's fully qualified key name.
*
* @return string
*/
protected function getQualifiedParentKeyName()
{
if ($parentRelation = $this->getParentRelation())
{
return $parentRelation->getPathHierarchy() . '.' . $this->parent->getKeyName();
}
return $this->parent->getKeyName();
}
/**
* Get the primary key value of the parent.
*
* @return string
*/
protected function getParentKey()
{
return $this->parent->getKey();
}
}
| walcott911/easymart | vendor/jenssegers/mongodb/src/Jenssegers/Mongodb/Relations/EmbedsOneOrMany.php | PHP | gpl-2.0 | 9,965 |
require 'spec_helper'
feature "Searching Entities" do
include CurbHelpers
include SearchHelpers
scenario 'entities are found by name', js: true, search: true do
entity = create(:entity, :with_parent, name: 'Foo bar')
index_changed_models
expect_entity_api_search_to_find('bar') do|json|
json_item = json['entities'].first
expect(json_item).to have_key('id').with_value(entity.id.to_s)
%w(parent_id name country_code url).each do |key|
expect(json_item).to have_key(key).with_value(entity.send(key.to_sym))
end
%w(address_line_1 address_line_2 state phone email city).each do |key|
expect(json_item).not_to have_key(key)
end
end
end
scenario 'the results have relevant metadata', js: true, search: true do
entity = create(:entity, name: 'Foo bar')
index_changed_models
expect_entity_api_search_to_find('bar') do|json|
metadata = json['meta']
expect(metadata).to have_key('current_page').with_value(1)
expect(metadata).to have_key('query').with_value("term" => "bar")
end
end
def expect_entity_api_search_to_find(term, options = {})
sleep 1
with_curb_get_for_json(
"entities/search.json",
options.merge(term: term)) do |curb|
json = JSON.parse(curb.body_str)
yield(json) if block_given?
end
end
end
| Domenoth/chillingeffects | spec/integration/entity_search_spec.rb | Ruby | gpl-2.0 | 1,365 |
<?
if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","user","password"); // your MySQL connection data
$db = mysql_select_db("DATABASENAME"); //put your database name in here
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM USERS WHERE login='$name'");
?>
| Tieks/php-login | connect.php | PHP | gpl-2.0 | 286 |
<?php
namespace Dennis\Tournament\Domain\Model;
/***************************************************************
*
* Copyright notice
*
* (c) 2014
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* Class PlayerKo
*
* @package Dennis\Tournament\Domain\Model
*/
class PlayerKo extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity {
/**
* name
*
* @var string
*/
protected $name = '';
/**
* Returns the name
*
* @return string $name
*/
public function getName() {
return $this->name;
}
/**
* Sets the name
*
* @param string $name
* @return self
*/
public function setName($name) {
$this->name = $name;
return $this;
}
}
| TildBJ/tournament | Classes/Domain/Model/PlayerKo.php | PHP | gpl-2.0 | 1,453 |
//
// --------------------------------------------------------------------------
// Gurux Ltd
//
//
//
// Filename: $HeadURL$
//
// Version: $Revision$,
// $Date$
// $Author$
//
// Copyright (c) Gurux Ltd
//
//---------------------------------------------------------------------------
//
// DESCRIPTION
//
// This file is a part of Gurux Device Framework.
//
// Gurux Device Framework is Open Source software; you can redistribute it
// and/or modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; version 2 of the License.
// Gurux Device Framework is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// More information of Gurux products: https://www.gurux.org
//
// This code is licensed under the GNU General Public License v2.
// Full text may be retrieved at http://www.gnu.org/licenses/gpl-2.0.txt
//---------------------------------------------------------------------------
using Gurux.DLMS.Internal;
using Gurux.DLMS.Plc;
using Gurux.DLMS.Plc.Enums;
using System;
using System.Collections.Generic;
namespace Gurux.DLMS
{
/// <summary>
/// PLC communication settings.
/// </summary>
public class GXPlcSettings
{
byte[] _systemTitle;
private GXDLMSSettings settings;
/// <summary>
/// Initial credit (IC) tells how many times the frame must be repeated. Maximum value is 7.
/// </summary>
public byte InitialCredit
{
get;
set;
}
/// <summary>
/// The current credit (CC) initial value equal to IC and automatically decremented by the MAC layer after each repetition.
/// Maximum value is 7.
/// </summary>
public byte CurrentCredit
{
get;
set;
}
/// <summary>
/// Delta credit (DC) is used by the system management application entity
/// (SMAE) of the Client for credit management, while it has no meaning for a Server or a REPEATER.
/// It represents the difference(IC-CC) of the last communication originated by the system identified by the DA address to the system identified by the SA address.
/// Maximum value is 3.
/// </summary>
public byte DeltaCredit
{
get;
set;
}
/// <summary>
/// IEC 61334-4-32 LLC uses 6 bytes long system title. IEC 61334-5-1 uses 8 bytes long system title so we can use the default one.
/// </summary>
public byte[] SystemTitle
{
get
{
if (settings != null && settings.InterfaceType != Enums.InterfaceType.Plc && settings.Cipher != null)
{
return settings.Cipher.SystemTitle;
}
return _systemTitle;
}
set
{
if (settings != null && settings.InterfaceType != Enums.InterfaceType.Plc && settings.Cipher != null)
{
settings.Cipher.SystemTitle = value;
}
_systemTitle = value;
}
}
/// <summary>
/// Source MAC address.
/// </summary>
public UInt16 MacSourceAddress
{
get;
set;
}
/// <summary>
/// Destination MAC address.
/// </summary>
public UInt16 MacDestinationAddress
{
get;
set;
}
/// <summary>
/// Response probability.
/// </summary>
public byte ResponseProbability
{
get;
set;
}
/// <summary>
/// Allowed time slots.
/// </summary>
public UInt16 AllowedTimeSlots
{
get;
set;
}
/// <summary>
/// Server saves client system title.
/// </summary>
public byte[] ClientSystemTitle
{
get;
set;
}
/// <summary>
/// Set default values.
/// </summary>
public void Reset()
{
InitialCredit = 7;
CurrentCredit = 7;
DeltaCredit = 0;
//New device addresses are used.
if (settings.InterfaceType == Enums.InterfaceType.Plc)
{
if (settings.IsServer)
{
MacSourceAddress = (UInt16)PlcSourceAddress.New;
MacDestinationAddress = (UInt16)PlcSourceAddress.Initiator;
}
else
{
MacSourceAddress = (UInt16)PlcSourceAddress.Initiator;
MacDestinationAddress = (UInt16)PlcDestinationAddress.AllPhysical;
}
}
else
{
if (settings.IsServer)
{
MacSourceAddress = (UInt16)PlcSourceAddress.New;
MacDestinationAddress = (UInt16)PlcHdlcSourceAddress.Initiator;
}
else
{
MacSourceAddress = (UInt16)PlcHdlcSourceAddress.Initiator;
MacDestinationAddress = (UInt16)PlcDestinationAddress.AllPhysical;
}
}
ResponseProbability = 100;
if (settings.InterfaceType == Enums.InterfaceType.Plc)
{
AllowedTimeSlots = 10;
}
else
{
AllowedTimeSlots = 0x14;
}
}
internal GXPlcSettings(GXDLMSSettings s)
{
settings = s;
Reset();
}
/// <summary>
/// Discover available PLC meters.
/// </summary>
/// <returns>Generated bytes.</returns>
public byte[] DiscoverRequest()
{
GXByteBuffer bb = new GXByteBuffer();
if (settings.InterfaceType != Enums.InterfaceType.Plc &&
settings.InterfaceType != Enums.InterfaceType.PlcHdlc)
{
throw new ArgumentOutOfRangeException("Invalid interface type.");
}
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
bb.Set(GXCommon.LLCSendBytes);
}
bb.SetUInt8((byte)Command.DiscoverRequest);
bb.SetUInt8(ResponseProbability);
bb.SetUInt16(AllowedTimeSlots);
//DiscoverReport initial credit
bb.SetUInt8(0);
// IC Equal credit
bb.SetUInt8(0);
int val = 0;
int clientAddress = settings.ClientAddress;
int serverAddress = settings.ServerAddress;
UInt16 da = settings.Plc.MacDestinationAddress;
UInt16 sa = settings.Plc.MacSourceAddress;
try
{
//10.4.6.4 Source and destination APs and addresses of CI-PDUs
//Client address is No-station in discoverReport.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
settings.Plc.InitialCredit = 0;
settings.Plc.CurrentCredit = 0;
settings.Plc.MacSourceAddress = 0xC01;
settings.Plc.MacDestinationAddress = 0xFFF;
settings.ClientAddress = 0x66;
// All-station
settings.ServerAddress = 0x33FF;
}
else
{
val = settings.Plc.InitialCredit << 5;
val |= settings.Plc.CurrentCredit << 2;
val |= settings.Plc.DeltaCredit & 0x3;
settings.Plc.MacSourceAddress = 0xC00;
settings.ClientAddress = 1;
settings.ServerAddress = 0;
}
return GXDLMS.GetMacFrame(settings, 0x13, (byte)val, bb);
}
finally
{
settings.ClientAddress = clientAddress;
settings.ServerAddress = serverAddress;
settings.Plc.MacDestinationAddress = da;
settings.Plc.MacSourceAddress = sa;
}
}
/// <summary>
/// Generates discover report.
/// </summary>
/// <param name="systemTitle">System title</param>
/// <param name="newMeter">Is this a new meter.</param>
/// <returns>Generated bytes.</returns>
public byte[] DiscoverReport(byte[] systemTitle, bool newMeter)
{
GXByteBuffer bb = new GXByteBuffer();
if (settings.InterfaceType != Enums.InterfaceType.Plc &&
settings.InterfaceType != Enums.InterfaceType.PlcHdlc)
{
throw new ArgumentOutOfRangeException("Invalid interface type.");
}
byte alarmDescription;
if (settings.InterfaceType == Enums.InterfaceType.Plc)
{
alarmDescription = (byte)(newMeter ? 1 : 0x82);
}
else
{
alarmDescription = 0;
}
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
bb.Set(GXCommon.LLCReplyBytes);
}
bb.SetUInt8((byte)Command.DiscoverReport);
bb.SetUInt8(1);
bb.Set(systemTitle);
if (alarmDescription != 0)
{
bb.SetUInt8(1);
}
bb.SetUInt8(alarmDescription);
int clientAddress = settings.ClientAddress;
int serverAddress = settings.ServerAddress;
UInt16 macSourceAddress = settings.Plc.MacSourceAddress;
UInt16 macTargetAddress = settings.Plc.MacDestinationAddress;
try
{
//10.4.6.4 Source and destination APs and addresses of CI-PDUs
//Client address is No-station in discoverReport.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
settings.Plc.MacDestinationAddress = (UInt16) PlcHdlcSourceAddress.Initiator;
}
else
{
settings.ClientAddress = 0;
settings.ServerAddress = 0xFD;
}
return GXDLMS.GetMacFrame(settings, 0x13, 0, bb);
}
finally
{
settings.ClientAddress = clientAddress;
settings.ServerAddress = serverAddress;
settings.Plc.MacSourceAddress = macSourceAddress;
settings.Plc.MacDestinationAddress = macTargetAddress;
}
}
/// <summary>
/// Parse discover reply.
/// </summary>
/// <param name="value"></param>
/// <returns>Array of system titles and alarm descriptor error code</returns>
public List<GXDLMSPlcMeterInfo> ParseDiscover(GXByteBuffer value, UInt16 sa, UInt16 da)
{
List<GXDLMSPlcMeterInfo> list = new List<GXDLMSPlcMeterInfo>();
byte count = value.GetUInt8();
for (int pos = 0; pos != count; ++pos)
{
GXDLMSPlcMeterInfo info = new GXDLMSPlcMeterInfo();
info.SourceAddress = sa;
info.DestinationAddress = da;
//Get System title.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
info.SystemTitle = new byte[8];
}
else
{
info.SystemTitle = new byte[6];
}
value.Get(info.SystemTitle);
// Alarm descriptor of the reporting system.
// Alarm-Descriptor presence flag
if (value.GetUInt8() != 0)
{
//Alarm-Descriptor
info.AlarmDescriptor = value.GetUInt8();
}
list.Add(info);
}
return list;
}
/// <summary>
/// Register PLC meters.
/// </summary>
/// <param name="initiatorSystemTitle">Active initiator systemtitle</param>
/// <param name="systemTitle"></param>
/// <returns>Generated bytes.</returns>
public byte[] RegisterRequest(byte[] initiatorSystemTitle, byte[] systemTitle)
{
GXByteBuffer bb = new GXByteBuffer();
//Control byte.
bb.SetUInt8((byte)Command.RegisterRequest);
bb.Set(initiatorSystemTitle);
//LEN
bb.SetUInt8(0x1);
bb.Set(systemTitle);
//MAC address.
bb.SetUInt16(MacSourceAddress);
int val = settings.Plc.InitialCredit << 5;
val |= settings.Plc.CurrentCredit << 2;
val |= settings.Plc.DeltaCredit & 0x3;
int clientAddress = settings.ClientAddress;
int serverAddress = settings.ServerAddress;
UInt16 macSourceAddress = settings.Plc.MacSourceAddress;
UInt16 macTargetAddress = settings.Plc.MacDestinationAddress;
try
{
//10.4.6.4 Source and destination APs and addresses of CI-PDUs
//Client address is No-station in discoverReport.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
settings.Plc.InitialCredit = 0;
settings.Plc.CurrentCredit = 0;
settings.Plc.MacSourceAddress = 0xC01;
settings.Plc.MacDestinationAddress = 0xFFF;
settings.ClientAddress = 0x66;
// All-station
settings.ServerAddress = 0x33FF;
}
else
{
settings.ClientAddress = 1;
settings.ServerAddress = 0;
settings.Plc.MacSourceAddress = 0xC00;
settings.Plc.MacDestinationAddress = 0xFFF;
}
return GXDLMS.GetMacFrame(settings, 0x13, (byte)val, bb);
}
finally
{
settings.ClientAddress = clientAddress;
settings.ServerAddress = serverAddress;
settings.Plc.MacSourceAddress = macSourceAddress;
settings.Plc.MacDestinationAddress = macTargetAddress;
}
}
/// <summary>
/// Parse register request.
/// </summary>
/// <param name="value"></param>
/// <returns>System title mac address.</returns>
public void ParseRegisterRequest(GXByteBuffer value)
{
//Get System title.
byte[] st;
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
st = new byte[8];
}
else
{
st = new byte[6];
}
value.Get(st);
byte count = value.GetUInt8();
for (int pos = 0; pos != count; ++pos)
{
//Get System title.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
st = new byte[8];
}
else
{
st = new byte[6];
}
value.Get(st);
SystemTitle = st;
//MAC address.
MacSourceAddress = value.GetUInt16();
}
}
/// <summary>
/// Parse discover request.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public GXDLMSPlcRegister ParseDiscoverRequest(GXByteBuffer value)
{
GXDLMSPlcRegister ret = new GXDLMSPlcRegister();
ret.ResponseProbability = value.GetUInt8();
ret.AllowedTimeSlots = value.GetUInt16();
ret.DiscoverReportInitialCredit = value.GetUInt8();
ret.ICEqualCredit = value.GetUInt8();
return ret;
}
/// <summary>
/// Ping PLC meter.
/// </summary>
/// <returns>Generated bytes.</returns>
public byte[] PingRequest(byte[] systemTitle)
{
GXByteBuffer bb = new GXByteBuffer();
//Control byte.
bb.SetUInt8((byte)Command.PingRequest);
bb.Set(systemTitle);
return GXDLMS.GetMacFrame(settings, 0x13, 0, bb);
}
/// <summary>
/// Parse ping response.
/// </summary>
/// <param name="value">Received data.</param>
public byte[] ParsePing(GXByteBuffer value)
{
return value.SubArray(1, 6);
}
/// <summary>
/// Repear call request.
/// </summary>
/// <returns>Generated bytes.</returns>
public byte[] RepeaterCallRequest()
{
GXByteBuffer bb = new GXByteBuffer();
//Control byte.
bb.SetUInt8((byte)Command.RepeatCallRequest);
//MaxAdrMac.
bb.SetUInt16(0x63);
//Nb_Tslot_For_New
bb.SetUInt8(0);
//Reception-Threshold default value
bb.SetUInt8(0);
return GXDLMS.GetMacFrame(settings, 0x13, 0xFC, bb);
}
}
} | Gurux/Gurux.DLMS.Net | Development/Plc/GXPlcSettings.cs | C# | gpl-2.0 | 17,732 |
<?php
// flush output buffer
die(json_encode(array(
'variables' => $variables,
'content' => render($page['content']) . render($page['content_bottom']),
)));
?> | mandelbro/Overlay-CMS | sites/all/themes/ursaminor/page--json.tpl.php | PHP | gpl-2.0 | 167 |
<?php
$logo = get_option('custom_logo', EBOR_THEME_DIRECTORY . 'style/img/logo-dark.png');
$logo_light = get_option('custom_logo_light', EBOR_THEME_DIRECTORY . 'style/img/logo-light.png');
?>
<div class="nav-container">
<a id="top"></a>
<nav class="nav-centered">
<?php get_template_part('inc/content-header','utility'); ?>
<div class="text-center">
<a href="<?php echo esc_url(home_url('/')); ?>">
<img class="logo logo-light" alt="<?php echo esc_attr(get_bloginfo('title')); ?>" src="<?php echo esc_url($logo_light); ?>" />
<img class="logo logo-dark" alt="<?php echo esc_attr(get_bloginfo('title')); ?>" src="<?php echo esc_url($logo); ?>" />
</a>
</div>
<div class="nav-bar text-center">
<div class="module widget-handle mobile-toggle right visible-sm visible-xs">
<i class="ti-menu"></i>
</div>
<div class="module-group text-left">
<div class="module left">
<?php
if ( has_nav_menu( 'primary' ) ){
wp_nav_menu(
array(
'theme_location' => 'primary',
'depth' => 3,
'container' => false,
'container_class' => false,
'menu_class' => 'menu',
'fallback_cb' => 'wp_bootstrap_navwalker::fallback',
'walker' => new ebor_framework_medium_rare_bootstrap_navwalker()
)
);
} else {
echo '<ul class="menu"><li><a href="'. admin_url('nav-menus.php') .'">Set up a navigation menu now</a></li></ul>';
}
?>
</div>
<?php
if( 'yes' == get_option('foundry_header_social', 'no') ){
get_template_part('inc/content-header', 'social');
}
if( 'yes' == get_option('foundry_header_button', 'no') ){
get_template_part('inc/content-header', 'button');
}
if( 'yes' == get_option('foundry_header_search', 'yes') ){
get_template_part('inc/content-header', 'search');
}
if( class_exists('Woocommerce') && 'yes' == get_option('foundry_header_cart', 'yes') ){
get_template_part('inc/content-header', 'cart');
}
if( function_exists('icl_get_languages') && 'yes' == get_option('foundry_header_wpml', 'yes') ){
get_template_part('inc/content-header', 'wpml');
}
?>
</div>
</div>
</nav>
</div> | seyekuyinu/highlifer | wp-content/themes/highlifer/inc/content-nav-centered.php | PHP | gpl-2.0 | 3,130 |
<?php
/*
Copyright (c) 2007 BeVolunteer
This file is part of BW Rox.
BW Rox is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
BW Rox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/> or
write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
$words = new MOD_words();
?>
<div id="tour">
<h1><?php echo $words->get('tour_maps')?></h1>
<h2><?php echo $words->getFormatted('tour_maps_title1')?></h2>
<p><?php echo $words->getFormatted('tour_maps_text1')?></p>
<div class="floatbox">
<img src="images/tour/map2.png" class="float_left" alt="maps" />
<h2><?php echo $words->getFormatted('tour_maps_title2')?></h2>
<p><?php echo $words->getFormatted('tour_maps_text2')?></p>
</div>
<h2><?php echo $words->getFormatted('tour_maps_title3')?></h2>
<p><?php echo $words->getFormatted('tour_maps_text3')?></p>
<h2><a class="bigbutton" href="tour/openness" onclick="this.blur();" style="margin-bottom: 20px"><span><?php echo $words->getFormatted('tour_goNext')?> »</span></a> <?php echo $words->getFormatted('tour_openness')?></h2>
</div>
| BeWelcome/rox.prototypes | build/tour/templates/tourpage6.php | PHP | gpl-2.0 | 1,630 |
package app.toonido.mindorks.toonido;
import android.app.Application;
import com.parse.Parse;
/**
* Created by janisharali on 30/09/15.
*/
public class ToonidoApp extends Application {
@Override
public void onCreate() {
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
Parse.initialize(this, ToonidoConstants.PARSE_APPLICATION_ID, ToonidoConstants.PARSE_CLIENT_KEY);
}
}
| mindorks/Toonido | Toonido/app/src/main/java/app/toonido/mindorks/toonido/ToonidoApp.java | Java | gpl-2.0 | 451 |
<?php
global $post, $sc_post_class;
$post_id = $post->ID;
$post_obj = new sc_post($post_id);
$post_comments = get_comments_number( $post_id );
?>
<!--item-->
<div class="entry <?php echo esc_attr( $sc_post_class ); ?> post-item">
<?php
$main_image = $post_obj->get_main_image('thumb-image');
if (!empty( $main_image ) ) { ?>
<figure>
<img src="<?php echo esc_url ( $main_image ); ?>" alt="<?php the_title(); ?>" />
<figcaption><a href="<?php echo esc_url ( $post_obj->get_permalink() ); ?>"><i class="ico eldorado_eyelash"></i> <span><?php _e('View post', 'socialchef'); ?></span></a></figcaption>
</figure>
<?php } ?>
<div class="container">
<h2><a href="<?php echo esc_url ( $post_obj->get_permalink() ); ?>"><?php the_title(); ?></a></h2>
<div class="actions">
<div>
<div class="date"><i class="ico eldorado_calendar_1"></i><?php the_time('F j, Y'); ?></div>
<div class="comments"><i class="ico eldorado_comment_baloon"></i><a href="<?php echo esc_url ( $post_obj->get_permalink() ); ?>#comments"><?php echo $post_comments; ?></a></div>
</div>
</div>
<div class="excerpt">
<?php the_excerpt(); ?>
</div>
</div>
</div>
<!--item--> | foodiedaily/tts | wp-content/themes/SocialChef/includes/parts/post-item.php | PHP | gpl-2.0 | 1,175 |
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2020 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
include ('../inc/includes.php');
Session::checkRight("reports", READ);
Html::header(Report::getTypeName(Session::getPluralNumber()), $_SERVER['PHP_SELF'], "tools", "report");
Report::title();
// Titre
echo "<form name='form' method='post' action='report.year.list.php'>";
echo "<table class='tab_cadre_fixe'>";
echo "<tr><th colspan='4'>".__("Equipment's report by year")."</th></tr>";
// 3. Selection d'affichage pour generer la liste
echo "<tr class='tab_bg_2'>";
echo "<td width='20%' class='b center'>".__('Item type')."</td>";
echo "<td width='30%'>";
$values = [0 => __('All')];
foreach ($CFG_GLPI["contract_types"] as $itemtype) {
if ($item = getItemForItemtype($itemtype)) {
$values[$itemtype] = $item->getTypeName();
}
}
Dropdown::showFromArray('item_type', $values, ['value' => 0,
'multiple' => true]);
echo "</td>";
echo "<td width='20%' class='center'><p class='b'>"._n('Date', 'Dates', 1)."</p></td>";
echo "<td width='30%'>";
$y = date("Y");
$values = [ 0 => __('All')];
for ($i=($y-10); $i<($y+10); $i++) {
$values[$i] = $i;
}
Dropdown::showFromArray('year', $values, ['value' => $y,
'multiple' => true]);
echo "</td></tr>";
echo "<tr class='tab_bg_2'><td colspan='4' class='center'>";
echo "<input type='submit' value=\"".__s('Display report')."\" class='submit'></td></tr>";
echo "</table>";
Html::closeForm();
Html::footer();
| edgardmessias/glpi | front/report.year.php | PHP | gpl-2.0 | 2,639 |
<div id="roomTitle">Welcome to Agavi :: home of the convention nazis :: 911GT2 coming soon :: http://www.agavi.org :: http://svn.agavi.org/branches/0.11/ if you want to use SVN (don't use trunk, earth will explode) :: Have a question? Just ask it, and wait patiently, because patience is the key to happiness :: We're looking for documentation contributors and developers :: http://trac.agavi.org/milestone/0.11 :: irc logs http://users.tkk.fi/~tjorri/agavi/logs</div>
<div id="watermark" class="transparent50"></div>
<div id="messages">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="name"><a href="info">RossC0</a></td>
<td class="message">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed eget nulla in lacus suscipit mattis. Vivamus non metus. Pellentesque eu urna sed pede dictum vulputate. Quisque enim nibh, vehicula ac, accumsan nec, sagittis aliquam, enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla vitae nulla quis est mollis vulputate. Sed lacinia volutpat eros. Mauris cursus dui et nibh. Vestibulum erat nisi, ornare et, adipiscing nec, interdum ut, turpis. Nulla facilisi. Quisque tincidunt est. Etiam gravida pede vestibulum tellus. Vivamus sit amet leo. Integer hendrerit. Fusce et nisl nec ante aliquam vehicula. Etiam pretium tincidunt velit.</td>
<td class="time">00:16</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">kaos|work</a></td>
<td class="message">oh, and it would be cool if there was an easy way injecting my own code in every receive</td>
<td class="time">00:28</td>
</tr>
<tr>
<td class="message">or something which gets called in a regular timeframe</td>
<td class="time">00:29</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">impl</a></td>
<td class="message">timers</td>
<td class="time">00:29</td>
</tr>
<tr class="action">
<td class="message">got it</td>
<td class="time">00:29</td>
</tr>
<tr class="self">
<td class="name"><a href="info">Wombert</a></td>
<td class="message">is that so?</td>
<td class="time">00:32</td>
</tr>
<tr class="highlight">
<td class="name"><a href="info">v-dogg</a></td>
<td class="message">Wombert Zombert :)</td>
<td class="time">00:33</td>
</tr>
<tr>
<td class="name"><a href="info">RossC0</a></td>
<td class="message">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed eget nulla in lacus suscipit mattis. Vivamus non metus. Pellentesque eu urna sed pede dictum vulputate. Quisque enim nibh, vehicula ac, accumsan nec, sagittis aliquam, enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla vitae nulla quis est mollis vulputate. Sed lacinia volutpat eros. Mauris cursus dui et nibh. Vestibulum erat nisi, ornare et, adipiscing nec, interdum ut, turpis. Nulla facilisi. Quisque tincidunt est. Etiam gravida pede vestibulum tellus. Vivamus sit amet leo. Integer hendrerit. Fusce et nisl nec ante aliquam vehicula. Etiam pretium tincidunt velit.</td>
<td class="time">00:16</td>
</tr>
<tr class="event">
<td class="name"><a href="info">kaos|work</a></td>
<td class="message">has joined the channel</td>
<td class="time">00:23</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">kaos|work</a></td>
<td class="message">oh, and it would be cool if there was an easy way injecting my own code in every receive</td>
<td class="time">00:28</td>
</tr>
<tr>
<td class="message">or something which gets called in a regular timeframe</td>
<td class="time">00:29</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">impl</a></td>
<td class="message">timers</td>
<td class="time">00:29</td>
</tr>
<tr>
<td class="message">got it</td>
<td class="time">00:29</td>
</tr>
<tr class="self">
<td class="name"><a href="info">Wombert</a></td>
<td class="message">is that so?</td>
<td class="time">00:32</td>
</tr>
<tr class="highlight">
<td class="name"><a href="info">v-dogg</a></td>
<td class="message">Wombert Zombert :)</td>
<td class="time">00:33</td>
</tr>
<tr>
<td class="name"><a href="info">RossC0</a></td>
<td class="message">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed eget nulla in lacus suscipit mattis. Vivamus non metus. Pellentesque eu urna sed pede dictum vulputate. Quisque enim nibh, vehicula ac, accumsan nec, sagittis aliquam, enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla vitae nulla quis est mollis vulputate. Sed lacinia volutpat eros. Mauris cursus dui et nibh. Vestibulum erat nisi, ornare et, adipiscing nec, interdum ut, turpis. Nulla facilisi. Quisque tincidunt est. Etiam gravida pede vestibulum tellus. Vivamus sit amet leo. Integer hendrerit. Fusce et nisl nec ante aliquam vehicula. Etiam pretium tincidunt velit.</td>
<td class="time">00:16</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">kaos|work</a></td>
<td class="message">oh, and it would be cool if there was an easy way injecting my own code in every receive</td>
<td class="time">00:28</td>
</tr>
<tr>
<td class="message">or something which gets called in a regular timeframe</td>
<td class="time">00:29</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">impl</a></td>
<td class="message">timers</td>
<td class="time">00:29</td>
</tr>
<tr>
<td class="message">got it</td>
<td class="time">00:29</td>
</tr>
<tr class="self">
<td class="name"><a href="info">Wombert</a></td>
<td class="message">is that so?</td>
<td class="time">00:32</td>
</tr>
<tr class="highlight">
<td class="name"><a href="info">v-dogg</a></td>
<td class="message">Wombert Zombert :)</td>
<td class="time">00:33</td>
</tr>
<tr>
<td class="name"><a href="info">RossC0</a></td>
<td class="message">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed eget nulla in lacus suscipit mattis. Vivamus non metus. Pellentesque eu urna sed pede dictum vulputate. Quisque enim nibh, vehicula ac, accumsan nec, sagittis aliquam, enim. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla vitae nulla quis est mollis vulputate. Sed lacinia volutpat eros. Mauris cursus dui et nibh. Vestibulum erat nisi, ornare et, adipiscing nec, interdum ut, turpis. Nulla facilisi. Quisque tincidunt est. Etiam gravida pede vestibulum tellus. Vivamus sit amet leo. Integer hendrerit. Fusce et nisl nec ante aliquam vehicula. Etiam pretium tincidunt velit.</td>
<td class="time">00:16</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">kaos|work</a></td>
<td class="message">oh, and it would be cool if there was an easy way injecting my own code in every receive</td>
<td class="time">00:28</td>
</tr>
<tr>
<td class="message">or something which gets called in a regular timeframe</td>
<td class="time">00:29</td>
</tr>
<tr>
<td class="name" rowspan="2"><a href="info">impl</a></td>
<td class="message">timers</td>
<td class="time">00:29</td>
</tr>
<tr>
<td class="message">got it</td>
<td class="time">00:29</td>
</tr>
<tr class="self">
<td class="name"><a href="info">Wombert</a></td>
<td class="message">is that so?</td>
<td class="time">00:32</td>
</tr>
<tr class="highlight">
<td class="name"><a href="info">v-dogg</a></td>
<td class="message">Wombert Zombert :)</td>
<td class="time">00:33</td>
</tr>
</table>
</div>
| dzuelke/Chuckwalla | app/modules/Web/templates/IndexSuccess.php | PHP | gpl-2.0 | 7,471 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.androidtweak.inputmethod.myanmar;
import android.content.Context;
import com.androidtweak.inputmethod.keyboard.ProximityInfo;
public class SynchronouslyLoadedUserBinaryDictionary extends UserBinaryDictionary {
public SynchronouslyLoadedUserBinaryDictionary(final Context context, final String locale) {
this(context, locale, false);
}
public SynchronouslyLoadedUserBinaryDictionary(final Context context, final String locale,
final boolean alsoUseMoreRestrictiveLocales) {
super(context, locale, alsoUseMoreRestrictiveLocales);
}
@Override
public synchronized void getWords(final WordComposer codes,
final CharSequence prevWordForBigrams, final WordCallback callback,
final ProximityInfo proximityInfo) {
syncReloadDictionaryIfRequired();
getWordsInner(codes, prevWordForBigrams, callback, proximityInfo);
}
@Override
public synchronized boolean isValidWord(CharSequence word) {
syncReloadDictionaryIfRequired();
return isValidWordInner(word);
}
}
| soeminnminn/MyanmarIME | src/com/androidtweak/inputmethod/myanmar/SynchronouslyLoadedUserBinaryDictionary.java | Java | gpl-2.0 | 1,712 |
<div class="row">
<div class="col-sm-12">
<div class="row">
<div class="text-center">
<h1 class="tada animated font-xl ">
<span style="position: relative;">
<i class="fa fa-play fa-rotate-90 fa-border fa-4x"></i>
<span>
<?php if($updated): ?>
<b style="position:absolute; right: -30px; top:-10" class="badge bg-color-green font-md"><i class="fa fa-check txt-color-black"></i> </b>
<?php else: ?>
<b style="position:absolute; right: -30px; top:-10" class="badge bg-color-red font-md"><i class="fa fa-refresh error"></i></b>
<?php endif; ?>
</span>
</span>
</h1>
<?php if($updated): ?>
<h2 class="font-xl"><strong>Great! Your FABtotum Personal Fabricator is up to date</strong></h2>
<?php else: ?>
<h2 class="font-xl title"><strong> New important software updates are now available</strong></h2>
<button id="update" class="btn btn-lg bg-color-red txt-color-white">Update now!</button>
<p class="lead semi-bold">
<small class="off-message hidden">Please don't turn off the printer until the operation is completed</small>
</p>
<button data-toggle="modal" data-backdrop="static" data-target="#modal" class="btn btn-xs bg-color-blue txt-color-white " style=""> See what's new!</button>
<?php endif; ?>
</div>
</div>
<?php if(!$updated): ?>
<div class="row">
<div class="col-sm-12">
<div class="text-center margin-top-10">
<div class="well mini">
<p class="text-left">
<span class="download-info">Downloading update files</span> <span class="pull-right"> <span class="percent"></span> </span>
</p>
<div class="progress">
<div class="progress progress-striped">
<div class="progress-bar download-progress bg-color-blue" role="progressbar" style="width: 0%"></div>
</div>
</div>
</div>
<button id="cancel" class="btn btn-lg bg-color-red txt-color-white"> Cancel</button>
</div>
</div>
</div>
<?php endif; ?>
</div>
</div>
<?php if(!$updated): ?>
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 class="modal-title" id="myModalLabel">FABUI v.<?php echo $remote_version; ?> Changelog</h4>
</div>
<div class="modal-body no-padding">
<?php echo fabui_changelog($remote_version) ?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">OK</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
<?php endif; ?> | FABtotum/FAB-UI | fabui/application/modules/updates/views/index/index.php | PHP | gpl-2.0 | 2,891 |
<h2 class="page-header"><a href="<?= $Page->Url ?>"><?= $Page->Title ?></a></h2>
<?= $Page->Content ?>
| sukovanej/Bundle | func/defaults/page_single.php | PHP | gpl-2.0 | 103 |
<?
session_start();
session_destroy();
header("Location: ../index.html");
?>
| EverywhereHouseControl/ServerBackEnd | LoginPro/php/salir.php | PHP | gpl-2.0 | 82 |
<link rel="stylesheet" type="text/css" href="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/css/jquery.jscrollpane.custom.css" />
<link rel="stylesheet" type="text/css" href="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/css/bookblock.css" />
<link rel="stylesheet" type="text/css" href="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/css/custom.css" />
<script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/modernizr.custom.79639.js"></script>
<div id="container" class="container">
<div class="menu-panel">
<h3>Table of Contents</h3>
<ul id="menu-toc" class="menu-toc">
<?php print $menu_items; ?>
</ul>
</div>
<div class="bb-custom-wrapper">
<div id="bb-bookblock" class="bb-bookblock">
<?php print $item_content; ?>
</div>
<nav>
<span id="bb-nav-prev">←</span>
<span id="bb-nav-next">→</span>
</nav>
<span id="tblcontents" class="menu-button">Table of Contents</span>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquery.mousewheel.js"></script>
<script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquery.jscrollpane.min.js"></script>
<script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquerypp.custom.js"></script>
<script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/jquery.bookblock.js"></script>
<script src="/dxf/<?php echo drupal_get_path('theme', 'dxf') ?>/js/page.js"></script>
<script>
$(function() {
Page.init();
});
</script> | aaronday/dxf | sites/all/modules/dxf_general/templates/foot_print_view.tpl.php | PHP | gpl-2.0 | 1,690 |
require 'rails_helper'
def topics_controller_show_gen_perm_tests(expected, ctx)
expected.each do |sym, status|
params = "topic_id: #{sym}.id, slug: #{sym}.slug"
if sym == :nonexist
params = "topic_id: nonexist_topic_id"
end
ctx.instance_eval("
it 'returns #{status} for #{sym}' do
begin
xhr :get, :show, #{params}
expect(response.status).to eq(#{status})
rescue Discourse::NotLoggedIn
expect(302).to eq(#{status})
end
end")
end
end
describe TopicsController do
context 'wordpress' do
let!(:user) { log_in(:moderator) }
let(:p1) { Fabricate(:post, user: user) }
let(:topic) { p1.topic }
let!(:p2) { Fabricate(:post, topic: topic, user:user )}
it "returns the JSON in the format our wordpress plugin needs" do
SiteSetting.external_system_avatars_enabled = false
xhr :get, :wordpress, topic_id: topic.id, best: 3
expect(response).to be_success
json = ::JSON.parse(response.body)
expect(json).to be_present
# The JSON has the data the wordpress plugin needs
expect(json['id']).to eq(topic.id)
expect(json['posts_count']).to eq(2)
expect(json['filtered_posts_count']).to eq(2)
# Posts
expect(json['posts'].size).to eq(1)
post = json['posts'][0]
expect(post['id']).to eq(p2.id)
expect(post['username']).to eq(user.username)
expect(post['avatar_template']).to eq("#{Discourse.base_url_no_prefix}#{user.avatar_template}")
expect(post['name']).to eq(user.name)
expect(post['created_at']).to be_present
expect(post['cooked']).to eq(p2.cooked)
# Participants
expect(json['participants'].size).to eq(1)
participant = json['participants'][0]
expect(participant['id']).to eq(user.id)
expect(participant['username']).to eq(user.username)
expect(participant['avatar_template']).to eq("#{Discourse.base_url_no_prefix}#{user.avatar_template}")
end
end
context 'move_posts' do
it 'needs you to be logged in' do
expect { xhr :post, :move_posts, topic_id: 111, title: 'blah', post_ids: [1,2,3] }.to raise_error(Discourse::NotLoggedIn)
end
describe 'moving to a new topic' do
let!(:user) { log_in(:moderator) }
let(:p1) { Fabricate(:post, user: user) }
let(:topic) { p1.topic }
it "raises an error without postIds" do
expect { xhr :post, :move_posts, topic_id: topic.id, title: 'blah' }.to raise_error(ActionController::ParameterMissing)
end
it "raises an error when the user doesn't have permission to move the posts" do
Guardian.any_instance.expects(:can_move_posts?).returns(false)
xhr :post, :move_posts, topic_id: topic.id, title: 'blah', post_ids: [1,2,3]
expect(response).to be_forbidden
end
context 'success' do
let(:p2) { Fabricate(:post, user: user) }
before do
Topic.any_instance.expects(:move_posts).with(user, [p2.id], title: 'blah', category_id: 123).returns(topic)
xhr :post, :move_posts, topic_id: topic.id, title: 'blah', post_ids: [p2.id], category_id: 123
end
it "returns success" do
expect(response).to be_success
result = ::JSON.parse(response.body)
expect(result['success']).to eq(true)
expect(result['url']).to be_present
end
end
context 'failure' do
let(:p2) { Fabricate(:post, user: user) }
before do
Topic.any_instance.expects(:move_posts).with(user, [p2.id], title: 'blah').returns(nil)
xhr :post, :move_posts, topic_id: topic.id, title: 'blah', post_ids: [p2.id]
end
it "returns JSON with a false success" do
expect(response).to be_success
result = ::JSON.parse(response.body)
expect(result['success']).to eq(false)
expect(result['url']).to be_blank
end
end
end
describe "moving replied posts" do
let!(:user) { log_in(:moderator) }
let!(:p1) { Fabricate(:post, user: user) }
let!(:topic) { p1.topic }
let!(:p2) { Fabricate(:post, topic: topic, user: user, reply_to_post_number: p1.post_number ) }
context 'success' do
before do
PostReply.create(post_id: p1.id, reply_id: p2.id)
end
it "moves the child posts too" do
Topic.any_instance.expects(:move_posts).with(user, [p1.id, p2.id], title: 'blah').returns(topic)
xhr :post, :move_posts, topic_id: topic.id, title: 'blah', post_ids: [p1.id], reply_post_ids: [p1.id]
end
end
end
describe 'moving to an existing topic' do
let!(:user) { log_in(:moderator) }
let(:p1) { Fabricate(:post, user: user) }
let(:topic) { p1.topic }
let(:dest_topic) { Fabricate(:topic) }
context 'success' do
let(:p2) { Fabricate(:post, user: user) }
before do
Topic.any_instance.expects(:move_posts).with(user, [p2.id], destination_topic_id: dest_topic.id).returns(topic)
xhr :post, :move_posts, topic_id: topic.id, post_ids: [p2.id], destination_topic_id: dest_topic.id
end
it "returns success" do
expect(response).to be_success
result = ::JSON.parse(response.body)
expect(result['success']).to eq(true)
expect(result['url']).to be_present
end
end
context 'failure' do
let(:p2) { Fabricate(:post, user: user) }
before do
Topic.any_instance.expects(:move_posts).with(user, [p2.id], destination_topic_id: dest_topic.id).returns(nil)
xhr :post, :move_posts, topic_id: topic.id, destination_topic_id: dest_topic.id, post_ids: [p2.id]
end
it "returns JSON with a false success" do
expect(response).to be_success
result = ::JSON.parse(response.body)
expect(result['success']).to eq(false)
expect(result['url']).to be_blank
end
end
end
end
context "merge_topic" do
it 'needs you to be logged in' do
expect { xhr :post, :merge_topic, topic_id: 111, destination_topic_id: 345 }.to raise_error(Discourse::NotLoggedIn)
end
describe 'moving to a new topic' do
let!(:user) { log_in(:moderator) }
let(:p1) { Fabricate(:post, user: user) }
let(:topic) { p1.topic }
it "raises an error without destination_topic_id" do
expect { xhr :post, :merge_topic, topic_id: topic.id }.to raise_error(ActionController::ParameterMissing)
end
it "raises an error when the user doesn't have permission to merge" do
Guardian.any_instance.expects(:can_move_posts?).returns(false)
xhr :post, :merge_topic, topic_id: 111, destination_topic_id: 345
expect(response).to be_forbidden
end
let(:dest_topic) { Fabricate(:topic) }
context 'moves all the posts to the destination topic' do
let(:p2) { Fabricate(:post, user: user) }
before do
Topic.any_instance.expects(:move_posts).with(user, [p1.id], destination_topic_id: dest_topic.id).returns(topic)
xhr :post, :merge_topic, topic_id: topic.id, destination_topic_id: dest_topic.id
end
it "returns success" do
expect(response).to be_success
result = ::JSON.parse(response.body)
expect(result['success']).to eq(true)
expect(result['url']).to be_present
end
end
end
end
context 'change_post_owners' do
it 'needs you to be logged in' do
expect { xhr :post, :change_post_owners, topic_id: 111, username: 'user_a', post_ids: [1,2,3] }.to raise_error(Discourse::NotLoggedIn)
end
describe 'forbidden to moderators' do
let!(:moderator) { log_in(:moderator) }
it 'correctly denies' do
xhr :post, :change_post_owners, topic_id: 111, username: 'user_a', post_ids: [1,2,3]
expect(response).to be_forbidden
end
end
describe 'forbidden to trust_level_4s' do
let!(:trust_level_4) { log_in(:trust_level_4) }
it 'correctly denies' do
xhr :post, :change_post_owners, topic_id: 111, username: 'user_a', post_ids: [1,2,3]
expect(response).to be_forbidden
end
end
describe 'changing ownership' do
let!(:editor) { log_in(:admin) }
let(:topic) { Fabricate(:topic) }
let(:user_a) { Fabricate(:user) }
let(:p1) { Fabricate(:post, topic_id: topic.id) }
let(:p2) { Fabricate(:post, topic_id: topic.id) }
it "raises an error with a parameter missing" do
expect { xhr :post, :change_post_owners, topic_id: 111, post_ids: [1,2,3] }.to raise_error(ActionController::ParameterMissing)
expect { xhr :post, :change_post_owners, topic_id: 111, username: 'user_a' }.to raise_error(ActionController::ParameterMissing)
end
it "calls PostOwnerChanger" do
PostOwnerChanger.any_instance.expects(:change_owner!).returns(true)
xhr :post, :change_post_owners, topic_id: topic.id, username: user_a.username_lower, post_ids: [p1.id]
expect(response).to be_success
end
it "changes multiple posts" do
# an integration test
xhr :post, :change_post_owners, topic_id: topic.id, username: user_a.username_lower, post_ids: [p1.id, p2.id]
p1.reload; p2.reload
expect(p1.user).not_to eq(nil)
expect(p1.user).to eq(p2.user)
end
it "works with deleted users" do
deleted_user = Fabricate(:user)
t2 = Fabricate(:topic, user: deleted_user)
p3 = Fabricate(:post, topic_id: t2.id, user: deleted_user)
deleted_user.save
t2.save
p3.save
UserDestroyer.new(editor).destroy(deleted_user, { delete_posts: true, context: 'test', delete_as_spammer: true })
xhr :post, :change_post_owners, topic_id: t2.id, username: user_a.username_lower, post_ids: [p3.id]
expect(response).to be_success
t2.reload
p3.reload
expect(t2.deleted_at).to be_nil
expect(p3.user).to eq(user_a)
end
end
end
context 'change_timestamps' do
let(:params) { { topic_id: 1, timestamp: Time.zone.now } }
it 'needs you to be logged in' do
expect { xhr :put, :change_timestamps, params }.to raise_error(Discourse::NotLoggedIn)
end
[:moderator, :trust_level_4].each do |user|
describe "forbidden to #{user}" do
let!(user) { log_in(user) }
it 'correctly denies' do
xhr :put, :change_timestamps, params
expect(response).to be_forbidden
end
end
end
describe 'changing timestamps' do
let!(:admin) { log_in(:admin) }
let(:old_timestamp) { Time.zone.now }
let(:new_timestamp) { old_timestamp - 1.day }
let!(:topic) { Fabricate(:topic, created_at: old_timestamp) }
let!(:p1) { Fabricate(:post, topic_id: topic.id, created_at: old_timestamp) }
let!(:p2) { Fabricate(:post, topic_id: topic.id, created_at: old_timestamp + 1.day) }
it 'raises an error with a missing parameter' do
expect { xhr :put, :change_timestamps, topic_id: 1 }.to raise_error(ActionController::ParameterMissing)
end
it 'should update the timestamps of selected posts' do
xhr :put, :change_timestamps, topic_id: topic.id, timestamp: new_timestamp.to_f
expect(topic.reload.created_at).to be_within_one_second_of(new_timestamp)
expect(p1.reload.created_at).to be_within_one_second_of(new_timestamp)
expect(p2.reload.created_at).to be_within_one_second_of(old_timestamp)
end
end
end
context 'clear_pin' do
it 'needs you to be logged in' do
expect { xhr :put, :clear_pin, topic_id: 1 }.to raise_error(Discourse::NotLoggedIn)
end
context 'when logged in' do
let(:topic) { Fabricate(:topic) }
let!(:user) { log_in }
it "fails when the user can't see the topic" do
Guardian.any_instance.expects(:can_see?).with(topic).returns(false)
xhr :put, :clear_pin, topic_id: topic.id
expect(response).not_to be_success
end
describe 'when the user can see the topic' do
it "calls clear_pin_for if the user can see the topic" do
Topic.any_instance.expects(:clear_pin_for).with(user).once
xhr :put, :clear_pin, topic_id: topic.id
end
it "succeeds" do
xhr :put, :clear_pin, topic_id: topic.id
expect(response).to be_success
end
end
end
end
context 'status' do
it 'needs you to be logged in' do
expect { xhr :put, :status, topic_id: 1, status: 'visible', enabled: true }.to raise_error(Discourse::NotLoggedIn)
end
describe 'when logged in' do
before do
@user = log_in(:moderator)
@topic = Fabricate(:topic, user: @user)
end
it "raises an exception if you can't change it" do
Guardian.any_instance.expects(:can_moderate?).with(@topic).returns(false)
xhr :put, :status, topic_id: @topic.id, status: 'visible', enabled: 'true'
expect(response).to be_forbidden
end
it 'requires the status parameter' do
expect { xhr :put, :status, topic_id: @topic.id, enabled: true }.to raise_error(ActionController::ParameterMissing)
end
it 'requires the enabled parameter' do
expect { xhr :put, :status, topic_id: @topic.id, status: 'visible' }.to raise_error(ActionController::ParameterMissing)
end
it 'raises an error with a status not in the whitelist' do
expect { xhr :put, :status, topic_id: @topic.id, status: 'title', enabled: 'true' }.to raise_error(Discourse::InvalidParameters)
end
it 'calls update_status on the forum topic with false' do
Topic.any_instance.expects(:update_status).with('closed', false, @user, until: nil)
xhr :put, :status, topic_id: @topic.id, status: 'closed', enabled: 'false'
end
it 'calls update_status on the forum topic with true' do
Topic.any_instance.expects(:update_status).with('closed', true, @user, until: nil)
xhr :put, :status, topic_id: @topic.id, status: 'closed', enabled: 'true'
end
end
end
context 'delete_timings' do
it 'needs you to be logged in' do
expect { xhr :delete, :destroy_timings, topic_id: 1 }.to raise_error(Discourse::NotLoggedIn)
end
context 'when logged in' do
before do
@user = log_in
@topic = Fabricate(:topic, user: @user)
@topic_user = TopicUser.get(@topic, @topic.user)
end
it 'deletes the forum topic user record' do
PostTiming.expects(:destroy_for).with(@user.id, [@topic.id])
xhr :delete, :destroy_timings, topic_id: @topic.id
end
end
end
describe 'mute/unmute' do
it 'needs you to be logged in' do
expect { xhr :put, :mute, topic_id: 99}.to raise_error(Discourse::NotLoggedIn)
end
it 'needs you to be logged in' do
expect { xhr :put, :unmute, topic_id: 99}.to raise_error(Discourse::NotLoggedIn)
end
describe 'when logged in' do
before do
@topic = Fabricate(:topic, user: log_in)
end
end
end
describe 'recover' do
it "won't allow us to recover a topic when we're not logged in" do
expect { xhr :put, :recover, topic_id: 1 }.to raise_error(Discourse::NotLoggedIn)
end
describe 'when logged in' do
let(:topic) { Fabricate(:topic, user: log_in, deleted_at: Time.now, deleted_by: log_in) }
describe 'without access' do
it "raises an exception when the user doesn't have permission to delete the topic" do
Guardian.any_instance.expects(:can_recover_topic?).with(topic).returns(false)
xhr :put, :recover, topic_id: topic.id
expect(response).to be_forbidden
end
end
context 'with permission' do
before do
Guardian.any_instance.expects(:can_recover_topic?).with(topic).returns(true)
end
it 'succeeds' do
PostDestroyer.any_instance.expects(:recover)
xhr :put, :recover, topic_id: topic.id
expect(response).to be_success
end
end
end
end
describe 'delete' do
it "won't allow us to delete a topic when we're not logged in" do
expect { xhr :delete, :destroy, id: 1 }.to raise_error(Discourse::NotLoggedIn)
end
describe 'when logged in' do
let(:topic) { Fabricate(:topic, user: log_in) }
describe 'without access' do
it "raises an exception when the user doesn't have permission to delete the topic" do
Guardian.any_instance.expects(:can_delete?).with(topic).returns(false)
xhr :delete, :destroy, id: topic.id
expect(response).to be_forbidden
end
end
describe 'with permission' do
before do
Guardian.any_instance.expects(:can_delete?).with(topic).returns(true)
end
it 'succeeds' do
PostDestroyer.any_instance.expects(:destroy)
xhr :delete, :destroy, id: topic.id
expect(response).to be_success
end
end
end
end
describe 'id_for_slug' do
let(:topic) { Fabricate(:post).topic }
it "returns JSON for the slug" do
xhr :get, :id_for_slug, slug: topic.slug
expect(response).to be_success
json = ::JSON.parse(response.body)
expect(json).to be_present
expect(json['topic_id']).to eq(topic.id)
expect(json['url']).to eq(topic.url)
expect(json['slug']).to eq(topic.slug)
end
it "returns invalid access if the user can't see the topic" do
Guardian.any_instance.expects(:can_see?).with(topic).returns(false)
xhr :get, :id_for_slug, slug: topic.slug
expect(response).not_to be_success
end
end
describe 'show full render' do
render_views
it 'correctly renders canoicals' do
topic = Fabricate(:post).topic
get :show, topic_id: topic.id, slug: topic.slug
expect(response).to be_success
expect(css_select("link[rel=canonical]").length).to eq(1)
end
end
describe 'show' do
let(:topic) { Fabricate(:post).topic }
let!(:p1) { Fabricate(:post, user: topic.user) }
let!(:p2) { Fabricate(:post, user: topic.user) }
it 'shows a topic correctly' do
xhr :get, :show, topic_id: topic.id, slug: topic.slug
expect(response).to be_success
end
it 'return 404 for an invalid page' do
xhr :get, :show, topic_id: topic.id, slug: topic.slug, page: 2
expect(response.code).to eq("404")
end
it 'can find a topic given a slug in the id param' do
xhr :get, :show, id: topic.slug
expect(response).to redirect_to(topic.relative_url)
end
it 'keeps the post_number parameter around when redirecting' do
xhr :get, :show, id: topic.slug, post_number: 42
expect(response).to redirect_to(topic.relative_url + "/42")
end
it 'keeps the page around when redirecting' do
xhr :get, :show, id: topic.slug, post_number: 42, page: 123
expect(response).to redirect_to(topic.relative_url + "/42?page=123")
end
it 'does not accept page params as an array' do
xhr :get, :show, id: topic.slug, post_number: 42, page: [2]
expect(response).to redirect_to("#{topic.relative_url}/42?page=1")
end
it 'returns 404 when an invalid slug is given and no id' do
xhr :get, :show, id: 'nope-nope'
expect(response.status).to eq(404)
end
it 'returns a 404 when slug and topic id do not match a topic' do
xhr :get, :show, topic_id: 123123, slug: 'topic-that-is-made-up'
expect(response.status).to eq(404)
end
context 'a topic with nil slug exists' do
before do
@nil_slug_topic = Fabricate(:topic)
Topic.connection.execute("update topics set slug=null where id = #{@nil_slug_topic.id}") # can't find a way to set slug column to null using the model
end
it 'returns a 404 when slug and topic id do not match a topic' do
xhr :get, :show, topic_id: 123123, slug: 'topic-that-is-made-up'
expect(response.status).to eq(404)
end
end
context 'permission errors' do
let(:allowed_user) { Fabricate(:user) }
let(:allowed_group) { Fabricate(:group) }
let(:secure_category) {
c = Fabricate(:category)
c.permissions = [[allowed_group, :full]]
c.save
allowed_user.groups = [allowed_group]
allowed_user.save
c }
let(:normal_topic) { Fabricate(:topic) }
let(:secure_topic) { Fabricate(:topic, category: secure_category) }
let(:private_topic) { Fabricate(:private_message_topic, user: allowed_user) }
let(:deleted_topic) { Fabricate(:deleted_topic) }
let(:deleted_secure_topic) { Fabricate(:topic, category: secure_category, deleted_at: 1.day.ago) }
let(:deleted_private_topic) { Fabricate(:private_message_topic, user: allowed_user, deleted_at: 1.day.ago) }
let(:nonexist_topic_id) { Topic.last.id + 10000 }
context 'anonymous' do
expected = {
:normal_topic => 200,
:secure_topic => 403,
:private_topic => 302,
:deleted_topic => 410,
:deleted_secure_topic => 403,
:deleted_private_topic => 302,
:nonexist => 404
}
topics_controller_show_gen_perm_tests(expected, self)
end
context 'anonymous with login required' do
before do
SiteSetting.login_required = true
end
expected = {
:normal_topic => 302,
:secure_topic => 302,
:private_topic => 302,
:deleted_topic => 302,
:deleted_secure_topic => 302,
:deleted_private_topic => 302,
:nonexist => 302
}
topics_controller_show_gen_perm_tests(expected, self)
end
context 'normal user' do
before do
log_in(:user)
end
expected = {
:normal_topic => 200,
:secure_topic => 403,
:private_topic => 403,
:deleted_topic => 410,
:deleted_secure_topic => 403,
:deleted_private_topic => 403,
:nonexist => 404
}
topics_controller_show_gen_perm_tests(expected, self)
end
context 'allowed user' do
before do
log_in_user(allowed_user)
end
expected = {
:normal_topic => 200,
:secure_topic => 200,
:private_topic => 200,
:deleted_topic => 410,
:deleted_secure_topic => 410,
:deleted_private_topic => 410,
:nonexist => 404
}
topics_controller_show_gen_perm_tests(expected, self)
end
context 'moderator' do
before do
log_in(:moderator)
end
expected = {
:normal_topic => 200,
:secure_topic => 403,
:private_topic => 403,
:deleted_topic => 200,
:deleted_secure_topic => 403,
:deleted_private_topic => 403,
:nonexist => 404
}
topics_controller_show_gen_perm_tests(expected, self)
end
context 'admin' do
before do
log_in(:admin)
end
expected = {
:normal_topic => 200,
:secure_topic => 200,
:private_topic => 200,
:deleted_topic => 200,
:deleted_secure_topic => 200,
:deleted_private_topic => 200,
:nonexist => 404
}
topics_controller_show_gen_perm_tests(expected, self)
end
end
it 'records a view' do
expect { xhr :get, :show, topic_id: topic.id, slug: topic.slug }.to change(TopicViewItem, :count).by(1)
end
it 'records incoming links' do
user = Fabricate(:user)
get :show, topic_id: topic.id, slug: topic.slug, u: user.username
expect(IncomingLink.count).to eq(1)
end
it 'records redirects' do
@request.env['HTTP_REFERER'] = 'http://twitter.com'
get :show, { id: topic.id }
@request.env['HTTP_REFERER'] = nil
get :show, topic_id: topic.id, slug: topic.slug
link = IncomingLink.first
expect(link.referer).to eq('http://twitter.com')
end
it 'tracks a visit for all html requests' do
current_user = log_in(:coding_horror)
TopicUser.expects(:track_visit!).with(topic.id, current_user.id)
get :show, topic_id: topic.id, slug: topic.slug
end
context 'consider for a promotion' do
let!(:user) { log_in(:coding_horror) }
let(:promotion) do
result = double
Promotion.stubs(:new).with(user).returns(result)
result
end
it "reviews the user for a promotion if they're new" do
user.update_column(:trust_level, TrustLevel[0])
Promotion.any_instance.expects(:review)
get :show, topic_id: topic.id, slug: topic.slug
end
end
context 'filters' do
it 'grabs first page when no filter is provided' do
TopicView.any_instance.expects(:filter_posts_in_range).with(0, 19)
xhr :get, :show, topic_id: topic.id, slug: topic.slug
end
it 'grabs first page when first page is provided' do
TopicView.any_instance.expects(:filter_posts_in_range).with(0, 19)
xhr :get, :show, topic_id: topic.id, slug: topic.slug, page: 1
end
it 'grabs correct range when a page number is provided' do
TopicView.any_instance.expects(:filter_posts_in_range).with(20, 39)
xhr :get, :show, topic_id: topic.id, slug: topic.slug, page: 2
end
it 'delegates a post_number param to TopicView#filter_posts_near' do
TopicView.any_instance.expects(:filter_posts_near).with(p2.post_number)
xhr :get, :show, topic_id: topic.id, slug: topic.slug, post_number: p2.post_number
end
end
context "when 'login required' site setting has been enabled" do
before { SiteSetting.login_required = true }
context 'and the user is logged in' do
before { log_in(:coding_horror) }
it 'shows the topic' do
get :show, topic_id: topic.id, slug: topic.slug
expect(response).to be_successful
end
end
context 'and the user is not logged in' do
let(:api_key) { topic.user.generate_api_key(topic.user) }
it 'redirects to the login page' do
get :show, topic_id: topic.id, slug: topic.slug
expect(response).to redirect_to login_path
end
it 'shows the topic if valid api key is provided' do
get :show, topic_id: topic.id, slug: topic.slug, api_key: api_key.key
expect(response).to be_successful
topic.reload
# free test, only costs a reload
expect(topic.views).to eq(1)
end
it 'returns 403 for an invalid key' do
get :show, topic_id: topic.id, slug: topic.slug, api_key: "bad"
expect(response.code.to_i).to be(403)
end
end
end
end
describe '#feed' do
let(:topic) { Fabricate(:post).topic }
it 'renders rss of the topic' do
get :feed, topic_id: topic.id, slug: 'foo', format: :rss
expect(response).to be_success
expect(response.content_type).to eq('application/rss+xml')
end
end
describe 'update' do
it "won't allow us to update a topic when we're not logged in" do
expect { xhr :put, :update, topic_id: 1, slug: 'xyz' }.to raise_error(Discourse::NotLoggedIn)
end
describe 'when logged in' do
before do
@topic = Fabricate(:topic, user: log_in)
Fabricate(:post, topic: @topic)
end
describe 'without permission' do
it "raises an exception when the user doesn't have permission to update the topic" do
Guardian.any_instance.expects(:can_edit?).with(@topic).returns(false)
xhr :put, :update, topic_id: @topic.id, slug: @topic.title
expect(response).to be_forbidden
end
end
describe 'with permission' do
before do
Guardian.any_instance.expects(:can_edit?).with(@topic).returns(true)
end
it 'succeeds' do
xhr :put, :update, topic_id: @topic.id, slug: @topic.title
expect(response).to be_success
expect(::JSON.parse(response.body)['basic_topic']).to be_present
end
it 'allows a change of title' do
xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: 'This is a new title for the topic'
@topic.reload
expect(@topic.title).to eq('This is a new title for the topic')
end
it 'triggers a change of category' do
Topic.any_instance.expects(:change_category_to_id).with(123).returns(true)
xhr :put, :update, topic_id: @topic.id, slug: @topic.title, category_id: 123
end
it 'allows to change category to "uncategorized"' do
Topic.any_instance.expects(:change_category_to_id).with(0).returns(true)
xhr :put, :update, topic_id: @topic.id, slug: @topic.title, category_id: ""
end
it "returns errors with invalid titles" do
xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: 'asdf'
expect(response).not_to be_success
end
it "returns errors when the rate limit is exceeded" do
EditRateLimiter.any_instance.expects(:performed!).raises(RateLimiter::LimitExceeded.new(60))
xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: 'This is a new title for the topic'
expect(response).not_to be_success
end
it "returns errors with invalid categories" do
Topic.any_instance.expects(:change_category_to_id).returns(false)
xhr :put, :update, topic_id: @topic.id, slug: @topic.title, category_id: -1
expect(response).not_to be_success
end
it "doesn't call the PostRevisor when there is no changes" do
PostRevisor.any_instance.expects(:revise!).never
xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: @topic.title, category_id: @topic.category_id
expect(response).to be_success
end
context 'when topic is private' do
before do
@topic.archetype = Archetype.private_message
@topic.category = nil
@topic.save!
end
context 'when there are no changes' do
it 'does not call the PostRevisor' do
PostRevisor.any_instance.expects(:revise!).never
xhr :put, :update, topic_id: @topic.id, slug: @topic.title, title: @topic.title, category_id: nil
expect(response).to be_success
end
end
end
context "allow_uncategorized_topics is false" do
before do
SiteSetting.stubs(:allow_uncategorized_topics).returns(false)
end
it "can add a category to an uncategorized topic" do
Topic.any_instance.expects(:change_category_to_id).with(456).returns(true)
xhr :put, :update, topic_id: @topic.id, slug: @topic.title, category_id: 456
expect(response).to be_success
end
end
end
end
end
describe 'invite' do
describe "group invites" do
it "works correctly" do
group = Fabricate(:group)
topic = Fabricate(:topic)
_admin = log_in(:admin)
xhr :post, :invite, topic_id: topic.id, email: 'hiro@from.heros', group_ids: "#{group.id}"
expect(response).to be_success
invite = Invite.find_by(email: 'hiro@from.heros')
groups = invite.groups.to_a
expect(groups.count).to eq(1)
expect(groups[0].id).to eq(group.id)
end
end
it "won't allow us to invite toa topic when we're not logged in" do
expect { xhr :post, :invite, topic_id: 1, email: 'jake@adventuretime.ooo' }.to raise_error(Discourse::NotLoggedIn)
end
describe 'when logged in as group manager' do
let(:group_manager) { log_in }
let(:group) { Fabricate(:group).tap { |g| g.add_owner(group_manager) } }
let(:private_category) { Fabricate(:private_category, group: group) }
let(:group_private_topic) { Fabricate(:topic, category: private_category, user: group_manager) }
let(:recipient) { 'jake@adventuretime.ooo' }
it "should attach group to the invite" do
xhr :post, :invite, topic_id: group_private_topic.id, user: recipient
expect(response).to be_success
expect(Invite.find_by(email: recipient).groups).to eq([group])
end
end
describe 'when logged in' do
before do
@topic = Fabricate(:topic, user: log_in)
end
it 'requires an email parameter' do
expect { xhr :post, :invite, topic_id: @topic.id }.to raise_error(ActionController::ParameterMissing)
end
describe 'without permission' do
it "raises an exception when the user doesn't have permission to invite to the topic" do
xhr :post, :invite, topic_id: @topic.id, user: 'jake@adventuretime.ooo'
expect(response).to be_forbidden
end
end
describe 'with admin permission' do
let!(:admin) do
log_in :admin
end
it 'should work as expected' do
xhr :post, :invite, topic_id: @topic.id, user: 'jake@adventuretime.ooo'
expect(response).to be_success
expect(::JSON.parse(response.body)).to eq({'success' => 'OK'})
expect(Invite.where(invited_by_id: admin.id).count).to eq(1)
end
it 'should fail on shoddy email' do
xhr :post, :invite, topic_id: @topic.id, user: 'i_am_not_an_email'
expect(response).not_to be_success
expect(::JSON.parse(response.body)).to eq({'failed' => 'FAILED'})
end
end
end
end
describe 'autoclose' do
it 'needs you to be logged in' do
expect {
xhr :put, :autoclose, topic_id: 99, auto_close_time: '24', auto_close_based_on_last_post: false
}.to raise_error(Discourse::NotLoggedIn)
end
it 'needs you to be an admin or mod' do
log_in
xhr :put, :autoclose, topic_id: 99, auto_close_time: '24', auto_close_based_on_last_post: false
expect(response).to be_forbidden
end
describe 'when logged in' do
before do
@admin = log_in(:admin)
@topic = Fabricate(:topic, user: @admin)
end
it "can set a topic's auto close time and 'based on last post' property" do
Topic.any_instance.expects(:set_auto_close).with("24", {by_user: @admin, timezone_offset: -240})
xhr :put, :autoclose, topic_id: @topic.id, auto_close_time: '24', auto_close_based_on_last_post: true, timezone_offset: -240
json = ::JSON.parse(response.body)
expect(json).to have_key('auto_close_at')
expect(json).to have_key('auto_close_hours')
end
it "can remove a topic's auto close time" do
Topic.any_instance.expects(:set_auto_close).with(nil, anything)
xhr :put, :autoclose, topic_id: @topic.id, auto_close_time: nil, auto_close_based_on_last_post: false, timezone_offset: -240
end
it "will close a topic when the time expires" do
topic = Fabricate(:topic)
Timecop.freeze(20.hours.ago) do
create_post(topic: topic, raw: "This is the body of my cool post in the topic, but it's a bit old now")
end
topic.save
Jobs.expects(:enqueue_at).at_least_once
xhr :put, :autoclose, topic_id: topic.id, auto_close_time: 24, auto_close_based_on_last_post: true
topic.reload
expect(topic.closed).to eq(false)
expect(topic.posts.last.raw).to match(/cool post/)
Timecop.freeze(5.hours.from_now) do
Jobs::CloseTopic.new.execute({topic_id: topic.id, user_id: @admin.id})
end
topic.reload
expect(topic.closed).to eq(true)
expect(topic.posts.last.raw).to match(/automatically closed/)
end
it "will immediately close if the last post is old enough" do
topic = Fabricate(:topic)
Timecop.freeze(20.hours.ago) do
create_post(topic: topic)
end
topic.save
Topic.reset_highest(topic.id)
topic.reload
xhr :put, :autoclose, topic_id: topic.id, auto_close_time: 10, auto_close_based_on_last_post: true
topic.reload
expect(topic.closed).to eq(true)
expect(topic.posts.last.raw).to match(/after the last reply/)
expect(topic.posts.last.raw).to match(/10 hours/)
end
end
end
describe 'make_banner' do
it 'needs you to be a staff member' do
log_in
xhr :put, :make_banner, topic_id: 99
expect(response).to be_forbidden
end
describe 'when logged in' do
it "changes the topic archetype to 'banner'" do
topic = Fabricate(:topic, user: log_in(:admin))
Topic.any_instance.expects(:make_banner!)
xhr :put, :make_banner, topic_id: topic.id
expect(response).to be_success
end
end
end
describe 'remove_banner' do
it 'needs you to be a staff member' do
log_in
xhr :put, :remove_banner, topic_id: 99
expect(response).to be_forbidden
end
describe 'when logged in' do
it "resets the topic archetype" do
topic = Fabricate(:topic, user: log_in(:admin))
Topic.any_instance.expects(:remove_banner!)
xhr :put, :remove_banner, topic_id: topic.id
expect(response).to be_success
end
end
end
describe "bulk" do
it 'needs you to be logged in' do
expect { xhr :put, :bulk }.to raise_error(Discourse::NotLoggedIn)
end
describe "when logged in" do
let!(:user) { log_in }
let(:operation) { {type: 'change_category', category_id: '1'} }
let(:topic_ids) { [1,2,3] }
it "requires a list of topic_ids or filter" do
expect { xhr :put, :bulk, operation: operation }.to raise_error(ActionController::ParameterMissing)
end
it "requires an operation param" do
expect { xhr :put, :bulk, topic_ids: topic_ids}.to raise_error(ActionController::ParameterMissing)
end
it "requires a type field for the operation param" do
expect { xhr :put, :bulk, topic_ids: topic_ids, operation: {}}.to raise_error(ActionController::ParameterMissing)
end
it "delegates work to `TopicsBulkAction`" do
topics_bulk_action = mock
TopicsBulkAction.expects(:new).with(user, topic_ids, operation, group: nil).returns(topics_bulk_action)
topics_bulk_action.expects(:perform!)
xhr :put, :bulk, topic_ids: topic_ids, operation: operation
end
end
end
describe 'remove_bookmarks' do
it "should remove bookmarks properly from non first post" do
bookmark = PostActionType.types[:bookmark]
user = log_in
post = create_post
post2 = create_post(topic_id: post.topic_id)
PostAction.act(user, post2, bookmark)
xhr :put, :bookmark, topic_id: post.topic_id
expect(PostAction.where(user_id: user.id, post_action_type: bookmark).count).to eq(2)
xhr :put, :remove_bookmarks, topic_id: post.topic_id
expect(PostAction.where(user_id: user.id, post_action_type: bookmark).count).to eq(0)
end
end
describe 'reset_new' do
it 'needs you to be logged in' do
expect { xhr :put, :reset_new }.to raise_error(Discourse::NotLoggedIn)
end
let(:user) { log_in(:user) }
it "updates the `new_since` date" do
old_date = 2.years.ago
user.user_stat.update_column(:new_since, old_date)
xhr :put, :reset_new
user.reload
expect(user.user_stat.new_since.to_date).not_to eq(old_date.to_date)
end
end
describe "feature_stats" do
it "works" do
xhr :get, :feature_stats, category_id: 1
expect(response).to be_success
json = JSON.parse(response.body)
expect(json["pinned_in_category_count"]).to eq(0)
expect(json["pinned_globally_count"]).to eq(0)
expect(json["banner_count"]).to eq(0)
end
it "allows unlisted banner topic" do
Fabricate(:topic, category_id: 1, archetype: Archetype.banner, visible: false)
xhr :get, :feature_stats, category_id: 1
json = JSON.parse(response.body)
expect(json["banner_count"]).to eq(1)
end
end
describe "x-robots-tag" do
it "is included for unlisted topics" do
topic = Fabricate(:topic, visible: false)
get :show, topic_id: topic.id, slug: topic.slug
expect(response.headers['X-Robots-Tag']).to eq('noindex')
end
it "is not included for normal topics" do
topic = Fabricate(:topic, visible: true)
get :show, topic_id: topic.id, slug: topic.slug
expect(response.headers['X-Robots-Tag']).to eq(nil)
end
end
end
| scossar/discourse-dev | spec/controllers/topics_controller_spec.rb | Ruby | gpl-2.0 | 40,999 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect, HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from subscriber.models import Consumer, ConsumerType, Recharge, TotalRecharge, ACL
from product.models import Product
from voice_records.models import VoiceRecord, VoiceReg
from sms.models import SMSPayment
# from local_lib.v3 import is_number, is_float
from local_lib.v3 import is_number, is_float, is_bangladeshi_number, is_japanese_number, send_sms
from transaction.models import Transaction, ProductsInTransaction, BuyerSellerAccount, dueTransaction
from shop_inventory.models import Inventory, BuySellProfitInventoryIndividual, BuySellProfitInventory
from transcriber_management.models import Transcriber, TranscriberInTranscription, FailedTranscription
import datetime
from django.db.models import Q
from django.contrib.auth.models import User
from django.contrib.sessions.backends.db import SessionStore
from django.db.models import Count
@csrf_exempt
def login_page(request):
return render(request, 'pages/login.html')
@csrf_exempt
def login_auth(request):
postdata = request.POST
print(postdata)
if 'username' and 'password' in postdata:
print(postdata['username'])
login_username = postdata['username']
print(postdata['password'])
if ACL.objects.filter(loginID=postdata['username'][-9:]).exists():
login_username = login_username[-9:]
else:
login_username = login_username
user = authenticate(username=login_username, password=postdata['password'])
if user is not None:
if user.is_active:
login(request, user)
request.session['user'] = login_username
if user.is_superuser:
res = redirect('/admin')
else:
res = redirect('/')
else:
res = render(request, 'pages/login.html',
{'wrong': True,
'text': 'The password is valid, but the account has been disabled!'})
else:
res = render(request, 'pages/login.html',
{'wrong': True,
'text': 'The username and password you have entered is not correct. Please retry'})
else:
res = render(request, 'pages/login.html', {'wrong': False})
res['Access-Control-Allow-Origin'] = "*"
res['Access-Control-Allow-Headers'] = "Origin, X-Requested-With, Content-Type, Accept"
res['Access-Control-Allow-Methods'] = "PUT, GET, POST, DELETE, OPTIONS"
return res
def logout_now(request):
logout(request)
return render(request, 'pages/login.html')
@login_required(login_url='/login/')
def home(request):
transcriber_name = request.session['user']
print request.session['user']
if ACL.objects.filter(loginID=transcriber_name).exists():
login_user = ACL.objects.get(loginID=transcriber_name)
print(login_user.loginUser.name)
transcriber_name = login_user.loginUser.name
if login_user.loginUser.type.type_name == 'Distributor':
if login_user.loginUser.number_of_child == 'CHANGED !!!':
return render(request, 'pages/Distributor/index.html', {'transcriber_name': transcriber_name})
else:
return redirect('/change_password/')
elif login_user.loginUser.type.type_name == 'SR':
if login_user.loginUser.number_of_child == 'CHANGED !!!':
return render(request, 'pages/SR/index.html', {'transcriber_name': transcriber_name})
else:
return redirect('/change_password/')
elif login_user.loginUser.type.type_name == 'Seller':
if login_user.loginUser.number_of_child == 'CHANGED !!!':
return render(request, 'pages/Shop/index.html', {'transcriber_name': transcriber_name})
else:
return redirect('/change_password/')
elif login_user.loginUser.type.type_name == 'Buyer':
if login_user.loginUser.number_of_child == 'CHANGED !!!':
return render(request, 'pages/Consumer/index.html', {'transcriber_name': transcriber_name})
else:
return redirect('/change_password/')
else:
number_of_reg_calls = VoiceReg.objects.filter().count()
number_of_transaction_calls = VoiceRecord.objects.filter().count()
total = number_of_reg_calls + number_of_transaction_calls
if total > 0:
reg_call_percentage = (number_of_reg_calls / float(total)) * 100
transaction_call_percentage = (number_of_transaction_calls / float(total)) * 100
else:
transaction_call_percentage = 0
reg_call_percentage = 0
today_month = datetime.date.today().month
today_year = datetime.date.today().year
count = 1
data_2 = ''
data_3 = ''
data_4 = ''
data_5 = ''
data_6 = ''
max = 0
max_table_2 = 0
total_sell = VoiceRecord.objects.filter(purpose='sell').count()
total_buy = VoiceRecord.objects.filter(purpose='buy').count()
total_money_transaction = SMSPayment.objects.filter().count()
total_for_chart2 = number_of_reg_calls + number_of_transaction_calls
if total_for_chart2 > 0:
sell_percentage = (total_sell / float(total_for_chart2)) * 100
buy_percentage = (total_buy / float(total_for_chart2)) * 100
money_transaction_percentage = (total_money_transaction / float(total_for_chart2)) * 100
else:
sell_percentage = 0
buy_percentage = 0
money_transaction_percentage = 0
while count < 32:
total_call_that_day = VoiceRecord.objects.filter(DateAdded__month=today_month,
DateAdded__year=today_year, DateAdded__day=count).count()
total_reg_that_day = VoiceReg.objects.filter(DateAdded__month=today_month,
DateAdded__year=today_year, DateAdded__day=count).count()
if max < total_call_that_day:
max = total_call_that_day + 2
if max < total_reg_that_day:
max = total_reg_that_day + 2
data_2 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_call_that_day)
data_3 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_reg_that_day)
total_buy_that_day = VoiceRecord.objects.filter(DateAdded__month=today_month,
DateAdded__year=today_year,
DateAdded__day=count,
purpose='buy').count()
total_sell_that_day = VoiceRecord.objects.filter(DateAdded__month=today_month,
DateAdded__year=today_year,
DateAdded__day=count,
purpose='sell').count()
total_payment_that_day = SMSPayment.objects.filter(DateAdded__month=today_month,
DateAdded__year=today_year,
DateAdded__day=count).count()
if max_table_2 < total_buy_that_day:
max_table_2 = total_buy_that_day + 2
if max_table_2 < total_sell_that_day:
max_table_2 = total_sell_that_day + 2
if max_table_2 < total_payment_that_day:
max_table_2 = total_payment_that_day + 2
data_4 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_buy_that_day)
data_5 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_sell_that_day)
data_6 += '[gd(%s, %s, %s), %s],' % (today_year, today_month, count, total_payment_that_day)
count += 1
data_2 = data_2[:-1]
data_3 = data_3[:-1]
data_4 = data_4[:-1]
data_5 = data_5[:-1]
data_6 = data_6[:-1]
number_of_transactions = Transaction.objects.filter().count()
number_of_transactions_with_due = Transaction.objects.filter(total_due__gt=0).count()
number_of_transactions_without_due = Transaction.objects.filter(total_due__lte=0).count()
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
print(all_consumer_for_base.count)
return render(request, 'pages/index.html', {'shop_list_base': all_shop_for_base,
'number_of_reg_calls': number_of_reg_calls,
'transcriber_name': transcriber_name,
'number_of_transaction_calls': number_of_transaction_calls,
'all_consumer_for_base' :all_consumer_for_base,
'reg_call_percentage': reg_call_percentage,
'transaction_call_percentage': transaction_call_percentage,
'data_2': data_2,
'data_3': data_3,
'data_4': data_4,
'data_5': data_5,
'data_6': data_6,
'max': max,
'number_of_transactions': number_of_transactions,
'number_of_transactions_with_due': number_of_transactions_with_due,
'number_of_transactions_without_due': number_of_transactions_without_due,
'max_table_2': max_table_2,
'total_sell': total_sell,
'total_buy': total_buy,
'total_money_transaction': total_money_transaction,
'sell_percentage': sell_percentage,
'buy_percentage': buy_percentage,
'money_transaction_percentage': money_transaction_percentage,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def translator_page(request):
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/translator.html', {'shop_list_base': all_shop_for_base,
'all_consumer_for_base' :all_consumer_for_base,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
# all report views are here
@login_required(login_url='/login/')
def report_monthly_shop(request):
get_data = request.GET
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
shop_id = shop_object.id
total_sell = 0
total_sell_due = 0
total_sell_paid = 0
total_purchase = 0
total_purchase_due = 0
total_purchase_paid = 0
for month_sell in BuyerSellerAccount.objects.filter(seller=shop_object):
total_sell += month_sell.total_amount_of_transaction
total_sell_due += month_sell.total_due
total_sell_paid += month_sell.total_paid
for month_purchase in BuyerSellerAccount.objects.filter(buyer=shop_object):
total_purchase += month_purchase.total_amount_of_transaction
total_purchase_due += month_purchase.total_due
total_purchase_paid += month_purchase.total_paid
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_monthly_shop.html', {'shop_list_base': all_shop_for_base,
'shop_name': shop_name,
'shop_id': shop_id,
'all_consumer_for_base' :all_consumer_for_base,
'total_sell': total_sell,
'transcriber_name': transcriber_name,
'total_sell_due': total_sell_due,
'total_sell_paid': total_sell_paid,
'bangla': bangla,
'total_purchase': total_purchase,
'total_purchase_due': total_purchase_due,
'total_purchase_paid': total_purchase_paid,
'all_user_for_base': all_user_for_base})
# report_monthly_shop_json
@login_required(login_url='/login/')
def report_monthly_shop_json(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(id=shop_name)
shop_inventory = BuySellProfitInventoryIndividual.objects.filter(shop=shop_object)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
output = '{"data": [ '
if get_data['t'] == '1':
rank = 1
this_year = datetime.date.today().year
# this_month = 1
this_day = 1
for this_month in range(1, 13, 1):
count = 0
for this_day in range(1, 32, 1):
for a_product in Product.objects.all():
product_price = 0
product_name = a_product.name
total_sell = 0
total_due = 0
total_paid = 0
for this_day_sell_transaction in Transaction.objects.filter(seller=shop_object,
DateAdded__year=this_year,
DateAdded__month=this_month,
DateAdded__day=this_day):
total_sell += this_day_sell_transaction.total_amount
total_due += this_day_sell_transaction.total_due
total_paid += this_day_sell_transaction.total_paid
count += 1
total_purchase = 0
total_purchase_due = 0
total_purchase_paid = 0
for this_day_purchase_transaction in Transaction.objects.filter(buyer=shop_object,
DateAdded__year=this_year,
DateAdded__month=this_month,
DateAdded__day=this_day):
total_purchase += this_day_purchase_transaction.total_amount
total_purchase_due += this_day_purchase_transaction.total_due
total_purchase_paid += this_day_purchase_transaction.total_paid
count += 1
if count > 0:
output += '["%s/%s/%s","%s","%s","%s","%s","%s","%s"] ,' % (this_day, this_month, this_year,
total_sell, total_paid, total_due,
total_purchase, total_purchase_paid,
total_purchase_due)
count = 0
# this_day += 1
# this_month = this_month + 1
if get_data['t'] == '2':
for this_day_transaction in Transaction.objects.filter(Q(seller=shop_object) | Q(buyer=shop_object)):
# start counting for this product
id = this_day_transaction.pk
date = this_day_transaction.DateAdded
if this_day_transaction.seller == shop_object:
with_trade = this_day_transaction.buyer
trade_type = 'Sell'
elif this_day_transaction.buyer == shop_object:
with_trade = this_day_transaction.seller
trade_type = 'Buy'
number_of_items = ProductsInTransaction.objects.filter(TID=this_day_transaction).count()
total_amount = this_day_transaction.total_amount
total_paid = this_day_transaction.total_paid
total_due = this_day_transaction.total_due
output += '["%s","%s","%s","%s","%s","%s","%s","%s"] ,' % (id, date, with_trade, trade_type,
number_of_items, total_amount,
total_paid, total_due)
output = output[:-1]
output += ']}'
return HttpResponse(output, content_type="text/plain")
@login_required(login_url='/login/')
def report_sales_analysis(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
shop_id = shop_object.id
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
if 'ban' in get_data:
bangla = True
else:
bangla = False
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_sales_analysis.html', {'shop_list_base': all_shop_for_base,
'shop_name': shop_name,
'all_consumer_for_base' :all_consumer_for_base,
'shop_id': shop_id,
'bangla': bangla,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_sales_analysis_json(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(id=shop_name)
shop_inventory = BuySellProfitInventoryIndividual.objects.filter(shop=shop_object)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
output = '{"data": [ '
if get_data['t'] == '1':
rank = 1
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for this_day_transaction in Transaction.objects.filter(seller=shop_object):
# start counting for this product
for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction):
if product_in_this_transaction.product == a_product:
if product_in_this_transaction.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
else:
count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit
product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
if count > 0:
output += '["%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit)
rank += 1
if get_data['t'] == '2':
rank = 1
for a_product in Product.objects.all():
count = 0
product_price = 0
previous_product_price = 0
change = 0
product_name = a_product.name
for this_day_transaction in Transaction.objects.filter(seller=shop_object):
# start counting for this product
for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction):
if product_in_this_transaction.product == a_product:
if count == 0:
previous_product_price = product_in_this_transaction.price_per_unit
product_price = product_in_this_transaction.price_per_unit
change += abs(previous_product_price - product_price)
count += 1
if count > 0:
output += '["%s","%s","%s","%s"] ,' % (rank, product_name, count,
change/count)
rank += 1
if get_data['t'] == '3':
this_year = datetime.date.today().year
this_month = datetime.date.today().month
day = 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
while day < 32:
day_string = True
rank = 1
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year,
DateAdded__month=this_month, DateAdded__day=day):
# start counting for this product
for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction):
if product_in_this_transaction.product == a_product:
if product_in_this_transaction.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
else:
count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit
product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
if count > 0:
if day_string:
output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
day_string = False
output += '["","%s","%s","%s","%s"] ,' % (rank, product_name,
str(count) + ' ' + a_product.retail_unit,
float(product_price / count))
rank += 1
day += 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
if get_data['t'] == '4':
day = 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
while day < 8:
day_string = True
rank = 1
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__week_day=day):
# start counting for this product
for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction):
if product_in_this_transaction.product == a_product:
if product_in_this_transaction.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
else:
count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit
product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
if count > 0:
if day_string:
if day == 1:
output += '["%s","","","",""] ,' % 'Sunday'
elif day == 2:
output += '["%s","","","",""] ,' % 'Monday'
elif day == 3:
output += '["%s","","","",""] ,' % 'Tuesday'
elif day == 4:
output += '["%s","","","",""] ,' % 'Wednesday'
elif day == 5:
output += '["%s","","","",""] ,' % 'Thursday'
elif day == 6:
output += '["%s","","","",""] ,' % 'Friday'
elif day == 7:
output += '["%s","","","",""] ,' % 'Saturday'
day_string = False
output += '["","%s","%s","%s","%s"] ,' % (rank, product_name,
str(count) + ' ' + a_product.retail_unit,
float(product_price / count))
rank += 1
day += 1
if get_data['t'] == '5':
this_year = datetime.date.today().year
day_string = True
for a_product in Product.objects.all():
count = 0
product_profit = 0
product_name = a_product.name
for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object):
# start counting for this product
if this_day_transaction.product == a_product:
product_profit += this_day_transaction.profit
count += 1
output += '["%s","%s"] ,' % (product_name, product_profit)
output = output[:-1]
output += ']}'
return HttpResponse(output, content_type="text/plain")
@login_required(login_url='/login/')
def report_payment(request):
get_data = request.GET
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
sell_transaction_with_due = Transaction.objects.filter(seller_id=shop_object, total_due__lte=0)
buy_transaction_with_due = Transaction.objects.filter(buyer_id=shop_object, total_due__lte=0)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
buyer_account = BuyerSellerAccount.objects.filter(seller=shop_object, total_due__lte=0)
seller_account = BuyerSellerAccount.objects.filter(buyer=shop_object, total_due__lte=0)
all_user_for_base = Consumer.objects.all()
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
transcriber_name = request.session['user']
return render(request, 'pages/report_payment.html', {'shop_list_base': all_shop_for_base,
'sell_transaction_with_due': sell_transaction_with_due,
'buy_transaction_with_due': buy_transaction_with_due,
'all_consumer_for_base' :all_consumer_for_base,
'buyer_account': buyer_account,
'transcriber_name': transcriber_name,
'seller_account': seller_account,
'shop_name': shop_name,
'bangla': bangla,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_due(request):
get_data = request.GET
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
sell_transaction_with_due = Transaction.objects.filter(seller_id=shop_object, total_due__gt=0)
buy_transaction_with_due = Transaction.objects.filter(buyer_id=shop_object, total_due__gt=0)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
buyer_account = SMSPayment.objects.filter(seller=shop_object)
seller_account = SMSPayment.objects.filter(buyer=shop_object)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_due.html', {'shop_list_base': all_shop_for_base,
'sell_transaction_with_due': sell_transaction_with_due,
'buy_transaction_with_due': buy_transaction_with_due,
'buyer_account': buyer_account,
'all_consumer_for_base' :all_consumer_for_base,
'bangla': bangla,
'seller_account': seller_account,
'transcriber_name': transcriber_name,
'shop_name': shop_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_profit(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
shop_id = shop_object.id
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_profit.html', {'shop_list_base': all_shop_for_base,
'shop_name': shop_name,
'shop_id': shop_id,
'all_consumer_for_base' :all_consumer_for_base,
'bangla': bangla,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_profit_json(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(id=shop_name)
shop_inventory = BuySellProfitInventoryIndividual.objects.filter(shop=shop_object)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
output = '{"data": [ '
if get_data['t'] == '1':
this_year = datetime.date.today().year
this_month = 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
while this_month < 13:
day_string = True
for a_product in Product.objects.all():
count = 0
product_profit = 0
product_name = a_product.name
for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object,
DateAdded__year=this_year,
DateAdded__month=this_month):
# start counting for this product
if this_day_transaction.product == a_product:
product_profit += this_day_transaction.profit
count += 1
if count > 0:
if day_string:
if this_month == 1:
output += '["January","",""], '
elif this_month == 2:
output += '["February","",""], '
elif this_month == 3:
output += '["March","",""], '
elif this_month == 4:
output += '["April","",""], '
elif this_month == 5:
output += '["May","",""], '
elif this_month == 6:
output += '["June","",""], '
elif this_month == 7:
output += '["July","",""], '
elif this_month == 8:
output += '["August","",""], '
elif this_month == 9:
output += '["September","",""], '
elif this_month == 10:
output += '["October","",""], '
elif this_month == 11:
output += '["November","",""], '
elif this_month == 12:
output += '["December","",""], '
day_string = False
output += '["","%s","%s"] ,' % (product_name, product_profit)
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
this_month += 1
if get_data['t'] == '2':
this_year = datetime.date.today().year
this_month = 1
while this_month < 13:
day = 1
while day < 32:
day_string = True
for a_product in Product.objects.all():
count = 0
product_profit = 0
product_name = a_product.name
for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object,
DateAdded__year=this_year,
DateAdded__month=this_month,
DateAdded__day=day):
# start counting for this product
if this_day_transaction.product == a_product:
product_profit += this_day_transaction.profit
count += 1
if count > 0:
if day_string:
output += '["%s/%s/%s","",""] ,' % (day, this_month, this_year)
day_string = False
output += '["","%s","%s"] ,' % (product_name, product_profit)
day += 1
this_month += 1
if get_data['t'] == '3':
this_year = datetime.date.today().year
this_month = datetime.date.today().month
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
day_string = True
for a_product in Product.objects.all():
count = 0
product_profit = 0
product_name = a_product.name
for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object,
DateAdded__year=this_year,
DateAdded__month=this_month):
# start counting for this product
if this_day_transaction.product == a_product:
product_profit += this_day_transaction.profit
count += 1
output += '["%s","%s"] ,' % (product_name, product_profit)
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
if get_data['t'] == '4':
this_year = datetime.date.today().year
day_string = True
for a_product in Product.objects.all():
count = 0
product_profit = 0
product_name = a_product.name
for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object,
DateAdded__year=this_year):
# start counting for this product
if this_day_transaction.product == a_product:
product_profit += this_day_transaction.profit
count += 1
output += '["%s","%s"] ,' % (product_name, product_profit)
if get_data['t'] == '5':
this_year = datetime.date.today().year
day_string = True
for a_product in Product.objects.all():
count = 0
product_profit = 0
product_name = a_product.name
for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object):
# start counting for this product
if this_day_transaction.product == a_product:
product_profit += this_day_transaction.profit
count += 1
output += '["%s","%s"] ,' % (product_name, product_profit)
output = output[:-1]
output += ']}'
return HttpResponse(output, content_type="text/plain")
@login_required(login_url='/login/')
def report_product(request):
get_data = request.GET
shop_name = get_data['shop']
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_object = Consumer.objects.get(name=shop_name)
shop_id = shop_object.id
shop_inventory = Inventory.objects.filter(shop=shop_object)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
selected_products = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(seller=shop_object))
selected_products_buy = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(buyer=shop_object))
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_product.html', {'shop_list_base': all_shop_for_base,
'shop_inventory': shop_inventory,
'shop_name': shop_name,
'shop_id': shop_id,
'bangla': bangla,
'all_consumer_for_base' :all_consumer_for_base,
'transcriber_name': transcriber_name,
'selected_products_buy': selected_products_buy,
'selected_products': selected_products,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_product_json(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(id=shop_name)
shop_inventory = Inventory.objects.filter(shop=shop_object)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
output = '{"data": [ '
if get_data['t'] == '1':
this_year = datetime.date.today().year
this_month = datetime.date.today().month
day = 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
while day < 32:
day_string = True
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year,
DateAdded__month=this_month, DateAdded__day=day):
# start counting for this product
for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction):
if product_in_this_transaction.product == a_product:
# if product_in_this_transaction.unit == a_product.bulk_wholesale_unit:
# if a_product.bulk_to_retail_unit == 0:
# count = count + product_in_this_transaction.quantity
# product_price = product_price + product_in_this_transaction.price_per_unit
# else:
# count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit
# product_price = product_price + product_in_this_transaction.price_per_unit
# else:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit * product_in_this_transaction.quantity
if count > 0:
if day_string:
output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
day_string = False
output += '["","%s","%s","%s","%s"] ,' % (product_name, count,
a_product.retail_unit,
float(product_price / count))
day += 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
if get_data['t'] == '2':
this_year = datetime.date.today().year
this_month = datetime.date.today().month
day = 1
while day < 32:
day_string = True
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for this_day_transaction in Transaction.objects.filter(buyer=shop_object, DateAdded__year=this_year,
DateAdded__month=this_month, DateAdded__day=day):
# start counting for this product
for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction):
if product_in_this_transaction.product == a_product:
if product_in_this_transaction.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
else:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
else:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
if count > 0:
if day_string:
output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
day_string = False
output += '["","%s","%s","%s","%s"] ,' % (product_name, count,
a_product.bulk_wholesale_unit,
float(product_price / count))
day += 1
if get_data['t'] == '3':
this_year = datetime.date.today().year
this_month = datetime.date.today().month
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year, DateAdded__month=this_month):
# start counting for this product
for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction):
if product_in_this_transaction.product == a_product:
if product_in_this_transaction.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
else:
count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit
product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
if count > 0:
output += '["%s","%s","%s","%s"] ,' % (product_name, count,
a_product.retail_unit,
float(product_price / count))
if get_data['t'] == '4':
this_year = datetime.date.today().year
this_month = datetime.date.today().month
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for this_day_transaction in Transaction.objects.filter(buyer=shop_object, DateAdded__year=this_year, DateAdded__month=this_month):
# start counting for this product
for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction):
if product_in_this_transaction.product == a_product:
if product_in_this_transaction.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
else:
count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit
product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
if count > 0:
output += '["%s","%s","%s","%s"] ,' % (product_name, count,
a_product.retail_unit,
float(product_price / count))
output = output[:-1]
output += ']}'
selected_products_buy = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(buyer=shop_object))
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
return HttpResponse(output, content_type="text/plain")
# paste the template name of the report_analytical instead of report_product here
@login_required(login_url='/login/')
def report_analytical(request):
all_product = Product.objects.all()
final_output = ''
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
shop_id = shop_object.id
for product in all_product:
print(product.name)
if ProductsInTransaction.objects.filter(product=product).exists():
product_output = "[%s, " % product.name
sold_amount = 0
for product_details in ProductsInTransaction.objects.filter(product=product):
sold_amount = sold_amount + product_details.quantity
product_output += str(sold_amount)
final_output += product_output
final_output += "] ,"
print(final_output)
final_output = final_output[:-1]
print(final_output)
add_notification = False
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/reports_analytical.html',
{'all_product': all_product, 'add_notification': add_notification,
'shop_list_base': all_shop_for_base, 'product_sell': final_output,
'all_consumer_for_base' :all_consumer_for_base,
'transcriber_name': transcriber_name,
'shop_name': shop_name,
'shop_id': shop_id,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_analytical_json(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(id=shop_name)
if get_data['t'] == '1':
all_product = Product.objects.all()
final_output = '{"cols": [ { "id": "", "label": "Topping", "pattern": "", "type": "string" }, ' \
'{ "id": "", "label": "Units", "pattern": "", "type": "number" } ], "rows": [ '
for product in all_product:
print(product.name)
if ProductsInTransaction.objects.filter(product=product).exists():
product_name = product.name
sold_amount = 0
for transaction_id in Transaction.objects.filter(seller=shop_object):
for product_details in ProductsInTransaction.objects.filter(product=product, TID=transaction_id):
sold_amount = sold_amount + product_details.quantity
final_output += '{"c": [{"v": "%s","f": null},{"v": %s,"f": null}]},' % (product_name,
sold_amount)
final_output = final_output[:-1]
print(final_output)
if get_data['t'] == '2':
all_product = BuySellProfitInventory.objects.filter(shop=shop_object)
final_output = '{"cols": [ { "id": "", "label": "Topping", "pattern": "", "type": "string" }, ' \
'{ "id": "", "label": "Profit", "pattern": "", "type": "number" } ], "rows": [ '
for product in all_product:
final_output += '{"c": [{"v": "%s","f": null},{"v": %s,"f": null}]},' % (product.product,
product.profit)
final_output = final_output[:-1]
print(final_output)
final_output += ']}'
print(final_output)
return HttpResponse(final_output, content_type="text/plain")
# till this views created based on the list from mail
@login_required(login_url='/login/')
def report_recharge(request):
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_recharge.html', {'shop_list_base': all_shop_for_base,
'all_consumer_for_base' :all_consumer_for_base,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_callduration(request):
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_callduration_graph.html', {'shop_list_base': all_shop_for_base,
'all_consumer_for_base' :all_consumer_for_base,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
# not necessary
@login_required(login_url='/login/')
def report_transaction(request):
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_transaction.html', {'shop_list_base': all_shop_for_base,
'all_consumer_for_base' :all_consumer_for_base,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_calltranscription(request):
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_transcription.html', {'shop_list_base': all_shop_for_base,
'all_consumer_for_base' :all_consumer_for_base,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_usercall(request):
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_user_call_recharge.html', {'shop_list_base': all_shop_for_base,
'transcriber_name': transcriber_name,
'all_consumer_for_base' :all_consumer_for_base,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def transcription_page(request):
print(request.POST)
number_of_pending_calls = VoiceRecord.objects.filter(transcribed=False).count()
number_of_pending_reg_calls = VoiceReg.objects.filter(completed=False).count()
type_of_subscriber = ConsumerType.objects.all()
number_of_fail_calls = VoiceRecord.objects.filter(with_error=True).count()
number_of_completed_calls = VoiceRecord.objects.filter(with_error=False, transcribed=True).count()
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
return render(request, 'pages/transcription.html',
dict(pending_calls=number_of_pending_calls, types=type_of_subscriber,
pending_calls_reg=number_of_pending_reg_calls, number_of_fail_calls=str(number_of_fail_calls),
number_of_completed_calls=number_of_completed_calls, transcriber_name=transcriber_name,
shop_list_base=all_shop_for_base,all_consumer_for_base=all_consumer_for_base,
all_user_for_base=all_user_for_base))
# report views ends here
@login_required(login_url='/login/')
def add_subscriber_page(request):
all_subscriber = Consumer.objects.all()
type_of_subscriber = ConsumerType.objects.all()
add_notification = False
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
notification = ''
if 'delete' in request.GET:
get_data = request.GET
add_notification = True
delID = get_data['delete']
if Consumer.objects.filter(id=delID).exists():
item_for_delete = Consumer.objects.get(id=delID)
notification = 'Daily statement for the user : ' + item_for_delete.name + ' is sent successfully.'
# item_for_delete.delete()
sales_statement = ''
purchase_statement = ''
today_date = datetime.date.today()
today_day = today_date.day
today_month = today_date.month
today_year = today_date.year
# for selling
sell_transactions = Transaction.objects.filter(seller=item_for_delete, DateAdded__day=today_day,
DateAdded__month=today_month, DateAdded__year=today_year)
total_sales = 0
total_due = 0
total_paid = 0
for sell_transaction in sell_transactions:
total_sales += sell_transaction.total_amount
total_paid += sell_transaction.total_paid
total_due += sell_transaction.total_due
if total_sales > 0:
sales_statement = ' bikroy korechen mot: ' + str(total_sales) + ' takar. nogod peyechen : ' + \
str(total_paid) + ' taka ebong baki royeche ' + str(total_due) + ' taka.'
buy_transactions = Transaction.objects.filter(buyer=item_for_delete, DateAdded__day=today_day,
DateAdded__month=today_month, DateAdded__year=today_year)
total_purchase = 0
total_due = 0
total_paid = 0
for buy_transaction in buy_transactions:
total_purchase += buy_transaction.total_amount
total_paid += buy_transaction.total_paid
total_due += buy_transaction.total_due
if total_purchase > 0:
purchase_statement = ' kinechen mot: ' + str(total_purchase) + ' takar. Nogod diyechen : ' + \
str(total_paid) + ' taka ebong baki royeche ' + str(total_due) + ' taka.'
final_text = 'Aj apni' + sales_statement + purchase_statement + ' Dhonnobad'
if total_purchase > 0 or total_sales > 0:
print(final_text)
send_sms(final_text, item_for_delete.phone)
else:
notification = 'Item not found'
return render(request, 'pages/add_subscriber.html',
{'subscribers': all_subscriber, 'types': type_of_subscriber, 'add_notification': add_notification,
'shop_list_base': all_shop_for_base,
'all_consumer_for_base' :all_consumer_for_base,
'transcriber_name': transcriber_name,
'notification':notification,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def add_product_page(request):
all_product = Product.objects.all()
add_notification = False
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
notification = ''
if 'delete' in request.GET:
get_data = request.GET
add_notification = True
delID = get_data['delete']
if Product.objects.filter(id=delID).exists():
item_for_delete = Product.objects.get(id=delID)
notification = 'The product : ' + item_for_delete.name + ' is deleted successfully.'
item_for_delete.delete()
else:
notification = 'Item not found'
return render(request, 'pages/add_product.html',
{'all_product': all_product, 'add_notification': add_notification,
'all_consumer_for_base' :all_consumer_for_base,
'transcriber_name': transcriber_name,'notification': notification,
'shop_list_base': all_shop_for_base, 'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_transcriber_performance(request):
all_product = Product.objects.all()
add_notification = False
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_transcriber_performance.html',
{'all_product': all_product, 'add_notification': add_notification,
'transcriber_name': transcriber_name,
'all_consumer_for_base' :all_consumer_for_base,
'shop_list_base': all_shop_for_base, 'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_transcriber_performance_json(request):
final_output = '{"data": [ '
for transcriber in Transcriber.objects.all():
number_of_transcriptions = TranscriberInTranscription.objects.filter(name=transcriber).count()
total_time_taken = 0
total_product_trancribed = 0
for transcriber_in_transaction in TranscriberInTranscription.objects.filter(name=transcriber):
total_time_taken += float(transcriber_in_transaction.time_taken)
total_product_trancribed += transcriber_in_transaction.number_of_products
if number_of_transcriptions > 0:
avg_time = total_time_taken / number_of_transcriptions
avg_product = total_product_trancribed / number_of_transcriptions
final_output += '["%s","%s","%s","%s","%s"] ,' % (transcriber.id, transcriber.name,
number_of_transcriptions, avg_time, avg_product)
final_output = final_output[:-1]
final_output += ']}'
return HttpResponse(final_output, content_type="text/plain")
@login_required(login_url='/login/')
def user_balance_recharge(request):
post_data = request.POST
notification = ''
for all_consumers in Consumer.objects.all():
if Recharge.objects.filter(user=all_consumers).exists():
print('Already_Added')
else:
new_added = Recharge(user=all_consumers)
new_added.save()
if TotalRecharge.objects.filter(user=all_consumers).exists():
print('Already_Added')
else:
new_added = TotalRecharge(user=all_consumers)
new_added.save()
add_notification = False
if 'user' in post_data and 'recharge_amount' in post_data:
user_name = post_data['user']
user_object = Consumer.objects.get(name=user_name)
if is_number(post_data['recharge_amount']) or is_float(post_data['recharge_amount']):
new_recharge_added = Recharge(user=user_object, amount=float(post_data['recharge_amount']))
new_recharge_added.save()
new_recharge_update = TotalRecharge.objects.get(user=user_object)
new_recharge_update.amount += float(post_data['recharge_amount'])
new_recharge_update.save()
add_notification = True
notification = 'Amount %s has been added to the number %s' %(post_data['recharge_amount'],
user_object.phone)
else:
notification = 'Something went wrong. Please try again.'
recharge_all = TotalRecharge.objects.all()
today_date = datetime.date.today()
today_day = today_date.day
today_month = today_date.month
today_year = today_date.year
recharge_today = Recharge.objects.filter(DateAdded__day=today_day,
DateAdded__month=today_month, DateAdded__year=today_year, amount__gt=0)
all_product = Product.objects.all()
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'pages/report_user_call_recharge.html',
{'all_product': all_product, 'add_notification': add_notification,
'all_consumer_for_base' :all_consumer_for_base,
'shop_list_base': all_shop_for_base, 'recharge_all': recharge_all,
'transcriber_name': transcriber_name,
'recharge_today': recharge_today, 'all_user_for_base': all_user_for_base,
'notification': notification})
# views for printing
@login_required(login_url='/login/')
def report_monthly_shop_print(request):
get_data = request.GET
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
total_sell = 0
total_sell_due = 0
total_sell_paid = 0
total_purchase = 0
total_purchase_due = 0
total_purchase_paid = 0
for month_sell in BuyerSellerAccount.objects.filter(seller=shop_object):
total_sell += month_sell.total_amount_of_transaction
total_sell_due += month_sell.total_due
total_sell_paid += month_sell.total_paid
for month_purchase in BuyerSellerAccount.objects.filter(buyer=shop_object):
total_purchase += month_purchase.total_amount_of_transaction
total_purchase_due += month_purchase.total_due
total_purchase_paid += month_purchase.total_paid
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
transcriber_name = request.session['user']
return render(request, 'print/report_monthly_shop.html', {'shop_list_base': all_shop_for_base,
'shop_name': shop_name,
'all_consumer_for_base' :all_consumer_for_base,
'total_sell': total_sell,
'transcriber_name': transcriber_name,
'total_sell_due': total_sell_due,
'total_sell_paid': total_sell_paid,
'bangla': bangla,
'total_purchase': total_purchase,
'total_purchase_due': total_purchase_due,
'total_purchase_paid': total_purchase_paid,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_due_print(request):
get_data = request.GET
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
sell_transaction_with_due = Transaction.objects.filter(seller_id=shop_object, total_due__gt=0)
buy_transaction_with_due = Transaction.objects.filter(buyer_id=shop_object, total_due__gt=0)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
buyer_account = BuyerSellerAccount.objects.filter(seller=shop_object, total_due__gt=0)
seller_account = BuyerSellerAccount.objects.filter(buyer=shop_object, total_due__gt=0)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'print/report_due.html', {'shop_list_base': all_shop_for_base,
'sell_transaction_with_due': sell_transaction_with_due,
'buy_transaction_with_due': buy_transaction_with_due,
'buyer_account': buyer_account,
'all_consumer_for_base' :all_consumer_for_base,
'bangla': bangla,
'seller_account': seller_account,
'transcriber_name': transcriber_name,
'shop_name': shop_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_payment_print(request):
get_data = request.GET
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_name = get_data['shop']
shop_object = Consumer.objects.get(name=shop_name)
sell_transaction_with_due = Transaction.objects.filter(seller_id=shop_object, total_due__lte=0)
buy_transaction_with_due = Transaction.objects.filter(buyer_id=shop_object, total_due__lte=0)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
buyer_account = BuyerSellerAccount.objects.filter(seller=shop_object, total_due__lte=0)
seller_account = BuyerSellerAccount.objects.filter(buyer=shop_object, total_due__lte=0)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'print/report_payment.html', {'shop_list_base': all_shop_for_base,
'sell_transaction_with_due': sell_transaction_with_due,
'buy_transaction_with_due': buy_transaction_with_due,
'all_consumer_for_base' :all_consumer_for_base,
'buyer_account': buyer_account,
'transcriber_name': transcriber_name,
'seller_account': seller_account,
'shop_name': shop_name,
'bangla': bangla,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_product_print(request):
get_data = request.GET
shop_name = get_data['shop']
if 'ban' in get_data:
bangla = True
else:
bangla = False
shop_object = Consumer.objects.get(name=shop_name)
shop_inventory = Inventory.objects.filter(shop=shop_object)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
selected_products = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(seller=shop_object))
selected_products_buy = ProductsInTransaction.objects.filter(TID=Transaction.objects.filter(buyer=shop_object))
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'print/report_product.html', {'shop_list_base': all_shop_for_base,
'shop_inventory': shop_inventory,
'shop_name': shop_name,
'bangla': bangla,
'all_consumer_for_base' :all_consumer_for_base,
'transcriber_name': transcriber_name,
'selected_products_buy': selected_products_buy,
'selected_products': selected_products,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_sales_analysis_print(request):
get_data = request.GET
shop_name = get_data['shop']
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
transcriber_name = request.session['user']
return render(request, 'print/report_sales_analysis.html', {'shop_list_base': all_shop_for_base,
'all_consumer_for_base' :all_consumer_for_base,
'shop_name': shop_name,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_profit_print(request):
get_data = request.GET
shop_name = get_data['shop']
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'print/report_profit.html', {'shop_list_base': all_shop_for_base,
'shop_name': shop_name,
'all_consumer_for_base':all_consumer_for_base,
'transcriber_name': transcriber_name,
'all_user_for_base': all_user_for_base})
@login_required(login_url='/login/')
def report_transcriber_performance_print(request):
all_product = Product.objects.all()
add_notification = False
shop_consumer = ConsumerType.objects.get(type_name='Seller')
all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
all_user_for_base = Consumer.objects.all()
transcriber_name = request.session['user']
shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
return render(request, 'print/report_transcriber_performance.html',
{'all_product': all_product, 'add_notification': add_notification,
'all_consumer_for_base':all_consumer_for_base,
'transcriber_name': transcriber_name,
'shop_list_base': all_shop_for_base, 'all_user_for_base': all_user_for_base})
# SR section
@login_required(login_url='/login/')
def sr_monthly_report(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object)
return render(request, 'pages/SR/report_monthly.html', {'transcriber_name': transcriber_name,
'allTransaction': allTransaction})
@login_required(login_url='/login/')
def sr_due_report(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
allBalance = BuyerSellerAccount.objects.filter(seller=sr_object)
sell_transaction = Transaction.objects.filter(seller=sr_object)
dueTransactions = dueTransaction.objects.filter(seller=sr_object)
return render(request, 'pages/SR/report_due.html', {'transcriber_name': transcriber_name,
'sell_transaction': sell_transaction,
'dueTransactions': dueTransactions,
'allBalance': allBalance})
@login_required(login_url='/login/')
def sr_report_sales_analysis(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
post_data = request.POST
print(post_data)
shop_object = sr_object
shop_name = shop_object.name
shop_id = shop_object.id
if 'month' in post_data and 'year' in post_data:
month = post_data['month']
year = post_data['year']
else:
month = datetime.date.today().month
year = datetime.date.today().year
return render(request, 'pages/SR/report_sales_analysis.html', {'shop_name': shop_name,
# 'all_consumer_for_base' :all_consumer_for_base,
'shop_id': shop_id,
# 'bangla': bangla,
'transcriber_name': transcriber_name,
'month': month,
'year': year})
@login_required(login_url='/login/')
def sr_report_sales_analysis_json(request):
get_data = request.GET
shop_name = get_data['shop']
shop_object = Consumer.objects.get(id=shop_name)
shop_inventory = BuySellProfitInventoryIndividual.objects.filter(shop=shop_object)
shop_consumer = ConsumerType.objects.get(type_name='Seller')
this_year = get_data['year']
print(this_year)
this_month = get_data['month']
output = '{"data": [ '
if get_data['t'] == '1':
rank = 1
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year,
DateAdded__month=this_month):
# start counting for this product
for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction):
if product_in_this_transaction.product == a_product:
if product_in_this_transaction.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
else:
count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit
product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
if count > 0:
output += '["%s","%s","%s"] ,' % (rank, product_name, str(count) + ' ' + a_product.retail_unit)
rank += 1
if get_data['t'] == '2':
rank = 1
for a_product in Product.objects.all():
count = 0
# product_price = 0
previous_product_price = 0
change = 0
product_name = a_product.name
for this_day_transaction in Transaction.objects.filter(seller=shop_object):
# start counting for this product
for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction):
if product_in_this_transaction.product == a_product:
if count == 0:
previous_product_price = product_in_this_transaction.price_per_unit
product_price = product_in_this_transaction.price_per_unit
change += abs(previous_product_price - product_price)
count += 1
if count > 0:
output += '["%s","%s","%s","%s"] ,' % (rank, product_name, count,
change/count)
rank += 1
if get_data['t'] == '3':
print(this_month)
day = 1
#
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
while day < 32:
day_string = True
rank = 1
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__year=this_year,
DateAdded__month=this_month, DateAdded__day=day):
# start counting for this product
for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction):
if product_in_this_transaction.product == a_product:
if product_in_this_transaction.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
else:
count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit
product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
if count > 0:
if day_string:
output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
day_string = False
output += '["","%s","%s","%s","%s"] ,' % (rank, product_name,
str(count) + ' ' + a_product.retail_unit,
float(product_price / count))
rank += 1
day += 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
if get_data['t'] == '4':
day = 1
# output += '["%s/%s/%s","","","",""] ,' % (day, this_month, this_year)
while day < 8:
day_string = True
rank = 1
for a_product in Product.objects.all():
count = 0
product_price = 0
product_name = a_product.name
for this_day_transaction in Transaction.objects.filter(seller=shop_object, DateAdded__week_day=day):
# start counting for this product
for product_in_this_transaction in ProductsInTransaction.objects.filter(TID=this_day_transaction):
if product_in_this_transaction.product == a_product:
if product_in_this_transaction.unit == a_product.bulk_wholesale_unit:
if a_product.bulk_to_retail_unit == 0:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
else:
count = count + product_in_this_transaction.quantity * a_product.bulk_to_retail_unit
product_price = product_price + product_in_this_transaction.price_per_unit / a_product.bulk_to_retail_unit
else:
count = count + product_in_this_transaction.quantity
product_price = product_price + product_in_this_transaction.price_per_unit
if count > 0:
if day_string:
if day == 1:
output += '["%s","","","",""] ,' % 'Sunday'
elif day == 2:
output += '["%s","","","",""] ,' % 'Monday'
elif day == 3:
output += '["%s","","","",""] ,' % 'Tuesday'
elif day == 4:
output += '["%s","","","",""] ,' % 'Wednesday'
elif day == 5:
output += '["%s","","","",""] ,' % 'Thursday'
elif day == 6:
output += '["%s","","","",""] ,' % 'Friday'
elif day == 7:
output += '["%s","","","",""] ,' % 'Saturday'
day_string = False
output += '["","%s","%s","%s","%s"] ,' % (rank, product_name,
str(count) + ' ' + a_product.retail_unit,
float(product_price / count))
rank += 1
day += 1
if get_data['t'] == '5':
this_year = datetime.date.today().year
day_string = True
for a_product in Product.objects.all():
count = 0
product_profit = 0
product_name = a_product.name
for this_day_transaction in BuySellProfitInventoryIndividual.objects.filter(shop_id=shop_object):
# start counting for this product
if this_day_transaction.product == a_product:
product_profit += this_day_transaction.profit
count += 1
output += '["%s","%s"] ,' % (product_name, product_profit)
output = output[:-1]
output += ']}'
return HttpResponse(output, content_type="text/plain")
# Distributor Section
@login_required(login_url='/login/')
def add_sr_page(request):
dr_name = request.session['user']
dr_object = ACL.objects.get(loginID=dr_name).loginUser
transcriber_name = dr_object.name
all_subscriber = ACL.objects.filter(distUser=dr_object)
# type_of_subscriber = ConsumerType.objects.all()
add_notification = False
# shop_consumer = ConsumerType.objects.get(type_name='Seller')
# all_shop_for_base = Consumer.objects.filter(type=shop_consumer)
# all_user_for_base = Consumer.objects.all()
# transcriber_name = request.session['user']
# shop_consumer2 = ConsumerType.objects.get(type_name='Buyer')
# all_consumer_for_base = Consumer.objects.filter(type=shop_consumer2)
notification = ''
if 'delete' in request.GET:
get_data = request.GET
add_notification = True
delID = get_data['delete']
if Consumer.objects.filter(id=delID).exists():
item_for_delete = Consumer.objects.get(id=delID)
notification = 'The Consumer : ' + item_for_delete.name + ' is deleted successfully.'
item_for_delete.delete()
else:
notification = 'Item not found'
return render(request, 'pages/Distributor/add_SR.html',
{'subscribers': all_subscriber,'add_notification': add_notification,
# 'shop_list_base': all_shop_for_base,
# 'all_consumer_for_base' :all_consumer_for_base,
'transcriber_name': transcriber_name,
'notification': notification})
@login_required(login_url='/login/')
def dr_monthly_report(request):
dr_name = request.session['user']
dr_object = ACL.objects.get(loginID=dr_name).loginUser
transcriber_name = dr_object.name
transcriber_id = dr_object.id
all_subscriber = ACL.objects.filter(distUser=dr_object)
post_data = request.POST
print(post_data)
if 'sr' in post_data:
sr_object = Consumer.objects.get(id=post_data['sr'])
allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object)
return render(request, 'pages/Distributor/report_monthly.html', {'transcriber_name': transcriber_name,
'hasReport': True,
'subscribers': all_subscriber,
'transcriber_id': transcriber_id,
'allTransaction': allTransaction})
else:
# allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object)
return render(request, 'pages/Distributor/report_monthly.html', {'transcriber_name': transcriber_name,
'transcriber_id': transcriber_id,
'subscribers': all_subscriber,
'hasReport': False})
@login_required(login_url='/login/')
def dr_due_report(request):
sr_name = request.session['user']
dr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = dr_object.name
transcriber_id = dr_object.id
all_subscriber = ACL.objects.filter(distUser=dr_object)
post_data = request.POST
if 'sr' in post_data:
sr_object = Consumer.objects.get(id=post_data['sr'])
allBalance = BuyerSellerAccount.objects.filter(seller=sr_object)
sell_transaction = Transaction.objects.filter(seller=sr_object)
dueTransactions = dueTransaction.objects.filter(seller=sr_object)
# allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object)
return render(request, 'pages/Distributor/report_due.html', {'transcriber_name': transcriber_name,
'sell_transaction': sell_transaction,
'dueTransactions': dueTransactions,
'transcriber_id': transcriber_id,
'hasReport': True,
'subscribers': all_subscriber,
'allBalance': allBalance})
else:
# allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object)
return render(request, 'pages/Distributor/report_due.html', {'transcriber_name': transcriber_name,
'transcriber_id': transcriber_id,
'subscribers': all_subscriber,
'hasReport': False})
@login_required(login_url='/login/')
def dr_report_sales_analysis(request):
dr_name = request.session['user']
dr_object = ACL.objects.get(loginID=dr_name).loginUser
transcriber_name = dr_object.name
transcriber_id = dr_object.id
post_data = request.POST
print(post_data)
# shop_object = sr_object
#
all_subscriber = ACL.objects.filter(distUser=dr_object)
hasReport = False
if 'sr' in post_data:
shop_id = post_data['sr']
shop_name = Consumer.objects.get(id=shop_id).name
hasReport = True
if 'month' in post_data and 'year' in post_data:
month = post_data['month']
year = post_data['year']
else:
month = datetime.date.today().month
year = datetime.date.today().year
return render(request, 'pages/Distributor/report_sales_analysis.html', {'shop_name': shop_name,
'transcriber_id': transcriber_id,
'shop_id': shop_id,
'subscribers': all_subscriber,
'transcriber_name': transcriber_name,
'month': month,
'hasReport': hasReport,
'year': year})
else:
return render(request, 'pages/Distributor/report_sales_analysis.html', {'shop_name': 'Not Selected',
'transcriber_id': transcriber_id,
'subscribers': all_subscriber,
'transcriber_name': transcriber_name,
'hasReport': hasReport})
# Shop Module
@login_required(login_url='/login/')
def shop_monthly_report(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object)
allTransactionIn = BuyerSellerAccount.objects.filter(buyer=sr_object)
return render(request, 'pages/Shop/report_monthly.html', {'transcriber_name': transcriber_name,
'allTransactionIn': allTransactionIn,
'allTransaction': allTransaction})
@login_required(login_url='/login/')
def shop_due_report(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
allBalance = BuyerSellerAccount.objects.filter(seller=sr_object)
sell_transaction = Transaction.objects.filter(seller=sr_object)
dueTransactions = dueTransaction.objects.filter(seller=sr_object)
allBalanceIn = BuyerSellerAccount.objects.filter(buyer=sr_object)
sell_transactionIn = Transaction.objects.filter(buyer=sr_object)
dueTransactionsIn = dueTransaction.objects.filter(buyer=sr_object)
return render(request, 'pages/Shop/report_due.html', {'transcriber_name': transcriber_name,
'sell_transaction': sell_transaction,
'dueTransactions': dueTransactions,
'allBalance': allBalance,
'sell_transactionIn': sell_transactionIn,
'dueTransactionsIn': dueTransactionsIn,
'allBalanceIn': allBalanceIn})
@login_required(login_url='/login/')
def shop_report_sales_analysis(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
post_data = request.POST
print(post_data)
shop_object = sr_object
shop_name = shop_object.name
shop_id = shop_object.id
if 'month' in post_data and 'year' in post_data:
month = post_data['month']
year = post_data['year']
else:
month = datetime.date.today().month
year = datetime.date.today().year
return render(request, 'pages/Shop/report_sales_analysis.html', {'shop_name': shop_name,
# 'all_consumer_for_base' :all_consumer_for_base,
'shop_id': shop_id,
# 'bangla': bangla,
'transcriber_name': transcriber_name,
'month': month,
'year': year})
# Consumer Module
@login_required(login_url='/login/')
def user_monthly_report(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
# allTransaction = BuyerSellerAccount.objects.filter(seller=sr_object)
allTransactionIn = BuyerSellerAccount.objects.filter(buyer=sr_object)
return render(request, 'pages/Consumer/report_monthly.html', {'transcriber_name': transcriber_name,
'allTransactionIn': allTransactionIn})
@login_required(login_url='/login/')
def user_due_report(request):
sr_name = request.session['user']
sr_object = ACL.objects.get(loginID=sr_name).loginUser
transcriber_name = sr_object.name
# allBalance = BuyerSellerAccount.objects.filter(seller=sr_object)
# sell_transaction = Transaction.objects.filter(seller=sr_object)
# dueTransactions = dueTransaction.objects.filter(seller=sr_object)
allBalanceIn = BuyerSellerAccount.objects.filter(buyer=sr_object)
sell_transactionIn = Transaction.objects.filter(buyer=sr_object)
dueTransactionsIn = dueTransaction.objects.filter(buyer=sr_object)
return render(request, 'pages/Consumer/report_due.html', {'transcriber_name': transcriber_name,
# 'sell_transaction': sell_transaction,
# 'dueTransactions': dueTransactions,
# 'allBalance': allBalance,
'sell_transactionIn': sell_transactionIn,
'dueTransactionsIn': dueTransactionsIn,
'allBalanceIn': allBalanceIn})
@login_required(login_url='/login/')
def change_password(request):
# user = request.session['user']
post_data = request.POST
user_name = request.session['user']
user_object = ACL.objects.get(loginID=user_name).loginUser
transcriber_name = user_object.name
user = user_object.phone[-9:]
wrong = False
text = ''
if 'csrfmiddlewaretoken' in post_data:
if post_data['password'] == post_data['re-password']:
if User.objects.filter(username=user).exists():
u = User.objects.get(username=user)
u.set_password(post_data['password'])
u.save()
user_ID = user_object.id
this_user = Consumer.objects.get(id=user_ID)
this_user.number_of_child = 'CHANGED !!!'
this_user.save()
wrong = True
text = 'Password is successfully changed'
if user_object.type.type_name == 'Distributor':
display = render(request, 'pages/Distributor/index.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'SR':
display = render(request, 'pages/SR/index.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Seller':
display = render(request, 'pages/Shop/index.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Buyer':
display = render(request, 'pages/Consumer/index.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
else:
wrong = True
text = 'Something Wrong'
if user_object.type.type_name == 'Distributor':
display = render(request, 'pages/Distributor/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'SR':
display = render(request, 'pages/SR/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Seller':
display = render(request, 'pages/Shop/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Buyer':
display = render(request, 'pages/Consumer/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
else:
wrong = True
text = 'Passwords do NOT match. Please try again'
if user_object.type.type_name == 'Distributor':
display = render(request, 'pages/Distributor/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'SR':
display = render(request, 'pages/SR/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Seller':
display = render(request, 'pages/Shop/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Buyer':
display = render(request, 'pages/Consumer/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
else:
wrong = False
if user_object.type.type_name == 'Distributor':
display = render(request, 'pages/Distributor/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'SR':
display = render(request, 'pages/SR/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Seller':
display = render(request, 'pages/Shop/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong,
'text': text})
elif user_object.type.type_name == 'Buyer':
display = render(request, 'pages/Consumer/change_password.html', {'transcriber_name': transcriber_name,
'wrong': wrong})
return display
| ShovanSarker/sense_v4_withLocal | template_manager/views.py | Python | gpl-2.0 | 113,348 |
<?php
/**
* Display single product reviews (comments)
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 2.1.0
*/
global $woocommerce, $product;
if ( ! defined( 'ABSPATH' ) )
exit; // Exit if accessed directly
if ( ! comments_open() )
return;
?>
<div id="reviews">
<div id="comments">
<h2><?php
if ( get_option( 'woocommerce_enable_review_rating' ) === 'yes' && ( $count = $product->get_rating_count() ) )
printf( _n('%s review for %s', '%s reviews for %s', $count, 'woocommerce'), $count, get_the_title() );
else
_e( 'Reviews', 'woocommerce' );
?></h2>
<?php if ( have_comments() ) : ?>
<ol class="commentlist">
<?php wp_list_comments( apply_filters( 'woocommerce_product_review_list_args', array( 'callback' => 'woocommerce_comments' ) ) ); ?>
</ol>
<?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) :
echo '<nav class="woocommerce-pagination">';
paginate_comments_links( apply_filters( 'woocommerce_comment_pagination_args', array(
'prev_text' => '←',
'next_text' => '→',
'type' => 'list',
) ) );
echo '</nav>';
endif; ?>
<?php else : ?>
<p class="woocommerce-noreviews"><?php _e( 'There are no reviews yet.', 'woocommerce' ); ?></p>
<?php endif; ?>
</div>
<?php if ( get_option( 'woocommerce_review_rating_verification_required' ) === 'no' || wc_customer_bought_product( '', get_current_user_id(), $product->id ) ) : ?>
<div id="review_form_wrapper">
<div id="review_form">
<?php
$commenter = wp_get_current_commenter();
$comment_form = array(
'title_reply' => have_comments() ? __( 'Add a review', 'woocommerce' ) : __( 'Be the first to review', 'woocommerce' ) . ' “' . get_the_title() . '”',
'title_reply_to' => __( 'Leave a Reply to %s', 'woocommerce' ),
'comment_notes_before' => '',
'comment_notes_after' => '',
'fields' => array(
'author' => '<p class="comment-form-author">' . '<label for="author">' . __( 'Name', 'woocommerce' ) . ' <span class="required">*</span></label> ' .
'<input id="author" name="author" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30" aria-required="true" /></p>',
'email' => '<p class="comment-form-email"><label for="email">' . __( 'Email', 'woocommerce' ) . ' <span class="required">*</span></label> ' .
'<input id="email" name="email" type="text" value="' . esc_attr( $commenter['comment_author_email'] ) . '" size="30" aria-required="true" /></p>',
),
'label_submit' => __( 'Submit', 'woocommerce' ),
'logged_in_as' => '',
'comment_field' => ''
);
if ( get_option( 'woocommerce_enable_review_rating' ) === 'yes' ) {
$comment_form['comment_field'] = '<p class="comment-form-rating"><label for="rating">' . __( 'Your Rating', 'woocommerce' ) .'</label><select name="rating" id="rating">
<option value="">' . __( 'Rate…', 'woocommerce' ) . '</option>
<option value="5">' . __( 'Perfect', 'woocommerce' ) . '</option>
<option value="4">' . __( 'Good', 'woocommerce' ) . '</option>
<option value="3">' . __( 'Average', 'woocommerce' ) . '</option>
<option value="2">' . __( 'Not that bad', 'woocommerce' ) . '</option>
<option value="1">' . __( 'Very Poor', 'woocommerce' ) . '</option>
</select></p>';
}
$comment_form['comment_field'] .= '<p class="comment-form-comment"><label for="comment">' . __( 'Your Review', 'woocommerce' ) . '</label><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"></textarea>' . wp_nonce_field( 'woocommerce-comment_rating', '_wpnonce', true, false ) . '</p>';
comment_form( apply_filters( 'woocommerce_product_review_comment_form_args', $comment_form ) );
?>
</div>
</div>
<?php else : ?>
<p class="woocommerce-verification-required"><?php _e( 'Only logged in customers who have purchased this product may leave a review.', 'woocommerce' ); ?></p>
<?php endif; ?>
<div class="clear"></div>
</div> | mickburgs/sjaaktramper | wp-content/plugins/woocommerce/templates/single-product-reviews.php | PHP | gpl-2.0 | 4,254 |
package com.atux.bean.consulta;
import com.atux.comun.FilterBaseLocal;
/**
* Created by MATRIX-JAVA on 27/11/2014.
*/
public class UnidadFlt extends FilterBaseLocal {
public static final String PICK = "PICK";
public UnidadFlt(String unidad) {
this.unidad = unidad;
}
public UnidadFlt() {
}
private String unidad;
private String coUnidad;
public String getUnidad() {
return unidad;
}
public void setUnidad(String unidad) {
this.unidad = unidad;
}
public String getCoUnidad() {
return coUnidad;
}
public void setCoUnidad(String coUnidad) {
this.coUnidad = coUnidad;
}
}
| AlanGuerraQuispe/SisAtuxVenta | atux-domain/src/main/java/com/atux/bean/consulta/UnidadFlt.java | Java | gpl-2.0 | 719 |
<?php
/**
* Kumbia Enterprise Framework
*
* LICENSE
*
* This source file is subject to the New BSD License that is bundled
* with this package in the file docs/LICENSE.txt.
*
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@loudertechnology.com so we can send you a copy immediately.
*
* @category Kumbia
* @package Generator
* @subpackage GeneratorReport
* @copyright Copyright (c) 2008-2009 Louder Technology COL. (http://www.loudertechnology.com)
* @copyright Copyright (c) 2005-2008 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com)
* @license New BSD License
* @version $Id: Doc.php 82 2009-09-13 21:06:31Z gutierrezandresfelipe $
*/
/**
* DocGenerator
*
* Generador de Reportes en Word
*
* @category Kumbia
* @package Generator
* @subpackage GeneratorReport
* @copyright Copyright (c) 2008-2009 Louder Technology COL. (http://www.loudertechnology.com)
* @copyright Copyright (c) 2005-2008 Andres Felipe Gutierrez (gutierrezandresfelipe at gmail.com)
* @license New BSD License
*/
function doc($result, $sumArray, $title, $weightArray, $headerArray){
$config = CoreConfig::readAppConfig();
$active_app = Router::getApplication();
$file = md5(uniqid());
$content = "
<html>
<head>
<title>REPORTE DE ".i18n::strtoupper($title)."</title>
</head>
<body bgcolor='white'>
<div style='font-size:20px;font-family:Verdana;color:#000000'>".i18n::strtoupper($config->application->name)."</div>\n
<div style='font-size:18px;font-family:Verdana;color:#000000'>REPORTE DE ".i18n::strtoupper($title)."</div>\n
<div style='font-size:18px;font-family:Verdana;color:#000000'>".date("Y-m-d H:i")."</div>\n
<br/>
<table cellspacing='0' border=1 style='border:1px solid #969696'>
";
$content.= "<tr bgcolor='#F2F2F2'>\n";
$numberHeaders = count($headerArray);
for($i=0;$i<$numberHeaders;++$i){
$content.= "<th style='font-family:Verdana;font-size:12px'>".$headerArray[$i]."</th>\n";
}
$content.= "</tr>\n";
$l = 5;
foreach($result as $row){
$content.= "<tr bgcolor='white'>\n";
$numberColumns = count($row);
for($i=0;$i<$numberColumns;++$i){
if(is_numeric($row[$i])){
$content.= "<td style='font-family:Verdana;font-size:12px' align='center'>{$row[$i]}</td>";
} else {
$content.= "<td style='font-family:Verdana;font-size:12px'>{$row[$i]} </td>";
}
}
$content.= "</tr>\n";
++$l;
}
file_put_contents("public/temp/$file.doc", $content);
if(isset($raw_output)){
echo "<script type='text/javascript'> window.open('".Core::getInstancePath()."temp/".$file.".doc', null); </script>";
} else {
Generator::formsPrint("<script type='text/javascript'> window.open('".Core::getInstancePath()."temp/".$file.".doc', null); </script>");
}
}
| softdesignermonteria/proyecto | Library/Kumbia/Generator/GeneratorReport/Format/Doc.php | PHP | gpl-2.0 | 2,823 |
// Locale support (codecvt) -*- C++ -*-
// Copyright (C) 2015 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
#include <codecvt>
#include <cstring> // std::memcpy, std::memcmp
#include <bits/stl_algobase.h> // std::max
#ifdef _GLIBCXX_USE_C99_STDINT_TR1
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
namespace
{
// Largest code point that fits in a single UTF-16 code unit.
const char32_t max_single_utf16_unit = 0xFFFF;
const char32_t max_code_point = 0x10FFFF;
template<typename Elem>
struct range
{
Elem* next;
Elem* end;
Elem operator*() const { return *next; }
range& operator++() { ++next; return *this; }
size_t size() const { return end - next; }
};
// Multibyte sequences can have "header" consisting of Byte Order Mark
const unsigned char utf8_bom[3] = { 0xEF, 0xBB, 0xBF };
const unsigned char utf16_bom[4] = { 0xFE, 0xFF };
const unsigned char utf16le_bom[4] = { 0xFF, 0xFE };
template<size_t N>
inline bool
write_bom(range<char>& to, const unsigned char (&bom)[N])
{
if (to.size() < N)
return false;
memcpy(to.next, bom, N);
to.next += N;
return true;
}
// If generate_header is set in mode write out UTF-8 BOM.
bool
write_utf8_bom(range<char>& to, codecvt_mode mode)
{
if (mode & generate_header)
return write_bom(to, utf8_bom);
return true;
}
// If generate_header is set in mode write out the UTF-16 BOM indicated
// by whether little_endian is set in mode.
bool
write_utf16_bom(range<char16_t>& to, codecvt_mode mode)
{
if (mode & generate_header)
{
if (!to.size())
return false;
auto* bom = (mode & little_endian) ? utf16le_bom : utf16_bom;
std::memcpy(to.next, bom, 2);
++to.next;
}
return true;
}
template<size_t N>
inline bool
read_bom(range<const char>& from, const unsigned char (&bom)[N])
{
if (from.size() >= N && !memcmp(from.next, bom, N))
{
from.next += N;
return true;
}
return false;
}
// If consume_header is set in mode update from.next to after any BOM.
void
read_utf8_bom(range<const char>& from, codecvt_mode mode)
{
if (mode & consume_header)
read_bom(from, utf8_bom);
}
// If consume_header is set in mode update from.next to after any BOM.
// Return little_endian iff the UTF-16LE BOM was present.
codecvt_mode
read_utf16_bom(range<const char16_t>& from, codecvt_mode mode)
{
if (mode & consume_header && from.size())
{
if (*from.next == 0xFEFF)
++from.next;
else if (*from.next == 0xFFFE)
{
++from.next;
return little_endian;
}
}
return {};
}
// Read a codepoint from a UTF-8 multibyte sequence.
// Updates from.next if the codepoint is not greater than maxcode.
// Returns -1 if there is an invalid or incomplete multibyte character.
char32_t
read_utf8_code_point(range<const char>& from, unsigned long maxcode)
{
size_t avail = from.size();
if (avail == 0)
return -1;
unsigned char c1 = from.next[0];
// https://en.wikipedia.org/wiki/UTF-8#Sample_code
if (c1 < 0x80)
{
++from.next;
return c1;
}
else if (c1 < 0xC2) // continuation or overlong 2-byte sequence
return -1;
else if (c1 < 0xE0) // 2-byte sequence
{
if (avail < 2)
return -1;
unsigned char c2 = from.next[1];
if ((c2 & 0xC0) != 0x80)
return -1;
char32_t c = (c1 << 6) + c2 - 0x3080;
if (c <= maxcode)
from.next += 2;
return c;
}
else if (c1 < 0xF0) // 3-byte sequence
{
if (avail < 3)
return -1;
unsigned char c2 = from.next[1];
if ((c2 & 0xC0) != 0x80)
return -1;
if (c1 == 0xE0 && c2 < 0xA0) // overlong
return -1;
unsigned char c3 = from.next[2];
if ((c3 & 0xC0) != 0x80)
return -1;
char32_t c = (c1 << 12) + (c2 << 6) + c3 - 0xE2080;
if (c <= maxcode)
from.next += 3;
return c;
}
else if (c1 < 0xF5) // 4-byte sequence
{
if (avail < 4)
return -1;
unsigned char c2 = from.next[1];
if ((c2 & 0xC0) != 0x80)
return -1;
if (c1 == 0xF0 && c2 < 0x90) // overlong
return -1;
if (c1 == 0xF4 && c2 >= 0x90) // > U+10FFFF
return -1;
unsigned char c3 = from.next[2];
if ((c3 & 0xC0) != 0x80)
return -1;
unsigned char c4 = from.next[3];
if ((c4 & 0xC0) != 0x80)
return -1;
char32_t c = (c1 << 18) + (c2 << 12) + (c3 << 6) + c4 - 0x3C82080;
if (c <= maxcode)
from.next += 4;
return c;
}
else // > U+10FFFF
return -1;
}
bool
write_utf8_code_point(range<char>& to, char32_t code_point)
{
if (code_point < 0x80)
{
if (to.size() < 1)
return false;
*to.next++ = code_point;
}
else if (code_point <= 0x7FF)
{
if (to.size() < 2)
return false;
*to.next++ = (code_point >> 6) + 0xC0;
*to.next++ = (code_point & 0x3F) + 0x80;
}
else if (code_point <= 0xFFFF)
{
if (to.size() < 3)
return false;
*to.next++ = (code_point >> 12) + 0xE0;
*to.next++ = ((code_point >> 6) & 0x3F) + 0x80;
*to.next++ = (code_point & 0x3F) + 0x80;
}
else if (code_point <= 0x10FFFF)
{
if (to.size() < 4)
return false;
*to.next++ = (code_point >> 18) + 0xF0;
*to.next++ = ((code_point >> 12) & 0x3F) + 0x80;
*to.next++ = ((code_point >> 6) & 0x3F) + 0x80;
*to.next++ = (code_point & 0x3F) + 0x80;
}
else
return false;
return true;
}
inline char16_t
adjust_byte_order(char16_t c, codecvt_mode mode)
{
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
return (mode & little_endian) ? __builtin_bswap16(c) : c;
#else
return (mode & little_endian) ? c : __builtin_bswap16(c);
#endif
}
// Read a codepoint from a UTF-16 multibyte sequence.
// The sequence's endianness is indicated by (mode & little_endian).
// Updates from.next if the codepoint is not greater than maxcode.
// Returns -1 if there is an incomplete multibyte character.
char32_t
read_utf16_code_point(range<const char16_t>& from, unsigned long maxcode,
codecvt_mode mode)
{
int inc = 1;
char32_t c = adjust_byte_order(from.next[0], mode);
if (c >= 0xD800 && c <= 0xDBFF)
{
if (from.size() < 2)
return -1;
const char16_t c2 = adjust_byte_order(from.next[1], mode);
if (c2 >= 0xDC00 && c2 <= 0xDFFF)
{
c = (c << 10) + c2 - 0x35FDC00;
inc = 2;
}
}
if (c <= maxcode)
from.next += inc;
return c;
}
template<typename C>
bool
write_utf16_code_point(range<C>& to, char32_t codepoint, codecvt_mode mode)
{
static_assert(sizeof(C) >= 2, "a code unit must be at least 16-bit");
if (codepoint < max_single_utf16_unit)
{
if (to.size() > 0)
{
*to.next = codepoint;
++to.next;
return true;
}
}
else if (to.size() > 1)
{
// Algorithm from http://www.unicode.org/faq/utf_bom.html#utf16-4
const char32_t LEAD_OFFSET = 0xD800 - (0x10000 >> 10);
char16_t lead = LEAD_OFFSET + (codepoint >> 10);
char16_t trail = 0xDC00 + (codepoint & 0x3FF);
to.next[0] = adjust_byte_order(lead, mode);
to.next[1] = adjust_byte_order(trail, mode);
to.next += 2;
return true;
}
return false;
}
// utf8 -> ucs4
codecvt_base::result
ucs4_in(range<const char>& from, range<char32_t>& to,
unsigned long maxcode = max_code_point, codecvt_mode mode = {})
{
read_utf8_bom(from, mode);
while (from.size() && to.size())
{
const char32_t codepoint = read_utf8_code_point(from, maxcode);
if (codepoint == char32_t(-1))
break;
if (codepoint > maxcode)
return codecvt_base::error;
*to.next++ = codepoint;
}
return from.size() ? codecvt_base::partial : codecvt_base::ok;
}
// ucs4 -> utf8
codecvt_base::result
ucs4_out(range<const char32_t>& from, range<char>& to,
unsigned long maxcode = max_code_point, codecvt_mode mode = {})
{
if (!write_utf8_bom(to, mode))
return codecvt_base::partial;
while (from.size())
{
const char32_t c = from.next[0];
if (c > maxcode)
return codecvt_base::error;
if (!write_utf8_code_point(to, c))
return codecvt_base::partial;
++from.next;
}
return codecvt_base::ok;
}
// utf16 -> ucs4
codecvt_base::result
ucs4_in(range<const char16_t>& from, range<char32_t>& to,
unsigned long maxcode = max_code_point, codecvt_mode mode = {})
{
if (read_utf16_bom(from, mode) == little_endian)
mode = codecvt_mode(mode & little_endian);
while (from.size() && to.size())
{
const char32_t codepoint = read_utf16_code_point(from, maxcode, mode);
if (codepoint == char32_t(-1))
break;
if (codepoint > maxcode)
return codecvt_base::error;
*to.next++ = codepoint;
}
return from.size() ? codecvt_base::partial : codecvt_base::ok;
}
// ucs4 -> utf16
codecvt_base::result
ucs4_out(range<const char32_t>& from, range<char16_t>& to,
unsigned long maxcode = max_code_point, codecvt_mode mode = {})
{
if (!write_utf16_bom(to, mode))
return codecvt_base::partial;
while (from.size())
{
const char32_t c = from.next[0];
if (c > maxcode)
return codecvt_base::error;
if (!write_utf16_code_point(to, c, mode))
return codecvt_base::partial;
++from.next;
}
return codecvt_base::ok;
}
// utf8 -> utf16
template<typename C>
codecvt_base::result
utf16_in(range<const char>& from, range<C>& to,
unsigned long maxcode = max_code_point, codecvt_mode mode = {})
{
read_utf8_bom(from, mode);
while (from.size() && to.size())
{
const char* first = from.next;
if ((unsigned char)*first >= 0xF0 && to.size() < 2)
return codecvt_base::partial;
const char32_t codepoint = read_utf8_code_point(from, maxcode);
if (codepoint == char32_t(-1))
return codecvt_base::partial;
if (codepoint > maxcode)
return codecvt_base::error;
if (!write_utf16_code_point(to, codepoint, mode))
{
from.next = first;
return codecvt_base::partial;
}
}
return codecvt_base::ok;
}
// utf16 -> utf8
template<typename C>
codecvt_base::result
utf16_out(range<const C>& from, range<char>& to,
unsigned long maxcode = max_code_point, codecvt_mode mode = {})
{
if (!write_utf8_bom(to, mode))
return codecvt_base::partial;
while (from.size())
{
char32_t c = from.next[0];
int inc = 1;
if (c >= 0xD800 && c <= 0xDBFF) // start of surrogate pair
{
if (from.size() < 2)
return codecvt_base::ok; // stop converting at this point
const char32_t c2 = from.next[1];
if (c2 >= 0xDC00 && c2 <= 0xDFFF)
{
inc = 2;
c = (c << 10) + c2 - 0x35FDC00;
}
else
return codecvt_base::error;
}
if (c > maxcode)
return codecvt_base::error;
if (!write_utf8_code_point(to, c))
return codecvt_base::partial;
from.next += inc;
}
return codecvt_base::ok;
}
// return pos such that [begin,pos) is valid UTF-16 string no longer than max
const char*
utf16_span(const char* begin, const char* end, size_t max,
char32_t maxcode = max_code_point, codecvt_mode mode = {})
{
range<const char> from{ begin, end };
read_utf8_bom(from, mode);
size_t count = 0;
while (count+1 < max)
{
char32_t c = read_utf8_code_point(from, maxcode);
if (c == char32_t(-1))
break;
else if (c > max_single_utf16_unit)
++count;
++count;
}
if (count+1 == max) // take one more character if it fits in a single unit
read_utf8_code_point(from, std::max(max_single_utf16_unit, maxcode));
return from.next;
}
// utf8 -> ucs2
codecvt_base::result
ucs2_in(range<const char>& from, range<char16_t>& to,
char32_t maxcode = max_code_point, codecvt_mode mode = {})
{
return utf16_in(from, to, std::max(max_single_utf16_unit, maxcode), mode);
}
// ucs2 -> utf8
codecvt_base::result
ucs2_out(range<const char16_t>& from, range<char>& to,
char32_t maxcode = max_code_point, codecvt_mode mode = {})
{
return utf16_out(from, to, std::max(max_single_utf16_unit, maxcode), mode);
}
// ucs2 -> utf16
codecvt_base::result
ucs2_out(range<const char16_t>& from, range<char16_t>& to,
char32_t maxcode = max_code_point, codecvt_mode mode = {})
{
if (!write_utf16_bom(to, mode))
return codecvt_base::partial;
while (from.size() && to.size())
{
char16_t c = from.next[0];
if (c >= 0xD800 && c <= 0xDBFF) // start of surrogate pair
return codecvt_base::error;
if (c > maxcode)
return codecvt_base::error;
*to.next++ = adjust_byte_order(c, mode);
++from.next;
}
return from.size() == 0 ? codecvt_base::ok : codecvt_base::partial;
}
// utf16 -> ucs2
codecvt_base::result
ucs2_in(range<const char16_t>& from, range<char16_t>& to,
char32_t maxcode = max_code_point, codecvt_mode mode = {})
{
if (read_utf16_bom(from, mode) == little_endian)
mode = codecvt_mode(mode & little_endian);
maxcode = std::max(max_single_utf16_unit, maxcode);
while (from.size() && to.size())
{
const char32_t c = read_utf16_code_point(from, maxcode, mode);
if (c == char32_t(-1))
break;
if (c >= maxcode)
return codecvt_base::error;
*to.next++ = c;
}
return from.size() == 0 ? codecvt_base::ok : codecvt_base::partial;
}
const char16_t*
ucs2_span(const char16_t* begin, const char16_t* end, size_t max,
char32_t maxcode, codecvt_mode mode)
{
range<const char16_t> from{ begin, end };
if (read_utf16_bom(from, mode) == little_endian)
mode = codecvt_mode(mode & little_endian);
maxcode = std::max(max_single_utf16_unit, maxcode);
char32_t c = 0;
while (max-- && c <= maxcode)
c = read_utf16_code_point(from, maxcode, mode);
return from.next;
}
const char*
ucs2_span(const char* begin, const char* end, size_t max,
char32_t maxcode, codecvt_mode mode)
{
range<const char> from{ begin, end };
read_utf8_bom(from, mode);
maxcode = std::max(max_single_utf16_unit, maxcode);
char32_t c = 0;
while (max-- && c <= maxcode)
c = read_utf8_code_point(from, maxcode);
return from.next;
}
// return pos such that [begin,pos) is valid UCS-4 string no longer than max
const char*
ucs4_span(const char* begin, const char* end, size_t max,
char32_t maxcode = max_code_point, codecvt_mode mode = {})
{
range<const char> from{ begin, end };
read_utf8_bom(from, mode);
char32_t c = 0;
while (max-- && c <= maxcode)
c = read_utf8_code_point(from, maxcode);
return from.next;
}
// return pos such that [begin,pos) is valid UCS-4 string no longer than max
const char16_t*
ucs4_span(const char16_t* begin, const char16_t* end, size_t max,
char32_t maxcode = max_code_point, codecvt_mode mode = {})
{
range<const char16_t> from{ begin, end };
if (read_utf16_bom(from, mode) == little_endian)
mode = codecvt_mode(mode & little_endian);
char32_t c = 0;
while (max-- && c <= maxcode)
c = read_utf16_code_point(from, maxcode, mode);
return from.next;
}
}
// Define members of codecvt<char16_t, char, mbstate_t> specialization.
// Converts from UTF-8 to UTF-16.
locale::id codecvt<char16_t, char, mbstate_t>::id;
codecvt<char16_t, char, mbstate_t>::~codecvt() { }
codecvt_base::result
codecvt<char16_t, char, mbstate_t>::
do_out(state_type&,
const intern_type* __from,
const intern_type* __from_end, const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const
{
range<const char16_t> from{ __from, __from_end };
range<char> to{ __to, __to_end };
auto res = utf16_out(from, to);
__from_next = from.next;
__to_next = to.next;
return res;
}
codecvt_base::result
codecvt<char16_t, char, mbstate_t>::
do_unshift(state_type&, extern_type* __to, extern_type*,
extern_type*& __to_next) const
{
__to_next = __to;
return noconv; // we don't use mbstate_t for the unicode facets
}
codecvt_base::result
codecvt<char16_t, char, mbstate_t>::
do_in(state_type&, const extern_type* __from, const extern_type* __from_end,
const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const
{
range<const char> from{ __from, __from_end };
range<char16_t> to{ __to, __to_end };
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
codecvt_mode mode = {};
#else
codecvt_mode mode = little_endian;
#endif
auto res = utf16_in(from, to, max_code_point, mode);
__from_next = from.next;
__to_next = to.next;
return res;
}
int
codecvt<char16_t, char, mbstate_t>::do_encoding() const throw()
{ return 0; }
bool
codecvt<char16_t, char, mbstate_t>::do_always_noconv() const throw()
{ return false; }
int
codecvt<char16_t, char, mbstate_t>::
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const
{
__end = utf16_span(__from, __end, __max);
return __end - __from;
}
int
codecvt<char16_t, char, mbstate_t>::do_max_length() const throw()
{
// Any valid UTF-8 sequence of 3 bytes fits in a single 16-bit code unit,
// whereas 4 byte sequences require two 16-bit code units.
return 3;
}
// Define members of codecvt<char32_t, char, mbstate_t> specialization.
// Converts from UTF-8 to UTF-32 (aka UCS-4).
locale::id codecvt<char32_t, char, mbstate_t>::id;
codecvt<char32_t, char, mbstate_t>::~codecvt() { }
codecvt_base::result
codecvt<char32_t, char, mbstate_t>::
do_out(state_type&, const intern_type* __from, const intern_type* __from_end,
const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const
{
range<const char32_t> from{ __from, __from_end };
range<char> to{ __to, __to_end };
auto res = ucs4_out(from, to);
__from_next = from.next;
__to_next = to.next;
return res;
}
codecvt_base::result
codecvt<char32_t, char, mbstate_t>::
do_unshift(state_type&, extern_type* __to, extern_type*,
extern_type*& __to_next) const
{
__to_next = __to;
return noconv;
}
codecvt_base::result
codecvt<char32_t, char, mbstate_t>::
do_in(state_type&, const extern_type* __from, const extern_type* __from_end,
const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const
{
range<const char> from{ __from, __from_end };
range<char32_t> to{ __to, __to_end };
auto res = ucs4_in(from, to);
__from_next = from.next;
__to_next = to.next;
return res;
}
int
codecvt<char32_t, char, mbstate_t>::do_encoding() const throw()
{ return 0; }
bool
codecvt<char32_t, char, mbstate_t>::do_always_noconv() const throw()
{ return false; }
int
codecvt<char32_t, char, mbstate_t>::
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const
{
__end = ucs4_span(__from, __end, __max);
return __end - __from;
}
int
codecvt<char32_t, char, mbstate_t>::do_max_length() const throw()
{ return 4; }
// Define members of codecvt_utf8<char16_t> base class implementation.
// Converts from UTF-8 to UCS-2.
__codecvt_utf8_base<char16_t>::~__codecvt_utf8_base() { }
codecvt_base::result
__codecvt_utf8_base<char16_t>::
do_out(state_type&, const intern_type* __from, const intern_type* __from_end,
const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const
{
range<const char16_t> from{ __from, __from_end };
range<char> to{ __to, __to_end };
auto res = ucs2_out(from, to, _M_maxcode, _M_mode);
__from_next = from.next;
__to_next = to.next;
return res;
}
codecvt_base::result
__codecvt_utf8_base<char16_t>::
do_unshift(state_type&, extern_type* __to, extern_type*,
extern_type*& __to_next) const
{
__to_next = __to;
return noconv;
}
codecvt_base::result
__codecvt_utf8_base<char16_t>::
do_in(state_type&, const extern_type* __from, const extern_type* __from_end,
const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const
{
range<const char> from{ __from, __from_end };
range<char16_t> to{ __to, __to_end };
auto res = ucs2_in(from, to, _M_maxcode, _M_mode);
__from_next = from.next;
__to_next = to.next;
return res;
}
int
__codecvt_utf8_base<char16_t>::do_encoding() const throw()
{ return 0; }
bool
__codecvt_utf8_base<char16_t>::do_always_noconv() const throw()
{ return false; }
int
__codecvt_utf8_base<char16_t>::
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const
{
__end = ucs2_span(__from, __end, __max, _M_maxcode, _M_mode);
return __end - __from;
}
int
__codecvt_utf8_base<char16_t>::do_max_length() const throw()
{ return 3; }
// Define members of codecvt_utf8<char32_t> base class implementation.
// Converts from UTF-8 to UTF-32 (aka UCS-4).
__codecvt_utf8_base<char32_t>::~__codecvt_utf8_base() { }
codecvt_base::result
__codecvt_utf8_base<char32_t>::
do_out(state_type&, const intern_type* __from, const intern_type* __from_end,
const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const
{
range<const char32_t> from{ __from, __from_end };
range<char> to{ __to, __to_end };
auto res = ucs4_out(from, to, _M_maxcode, _M_mode);
__from_next = from.next;
__to_next = to.next;
return res;
}
codecvt_base::result
__codecvt_utf8_base<char32_t>::
do_unshift(state_type&, extern_type* __to, extern_type*,
extern_type*& __to_next) const
{
__to_next = __to;
return noconv;
}
codecvt_base::result
__codecvt_utf8_base<char32_t>::
do_in(state_type&, const extern_type* __from, const extern_type* __from_end,
const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const
{
range<const char> from{ __from, __from_end };
range<char32_t> to{ __to, __to_end };
auto res = ucs4_in(from, to, _M_maxcode, _M_mode);
__from_next = from.next;
__to_next = to.next;
return res;
}
int
__codecvt_utf8_base<char32_t>::do_encoding() const throw()
{ return 0; }
bool
__codecvt_utf8_base<char32_t>::do_always_noconv() const throw()
{ return false; }
int
__codecvt_utf8_base<char32_t>::
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const
{
__end = ucs4_span(__from, __end, __max, _M_maxcode, _M_mode);
return __end - __from;
}
int
__codecvt_utf8_base<char32_t>::do_max_length() const throw()
{ return 4; }
#ifdef _GLIBCXX_USE_WCHAR_T
// Define members of codecvt_utf8<wchar_t> base class implementation.
// Converts from UTF-8 to UCS-2 or UCS-4 depending on sizeof(wchar_t).
__codecvt_utf8_base<wchar_t>::~__codecvt_utf8_base() { }
codecvt_base::result
__codecvt_utf8_base<wchar_t>::
do_out(state_type&, const intern_type* __from, const intern_type* __from_end,
const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const
{
range<char> to{ __to, __to_end };
#if __SIZEOF_WCHAR_T__ == 2
range<const char16_t> from{
reinterpret_cast<const char16_t*>(__from),
reinterpret_cast<const char16_t*>(__from_end)
};
auto res = ucs2_out(from, to, _M_maxcode, _M_mode);
#elif __SIZEOF_WCHAR_T__ == 4
range<const char32_t> from{
reinterpret_cast<const char32_t*>(__from),
reinterpret_cast<const char32_t*>(__from_end)
};
auto res = ucs4_out(from, to, _M_maxcode, _M_mode);
#else
return codecvt_base::error;
#endif
__from_next = reinterpret_cast<const wchar_t*>(from.next);
__to_next = to.next;
return res;
}
codecvt_base::result
__codecvt_utf8_base<wchar_t>::
do_unshift(state_type&, extern_type* __to, extern_type*,
extern_type*& __to_next) const
{
__to_next = __to;
return noconv;
}
codecvt_base::result
__codecvt_utf8_base<wchar_t>::
do_in(state_type&, const extern_type* __from, const extern_type* __from_end,
const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const
{
range<const char> from{ __from, __from_end };
#if __SIZEOF_WCHAR_T__ == 2
range<char16_t> to{
reinterpret_cast<char16_t*>(__to),
reinterpret_cast<char16_t*>(__to_end)
};
auto res = ucs2_in(from, to, _M_maxcode, _M_mode);
#elif __SIZEOF_WCHAR_T__ == 4
range<char32_t> to{
reinterpret_cast<char32_t*>(__to),
reinterpret_cast<char32_t*>(__to_end)
};
auto res = ucs4_in(from, to, _M_maxcode, _M_mode);
#else
return codecvt_base::error;
#endif
__from_next = from.next;
__to_next = reinterpret_cast<wchar_t*>(to.next);
return res;
}
int
__codecvt_utf8_base<wchar_t>::do_encoding() const throw()
{ return 0; }
bool
__codecvt_utf8_base<wchar_t>::do_always_noconv() const throw()
{ return false; }
int
__codecvt_utf8_base<wchar_t>::
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const
{
#if __SIZEOF_WCHAR_T__ == 2
__end = ucs2_span(__from, __end, __max, _M_maxcode, _M_mode);
#elif __SIZEOF_WCHAR_T__ == 4
__end = ucs4_span(__from, __end, __max, _M_maxcode, _M_mode);
#else
__end = __from;
#endif
return __end - __from;
}
int
__codecvt_utf8_base<wchar_t>::do_max_length() const throw()
{ return 4; }
#endif
// Define members of codecvt_utf16<char16_t> base class implementation.
// Converts from UTF-16 to UCS-2.
__codecvt_utf16_base<char16_t>::~__codecvt_utf16_base() { }
codecvt_base::result
__codecvt_utf16_base<char16_t>::
do_out(state_type&, const intern_type* __from, const intern_type* __from_end,
const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const
{
range<const char16_t> from{ __from, __from_end };
range<char16_t> to{
reinterpret_cast<char16_t*>(__to),
reinterpret_cast<char16_t*>(__to_end)
};
auto res = ucs2_out(from, to, _M_maxcode, _M_mode);
__from_next = from.next;
__to_next = reinterpret_cast<char*>(to.next);
return res;
}
codecvt_base::result
__codecvt_utf16_base<char16_t>::
do_unshift(state_type&, extern_type* __to, extern_type*,
extern_type*& __to_next) const
{
__to_next = __to;
return noconv;
}
codecvt_base::result
__codecvt_utf16_base<char16_t>::
do_in(state_type&, const extern_type* __from, const extern_type* __from_end,
const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const
{
range<const char16_t> from{
reinterpret_cast<const char16_t*>(__from),
reinterpret_cast<const char16_t*>(__from_end)
};
range<char16_t> to{ __to, __to_end };
auto res = ucs2_in(from, to, _M_maxcode, _M_mode);
__from_next = reinterpret_cast<const char*>(from.next);
__to_next = to.next;
return res;
}
int
__codecvt_utf16_base<char16_t>::do_encoding() const throw()
{ return 1; }
bool
__codecvt_utf16_base<char16_t>::do_always_noconv() const throw()
{ return false; }
int
__codecvt_utf16_base<char16_t>::
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const
{
auto next = reinterpret_cast<const char16_t*>(__from);
next = ucs2_span(next, reinterpret_cast<const char16_t*>(__end), __max,
_M_maxcode, _M_mode);
return reinterpret_cast<const char*>(next) - __from;
}
int
__codecvt_utf16_base<char16_t>::do_max_length() const throw()
{ return 3; }
// Define members of codecvt_utf16<char32_t> base class implementation.
// Converts from UTF-16 to UTF-32 (aka UCS-4).
__codecvt_utf16_base<char32_t>::~__codecvt_utf16_base() { }
codecvt_base::result
__codecvt_utf16_base<char32_t>::
do_out(state_type&, const intern_type* __from, const intern_type* __from_end,
const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const
{
range<const char32_t> from{ __from, __from_end };
range<char16_t> to{
reinterpret_cast<char16_t*>(__to),
reinterpret_cast<char16_t*>(__to_end)
};
auto res = ucs4_out(from, to, _M_maxcode, _M_mode);
__from_next = from.next;
__to_next = reinterpret_cast<char*>(to.next);
return res;
}
codecvt_base::result
__codecvt_utf16_base<char32_t>::
do_unshift(state_type&, extern_type* __to, extern_type*,
extern_type*& __to_next) const
{
__to_next = __to;
return noconv;
}
codecvt_base::result
__codecvt_utf16_base<char32_t>::
do_in(state_type&, const extern_type* __from, const extern_type* __from_end,
const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const
{
range<const char16_t> from{
reinterpret_cast<const char16_t*>(__from),
reinterpret_cast<const char16_t*>(__from_end)
};
range<char32_t> to{ __to, __to_end };
auto res = ucs4_in(from, to, _M_maxcode, _M_mode);
__from_next = reinterpret_cast<const char*>(from.next);
__to_next = to.next;
return res;
}
int
__codecvt_utf16_base<char32_t>::do_encoding() const throw()
{ return 0; }
bool
__codecvt_utf16_base<char32_t>::do_always_noconv() const throw()
{ return false; }
int
__codecvt_utf16_base<char32_t>::
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const
{
auto next = reinterpret_cast<const char16_t*>(__from);
next = ucs4_span(next, reinterpret_cast<const char16_t*>(__end), __max,
_M_maxcode, _M_mode);
return reinterpret_cast<const char*>(next) - __from;
}
int
__codecvt_utf16_base<char32_t>::do_max_length() const throw()
{ return 3; }
#ifdef _GLIBCXX_USE_WCHAR_T
// Define members of codecvt_utf16<wchar_t> base class implementation.
// Converts from UTF-8 to UCS-2 or UCS-4 depending on sizeof(wchar_t).
__codecvt_utf16_base<wchar_t>::~__codecvt_utf16_base() { }
codecvt_base::result
__codecvt_utf16_base<wchar_t>::
do_out(state_type&, const intern_type* __from, const intern_type* __from_end,
const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const
{
range<char> to{ __to, __to_end };
#if __SIZEOF_WCHAR_T__ == 2
range<const char16_t> from{
reinterpret_cast<const char16_t*>(__from),
reinterpret_cast<const char16_t*>(__from_end)
};
auto res = ucs2_out(from, to, _M_maxcode, _M_mode);
#elif __SIZEOF_WCHAR_T__ == 4
range<const char32_t> from{
reinterpret_cast<const char32_t*>(__from),
reinterpret_cast<const char32_t*>(__from_end)
};
auto res = ucs4_out(from, to, _M_maxcode, _M_mode);
#else
return codecvt_base::error;
#endif
__from_next = reinterpret_cast<const wchar_t*>(from.next);
__to_next = to.next;
return res;
}
codecvt_base::result
__codecvt_utf16_base<wchar_t>::
do_unshift(state_type&, extern_type* __to, extern_type*,
extern_type*& __to_next) const
{
__to_next = __to;
return noconv;
}
codecvt_base::result
__codecvt_utf16_base<wchar_t>::
do_in(state_type&, const extern_type* __from, const extern_type* __from_end,
const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const
{
range<const char> from{ __from, __from_end };
#if __SIZEOF_WCHAR_T__ == 2
range<char16_t> to{
reinterpret_cast<char16_t*>(__to),
reinterpret_cast<char16_t*>(__to_end)
};
auto res = ucs2_in(from, to, _M_maxcode, _M_mode);
#elif __SIZEOF_WCHAR_T__ == 4
range<char32_t> to{
reinterpret_cast<char32_t*>(__to),
reinterpret_cast<char32_t*>(__to_end)
};
auto res = ucs4_in(from, to, _M_maxcode, _M_mode);
#else
return codecvt_base::error;
#endif
__from_next = from.next;
__to_next = reinterpret_cast<wchar_t*>(to.next);
return res;
}
int
__codecvt_utf16_base<wchar_t>::do_encoding() const throw()
{ return 0; }
bool
__codecvt_utf16_base<wchar_t>::do_always_noconv() const throw()
{ return false; }
int
__codecvt_utf16_base<wchar_t>::
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const
{
auto next = reinterpret_cast<const char16_t*>(__from);
#if __SIZEOF_WCHAR_T__ == 2
next = ucs2_span(next, reinterpret_cast<const char16_t*>(__end), __max,
_M_maxcode, _M_mode);
#elif __SIZEOF_WCHAR_T__ == 4
next = ucs4_span(next, reinterpret_cast<const char16_t*>(__end), __max,
_M_maxcode, _M_mode);
#endif
return reinterpret_cast<const char*>(next) - __from;
}
int
__codecvt_utf16_base<wchar_t>::do_max_length() const throw()
{ return 4; }
#endif
// Define members of codecvt_utf8_utf16<char16_t> base class implementation.
// Converts from UTF-8 to UTF-16.
__codecvt_utf8_utf16_base<char16_t>::~__codecvt_utf8_utf16_base() { }
codecvt_base::result
__codecvt_utf8_utf16_base<char16_t>::
do_out(state_type&, const intern_type* __from, const intern_type* __from_end,
const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const
{
range<const char16_t> from{ __from, __from_end };
range<char> to{ __to, __to_end };
auto res = utf16_out(from, to, _M_maxcode, _M_mode);
__from_next = from.next;
__to_next = to.next;
return res;
}
codecvt_base::result
__codecvt_utf8_utf16_base<char16_t>::
do_unshift(state_type&, extern_type* __to, extern_type*,
extern_type*& __to_next) const
{
__to_next = __to;
return noconv;
}
codecvt_base::result
__codecvt_utf8_utf16_base<char16_t>::
do_in(state_type&, const extern_type* __from, const extern_type* __from_end,
const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const
{
range<const char> from{ __from, __from_end };
range<char16_t> to{ __to, __to_end };
auto res = utf16_in(from, to, _M_maxcode, _M_mode);
__from_next = from.next;
__to_next = to.next;
return res;
}
int
__codecvt_utf8_utf16_base<char16_t>::do_encoding() const throw()
{ return 0; }
bool
__codecvt_utf8_utf16_base<char16_t>::do_always_noconv() const throw()
{ return false; }
int
__codecvt_utf8_utf16_base<char16_t>::
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const
{
__end = utf16_span(__from, __end, __max, _M_maxcode, _M_mode);
return __end - __from;
}
int
__codecvt_utf8_utf16_base<char16_t>::do_max_length() const throw()
{
// Any valid UTF-8 sequence of 3 bytes fits in a single 16-bit code unit,
// whereas 4 byte sequences require two 16-bit code units.
return 3;
}
// Define members of codecvt_utf8_utf16<char32_t> base class implementation.
// Converts from UTF-8 to UTF-16.
__codecvt_utf8_utf16_base<char32_t>::~__codecvt_utf8_utf16_base() { }
codecvt_base::result
__codecvt_utf8_utf16_base<char32_t>::
do_out(state_type&, const intern_type* __from, const intern_type* __from_end,
const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const
{
range<const char32_t> from{ __from, __from_end };
range<char> to{ __to, __to_end };
auto res = utf16_out(from, to, _M_maxcode, _M_mode);
__from_next = from.next;
__to_next = to.next;
return res;
}
codecvt_base::result
__codecvt_utf8_utf16_base<char32_t>::
do_unshift(state_type&, extern_type* __to, extern_type*,
extern_type*& __to_next) const
{
__to_next = __to;
return noconv;
}
codecvt_base::result
__codecvt_utf8_utf16_base<char32_t>::
do_in(state_type&, const extern_type* __from, const extern_type* __from_end,
const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const
{
range<const char> from{ __from, __from_end };
range<char32_t> to{ __to, __to_end };
auto res = utf16_in(from, to, _M_maxcode, _M_mode);
__from_next = from.next;
__to_next = to.next;
return res;
}
int
__codecvt_utf8_utf16_base<char32_t>::do_encoding() const throw()
{ return 0; }
bool
__codecvt_utf8_utf16_base<char32_t>::do_always_noconv() const throw()
{ return false; }
int
__codecvt_utf8_utf16_base<char32_t>::
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const
{
__end = utf16_span(__from, __end, __max, _M_maxcode, _M_mode);
return __end - __from;
}
int
__codecvt_utf8_utf16_base<char32_t>::do_max_length() const throw()
{
// Any valid UTF-8 sequence of 3 bytes fits in a single 16-bit code unit,
// whereas 4 byte sequences require two 16-bit code units.
return 3;
}
#ifdef _GLIBCXX_USE_WCHAR_T
// Define members of codecvt_utf8_utf16<wchar_t> base class implementation.
// Converts from UTF-8 to UTF-16.
__codecvt_utf8_utf16_base<wchar_t>::~__codecvt_utf8_utf16_base() { }
codecvt_base::result
__codecvt_utf8_utf16_base<wchar_t>::
do_out(state_type&, const intern_type* __from, const intern_type* __from_end,
const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const
{
range<const wchar_t> from{ __from, __from_end };
range<char> to{ __to, __to_end };
auto res = utf16_out(from, to, _M_maxcode, _M_mode);
__from_next = from.next;
__to_next = to.next;
return res;
}
codecvt_base::result
__codecvt_utf8_utf16_base<wchar_t>::
do_unshift(state_type&, extern_type* __to, extern_type*,
extern_type*& __to_next) const
{
__to_next = __to;
return noconv;
}
codecvt_base::result
__codecvt_utf8_utf16_base<wchar_t>::
do_in(state_type&, const extern_type* __from, const extern_type* __from_end,
const extern_type*& __from_next,
intern_type* __to, intern_type* __to_end,
intern_type*& __to_next) const
{
range<const char> from{ __from, __from_end };
range<wchar_t> to{ __to, __to_end };
auto res = utf16_in(from, to, _M_maxcode, _M_mode);
__from_next = from.next;
__to_next = to.next;
return res;
}
int
__codecvt_utf8_utf16_base<wchar_t>::do_encoding() const throw()
{ return 0; }
bool
__codecvt_utf8_utf16_base<wchar_t>::do_always_noconv() const throw()
{ return false; }
int
__codecvt_utf8_utf16_base<wchar_t>::
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const
{
__end = utf16_span(__from, __end, __max, _M_maxcode, _M_mode);
return __end - __from;
}
int
__codecvt_utf8_utf16_base<wchar_t>::do_max_length() const throw()
{
// Any valid UTF-8 sequence of 3 bytes fits in a single 16-bit code unit,
// whereas 4 byte sequences require two 16-bit code units.
return 3;
}
#endif
inline template class __codecvt_abstract_base<char16_t, char, mbstate_t>;
inline template class __codecvt_abstract_base<char32_t, char, mbstate_t>;
template class codecvt_byname<char16_t, char, mbstate_t>;
template class codecvt_byname<char32_t, char, mbstate_t>;
_GLIBCXX_END_NAMESPACE_VERSION
}
#endif // _GLIBCXX_USE_C99_STDINT_TR1
| villevoutilainen/gcc | libstdc++-v3/src/c++11/codecvt.cc | C++ | gpl-2.0 | 39,721 |
/**
* Provides a DataSchema implementation which can be used to work with
* delimited text data.
*
* @module dataschema
* @submodule dataschema-text
*/
/**
Provides a DataSchema implementation which can be used to work with
delimited text data.
See the `apply` method for usage.
@class DataSchema.Text
@extends DataSchema.Base
@static
**/
var Lang = Y.Lang,
isString = Lang.isString,
isUndef = Lang.isUndefined,
SchemaText = {
////////////////////////////////////////////////////////////////////////
//
// DataSchema.Text static methods
//
////////////////////////////////////////////////////////////////////////
/**
Applies a schema to a string of delimited data, returning a normalized
object with results in the `results` property. The `meta` property of
the response object is present for consistency, but is assigned an
empty object. If the input data is absent or not a string, an `error`
property will be added.
Use _schema.resultDelimiter_ and _schema.fieldDelimiter_ to instruct
`apply` how to split up the string into an array of data arrays for
processing.
Use _schema.resultFields_ to specify the keys in the generated result
objects in `response.results`. The key:value pairs will be assigned
in the order of the _schema.resultFields_ array, assuming the values
in the data records are defined in the same order.
_schema.resultFields_ field identifiers are objects with the following
properties:
* `key` : <strong>(required)</strong> The property name you want
the data value assigned to in the result object (String)
* `parser`: A function or the name of a function on `Y.Parsers` used
to convert the input value into a normalized type. Parser
functions are passed the value as input and are expected to
return a value.
If no value parsing is needed, you can use just the desired property
name string as the field identifier instead of an object (see example
below).
@example
// Process simple csv
var schema = {
resultDelimiter: "\n",
fieldDelimiter: ",",
resultFields: [ 'fruit', 'color' ]
},
data = "Banana,yellow\nOrange,orange\nEggplant,purple";
var response = Y.DataSchema.Text.apply(schema, data);
// response.results[0] is { fruit: "Banana", color: "yellow" }
// Use parsers
schema.resultFields = [
{
key: 'fruit',
parser: function (val) { return val.toUpperCase(); }
},
'color' // mix and match objects and strings
];
response = Y.DataSchema.Text.apply(schema, data);
// response.results[0] is { fruit: "BANANA", color: "yellow" }
@method apply
@param {Object} schema Schema to apply. Supported configuration
properties are:
@param {String} schema.resultDelimiter Character or character
sequence that marks the end of one record and the start of
another.
@param {String} [schema.fieldDelimiter] Character or character
sequence that marks the end of a field and the start of
another within the same record.
@param {Array} [schema.resultFields] Field identifiers to
assign values in the response records. See above for details.
@param {String} data Text data.
@return {Object} An Object with properties `results` and `meta`
@static
**/
apply: function(schema, data) {
var data_in = data,
data_out = { results: [], meta: {} };
if (isString(data) && schema && isString(schema.resultDelimiter)) {
// Parse results data
data_out = SchemaText._parseResults.call(this, schema, data_in, data_out);
} else {
Y.log("Text data could not be schema-parsed: " + Y.dump(data) + " " + Y.dump(data), "error", "dataschema-text");
data_out.error = new Error("Text schema parse failure");
}
return data_out;
},
/**
* Schema-parsed list of results from full data
*
* @method _parseResults
* @param schema {Array} Schema to parse against.
* @param text_in {String} Text to parse.
* @param data_out {Object} In-progress parsed data to update.
* @return {Object} Parsed data object.
* @static
* @protected
*/
_parseResults: function(schema, text_in, data_out) {
var resultDelim = schema.resultDelimiter,
fieldDelim = isString(schema.fieldDelimiter) &&
schema.fieldDelimiter,
fields = schema.resultFields || [],
results = [],
parse = Y.DataSchema.Base.parse,
results_in, fields_in, result, item,
field, key, value, i, j;
// Delete final delimiter at end of string if there
if (text_in.slice(-resultDelim.length) === resultDelim) {
text_in = text_in.slice(0, -resultDelim.length);
}
// Split into results
results_in = text_in.split(schema.resultDelimiter);
if (fieldDelim) {
for (i = results_in.length - 1; i >= 0; --i) {
result = {};
item = results_in[i];
fields_in = item.split(schema.fieldDelimiter);
for (j = fields.length - 1; j >= 0; --j) {
field = fields[j];
key = (!isUndef(field.key)) ? field.key : field;
// FIXME: unless the key is an array index, this test
// for fields_in[key] is useless.
value = (!isUndef(fields_in[key])) ?
fields_in[key] :
fields_in[j];
result[key] = parse.call(this, value, field);
}
results[i] = result;
}
} else {
results = results_in;
}
data_out.results = results;
return data_out;
}
};
Y.DataSchema.Text = Y.mix(SchemaText, Y.DataSchema.Base);
| schancel/gameserver | public/js/yui3-3.12.0/src/dataschema/js/dataschema-text.js | JavaScript | gpl-2.0 | 6,718 |
# -*- coding: utf-8 -*-
#
# Watermarks documentation build configuration file, created by
# sphinx-quickstart on Tue Apr 8 16:49:39 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
src_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'src')
sys.path.insert(0, src_dir)
import watermarks
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Watermarks'
copyright = u'2014, Vladimir Chovanec'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = watermarks.__version__
# The full version, including alpha/beta/rc tags.
release = watermarks.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Watermarksdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'Watermarks.tex', u'Watermarks Documentation',
u'Vladimir Chovanec', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'watermarks', u'Watermarks Documentation',
[u'Vladimir Chovanec'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Watermarks', u'Watermarks Documentation',
u'Vladimir Chovanec', 'Watermarks', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
| vladozc/watermarks | doc/source/conf.py | Python | gpl-2.0 | 8,359 |
<?php
/*
* Page that is shown to the user when the plugin was not correctly installed.
* This is just a fallback in case something went wrong somewhere.
* Maybe it just needs to be removed alltogether.
*/
function gwolle_gb_installSplash() {
?>
<div class="wrap">
<div id="icon-gwolle-gb"><br /></div>
<h1>Gwolle-GB —
<?php _e('Installation','gwolle-gb'); ?>
</h1>
<div>
<?php
if ( !isset($_REQUEST['install_gwolle_gb']) || $_REQUEST['install_gwolle_gb'] != 'install_gwolle_gb') {
_e('Welcome!<br>It seems that either you\'re using this plugin for the first time or you\'ve deleted all settings.<br>However, to use this plugin we have to setup the database tables. Good for you, we\'ve made this as easy as possible.<br>All you\'ve got to do is click on that button below, and that\'s it.','gwolle-gb');
?>
<br /><br />
<div>
<form action="<?php echo $_SERVER['PHP_SELF'] . '?page=' . $_REQUEST['page']; ?>" method="POST">
<input type="hidden" id="install_gwolle_gb" name="install_gwolle_gb" value="install_gwolle_gb" />
<input type="submit" class="button button-primary" value="<?php esc_attr_e('Sure, let\'s do this!', 'gwolle-gb'); ?>">
</form>
</div>
<?php
} elseif ( isset($_REQUEST['install_gwolle_gb']) && $_REQUEST['install_gwolle_gb'] == 'install_gwolle_gb' && !get_option('gwolle_gb_version') ) {
// perform installation
gwolle_gb_install();
echo sprintf( __('Allright, we\'re done. <a href="%s">Click here to continue...</a>', 'gwolle-gb'), $_SERVER['PHP_SELF'] . '?page=' . $_REQUEST['page'] );
} else {
echo sprintf( __('It looks like there has been an error. <a href="%s">Click here to continue...</a>', 'gwolle-gb'), $_SERVER['PHP_SELF'] . '?page=' . $_REQUEST['page'] );
}
?>
</div>
</div>
<?php
}
| artran03/AriChezVous | wp-content/plugins/gwolle-gb/admin/installSplash.php | PHP | gpl-2.0 | 1,824 |
/* This file was generated by SableCC (http://www.sablecc.org/). */
package se.sics.kola.node;
public abstract class PResource extends Node
{
// Empty body
}
| kompics/kola | src/main/java/se/sics/kola/node/PResource.java | Java | gpl-2.0 | 164 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 2.2 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2009 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License along with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2009
* $Id$
*
*/
require_once 'CRM/Core/Selector/Base.php';
require_once 'CRM/Core/Selector/API.php';
require_once 'CRM/Utils/Pager.php';
require_once 'CRM/Utils/Sort.php';
require_once 'CRM/Contact/BAO/Query.php';
/**
* This class is used to retrieve and display a range of
* contacts that match the given criteria (specifically for
* results of advanced search options.
*
*/
class CRM_Grant_Selector_Search extends CRM_Core_Selector_Base implements CRM_Core_Selector_API
{
/**
* This defines two actions- View and Edit.
*
* @var array
* @static
*/
static $_links = null;
/**
* we use desc to remind us what that column is, name is used in the tpl
*
* @var array
* @static
*/
static $_columnHeaders;
/**
* Properties of contact we're interested in displaying
* @var array
* @static
*/
static $_properties = array( 'contact_id',
'contact_type',
'sort_name',
'grant_id',
'grant_status_id',
'grant_type_id',
'grant_amount_total',
'grant_amount_requested',
'grant_amount_granted',
'grant_application_received_date',
'grant_report_received',
'grant_money_transfer_date',
);
/**
* are we restricting ourselves to a single contact
*
* @access protected
* @var boolean
*/
protected $_single = false;
/**
* are we restricting ourselves to a single contact
*
* @access protected
* @var boolean
*/
protected $_limit = null;
/**
* what context are we being invoked from
*
* @access protected
* @var string
*/
protected $_context = null;
/**
* queryParams is the array returned by exportValues called on
* the HTML_QuickForm_Controller for that page.
*
* @var array
* @access protected
*/
public $_queryParams;
/**
* represent the type of selector
*
* @var int
* @access protected
*/
protected $_action;
/**
* The additional clause that we restrict the search with
*
* @var string
*/
protected $_grantClause = null;
/**
* The query object
*
* @var string
*/
protected $_query;
/**
* Class constructor
*
* @param array $queryParams array of parameters for query
* @param int $action - action of search basic or advanced.
* @param string $grantClause if the caller wants to further restrict the search
* @param boolean $single are we dealing only with one contact?
* @param int $limit how many participations do we want returned
*
* @return CRM_Contact_Selector
* @access public
*/
function __construct(&$queryParams,
$action = CRM_Core_Action::NONE,
$grantClause = null,
$single = false,
$limit = null,
$context = 'search' )
{
// submitted form values
$this->_queryParams =& $queryParams;
$this->_single = $single;
$this->_limit = $limit;
$this->_context = $context;
$this->_grantClause = $grantClause;
// type of selector
$this->_action = $action;
$this->_query =& new CRM_Contact_BAO_Query( $this->_queryParams, null, null, false, false,
CRM_Contact_BAO_Query::MODE_GRANT );
}//end of constructor
/**
* This method returns the links that are given for each search row.
* currently the links added for each row are
*
* - View
* - Edit
*
* @return array
* @access public
*
*/
static function &links()
{
$cid = CRM_Utils_Request::retrieve('cid', 'Integer', $this);
if (!(self::$_links)) {
self::$_links = array(
CRM_Core_Action::VIEW => array(
'name' => ts('View'),
'url' => 'civicrm/contact/view/grant',
'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=grant',
'title' => ts('View Grant'),
),
CRM_Core_Action::UPDATE => array(
'name' => ts('Edit'),
'url' => 'civicrm/contact/view/grant',
'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%',
'title' => ts('Edit Grant'),
),
);
if ( $cid ) {
$deleteExtra = ts('Are you sure you want to delete this grant?');
$delLink = array(
CRM_Core_Action::DELETE => array( 'name' => ts('Delete'),
'url' => 'civicrm/contact/view/grant',
'qs' => 'action=delete&reset=1&cid=%%cid%%&id=%%id%%&selectedChild=grant',
'extra' => 'onclick = "if (confirm(\'' . $deleteExtra . '\') ) this.href+=\'&confirmed=1\'; else return false;"',
'title' => ts('Delete Grant')
)
);
self::$_links = self::$_links + $delLink ;
}
}
return self::$_links;
} //end of function
/**
* getter for array of the parameters required for creating pager.
*
* @param
* @access public
*/
function getPagerParams($action, &$params)
{
$params['status'] = ts('Grant') . ' %%StatusMessage%%';
$params['csvString'] = null;
if ( $this->_limit ) {
$params['rowCount'] = $this->_limit;
} else {
$params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
}
$params['buttonTop'] = 'PagerTopButton';
$params['buttonBottom'] = 'PagerBottomButton';
} //end of function
/**
* Returns total number of rows for the query.
*
* @param
* @return int Total number of rows
* @access public
*/
function getTotalCount($action)
{
return $this->_query->searchQuery( 0, 0, null,
true, false,
false, false,
false,
$this->_grantClause );
}
/**
* returns all the rows in the given offset and rowCount *
* @param enum $action the action being performed
* @param int $offset the row number to start from
* @param int $rowCount the number of rows to return
* @param string $sort the sql string that describes the sort order
* @param enum $output what should the result set include (web/email/csv)
*
* @return int the total number of rows for this action
*/
function &getRows($action, $offset, $rowCount, $sort, $output = null)
{
$result = $this->_query->searchQuery( $offset, $rowCount, $sort,
false, false,
false, false,
false,
$this->_grantClause );
// process the result of the query
$rows = array( );
// check is the user has view/edit permission
$permission = CRM_Core_Permission::VIEW;
if ( CRM_Core_Permission::check( 'edit grants' ) ) {
$permission = CRM_Core_Permission::EDIT;
}
require_once 'CRM/Grant/PseudoConstant.php';
$grantStatus = array( );
$grantStatus = CRM_Grant_PseudoConstant::grantStatus( );
$grantType = array( );
$grantType = CRM_Grant_PseudoConstant::grantType( );
$mask = CRM_Core_Action::mask( $permission );
while ($result->fetch()) {
$row = array();
// the columns we are interested in
foreach (self::$_properties as $property) {
if ( isset( $result->$property ) ) {
$row[$property] = $result->$property;
}
}
//fix status display
$row['grant_status'] = $grantStatus[$row['grant_status_id']];
$row['grant_type'] = $grantType[$row['grant_type_id']];
if ($this->_context == 'search') {
$row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->grant_id;
}
$row['action'] = CRM_Core_Action::formLink( self::links(), $mask,
array( 'id' => $result->grant_id,
'cid' => $result->contact_id,
'cxt' => $this->_context ) );
require_once( 'CRM/Contact/BAO/Contact/Utils.php' );
$row['contact_type' ] = CRM_Contact_BAO_Contact_Utils::getImage( $result->contact_type );
$rows[] = $row;
}
return $rows;
}
/**
* @return array $qill which contains an array of strings
* @access public
*/
// the current internationalisation is bad, but should more or less work
// for most of "European" languages
public function getQILL( )
{
return $this->_query->qill( );
}
/**
* returns the column headers as an array of tuples:
* (name, sortName (key to the sort array))
*
* @param string $action the action being performed
* @param enum $output what should the result set include (web/email/csv)
*
* @return array the column headers that need to be displayed
* @access public
*/
public function &getColumnHeaders( $action = null, $output = null )
{
if ( ! isset( self::$_columnHeaders ) ) {
self::$_columnHeaders = array(
array('name' => ts('Status'),
'sort' => 'grant_status_id',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Type'),
'sort' => 'grant_type_id',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Amount Requested'),
'sort' => 'grant_amount_total',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Amount Granted'),
'sort' => 'grant_amount_granted',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Application Received'),
'sort' => 'grant_application_received_date',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Report Received'),
'sort' => 'grant_report_received',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array(
'name' => ts('Money Transferred'),
'sort' => 'money_transfer_date',
'direction' => CRM_Utils_Sort::DONTCARE,
),
array('desc' => ts('Actions') ),
);
if ( ! $this->_single ) {
$pre = array(
array('desc' => ts('Contact Type') ),
array(
'name' => ts('Name'),
'sort' => 'sort_name',
'direction' => CRM_Utils_Sort::ASCENDING,
)
);
self::$_columnHeaders = array_merge( $pre, self::$_columnHeaders );
}
}
return self::$_columnHeaders;
}
function &getQuery( ) {
return $this->_query;
}
/**
* name of export file.
*
* @param string $output type of output
* @return string name of the file
*/
function getExportFileName( $output = 'csv') {
return ts('CiviCRM Grant Search');
}
}//end of class
| btribulski/girlsknowhow | sites/all/modules/civicrm/CRM/Grant/Selector/Search.php | PHP | gpl-2.0 | 16,778 |
using System;
namespace Server.Items
{
public class LanternHand : BaseLight, IFlipable
{
public override int LabelNumber { get { return 1011221; } } // lantern
public override int LitItemID { get { return ItemID == 0xA471 ? 0xA472 : 0xA476; } }
public override int UnlitItemID { get { return ItemID == 0xA472 ? 0xA471 : 0xA475; } }
public int NorthID { get { return Burning ? 0xA472 : 0xA471; } }
public int WestID { get { return Burning ? 0xA476 : 0xA475; } }
[Constructable]
public LanternHand()
: base(0xA471)
{
Weight = 1;
}
public void OnFlip(Mobile from)
{
if (ItemID == NorthID)
ItemID = WestID;
else if (ItemID == WestID)
ItemID = NorthID;
}
public LanternHand(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
| kevin-10/ServUO | Scripts/Items/Decorative/ArtisanFestivalRewards/LanternHand.cs | C# | gpl-2.0 | 1,255 |
class Extended_GetIn_EventHandlers
{
class StaticMGWeapon
{
class ace_ifa3staticweapon
{
getIn = "_this call ace_ifa3staticweapon_fnc_getIn";
};
};
class StaticMortar
{
class ace_ifa3staticweapon
{
getIn = "_this call ace_ifa3staticweapon_fnc_getIn";
};
};
}; | bux/IFA3_ACE_COMPAT | addons/staticweapon/Extended_GetIn_EventHandlers.hpp | C++ | gpl-2.0 | 283 |
<?php
defined('ABSPATH') OR exit;
if(!class_exists('Picturefill_WP_Function_Helpers')){
class Picturefill_WP_Function_Helpers{
private $filter = '';
private $cache_duration = 86400;
private $image_sizes_to_remove = array();
private $image_size_to_add = '';
private $insert_before = '';
private $image_size_array = array();
private $new_image_size_queue = array();
public $post_type_to_exclude = '';
public $post_id_to_exclude = '';
public $post_slug_to_exclude = '';
public $post_tag_to_exclude = '';
public $post_category_to_exclude = '';
public static function retina_only($default_image_sizes, $image_attributes){
if('full' === $image_attributes['size'][1]){
return array($image_attributes['size'][1]);
}else{
return array(
$image_attributes['size'][1],
$image_attributes['size'][1] . '@2x'
);
}
}
public static function remove_line_breaks($output){
return str_replace("\n", '', $output);
}
public static function min_template($template_file_path, $template, $template_path){
return $template_path . 'min/' . $template . '-template.php';
}
public function apply_to_filter($filter){
$this->filter = $filter;
add_filter($filter, array($this, '_apply_picturefill_wp_to_filter'));
}
public function set_cache_duration($cache_duration){
$this->cache_duration = $cache_duration;
add_filter('picturefill_wp_cache_duration', array($this, '_set_cache_duration'));
}
public function remove_image_from_responsive_list($image_size){
if('string' === gettype($image_size)){
$this->image_sizes_to_remove = array($image_size, $image_size . '@2x');
}elseif('array' === gettype($image_size)){
$this->image_sizes_to_remove = array();
foreach($image_size as $size){
$this->image_sizes_to_remove[] = $size;
$this->image_sizes_to_remove[] = $size . '@2x';
}
}
add_filter('picturefill_wp_image_sizes', array($this, '_remove_image_from_responsive_list'), 10, 2);
}
public function add_image_to_responsive_queue($image_size, $insert_before){
$this->image_size_to_add = $image_size;
$this->insert_before = $insert_before;
add_filter('picturefill_wp_image_attachment_data', array($this, '_add_size_attachment_data'), 10, 2);
add_filter('picturefill_wp_image_sizes', array($this, '_add_size_to_responsive_image_list'), 11, 2);
}
public function set_responsive_image_sizes($image_size_array){
$this->image_size_array = $image_size_array;
$this->new_image_size_queue = $this->setup_responsive_image_sizes($image_size_array);
add_filter('picturefill_wp_image_sizes', array($this, '_set_responsive_image_sizes'), 10, 2);
add_filter('picturefill_wp_image_attachment_data', array($this, '_set_new_responsive_image_attachment_data'), 10, 2);
}
public function apply_to_post_thumbnail(){
$this->image_size_to_add = 'post-thumbnail';
add_action('init', array($this, '_add_retina_post_thumbnail'));
add_filter('post_thumbnail_html', array($this, '_add_size_to_post_thumbnail_class'), 9, 5);
add_filter('picturefill_wp_image_attachment_data', array($this, '_add_size_attachment_data'), 10, 2);
add_filter('picturefill_wp_image_sizes', array($this, '_post_thumbnail_sizes'), 10, 2);
$this->apply_to_filter('post_thumbnail_html');
}
public function exclude_post_type($post){
if($this->post_type_to_exclude === $post->post_type){
remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11);
}
}
public function exclude_post_id($post){
if($this->post_id_to_exclude === $post->ID){
remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11);
}
}
public function exclude_post_slug($post){
if($this->post_slug_to_exclude === $post->post_name){
remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11);
}
}
public function exclude_post_tag($post){
$post_tags = wp_get_post_tags($post->ID, array('fields' => 'names'));
if(in_array($this->post_tag_to_exclude, $post_tags)){
remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11);
}
}
public function exclude_post_category($post){
$post_tags = wp_get_post_categories($post->ID, array('fields' => 'names'));
if(in_array($this->post_category_to_exclude, $post_tags)){
remove_filter('the_content', array(Picturefill_WP::get_instance(), 'apply_picturefill_wp_to_the_content'), 11);
}
}
public function _set_responsive_image_sizes($image_queue, $image_attributes){
$new_image_queue = array();
$minimum_reached = empty($image_attributes['min-size'][1]) ? true : false;
foreach($this->new_image_size_queue as $image_name){
if($minimum_reached || $image_attributes['min-size'][1] === $image_name){
$minimum_reached = true;
$new_image_queue[] = $image_name;
$new_image_queue[] = $image_name . '@2x';
}
if($image_attributes['size'][1] === $image_name){
return $new_image_queue;
}
}
return !empty($new_image_queue) ? $new_image_queue : $image_queue;
}
public function _set_new_responsive_image_attachment_data($attachment_data, $id){
$new_attachment_data = array();
foreach($this->new_image_size_queue as $size){
$new_attachment_data[$size] = wp_get_attachment_image_src($id, $size);
}
return array_merge($attachment_data, $new_attachment_data);
}
public function _post_thumbnail_sizes($default_image_sizes, $image_attributes){
return 'post-thumbnail' === $image_attributes['size'][1] ? array(
'post-thumbnail',
'post-thumbnail@2x'
) : $default_image_sizes;
}
public function _add_retina_post_thumbnail(){
global $_wp_additional_image_sizes;
add_image_size('post-thumbnail@2x', $_wp_additional_image_sizes['post-thumbnail']['width'] * 2, $_wp_additional_image_sizes['post-thumbnail']['height'] * 2, $_wp_additional_image_sizes['post-thumbnail']['crop']);
}
public function _add_size_to_post_thumbnail_class($html, $post_id, $post_thumbnail_id, $size, $attr){
return preg_replace('/class="([^"]+)"/', 'class="$1 size-' . $size . '"', $html);
}
public function _add_size_to_responsive_image_list($image_sizes, $image_attributes){
if('@2x' === substr($this->insert_before, -3)){
return $image_sizes;
}
$position = array_search($this->insert_before, $image_sizes);
if($image_attributes['min_size'] !== $this->insert_before){
if(1 > $position){
return array_merge(array($this->image_size_to_add, $this->image_size_to_add . '@2x'), $image_sizes);
}else{
array_splice($image_sizes, $position, 0, array($this->image_size_to_add, $this->image_size_to_add . '@2x'));
return $image_sizes;
}
}else{
return $image_sizes;
}
}
public function _add_size_attachment_data($attachment_data, $attachment_id){
$new_size_data = array(
$this->image_size_to_add => wp_get_attachment_image_src($attachment_id, $this->image_size_to_add),
$this->image_size_to_add . '@2x' => wp_get_attachment_image_src($attachment_id, $this->image_size_to_add . '@2x')
);
return array_merge($attachment_data, $new_size_data);
}
public function _apply_picturefill_wp_to_filter($content){
return Picturefill_WP::get_instance()->cache_picturefill_output($content, $this->filter);
}
public function _set_cache_duration($old_cache_duration){
return $this->cache_duration;
}
public function _remove_image_from_responsive_list($image_sizes, $image_attributes){
return array_diff($image_sizes, $this->image_sizes_to_remove);
}
private function setup_responsive_image_sizes($image_size_array){
global $_wp_additional_image_sizes;
$existing_image_sizes = get_intermediate_image_sizes();
$new_image_queue = array();
foreach($image_size_array as $image_name){
if('@2x' === substr($image_name, -3) || !in_array($image_name, $existing_image_sizes)){
return $new_image_queue;
}
if(!in_array($image_name . '@2x', $existing_image_sizes)){
add_image_size($image_name . '@2x', $_wp_additional_image_sizes[$image_name]['width'] * 2, $_wp_additional_image_sizes[$image_name]['height'] * 2, $_wp_additional_image_sizes[$image_name]['crop']);
}
$new_image_queue[] = $image_name;
// $new_image_queue[] = $image_name . '@2x';
}
return $new_image_queue;
}
}
}
| fndtn357/client | wp-content/plugins/picturefillwp/inc/class-picturefill-wp-function-helpers.php | PHP | gpl-2.0 | 8,987 |
/******************************************************************************
** kjmp2 -- a minimal MPEG-1/2 Audio Layer II decoder library **
** version 1.1 **
*******************************************************************************
** Copyright (C) 2006-2013 Martin J. Fiedler <martin.fiedler@gmx.net> **
** **
** This software is provided 'as-is', without any express or implied **
** warranty. In no event will the authors be held liable for any damages **
** arising from the use of this software. **
** **
** Permission is granted to anyone to use this software for any purpose, **
** including commercial applications, and to alter it and redistribute it **
** freely, subject to the following restrictions: **
** 1. The origin of this software must not be misrepresented; you must not **
** claim that you wrote the original software. If you use this software **
** in a product, an acknowledgment in the product documentation would **
** be appreciated but is not required. **
** 2. Altered source versions must be plainly marked as such, and must not **
** be misrepresented as being the original software. **
** 3. This notice may not be removed or altered from any source **
** distribution. **
******************************************************************************/
//
// Code adapted of the original code:
// - it is made into a class for use within the framework
// of the sdr-j DAB/DAB+ software
//
#include "mp2processor.h"
#include "radio.h"
#include "pad-handler.h"
#ifdef _MSC_VER
#define FASTCALL __fastcall
#else
#define FASTCALL
#endif
////////////////////////////////////////////////////////////////////////////////
// TABLES AND CONSTANTS //
////////////////////////////////////////////////////////////////////////////////
// mode constants
#define STEREO 0
#define JOINT_STEREO 1
#define DUAL_CHANNEL 2
#define MONO 3
// sample rate table
static
const unsigned short sample_rates[8] = {
44100, 48000, 32000, 0, // MPEG-1
22050, 24000, 16000, 0 // MPEG-2
};
// bitrate table
static
const short bitrates[28] = {
32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, // MPEG-1
8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 // MPEG-2
};
// scale factor base values (24-bit fixed-point)
static
const int scf_base [3] = {0x02000000, 0x01965FEA, 0x01428A30};
// synthesis window
static
const int D[512] = {
0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000, 0x00000,-0x00001,
-0x00001,-0x00001,-0x00001,-0x00002,-0x00002,-0x00003,-0x00003,-0x00004,
-0x00004,-0x00005,-0x00006,-0x00006,-0x00007,-0x00008,-0x00009,-0x0000A,
-0x0000C,-0x0000D,-0x0000F,-0x00010,-0x00012,-0x00014,-0x00017,-0x00019,
-0x0001C,-0x0001E,-0x00022,-0x00025,-0x00028,-0x0002C,-0x00030,-0x00034,
-0x00039,-0x0003E,-0x00043,-0x00048,-0x0004E,-0x00054,-0x0005A,-0x00060,
-0x00067,-0x0006E,-0x00074,-0x0007C,-0x00083,-0x0008A,-0x00092,-0x00099,
-0x000A0,-0x000A8,-0x000AF,-0x000B6,-0x000BD,-0x000C3,-0x000C9,-0x000CF,
0x000D5, 0x000DA, 0x000DE, 0x000E1, 0x000E3, 0x000E4, 0x000E4, 0x000E3,
0x000E0, 0x000DD, 0x000D7, 0x000D0, 0x000C8, 0x000BD, 0x000B1, 0x000A3,
0x00092, 0x0007F, 0x0006A, 0x00053, 0x00039, 0x0001D,-0x00001,-0x00023,
-0x00047,-0x0006E,-0x00098,-0x000C4,-0x000F3,-0x00125,-0x0015A,-0x00190,
-0x001CA,-0x00206,-0x00244,-0x00284,-0x002C6,-0x0030A,-0x0034F,-0x00396,
-0x003DE,-0x00427,-0x00470,-0x004B9,-0x00502,-0x0054B,-0x00593,-0x005D9,
-0x0061E,-0x00661,-0x006A1,-0x006DE,-0x00718,-0x0074D,-0x0077E,-0x007A9,
-0x007D0,-0x007EF,-0x00808,-0x0081A,-0x00824,-0x00826,-0x0081F,-0x0080E,
0x007F5, 0x007D0, 0x007A0, 0x00765, 0x0071E, 0x006CB, 0x0066C, 0x005FF,
0x00586, 0x00500, 0x0046B, 0x003CA, 0x0031A, 0x0025D, 0x00192, 0x000B9,
-0x0002C,-0x0011F,-0x00220,-0x0032D,-0x00446,-0x0056B,-0x0069B,-0x007D5,
-0x00919,-0x00A66,-0x00BBB,-0x00D16,-0x00E78,-0x00FDE,-0x01148,-0x012B3,
-0x01420,-0x0158C,-0x016F6,-0x0185C,-0x019BC,-0x01B16,-0x01C66,-0x01DAC,
-0x01EE5,-0x02010,-0x0212A,-0x02232,-0x02325,-0x02402,-0x024C7,-0x02570,
-0x025FE,-0x0266D,-0x026BB,-0x026E6,-0x026ED,-0x026CE,-0x02686,-0x02615,
-0x02577,-0x024AC,-0x023B2,-0x02287,-0x0212B,-0x01F9B,-0x01DD7,-0x01BDD,
0x019AE, 0x01747, 0x014A8, 0x011D1, 0x00EC0, 0x00B77, 0x007F5, 0x0043A,
0x00046,-0x003E5,-0x00849,-0x00CE3,-0x011B4,-0x016B9,-0x01BF1,-0x0215B,
-0x026F6,-0x02CBE,-0x032B3,-0x038D3,-0x03F1A,-0x04586,-0x04C15,-0x052C4,
-0x05990,-0x06075,-0x06771,-0x06E80,-0x0759F,-0x07CCA,-0x083FE,-0x08B37,
-0x09270,-0x099A7,-0x0A0D7,-0x0A7FD,-0x0AF14,-0x0B618,-0x0BD05,-0x0C3D8,
-0x0CA8C,-0x0D11D,-0x0D789,-0x0DDC9,-0x0E3DC,-0x0E9BD,-0x0EF68,-0x0F4DB,
-0x0FA12,-0x0FF09,-0x103BD,-0x1082C,-0x10C53,-0x1102E,-0x113BD,-0x116FB,
-0x119E8,-0x11C82,-0x11EC6,-0x120B3,-0x12248,-0x12385,-0x12467,-0x124EF,
0x1251E, 0x124F0, 0x12468, 0x12386, 0x12249, 0x120B4, 0x11EC7, 0x11C83,
0x119E9, 0x116FC, 0x113BE, 0x1102F, 0x10C54, 0x1082D, 0x103BE, 0x0FF0A,
0x0FA13, 0x0F4DC, 0x0EF69, 0x0E9BE, 0x0E3DD, 0x0DDCA, 0x0D78A, 0x0D11E,
0x0CA8D, 0x0C3D9, 0x0BD06, 0x0B619, 0x0AF15, 0x0A7FE, 0x0A0D8, 0x099A8,
0x09271, 0x08B38, 0x083FF, 0x07CCB, 0x075A0, 0x06E81, 0x06772, 0x06076,
0x05991, 0x052C5, 0x04C16, 0x04587, 0x03F1B, 0x038D4, 0x032B4, 0x02CBF,
0x026F7, 0x0215C, 0x01BF2, 0x016BA, 0x011B5, 0x00CE4, 0x0084A, 0x003E6,
-0x00045,-0x00439,-0x007F4,-0x00B76,-0x00EBF,-0x011D0,-0x014A7,-0x01746,
0x019AE, 0x01BDE, 0x01DD8, 0x01F9C, 0x0212C, 0x02288, 0x023B3, 0x024AD,
0x02578, 0x02616, 0x02687, 0x026CF, 0x026EE, 0x026E7, 0x026BC, 0x0266E,
0x025FF, 0x02571, 0x024C8, 0x02403, 0x02326, 0x02233, 0x0212B, 0x02011,
0x01EE6, 0x01DAD, 0x01C67, 0x01B17, 0x019BD, 0x0185D, 0x016F7, 0x0158D,
0x01421, 0x012B4, 0x01149, 0x00FDF, 0x00E79, 0x00D17, 0x00BBC, 0x00A67,
0x0091A, 0x007D6, 0x0069C, 0x0056C, 0x00447, 0x0032E, 0x00221, 0x00120,
0x0002D,-0x000B8,-0x00191,-0x0025C,-0x00319,-0x003C9,-0x0046A,-0x004FF,
-0x00585,-0x005FE,-0x0066B,-0x006CA,-0x0071D,-0x00764,-0x0079F,-0x007CF,
0x007F5, 0x0080F, 0x00820, 0x00827, 0x00825, 0x0081B, 0x00809, 0x007F0,
0x007D1, 0x007AA, 0x0077F, 0x0074E, 0x00719, 0x006DF, 0x006A2, 0x00662,
0x0061F, 0x005DA, 0x00594, 0x0054C, 0x00503, 0x004BA, 0x00471, 0x00428,
0x003DF, 0x00397, 0x00350, 0x0030B, 0x002C7, 0x00285, 0x00245, 0x00207,
0x001CB, 0x00191, 0x0015B, 0x00126, 0x000F4, 0x000C5, 0x00099, 0x0006F,
0x00048, 0x00024, 0x00002,-0x0001C,-0x00038,-0x00052,-0x00069,-0x0007E,
-0x00091,-0x000A2,-0x000B0,-0x000BC,-0x000C7,-0x000CF,-0x000D6,-0x000DC,
-0x000DF,-0x000E2,-0x000E3,-0x000E3,-0x000E2,-0x000E0,-0x000DD,-0x000D9,
0x000D5, 0x000D0, 0x000CA, 0x000C4, 0x000BE, 0x000B7, 0x000B0, 0x000A9,
0x000A1, 0x0009A, 0x00093, 0x0008B, 0x00084, 0x0007D, 0x00075, 0x0006F,
0x00068, 0x00061, 0x0005B, 0x00055, 0x0004F, 0x00049, 0x00044, 0x0003F,
0x0003A, 0x00035, 0x00031, 0x0002D, 0x00029, 0x00026, 0x00023, 0x0001F,
0x0001D, 0x0001A, 0x00018, 0x00015, 0x00013, 0x00011, 0x00010, 0x0000E,
0x0000D, 0x0000B, 0x0000A, 0x00009, 0x00008, 0x00007, 0x00007, 0x00006,
0x00005, 0x00005, 0x00004, 0x00004, 0x00003, 0x00003, 0x00002, 0x00002,
0x00002, 0x00002, 0x00001, 0x00001, 0x00001, 0x00001, 0x00001, 0x00001
};
///////////// Table 3-B.2: Possible quantization per subband ///////////////////
// quantizer lookup, step 1: bitrate classes
static uint8_t quant_lut_step1[2][16] = {
// 32, 48, 56, 64, 80, 96,112,128,160,192,224,256,320,384 <- bitrate
{ 0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2 }, // mono
// 16, 24, 28, 32, 40, 48, 56, 64, 80, 96,112,128,160,192 <- BR / chan
{ 0, 0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2 } // stereo
};
// quantizer lookup, step 2: bitrate class, sample rate -> B2 table idx, sblimit
#define QUANT_TAB_A (27 | 64) // Table 3-B.2a: high-rate, sblimit = 27
#define QUANT_TAB_B (30 | 64) // Table 3-B.2b: high-rate, sblimit = 30
#define QUANT_TAB_C 8 // Table 3-B.2c: low-rate, sblimit = 8
#define QUANT_TAB_D 12 // Table 3-B.2d: low-rate, sblimit = 12
static
const char quant_lut_step2 [3][4] = {
// 44.1 kHz, 48 kHz, 32 kHz
{ QUANT_TAB_C, QUANT_TAB_C, QUANT_TAB_D }, // 32 - 48 kbit/sec/ch
{ QUANT_TAB_A, QUANT_TAB_A, QUANT_TAB_A }, // 56 - 80 kbit/sec/ch
{ QUANT_TAB_B, QUANT_TAB_A, QUANT_TAB_B }, // 96+ kbit/sec/ch
};
// quantizer lookup, step 3: B2 table, subband -> nbal, row index
// (upper 4 bits: nbal, lower 4 bits: row index)
static
uint8_t quant_lut_step3 [3][32] = {
// low-rate table (3-B.2c and 3-B.2d)
{ 0x44,0x44, // SB 0 - 1
0x34,0x34,0x34,0x34,0x34,0x34,0x34,0x34,0x34,0x34 // SB 2 - 12
},
// high-rate table (3-B.2a and 3-B.2b)
{ 0x43,0x43,0x43, // SB 0 - 2
0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42, // SB 3 - 10
0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31,0x31, // SB 11 - 22
0x20,0x20,0x20,0x20,0x20,0x20,0x20 // SB 23 - 29
},
// MPEG-2 LSR table (B.2 in ISO 13818-3)
{ 0x45,0x45,0x45,0x45, // SB 0 - 3
0x34,0x34,0x34,0x34,0x34,0x34,0x34, // SB 4 - 10
0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24, // SB 11 -
0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24,0x24 // - 29
}
};
// quantizer lookup, step 4: table row, allocation[] value -> quant table index
static
const char quant_lut_step4 [6][16] = {
{ 0, 1, 2, 17 },
{ 0, 1, 2, 3, 4, 5, 6, 17 },
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17 },
{ 0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 },
{ 0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17 },
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }
};
// quantizer table
static
struct quantizer_spec quantizer_table [17] = {
{ 3, 1, 5 }, // 1
{ 5, 1, 7 }, // 2
{ 7, 0, 3 }, // 3
{ 9, 1, 10 }, // 4
{ 15, 0, 4 }, // 5
{ 31, 0, 5 }, // 6
{ 63, 0, 6 }, // 7
{ 127, 0, 7 }, // 8
{ 255, 0, 8 }, // 9
{ 511, 0, 9 }, // 10
{ 1023, 0, 10 }, // 11
{ 2047, 0, 11 }, // 12
{ 4095, 0, 12 }, // 13
{ 8191, 0, 13 }, // 14
{ 16383, 0, 14 }, // 15
{ 32767, 0, 15 }, // 16
{ 65535, 0, 16 } // 17
};
////////////////////////////////////////////////////////////////////////////////
// The initialization is now done in the constructor
// (J van Katwijk)
////////////////////////////////////////////////////////////////////////////////
mp2Processor::mp2Processor (RadioInterface *mr,
int16_t bitRate,
RingBuffer<int16_t> *buffer,
RingBuffer<uint8_t> *frameBuffer):
my_padhandler (mr) {
int16_t i, j;
int16_t *nPtr = &N [0][0];
// compute N[i][j]
for (i = 0; i < 64; i ++)
for (j = 0; j < 32; ++j)
*nPtr++ = (int16_t) (256.0 *
cos(((16 + i) * ((j << 1) + 1)) *
0.0490873852123405));
// perform local initialization:
for (i = 0; i < 2; ++i)
for (j = 1023; j >= 0; j--)
V [i][j] = 0;
myRadioInterface = mr;
this -> buffer = buffer;
this -> bitRate = bitRate;
connect (this, SIGNAL (show_frameErrors (int)),
mr, SLOT (show_frameErrors (int)));
connect (this, SIGNAL (newAudio (int, int)),
mr, SLOT (newAudio (int, int)));
connect (this, SIGNAL (isStereo (bool)),
mr, SLOT (setStereo (bool)));
Voffs = 0;
baudRate = 48000; // default for DAB
MP2framesize = 24 * bitRate; // may be changed
MP2frame = new uint8_t [2 * MP2framesize];
MP2Header_OK = 0;
MP2headerCount = 0;
MP2bitCount = 0;
numberofFrames = 0;
errorFrames = 0;
}
mp2Processor::~mp2Processor() {
delete[] MP2frame;
}
//
#define valid(x) ((x == 48000) || (x == 24000))
void mp2Processor::setSamplerate (int32_t rate) {
if (baudRate == rate)
return;
if (!valid (rate))
return;
// ourSink -> setMode (0, rate);
baudRate = rate;
}
////////////////////////////////////////////////////////////////////////////////
// INITIALIZATION: is moved into the constructor for the class
// //
////////////////////////////////////////////////////////////////////////////////
int32_t mp2Processor::mp2sampleRate (uint8_t *frame) {
if (!frame)
return 0;
if (( frame[0] != 0xFF) // no valid syncword?
|| ((frame[1] & 0xF6) != 0xF4) // no MPEG-1/2 Audio Layer II?
|| ((frame[2] - 0x10) >= 0xE0)) // invalid bitrate?
return 0;
return sample_rates[(((frame[1] & 0x08) >> 1) ^ 4) // MPEG-1/2 switch
+ ((frame[2] >> 2) & 3)]; // actual rate
}
////////////////////////////////////////////////////////////////////////////////
// DECODE HELPER FUNCTIONS //
////////////////////////////////////////////////////////////////////////////////
struct quantizer_spec*
mp2Processor::read_allocation (int sb, int b2_table) {
int table_idx = quant_lut_step3 [b2_table][sb];
table_idx = quant_lut_step4 [table_idx & 15] [get_bits(table_idx >> 4)];
return table_idx ? (&quantizer_table[table_idx - 1]) : nullptr;
}
void mp2Processor::read_samples (struct quantizer_spec *q,
int scalefactor, int *sample) {
int idx, adj, scale;
int val;
if (!q) {
// no bits allocated for this subband
sample[0] = sample[1] = sample[2] = 0;
return;
}
// resolve scalefactor
if (scalefactor == 63) {
scalefactor = 0;
} else {
adj = scalefactor / 3;
scalefactor = (scf_base[scalefactor % 3] + ((1 << adj) >> 1)) >> adj;
}
// decode samples
adj = q -> nlevels;
if (q -> grouping) { // decode grouped samples
val = get_bits (q -> cw_bits);
sample [0] = val % adj;
val /= adj;
sample [1] = val % adj;
sample [2] = val / adj;
} else { // decode direct samples
for (idx = 0; idx < 3; ++idx)
sample [idx] = get_bits (q -> cw_bits);
}
// postmultiply samples
scale = 65536 / (adj + 1);
adj = ((adj + 1) >> 1) - 1;
for (idx = 0; idx < 3; ++idx) {
// step 1: renormalization to [-1..1]
val = (adj - sample[idx]) * scale;
// step 2: apply scalefactor
sample[idx] = ( val * (scalefactor >> 12) // upper part
+ ((val * (scalefactor & 4095) + 2048) >> 12)) // lower part
>> 12; // scale adjust
}
}
#define show_bits(bit_count) (bit_window >> (24 - (bit_count)))
int32_t mp2Processor::get_bits (int32_t bit_count) {
//int32_t result = show_bits (bit_count);
int32_t result = bit_window >> (24 - bit_count);
bit_window = (bit_window << bit_count) & 0xFFFFFF;
bits_in_window -= bit_count;
while (bits_in_window < 16) {
bit_window |= (*frame_pos++) << (16 - bits_in_window);
bits_in_window += 8;
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
// FRAME DECODE FUNCTION //
////////////////////////////////////////////////////////////////////////////////
int32_t mp2Processor::mp2decodeFrame (uint8_t *frame, int16_t *pcm) {
uint32_t bit_rate_index_minus1;
uint32_t sampling_frequency;
uint32_t padding_bit;
uint32_t mode;
uint32_t frame_size;
int32_t bound, sblimit;
int32_t sb, ch, gr, part, idx, nch, i, j, sum;
int32_t table_idx;
numberofFrames ++;
if (numberofFrames >= 25) {
show_frameErrors (errorFrames);
numberofFrames = 0;
errorFrames = 0;
}
// check for valid header: syncword OK, MPEG-Audio Layer 2
if (( frame[0] != 0xFF) // no valid syncword?
|| ((frame[1] & 0xF6) != 0xF4) // no MPEG-1/2 Audio Layer II?
|| ((frame[2] - 0x10) >= 0xE0)) { // invalid bitrate?
errorFrames ++;
return 0;
}
// set up the bitstream reader
bit_window = frame [2] << 16;
bits_in_window = 8;
frame_pos = &frame[3];
// read the rest of the header
bit_rate_index_minus1 = get_bits(4) - 1;
if (bit_rate_index_minus1 > 13)
return 0; // invalid bit rate or 'free format'
sampling_frequency = get_bits(2);
if (sampling_frequency == 3)
return 0;
if ((frame[1] & 0x08) == 0) { // MPEG-2
sampling_frequency += 4;
bit_rate_index_minus1 += 14;
}
padding_bit = get_bits(1);
get_bits(1); // discard private_bit
mode = get_bits(2);
// parse the mode_extension, set up the stereo bound
if (mode == JOINT_STEREO)
bound = (get_bits(2) + 1) << 2;
else {
get_bits(2);
bound = (mode == MONO) ? 0 : 32;
}
emit isStereo ((mode == JOINT_STEREO) || (mode == STEREO));
// discard the last 4 bits of the header and the CRC value, if present
get_bits(4);
if ((frame [1] & 1) == 0)
get_bits(16);
// compute the frame size
frame_size = (144000 * bitrates[bit_rate_index_minus1]
/ sample_rates [sampling_frequency]) + padding_bit;
if (!pcm)
return frame_size; // no decoding
// prepare the quantizer table lookups
if (sampling_frequency & 4) {
// MPEG-2 (LSR)
table_idx = 2;
sblimit = 30;
} else {
// MPEG-1
table_idx = (mode == MONO) ? 0 : 1;
table_idx = quant_lut_step1[table_idx][bit_rate_index_minus1];
table_idx = quant_lut_step2[table_idx][sampling_frequency];
sblimit = table_idx & 63;
table_idx >>= 6;
}
if (bound > sblimit)
bound = sblimit;
// read the allocation information
for (sb = 0; sb < bound; ++sb)
for (ch = 0; ch < 2; ++ch)
allocation [ch][sb] = read_allocation(sb, table_idx);
for (sb = bound; sb < sblimit; ++sb)
allocation[0][sb] =
allocation[1][sb] = read_allocation (sb, table_idx);
// read scale factor selector information
nch = (mode == MONO) ? 1 : 2;
for (sb = 0; sb < sblimit; ++sb) {
for (ch = 0; ch < nch; ++ch)
if (allocation [ch][sb])
scfsi [ch][sb] = get_bits (2);
if (mode == MONO)
scfsi[1][sb] = scfsi[0][sb];
}
// read scale factors
for (sb = 0; sb < sblimit; ++sb) {
for (ch = 0; ch < nch; ++ch) {
if (allocation[ch][sb]) {
switch (scfsi[ch][sb]) {
case 0: scalefactor[ch][sb][0] = get_bits(6);
scalefactor[ch][sb][1] = get_bits(6);
scalefactor[ch][sb][2] = get_bits(6);
break;
case 1: scalefactor[ch][sb][0] =
scalefactor[ch][sb][1] = get_bits(6);
scalefactor[ch][sb][2] = get_bits(6);
break;
case 2: scalefactor[ch][sb][0] =
scalefactor[ch][sb][1] =
scalefactor[ch][sb][2] = get_bits(6);
break;
case 3: scalefactor[ch][sb][0] = get_bits(6);
scalefactor[ch][sb][1] =
scalefactor[ch][sb][2] = get_bits(6);
break;
}
}
}
if (mode == MONO)
for (part = 0; part < 3; ++part)
scalefactor[1][sb][part] = scalefactor[0][sb][part];
}
// coefficient input and reconstruction
for (part = 0; part < 3; ++part) {
for (gr = 0; gr < 4; ++gr) {
// read the samples
for (sb = 0; sb < bound; ++sb)
for (ch = 0; ch < 2; ++ch)
read_samples (allocation[ch][sb],
scalefactor[ch][sb][part],
&sample[ch][sb][0]);
for (sb = bound; sb < sblimit; ++sb) {
read_samples (allocation[0][sb],
scalefactor[0][sb][part],
&sample[0][sb][0]);
for (idx = 0; idx < 3; ++idx)
sample[1][sb][idx] = sample[0][sb][idx];
}
for (ch = 0; ch < 2; ++ch)
for (sb = sblimit; sb < 32; ++sb)
for (idx = 0; idx < 3; ++idx)
sample[ch][sb][idx] = 0;
// synthesis loop
for (idx = 0; idx < 3; ++idx) {
// shifting step
Voffs = table_idx = (Voffs - 64) & 1023;
for (ch = 0; ch < 2; ++ch) {
// matrixing
for (i = 0; i < 64; ++i) {
sum = 0;
for (j = 0; j < 32; ++j) // 8b*15b=23b
sum += N[i][j] * sample[ch][j][idx];
// intermediate value is 28 bit (23 + 5), clamp to 14b
//
V [ch][table_idx + i] = (sum + 8192) >> 14;
}
// construction of U
for (i = 0; i < 8; ++i)
for (j = 0; j < 32; ++j) {
U [(i << 6) + j]
= V [ch][(table_idx + (i << 7) + j) & 1023];
U [(i << 6) + j + 32] =
V [ch][(table_idx + (i << 7) + j + 96) & 1023];
}
// apply window
for (i = 0; i < 512; ++i)
U [i] = (U [i] * D [i] + 32) >> 6;
// output samples
for (j = 0; j < 32; ++j) {
sum = 0;
for (i = 0; i < 16; ++i)
sum -= U [(i << 5) + j];
sum = (sum + 8) >> 4;
if (sum < -32768)
sum = -32768;
if (sum > 32767)
sum = 32767;
pcm[(idx << 6) | (j << 1) | ch] = (uint16_t) sum;
}
} // end of synthesis channel loop
} // end of synthesis sub-block loop
// adjust PCM output pointer: decoded 3 * 32 = 96 stereo samples
pcm += 192;
} // decoding of the granule finished
}
return frame_size;
}
//
// bits to MP2 frames, amount is amount of bits
void mp2Processor::addtoFrame (std::vector<uint8_t> v) {
int16_t i, j;
int16_t lf = baudRate == 48000 ? MP2framesize : 2 * MP2framesize;
int16_t amount = MP2framesize;
uint8_t help [24 * bitRate / 8];
int16_t vLength = 24 * bitRate / 8;
//fprintf (stderr, "baudrate = %d, inputsize = %d\n",
// baudRate, v. size ());
// fprintf (stderr, "\n");
for (i = 0; i < 24 * bitRate / 8; i ++) {
help [i] = 0;
for (j = 0; j < 8; j ++) {
help [i] <<= 1;
help [i] |= v [8 * i + j] & 01;
}
}
{ uint8_t L0 = help [vLength - 1];
uint8_t L1 = help [vLength - 2];
int16_t down = bitRate * 1000 >= 56000 ? 4 : 2;
my_padhandler. processPAD (help, vLength - 2 - down - 1, L1, L0);
}
for (i = 0; i < amount; i ++) {
if (MP2Header_OK == 2) {
addbittoMP2 (MP2frame, v [i], MP2bitCount ++);
if (MP2bitCount >= lf) {
int16_t sample_buf [KJMP2_SAMPLES_PER_FRAME * 2];
if (mp2decodeFrame (MP2frame, sample_buf)) {
buffer -> putDataIntoBuffer (sample_buf,
2 * (int32_t)KJMP2_SAMPLES_PER_FRAME);
if (buffer -> GetRingBufferReadAvailable () > baudRate / 8)
newAudio (2 * (int32_t)KJMP2_SAMPLES_PER_FRAME,
baudRate);
}
MP2Header_OK = 0;
MP2headerCount = 0;
MP2bitCount = 0;
}
} else
if (MP2Header_OK == 0) {
// apparently , we are not in sync yet
if (v [i] == 01) {
if (++ MP2headerCount == 12) {
MP2bitCount = 0;
for (j = 0; j < 12; j ++)
addbittoMP2 (MP2frame, 1, MP2bitCount ++);
MP2Header_OK = 1;
}
}
else
MP2headerCount = 0;
}
else
if (MP2Header_OK == 1) {
addbittoMP2 (MP2frame, v [i], MP2bitCount ++);
if (MP2bitCount == 24) {
setSamplerate (mp2sampleRate (MP2frame));
MP2Header_OK = 2;
}
}
}
}
void mp2Processor::addbittoMP2 (uint8_t *v, uint8_t b, int16_t nm) {
uint8_t byte = v [nm / 8];
int16_t bitnr = 7 - (nm & 7);
uint8_t newbyte = (01 << bitnr);
if (b == 0)
byte &= ~newbyte;
else
byte |= newbyte;
v [nm / 8] = byte;
}
| JvanKatwijk/qt-dab | src/backend/audio/mp2processor.cpp | C++ | gpl-2.0 | 24,771 |
#include <QApplication>
#include <QMenuBar>
#include <QMessageBox>
#include <QFileDialog>
#include <QVBoxLayout>
#include <QDockWidget>
#include <QProgressDialog>
#include <QDesktopWidget>
#include "vfs_dialog.h"
#include "save_manager_dialog.h"
#include "kernel_explorer.h"
#include "game_list_frame.h"
#include "debugger_frame.h"
#include "log_frame.h"
#include "settings_dialog.h"
#include "auto_pause_settings_dialog.h"
#include "cg_disasm_window.h"
#include "memory_string_searcher.h"
#include "memory_viewer_panel.h"
#include "rsx_debugger.h"
#include "main_window.h"
#include "emu_settings.h"
#include "about_dialog.h"
#include "gamepads_settings_dialog.h"
#include <thread>
#include "stdafx.h"
#include "Emu/System.h"
#include "Emu/Memory/Memory.h"
#include "Crypto/unpkg.h"
#include "Crypto/unself.h"
#include "Loader/PUP.h"
#include "Loader/TAR.h"
#include "Utilities/Thread.h"
#include "Utilities/StrUtil.h"
#include "rpcs3_version.h"
#include "Utilities/sysinfo.h"
#include "ui_main_window.h"
inline std::string sstr(const QString& _in) { return _in.toUtf8().toStdString(); }
main_window::main_window(std::shared_ptr<gui_settings> guiSettings, QWidget *parent) : QMainWindow(parent), guiSettings(guiSettings), m_sys_menu_opened(false), ui(new Ui::main_window)
{
}
main_window::~main_window()
{
delete ui;
}
auto Pause = []()
{
if (Emu.IsReady()) Emu.Run();
else if (Emu.IsPaused()) Emu.Resume();
else if (Emu.IsRunning()) Emu.Pause();
else if (!Emu.GetPath().empty()) Emu.Load();
};
/* An init method is used so that RPCS3App can create the necessary connects before calling init (specifically the stylesheet connect).
* Simplifies logic a bit.
*/
void main_window::Init()
{
ui->setupUi(this);
m_appIcon = QIcon(":/rpcs3.ico");
// hide utilities from the average user
ui->menuUtilities->menuAction()->setVisible(guiSettings->GetValue(GUI::m_showDebugTab).toBool());
// add toolbar widgets (crappy Qt designer is not able to)
ui->toolBar->setObjectName("mw_toolbar");
ui->sizeSlider->setRange(0, GUI::gl_max_slider_pos);
ui->sizeSlider->setSliderPosition(guiSettings->GetValue(GUI::gl_iconSize).toInt());
ui->toolBar->addWidget(ui->sizeSliderContainer);
ui->toolBar->addSeparator();
ui->toolBar->addWidget(ui->mw_searchbar);
// for highdpi resize toolbar icons and height dynamically
// choose factors to mimic Gui-Design in main_window.ui
// TODO: in case Qt::AA_EnableHighDpiScaling is enabled in main.cpp we only need the else branch
#ifdef _WIN32
const int toolBarHeight = menuBar()->sizeHint().height() * 1.5;
ui->toolBar->setIconSize(QSize(toolBarHeight, toolBarHeight));
#else
const int toolBarHeight = ui->toolBar->iconSize().height();
#endif
ui->sizeSliderContainer->setFixedWidth(toolBarHeight * 5);
ui->sizeSlider->setFixedHeight(toolBarHeight * 0.65f);
CreateActions();
CreateDockWindows();
setMinimumSize(350, minimumSizeHint().height()); // seems fine on win 10
CreateConnects();
setWindowTitle(QString::fromStdString("RPCS3 v" + rpcs3::version.to_string()));
!m_appIcon.isNull() ? setWindowIcon(m_appIcon) : LOG_WARNING(GENERAL, "AppImage could not be loaded!");
Q_EMIT RequestGlobalStylesheetChange(guiSettings->GetCurrentStylesheetPath());
ConfigureGuiFromSettings(true);
RepaintToolBarIcons();
m_gameListFrame->RepaintToolBarIcons();
if (!utils::has_ssse3())
{
QMessageBox::critical(this, "SSSE3 Error (with three S, not two)",
"Your system does not meet the minimum requirements needed to run RPCS3.\n"
"Your CPU does not support SSSE3 (with three S, not two).\n");
std::exit(EXIT_FAILURE);
}
#ifdef BRANCH
if ("RPCS3/rpcs3/master"s != STRINGIZE(BRANCH))
#elif _MSC_VER
fs::stat_t st;
if (!fs::stat(fs::get_config_dir() + "rpcs3.pdb", st) || st.is_directory || st.size < 1024 * 1024 * 100)
#else
if (false)
#endif
{
LOG_WARNING(GENERAL, "Experimental Build Warning! Build origin: " STRINGIZE(BRANCH));
QMessageBox msg;
msg.setWindowTitle("Experimental Build Warning");
msg.setWindowIcon(m_appIcon);
msg.setIcon(QMessageBox::Critical);
msg.setTextFormat(Qt::RichText);
msg.setText("Please understand that this build is not an official RPCS3 release.<br>This build contains changes that may break games, or even <b>damage</b> your data.<br>It's recommended to download and use the official build from <a href='https://rpcs3.net/download'>RPCS3 website</a>.<br><br>Build origin: " STRINGIZE(BRANCH) "<br>Do you wish to use this build anyway?");
msg.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msg.setDefaultButton(QMessageBox::No);
if (msg.exec() == QMessageBox::No)
{
std::exit(EXIT_SUCCESS);
}
}
}
void main_window::CreateThumbnailToolbar()
{
#ifdef _WIN32
m_icon_thumb_play = QIcon(":/Icons/play_blue.png");
m_icon_thumb_pause = QIcon(":/Icons/pause_blue.png");
m_icon_thumb_stop = QIcon(":/Icons/stop_blue.png");
m_icon_thumb_restart = QIcon(":/Icons/restart_blue.png");
m_thumb_bar = new QWinThumbnailToolBar(this);
m_thumb_bar->setWindow(windowHandle());
m_thumb_playPause = new QWinThumbnailToolButton(m_thumb_bar);
m_thumb_playPause->setToolTip(tr("Pause"));
m_thumb_playPause->setIcon(m_icon_thumb_pause);
m_thumb_playPause->setEnabled(false);
m_thumb_stop = new QWinThumbnailToolButton(m_thumb_bar);
m_thumb_stop->setToolTip(tr("Stop"));
m_thumb_stop->setIcon(m_icon_thumb_stop);
m_thumb_stop->setEnabled(false);
m_thumb_restart = new QWinThumbnailToolButton(m_thumb_bar);
m_thumb_restart->setToolTip(tr("Restart"));
m_thumb_restart->setIcon(m_icon_thumb_restart);
m_thumb_restart->setEnabled(false);
m_thumb_bar->addButton(m_thumb_playPause);
m_thumb_bar->addButton(m_thumb_stop);
m_thumb_bar->addButton(m_thumb_restart);
connect(m_thumb_stop, &QWinThumbnailToolButton::clicked, [=]() { Emu.Stop(); });
connect(m_thumb_restart, &QWinThumbnailToolButton::clicked, [=]() { Emu.Stop(); Emu.Load(); });
connect(m_thumb_playPause, &QWinThumbnailToolButton::clicked, Pause);
#endif
}
// returns appIcon
QIcon main_window::GetAppIcon()
{
return m_appIcon;
}
// loads the appIcon from path and embeds it centered into an empty square icon
void main_window::SetAppIconFromPath(const std::string path)
{
// get Icon for the gs_frame from path. this handles presumably all possible use cases
QString qpath = qstr(path);
std::string icon_list[] = { "/ICON0.PNG", "/PS3_GAME/ICON0.PNG" };
std::string path_list[] = { path, sstr(qpath.section("/", 0, -2)), sstr(qpath.section("/", 0, -3)) };
for (std::string pth : path_list)
{
if (!fs::is_dir(pth)) continue;
for (std::string ico : icon_list)
{
ico = pth + ico;
if (fs::is_file(ico))
{
// load the image from path. It will most likely be a rectangle
QImage source = QImage(qstr(ico));
int edgeMax = std::max(source.width(), source.height());
// create a new transparent image with square size and same format as source (maybe handle other formats than RGB32 as well?)
QImage::Format format = source.format() == QImage::Format_RGB32 ? QImage::Format_ARGB32 : source.format();
QImage dest = QImage(edgeMax, edgeMax, format);
dest.fill(QColor("transparent"));
// get the location to draw the source image centered within the dest image.
QPoint destPos = source.width() > source.height() ? QPoint(0, (source.width() - source.height()) / 2)
: QPoint((source.height() - source.width()) / 2, 0);
// Paint the source into/over the dest
QPainter painter(&dest);
painter.drawImage(destPos, source);
painter.end();
// set Icon
m_appIcon = QIcon(QPixmap::fromImage(dest));
return;
}
}
}
// if nothing was found reset the icon to default
m_appIcon = QIcon(":/rpcs3.ico");
}
void main_window::BootElf()
{
bool stopped = false;
if (Emu.IsRunning())
{
Emu.Pause();
stopped = true;
}
QString path_last_ELF = guiSettings->GetValue(GUI::fd_boot_elf).toString();
QString filePath = QFileDialog::getOpenFileName(this, tr("Select (S)ELF To Boot"), path_last_ELF, tr(
"(S)ELF files (*BOOT.BIN *.elf *.self);;"
"ELF files (BOOT.BIN *.elf);;"
"SELF files (EBOOT.BIN *.self);;"
"BOOT files (*BOOT.BIN);;"
"BIN files (*.bin);;"
"All files (*.*)"),
Q_NULLPTR, QFileDialog::DontResolveSymlinks);
if (filePath == NULL)
{
if (stopped) Emu.Resume();
return;
}
LOG_NOTICE(LOADER, "(S)ELF: booting...");
// If we resolved the filepath earlier we would end up setting the last opened dir to the unwanted
// game folder in case of having e.g. a Game Folder with collected links to elf files.
// Don't set last path earlier in case of cancelled dialog
guiSettings->SetValue(GUI::fd_boot_elf, filePath);
const std::string path = sstr(QFileInfo(filePath).canonicalFilePath());
SetAppIconFromPath(path);
Emu.Stop();
if (!Emu.BootGame(path, true))
{
LOG_ERROR(GENERAL, "PS3 executable not found at path (%s)", path);
}
else
{
LOG_SUCCESS(LOADER, "(S)ELF: boot done.");
const std::string serial = Emu.GetTitleID().empty() ? "" : "[" + Emu.GetTitleID() + "] ";
AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), qstr(serial + Emu.GetTitle())));
m_gameListFrame->Refresh(true);
}
}
void main_window::BootGame()
{
bool stopped = false;
if (Emu.IsRunning())
{
Emu.Pause();
stopped = true;
}
QString path_last_Game = guiSettings->GetValue(GUI::fd_boot_game).toString();
QString dirPath = QFileDialog::getExistingDirectory(this, tr("Select Game Folder"), path_last_Game, QFileDialog::ShowDirsOnly);
if (dirPath == NULL)
{
if (stopped) Emu.Resume();
return;
}
Emu.Stop();
guiSettings->SetValue(GUI::fd_boot_game, QFileInfo(dirPath).path());
const std::string path = sstr(dirPath);
SetAppIconFromPath(path);
if (!Emu.BootGame(path))
{
LOG_ERROR(GENERAL, "PS3 executable not found in selected folder (%s)", path);
}
else
{
LOG_SUCCESS(LOADER, "Boot Game: boot done.");
const std::string serial = Emu.GetTitleID().empty() ? "" : "[" + Emu.GetTitleID() + "] ";
AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), qstr(serial + Emu.GetTitle())));
m_gameListFrame->Refresh(true);
}
}
void main_window::InstallPkg(const QString& dropPath)
{
QString filePath = dropPath;
if (filePath.isEmpty())
{
QString path_last_PKG = guiSettings->GetValue(GUI::fd_install_pkg).toString();
filePath = QFileDialog::getOpenFileName(this, tr("Select PKG To Install"), path_last_PKG, tr("PKG files (*.pkg);;All files (*.*)"));
}
else
{
if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Install package: %1?").arg(filePath),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
{
LOG_NOTICE(LOADER, "PKG: Cancelled installation from drop. File: %s", sstr(filePath));
return;
}
}
if (filePath == NULL)
{
return;
}
Emu.Stop();
guiSettings->SetValue(GUI::fd_install_pkg, QFileInfo(filePath).path());
const std::string fileName = sstr(QFileInfo(filePath).fileName());
const std::string path = sstr(filePath);
// Open PKG file
fs::file pkg_f(path);
if (!pkg_f || pkg_f.size() < 64)
{
LOG_ERROR(LOADER, "PKG: Failed to open %s", path);
return;
}
//Check header
u32 pkg_signature;
pkg_f.seek(0);
pkg_f.read(pkg_signature);
if (pkg_signature != "\x7FPKG"_u32)
{
LOG_ERROR(LOADER, "PKG: %s is not a pkg file", fileName);
return;
}
// Get title ID
std::vector<char> title_id(9);
pkg_f.seek(55);
pkg_f.read(title_id);
pkg_f.seek(0);
// Get full path
const auto& local_path = Emu.GetHddDir() + "game/" + std::string(std::begin(title_id), std::end(title_id));
if (!fs::create_dir(local_path))
{
if (fs::is_dir(local_path))
{
if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Another installation found. Do you want to overwrite it?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
{
LOG_ERROR(LOADER, "PKG: Cancelled installation to existing directory %s", local_path);
return;
}
}
else
{
LOG_ERROR(LOADER, "PKG: Could not create the installation directory %s", local_path);
return;
}
}
QProgressDialog pdlg(tr("Installing package ... please wait ..."), tr("Cancel"), 0, 1000, this);
pdlg.setWindowTitle(tr("RPCS3 Package Installer"));
pdlg.setWindowModality(Qt::WindowModal);
pdlg.setFixedSize(500, pdlg.height());
pdlg.show();
#ifdef _WIN32
QWinTaskbarButton *taskbar_button = new QWinTaskbarButton();
taskbar_button->setWindow(windowHandle());
QWinTaskbarProgress *taskbar_progress = taskbar_button->progress();
taskbar_progress->setRange(0, 1000);
taskbar_progress->setVisible(true);
#endif
// Synchronization variable
atomic_t<double> progress(0.);
{
// Run PKG unpacking asynchronously
scope_thread worker("PKG Installer", [&]
{
if (pkg_install(pkg_f, local_path + '/', progress, path))
{
progress = 1.;
return;
}
// TODO: Ask user to delete files on cancellation/failure?
progress = -1.;
});
// Wait for the completion
while (std::this_thread::sleep_for(5ms), std::abs(progress) < 1.)
{
if (pdlg.wasCanceled())
{
progress -= 1.;
#ifdef _WIN32
taskbar_progress->hide();
taskbar_button->~QWinTaskbarButton();
#endif
if (QMessageBox::question(this, tr("PKG Decrypter / Installer"), tr("Remove incomplete folder?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes)
{
fs::remove_all(local_path);
m_gameListFrame->Refresh(true);
LOG_SUCCESS(LOADER, "PKG: removed incomplete installation in %s", local_path);
return;
}
break;
}
// Update progress window
pdlg.setValue(static_cast<int>(progress * pdlg.maximum()));
#ifdef _WIN32
taskbar_progress->setValue(static_cast<int>(progress * taskbar_progress->maximum()));
#endif
QCoreApplication::processEvents();
}
if (progress > 0.)
{
pdlg.setValue(pdlg.maximum());
#ifdef _WIN32
taskbar_progress->setValue(taskbar_progress->maximum());
#endif
std::this_thread::sleep_for(100ms);
}
}
if (progress >= 1.)
{
m_gameListFrame->Refresh(true);
LOG_SUCCESS(GENERAL, "Successfully installed %s.", fileName);
guiSettings->ShowInfoBox(GUI::ib_pkg_success, tr("Success!"), tr("Successfully installed software from package!"), this);
#ifdef _WIN32
taskbar_progress->hide();
taskbar_button->~QWinTaskbarButton();
#endif
}
}
void main_window::InstallPup(const QString& dropPath)
{
QString filePath = dropPath;
if (filePath.isEmpty())
{
QString path_last_PUP = guiSettings->GetValue(GUI::fd_install_pup).toString();
filePath = QFileDialog::getOpenFileName(this, tr("Select PS3UPDAT.PUP To Install"), path_last_PUP, tr("PS3 update file (PS3UPDAT.PUP)"));
}
else
{
if (QMessageBox::question(this, tr("RPCS3 Firmware Installer"), tr("Install firmware: %1?").arg(filePath),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
{
LOG_NOTICE(LOADER, "Firmware: Cancelled installation from drop. File: %s", sstr(filePath));
return;
}
}
if (filePath == NULL)
{
return;
}
Emu.Stop();
guiSettings->SetValue(GUI::fd_install_pup, QFileInfo(filePath).path());
const std::string path = sstr(filePath);
fs::file pup_f(path);
pup_object pup(pup_f);
if (!pup)
{
LOG_ERROR(GENERAL, "Error while installing firmware: PUP file is invalid.");
QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: PUP file is invalid."));
return;
}
fs::file update_files_f = pup.get_file(0x300);
tar_object update_files(update_files_f);
auto updatefilenames = update_files.get_filenames();
updatefilenames.erase(std::remove_if(
updatefilenames.begin(), updatefilenames.end(), [](std::string s) { return s.find("dev_flash_") == std::string::npos; }),
updatefilenames.end());
std::string version_string = pup.get_file(0x100).to_string();
version_string.erase(version_string.find('\n'));
const std::string cur_version = "4.81";
if (version_string < cur_version &&
QMessageBox::question(this, tr("RPCS3 Firmware Installer"), tr("Old firmware detected.\nThe newest firmware version is %1 and you are trying to install version %2\nContinue installation?").arg(QString::fromStdString(cur_version), QString::fromStdString(version_string)),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No)
{
return;
}
QProgressDialog pdlg(tr("Installing firmware version %1\nPlease wait...").arg(QString::fromStdString(version_string)), tr("Cancel"), 0, static_cast<int>(updatefilenames.size()), this);
pdlg.setWindowTitle(tr("RPCS3 Firmware Installer"));
pdlg.setWindowModality(Qt::WindowModal);
pdlg.setFixedSize(500, pdlg.height());
pdlg.show();
#ifdef _WIN32
QWinTaskbarButton *taskbar_button = new QWinTaskbarButton();
taskbar_button->setWindow(windowHandle());
QWinTaskbarProgress *taskbar_progress = taskbar_button->progress();
taskbar_progress->setRange(0, static_cast<int>(updatefilenames.size()));
taskbar_progress->setVisible(true);
#endif
// Synchronization variable
atomic_t<int> progress(0);
{
// Run asynchronously
scope_thread worker("Firmware Installer", [&]
{
for (auto updatefilename : updatefilenames)
{
if (progress == -1) break;
fs::file updatefile = update_files.get_file(updatefilename);
SCEDecrypter self_dec(updatefile);
self_dec.LoadHeaders();
self_dec.LoadMetadata(SCEPKG_ERK, SCEPKG_RIV);
self_dec.DecryptData();
auto dev_flash_tar_f = self_dec.MakeFile();
if (dev_flash_tar_f.size() < 3)
{
LOG_ERROR(GENERAL, "Error while installing firmware: PUP contents are invalid.");
QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: PUP contents are invalid."));
progress = -1;
}
tar_object dev_flash_tar(dev_flash_tar_f[2]);
if (!dev_flash_tar.extract(fs::get_config_dir()))
{
LOG_ERROR(GENERAL, "Error while installing firmware: TAR contents are invalid.");
QMessageBox::critical(this, tr("Failure!"), tr("Error while installing firmware: TAR contents are invalid."));
progress = -1;
}
if (progress >= 0)
progress += 1;
}
});
// Wait for the completion
while (std::this_thread::sleep_for(5ms), std::abs(progress) < pdlg.maximum())
{
if (pdlg.wasCanceled())
{
progress = -1;
#ifdef _WIN32
taskbar_progress->hide();
taskbar_button->~QWinTaskbarButton();
#endif
break;
}
// Update progress window
pdlg.setValue(static_cast<int>(progress));
#ifdef _WIN32
taskbar_progress->setValue(static_cast<int>(progress));
#endif
QCoreApplication::processEvents();
}
update_files_f.close();
pup_f.close();
if (progress > 0)
{
pdlg.setValue(pdlg.maximum());
#ifdef _WIN32
taskbar_progress->setValue(taskbar_progress->maximum());
#endif
std::this_thread::sleep_for(100ms);
}
}
if (progress > 0)
{
LOG_SUCCESS(GENERAL, "Successfully installed PS3 firmware version %s.", version_string);
guiSettings->ShowInfoBox(GUI::ib_pup_success, tr("Success!"), tr("Successfully installed PS3 firmware and LLE Modules!"), this);
#ifdef _WIN32
taskbar_progress->hide();
taskbar_button->~QWinTaskbarButton();
#endif
}
}
// This is ugly, but PS3 headers shall not be included there.
extern void sysutil_send_system_cmd(u64 status, u64 param);
void main_window::DecryptSPRXLibraries()
{
QString path_last_SPRX = guiSettings->GetValue(GUI::fd_decrypt_sprx).toString();
QStringList modules = QFileDialog::getOpenFileNames(this, tr("Select SPRX files"), path_last_SPRX, tr("SPRX files (*.sprx)"));
if (modules.isEmpty())
{
return;
}
Emu.Stop();
guiSettings->SetValue(GUI::fd_decrypt_sprx, QFileInfo(modules.first()).path());
LOG_NOTICE(GENERAL, "Decrypting SPRX libraries...");
for (QString& module : modules)
{
std::string prx_path = sstr(module);
const std::string& prx_dir = fs::get_parent_dir(prx_path);
fs::file elf_file(prx_path);
if (elf_file && elf_file.size() >= 4 && elf_file.read<u32>() == "SCE\0"_u32)
{
const std::size_t prx_ext_pos = prx_path.find_last_of('.');
const std::string& prx_name = prx_path.substr(prx_dir.size());
elf_file = decrypt_self(std::move(elf_file));
prx_path.erase(prx_path.size() - 4, 1); // change *.sprx to *.prx
if (elf_file)
{
if (fs::file new_file{ prx_path, fs::rewrite })
{
new_file.write(elf_file.to_string());
LOG_SUCCESS(GENERAL, "Decrypted %s", prx_dir + prx_name);
}
else
{
LOG_ERROR(GENERAL, "Failed to create %s", prx_path);
}
}
else
{
LOG_ERROR(GENERAL, "Failed to decrypt %s", prx_dir + prx_name);
}
}
}
LOG_NOTICE(GENERAL, "Finished decrypting all SPRX libraries.");
}
/** Needed so that when a backup occurs of window state in guisettings, the state is current.
* Also, so that on close, the window state is preserved.
*/
void main_window::SaveWindowState()
{
// Save gui settings
guiSettings->SetValue(GUI::mw_geometry, saveGeometry());
guiSettings->SetValue(GUI::mw_windowState, saveState());
guiSettings->SetValue(GUI::mw_mwState, m_mw->saveState());
// Save column settings
m_gameListFrame->SaveSettings();
// Save splitter state
m_debuggerFrame->SaveSettings();
}
void main_window::RepaintToolBarIcons()
{
QColor newColor;
if (guiSettings->GetValue(GUI::m_enableUIColors).toBool())
{
newColor = guiSettings->GetValue(GUI::mw_toolIconColor).value<QColor>();
}
else
{
newColor = GUI::get_Label_Color("toolbar_icon_color");
}
auto icon = [&newColor](const QString& path)
{
return gui_settings::colorizedIcon(QIcon(path), GUI::mw_tool_icon_color, newColor);
};
m_icon_play = icon(":/Icons/play.png");
m_icon_pause = icon(":/Icons/pause.png");
m_icon_stop = icon(":/Icons/stop.png");
m_icon_restart = icon(":/Icons/restart.png");
m_icon_fullscreen_on = icon(":/Icons/fullscreen.png");
m_icon_fullscreen_off = icon(":/Icons/fullscreen_invert.png");
ui->toolbar_config ->setIcon(icon(":/Icons/configure.png"));
ui->toolbar_controls->setIcon(icon(":/Icons/controllers.png"));
ui->toolbar_disc ->setIcon(icon(":/Icons/disc.png"));
ui->toolbar_grid ->setIcon(icon(":/Icons/grid.png"));
ui->toolbar_list ->setIcon(icon(":/Icons/list.png"));
ui->toolbar_refresh ->setIcon(icon(":/Icons/refresh.png"));
ui->toolbar_snap ->setIcon(icon(":/Icons/screenshot.png"));
ui->toolbar_sort ->setIcon(icon(":/Icons/sort.png"));
ui->toolbar_stop ->setIcon(icon(":/Icons/stop.png"));
if (Emu.IsRunning())
{
ui->toolbar_start->setIcon(m_icon_pause);
}
else if (Emu.IsStopped() && !Emu.GetPath().empty())
{
ui->toolbar_start->setIcon(m_icon_restart);
}
else
{
ui->toolbar_start->setIcon(m_icon_play);
}
if (isFullScreen())
{
ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on);
}
else
{
ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_off);
}
ui->sizeSlider->setStyleSheet(ui->sizeSlider->styleSheet().append("QSlider::handle:horizontal{ background: rgba(%1, %2, %3, %4); }")
.arg(newColor.red()).arg(newColor.green()).arg(newColor.blue()).arg(newColor.alpha()));
}
void main_window::OnEmuRun()
{
m_debuggerFrame->EnableButtons(true);
#ifdef _WIN32
m_thumb_playPause->setToolTip(tr("Pause emulation"));
m_thumb_playPause->setIcon(m_icon_thumb_pause);
#endif
ui->sysPauseAct->setText(tr("&Pause\tCtrl+P"));
ui->sysPauseAct->setIcon(m_icon_pause);
ui->toolbar_start->setIcon(m_icon_pause);
ui->toolbar_start->setToolTip(tr("Pause emulation"));
EnableMenus(true);
}
void main_window::OnEmuResume()
{
#ifdef _WIN32
m_thumb_playPause->setToolTip(tr("Pause emulation"));
m_thumb_playPause->setIcon(m_icon_thumb_pause);
#endif
ui->sysPauseAct->setText(tr("&Pause\tCtrl+P"));
ui->sysPauseAct->setIcon(m_icon_pause);
ui->toolbar_start->setIcon(m_icon_pause);
ui->toolbar_start->setToolTip(tr("Pause emulation"));
}
void main_window::OnEmuPause()
{
#ifdef _WIN32
m_thumb_playPause->setToolTip(tr("Resume emulation"));
m_thumb_playPause->setIcon(m_icon_thumb_play);
#endif
ui->sysPauseAct->setText(tr("&Resume\tCtrl+E"));
ui->sysPauseAct->setIcon(m_icon_play);
ui->toolbar_start->setIcon(m_icon_play);
ui->toolbar_start->setToolTip(tr("Resume emulation"));
}
void main_window::OnEmuStop()
{
m_debuggerFrame->EnableButtons(false);
m_debuggerFrame->ClearBreakpoints();
ui->sysPauseAct->setText(Emu.IsReady() ? tr("&Start\tCtrl+E") : tr("&Resume\tCtrl+E"));
ui->sysPauseAct->setIcon(m_icon_play);
#ifdef _WIN32
m_thumb_playPause->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation"));
m_thumb_playPause->setIcon(m_icon_thumb_play);
#endif
EnableMenus(false);
if (!Emu.GetPath().empty())
{
ui->toolbar_start->setEnabled(true);
ui->toolbar_start->setIcon(m_icon_restart);
ui->toolbar_start->setToolTip(tr("Restart emulation"));
ui->sysRebootAct->setEnabled(true);
#ifdef _WIN32
m_thumb_restart->setEnabled(true);
#endif
}
else
{
ui->toolbar_start->setIcon(m_icon_play);
ui->toolbar_start->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation"));
}
}
void main_window::OnEmuReady()
{
m_debuggerFrame->EnableButtons(true);
#ifdef _WIN32
m_thumb_playPause->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation"));
m_thumb_playPause->setIcon(m_icon_thumb_play);
#endif
ui->sysPauseAct->setText(Emu.IsReady() ? tr("&Start\tCtrl+E") : tr("&Resume\tCtrl+E"));
ui->sysPauseAct->setIcon(m_icon_play);
ui->toolbar_start->setIcon(m_icon_play);
ui->toolbar_start->setToolTip(Emu.IsReady() ? tr("Start emulation") : tr("Resume emulation"));
EnableMenus(true);
}
void main_window::EnableMenus(bool enabled)
{
// Thumbnail Buttons
#ifdef _WIN32
m_thumb_playPause->setEnabled(enabled);
m_thumb_stop->setEnabled(enabled);
m_thumb_restart->setEnabled(enabled);
#endif
// Toolbar
ui->toolbar_start->setEnabled(enabled);
ui->toolbar_stop->setEnabled(enabled);
// Emulation
ui->sysPauseAct->setEnabled(enabled);
ui->sysStopAct->setEnabled(enabled);
ui->sysRebootAct->setEnabled(enabled);
// PS3 Commands
ui->sysSendOpenMenuAct->setEnabled(enabled);
ui->sysSendExitAct->setEnabled(enabled);
// Tools
ui->toolskernel_explorerAct->setEnabled(enabled);
ui->toolsmemory_viewerAct->setEnabled(enabled);
ui->toolsRsxDebuggerAct->setEnabled(enabled);
ui->toolsStringSearchAct->setEnabled(enabled);
}
void main_window::BootRecentAction(const QAction* act)
{
if (Emu.IsRunning())
{
return;
}
const QString pth = act->data().toString();
QString nam;
bool containsPath = false;
int idx = -1;
for (int i = 0; i < m_rg_entries.count(); i++)
{
if (m_rg_entries.at(i).first == pth)
{
idx = i;
containsPath = true;
nam = m_rg_entries.at(idx).second;
}
}
// path is invalid: remove action from list return
if ((containsPath && nam.isEmpty()) || (!QFileInfo(pth).isDir() && !QFileInfo(pth).isFile()))
{
if (containsPath)
{
// clear menu of actions
for (auto act : m_recentGameActs)
{
ui->bootRecentMenu->removeAction(act);
}
// remove action from list
m_rg_entries.removeAt(idx);
m_recentGameActs.removeAt(idx);
guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries));
LOG_ERROR(GENERAL, "Recent Game not valid, removed from Boot Recent list: %s", sstr(pth));
// refill menu with actions
for (int i = 0; i < m_recentGameActs.count(); i++)
{
m_recentGameActs[i]->setShortcut(tr("Ctrl+%1").arg(i + 1));
m_recentGameActs[i]->setToolTip(m_rg_entries.at(i).second);
ui->bootRecentMenu->addAction(m_recentGameActs[i]);
}
LOG_WARNING(GENERAL, "Boot Recent list refreshed");
return;
}
LOG_ERROR(GENERAL, "Path invalid and not in m_rg_paths: %s", sstr(pth));
return;
}
SetAppIconFromPath(sstr(pth));
Emu.Stop();
if (!Emu.BootGame(sstr(pth), true))
{
LOG_ERROR(LOADER, "Failed to boot %s", sstr(pth));
}
else
{
LOG_SUCCESS(LOADER, "Boot from Recent List: done");
AddRecentAction(GUI::Recent_Game(qstr(Emu.GetBoot()), nam));
m_gameListFrame->Refresh(true);
}
};
QAction* main_window::CreateRecentAction(const q_string_pair& entry, const uint& sc_idx)
{
// if path is not valid remove from list
if (entry.second.isEmpty() || (!QFileInfo(entry.first).isDir() && !QFileInfo(entry.first).isFile()))
{
if (m_rg_entries.contains(entry))
{
LOG_ERROR(GENERAL, "Recent Game not valid, removing from Boot Recent list: %s", sstr(entry.first));
int idx = m_rg_entries.indexOf(entry);
m_rg_entries.removeAt(idx);
guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries));
}
return nullptr;
}
// if name is a path get filename
QString shown_name = entry.second;
if (QFileInfo(entry.second).isFile())
{
shown_name = entry.second.section('/', -1);
}
// create new action
QAction* act = new QAction(shown_name, this);
act->setData(entry.first);
act->setToolTip(entry.second);
act->setShortcut(tr("Ctrl+%1").arg(sc_idx));
// truncate if too long
if (shown_name.length() > 60)
{
act->setText(shown_name.left(27) + "(....)" + shown_name.right(27));
}
// connect boot
connect(act, &QAction::triggered, [=]() {BootRecentAction(act); });
return act;
};
void main_window::AddRecentAction(const q_string_pair& entry)
{
// don't change list on freeze
if (ui->freezeRecentAct->isChecked())
{
return;
}
// create new action, return if not valid
QAction* act = CreateRecentAction(entry, 1);
if (!act)
{
return;
}
// clear menu of actions
for (auto act : m_recentGameActs)
{
ui->bootRecentMenu->removeAction(act);
}
// if path already exists, remove it in order to get it to beginning
if (m_rg_entries.contains(entry))
{
int idx = m_rg_entries.indexOf(entry);
m_rg_entries.removeAt(idx);
m_recentGameActs.removeAt(idx);
}
// remove oldest action at the end if needed
if (m_rg_entries.count() == 9)
{
m_rg_entries.removeLast();
m_recentGameActs.removeLast();
}
else if (m_rg_entries.count() > 9)
{
LOG_ERROR(LOADER, "Recent games entrylist too big");
}
if (m_rg_entries.count() < 9)
{
// add new action at the beginning
m_rg_entries.prepend(entry);
m_recentGameActs.prepend(act);
}
// refill menu with actions
for (int i = 0; i < m_recentGameActs.count(); i++)
{
m_recentGameActs[i]->setShortcut(tr("Ctrl+%1").arg(i+1));
m_recentGameActs[i]->setToolTip(m_rg_entries.at(i).second);
ui->bootRecentMenu->addAction(m_recentGameActs[i]);
}
guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(m_rg_entries));
}
void main_window::RepaintGui()
{
m_gameListFrame->RepaintIcons(true);
m_gameListFrame->RepaintToolBarIcons();
RepaintToolbar();
RepaintToolBarIcons();
}
void main_window::RepaintToolbar()
{
if (guiSettings->GetValue(GUI::m_enableUIColors).toBool())
{
QColor tbc = guiSettings->GetValue(GUI::mw_toolBarColor).value<QColor>();
ui->toolBar->setStyleSheet(GUI::stylesheet + QString(
"QToolBar { background-color: rgba(%1, %2, %3, %4); }"
"QToolBar::separator {background-color: rgba(%5, %6, %7, %8); width: 1px; margin-top: 2px; margin-bottom: 2px;}"
"QSlider { background-color: rgba(%1, %2, %3, %4); }"
"QLineEdit { background-color: rgba(%1, %2, %3, %4); }")
.arg(tbc.red()).arg(tbc.green()).arg(tbc.blue()).arg(tbc.alpha())
.arg(tbc.red() - 20).arg(tbc.green() - 20).arg(tbc.blue() - 20).arg(tbc.alpha() - 20)
);
}
else
{
ui->toolBar->setStyleSheet(GUI::stylesheet);
}
}
void main_window::CreateActions()
{
ui->exitAct->setShortcuts(QKeySequence::Quit);
ui->toolbar_start->setEnabled(false);
ui->toolbar_stop->setEnabled(false);
m_categoryVisibleActGroup = new QActionGroup(this);
m_categoryVisibleActGroup->addAction(ui->showCatHDDGameAct);
m_categoryVisibleActGroup->addAction(ui->showCatDiscGameAct);
m_categoryVisibleActGroup->addAction(ui->showCatHomeAct);
m_categoryVisibleActGroup->addAction(ui->showCatAudioVideoAct);
m_categoryVisibleActGroup->addAction(ui->showCatGameDataAct);
m_categoryVisibleActGroup->addAction(ui->showCatUnknownAct);
m_categoryVisibleActGroup->addAction(ui->showCatOtherAct);
m_categoryVisibleActGroup->setExclusive(false);
m_iconSizeActGroup = new QActionGroup(this);
m_iconSizeActGroup->addAction(ui->setIconSizeTinyAct);
m_iconSizeActGroup->addAction(ui->setIconSizeSmallAct);
m_iconSizeActGroup->addAction(ui->setIconSizeMediumAct);
m_iconSizeActGroup->addAction(ui->setIconSizeLargeAct);
m_listModeActGroup = new QActionGroup(this);
m_listModeActGroup->addAction(ui->setlistModeListAct);
m_listModeActGroup->addAction(ui->setlistModeGridAct);
}
void main_window::CreateConnects()
{
connect(ui->bootElfAct, &QAction::triggered, this, &main_window::BootElf);
connect(ui->bootGameAct, &QAction::triggered, this, &main_window::BootGame);
connect(ui->bootRecentMenu, &QMenu::aboutToShow, [=]
{
// Enable/Disable Recent Games List
const bool stopped = Emu.IsStopped();
for (auto act : ui->bootRecentMenu->actions())
{
if (act != ui->freezeRecentAct && act != ui->clearRecentAct)
{
act->setEnabled(stopped);
}
}
});
connect(ui->clearRecentAct, &QAction::triggered, [this]
{
if (ui->freezeRecentAct->isChecked()) { return; }
m_rg_entries.clear();
for (auto act : m_recentGameActs)
{
ui->bootRecentMenu->removeAction(act);
}
m_recentGameActs.clear();
guiSettings->SetValue(GUI::rg_entries, guiSettings->List2Var(q_pair_list()));
});
connect(ui->freezeRecentAct, &QAction::triggered, [=](bool checked)
{
guiSettings->SetValue(GUI::rg_freeze, checked);
});
connect(ui->bootInstallPkgAct, &QAction::triggered, [this] {InstallPkg(); });
connect(ui->bootInstallPupAct, &QAction::triggered, [this] {InstallPup(); });
connect(ui->exitAct, &QAction::triggered, this, &QWidget::close);
connect(ui->sysPauseAct, &QAction::triggered, Pause);
connect(ui->sysStopAct, &QAction::triggered, [=]() { Emu.Stop(); });
connect(ui->sysRebootAct, &QAction::triggered, [=]() { Emu.Stop(); Emu.Load(); });
connect(ui->sysSendOpenMenuAct, &QAction::triggered, [=]
{
sysutil_send_system_cmd(m_sys_menu_opened ? 0x0132 /* CELL_SYSUTIL_SYSTEM_MENU_CLOSE */ : 0x0131 /* CELL_SYSUTIL_SYSTEM_MENU_OPEN */, 0);
m_sys_menu_opened = !m_sys_menu_opened;
ui->sysSendOpenMenuAct->setText(tr("Send &%0 system menu cmd").arg(m_sys_menu_opened ? tr("close") : tr("open")));
});
connect(ui->sysSendExitAct, &QAction::triggered, [=]
{
sysutil_send_system_cmd(0x0101 /* CELL_SYSUTIL_REQUEST_EXITGAME */, 0);
});
auto openSettings = [=](int tabIndex)
{
settings_dialog dlg(guiSettings, m_Render_Creator, tabIndex, this);
connect(&dlg, &settings_dialog::GuiSettingsSaveRequest, this, &main_window::SaveWindowState);
connect(&dlg, &settings_dialog::GuiSettingsSyncRequest, [=]() {ConfigureGuiFromSettings(true); });
connect(&dlg, &settings_dialog::GuiStylesheetRequest, this, &main_window::RequestGlobalStylesheetChange);
connect(&dlg, &settings_dialog::GuiRepaintRequest, this, &main_window::RepaintGui);
dlg.exec();
};
connect(ui->confCPUAct, &QAction::triggered, [=]() { openSettings(0); });
connect(ui->confGPUAct, &QAction::triggered, [=]() { openSettings(1); });
connect(ui->confAudioAct, &QAction::triggered, [=]() { openSettings(2); });
connect(ui->confIOAct, &QAction::triggered, [=]() { openSettings(3); });
connect(ui->confSystemAct, &QAction::triggered, [=]() { openSettings(4); });
connect(ui->confPadsAct, &QAction::triggered, this, [=]
{
gamepads_settings_dialog dlg(this);
dlg.exec();
});
connect(ui->confAutopauseManagerAct, &QAction::triggered, [=]
{
auto_pause_settings_dialog dlg(this);
dlg.exec();
});
connect(ui->confVFSDialogAct, &QAction::triggered, [=]
{
vfs_dialog dlg(this);
dlg.exec();
m_gameListFrame->Refresh(true); // dev-hdd0 may have changed. Refresh just in case.
});
connect(ui->confSavedataManagerAct, &QAction::triggered, [=]
{
save_manager_dialog* sdid = new save_manager_dialog();
sdid->show();
});
connect(ui->toolsCgDisasmAct, &QAction::triggered, [=]
{
cg_disasm_window* cgdw = new cg_disasm_window(guiSettings);
cgdw->show();
});
connect(ui->toolskernel_explorerAct, &QAction::triggered, [=]
{
kernel_explorer* kernelExplorer = new kernel_explorer(this);
kernelExplorer->show();
});
connect(ui->toolsmemory_viewerAct, &QAction::triggered, [=]
{
memory_viewer_panel* mvp = new memory_viewer_panel(this);
mvp->show();
});
connect(ui->toolsRsxDebuggerAct, &QAction::triggered, [=]
{
rsx_debugger* rsx = new rsx_debugger(this);
rsx->show();
});
connect(ui->toolsStringSearchAct, &QAction::triggered, [=]
{
memory_string_searcher* mss = new memory_string_searcher(this);
mss->show();
});
connect(ui->toolsDecryptSprxLibsAct, &QAction::triggered, this, &main_window::DecryptSPRXLibraries);
connect(ui->showDebuggerAct, &QAction::triggered, [=](bool checked)
{
checked ? m_debuggerFrame->show() : m_debuggerFrame->hide();
guiSettings->SetValue(GUI::mw_debugger, checked);
});
connect(ui->showLogAct, &QAction::triggered, [=](bool checked)
{
checked ? m_logFrame->show() : m_logFrame->hide();
guiSettings->SetValue(GUI::mw_logger, checked);
});
connect(ui->showGameListAct, &QAction::triggered, [=](bool checked)
{
checked ? m_gameListFrame->show() : m_gameListFrame->hide();
guiSettings->SetValue(GUI::mw_gamelist, checked);
});
connect(ui->showToolBarAct, &QAction::triggered, [=](bool checked)
{
ui->toolBar->setVisible(checked);
guiSettings->SetValue(GUI::mw_toolBarVisible, checked);
});
connect(ui->showGameToolBarAct, &QAction::triggered, [=](bool checked)
{
m_gameListFrame->SetToolBarVisible(checked);
});
connect(ui->refreshGameListAct, &QAction::triggered, [=]
{
m_gameListFrame->Refresh(true);
});
connect(m_categoryVisibleActGroup, &QActionGroup::triggered, [=](QAction* act)
{
QStringList categories;
int id;
const bool& checked = act->isChecked();
if (act == ui->showCatHDDGameAct) categories += category::non_disc_games, id = Category::Non_Disc_Game;
else if (act == ui->showCatDiscGameAct) categories += category::disc_Game, id = Category::Disc_Game;
else if (act == ui->showCatHomeAct) categories += category::home, id = Category::Home;
else if (act == ui->showCatAudioVideoAct) categories += category::media, id = Category::Media;
else if (act == ui->showCatGameDataAct) categories += category::data, id = Category::Data;
else if (act == ui->showCatUnknownAct) categories += category::unknown, id = Category::Unknown_Cat;
else if (act == ui->showCatOtherAct) categories += category::others, id = Category::Others;
else LOG_WARNING(GENERAL, "categoryVisibleActGroup: category action not found");
m_gameListFrame->SetCategoryActIcon(m_categoryVisibleActGroup->actions().indexOf(act), checked);
m_gameListFrame->ToggleCategoryFilter(categories, checked);
guiSettings->SetCategoryVisibility(id, checked);
});
connect(ui->aboutAct, &QAction::triggered, [this]
{
about_dialog dlg(this);
dlg.exec();
});
connect(ui->aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt);
auto resizeIcons = [=](const int& index)
{
int val = ui->sizeSlider->value();
if (val != index)
{
ui->sizeSlider->setSliderPosition(index);
}
if (val != m_gameListFrame->GetSliderValue())
{
if (m_save_slider_pos)
{
m_save_slider_pos = false;
guiSettings->SetValue(GUI::gl_iconSize, index);
}
m_gameListFrame->ResizeIcons(index);
}
};
connect(m_iconSizeActGroup, &QActionGroup::triggered, [=](QAction* act)
{
int index;
if (act == ui->setIconSizeTinyAct) index = 0;
else if (act == ui->setIconSizeSmallAct) index = GUI::get_Index(GUI::gl_icon_size_small);
else if (act == ui->setIconSizeMediumAct) index = GUI::get_Index(GUI::gl_icon_size_medium);
else index = GUI::gl_max_slider_pos;
resizeIcons(index);
});
connect (m_gameListFrame, &game_list_frame::RequestIconSizeActSet, [=](const int& idx)
{
if (idx < GUI::get_Index((GUI::gl_icon_size_small + GUI::gl_icon_size_min) / 2)) ui->setIconSizeTinyAct->setChecked(true);
else if (idx < GUI::get_Index((GUI::gl_icon_size_medium + GUI::gl_icon_size_small) / 2)) ui->setIconSizeSmallAct->setChecked(true);
else if (idx < GUI::get_Index((GUI::gl_icon_size_max + GUI::gl_icon_size_medium) / 2)) ui->setIconSizeMediumAct->setChecked(true);
else ui->setIconSizeLargeAct->setChecked(true);
resizeIcons(idx);
});
connect(m_gameListFrame, &game_list_frame::RequestSaveSliderPos, [=](const bool& save)
{
Q_UNUSED(save);
m_save_slider_pos = true;
});
connect(m_gameListFrame, &game_list_frame::RequestListModeActSet, [=](const bool& isList)
{
isList ? ui->setlistModeListAct->trigger() : ui->setlistModeGridAct->trigger();
});
connect(m_gameListFrame, &game_list_frame::RequestCategoryActSet, [=](const int& id)
{
m_categoryVisibleActGroup->actions().at(id)->trigger();
});
connect(m_listModeActGroup, &QActionGroup::triggered, [=](QAction* act)
{
bool isList = act == ui->setlistModeListAct;
m_gameListFrame->SetListMode(isList);
m_categoryVisibleActGroup->setEnabled(isList);
});
connect(ui->toolbar_disc, &QAction::triggered, this, &main_window::BootGame);
connect(ui->toolbar_refresh, &QAction::triggered, [=]() { m_gameListFrame->Refresh(true); });
connect(ui->toolbar_stop, &QAction::triggered, [=]() { Emu.Stop(); });
connect(ui->toolbar_start, &QAction::triggered, Pause);
connect(ui->toolbar_fullscreen, &QAction::triggered, [=]
{
if (isFullScreen())
{
showNormal();
ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on);
}
else
{
showFullScreen();
ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_off);
}
});
connect(ui->toolbar_controls, &QAction::triggered, [=]() { gamepads_settings_dialog dlg(this); dlg.exec(); });
connect(ui->toolbar_config, &QAction::triggered, [=]() { openSettings(0); });
connect(ui->toolbar_list, &QAction::triggered, [=]() { ui->setlistModeListAct->trigger(); });
connect(ui->toolbar_grid, &QAction::triggered, [=]() { ui->setlistModeGridAct->trigger(); });
connect(ui->sizeSlider, &QSlider::valueChanged, resizeIcons);
connect(ui->sizeSlider, &QSlider::sliderReleased, this, [&] { guiSettings->SetValue(GUI::gl_iconSize, ui->sizeSlider->value()); });
connect(ui->sizeSlider, &QSlider::actionTriggered, [&](int action)
{
if (action != QAbstractSlider::SliderNoAction && action != QAbstractSlider::SliderMove)
{ // we only want to save on mouseclicks or slider release (the other connect handles this)
m_save_slider_pos = true; // actionTriggered happens before the value was changed
}
});
connect(ui->mw_searchbar, &QLineEdit::textChanged, m_gameListFrame, &game_list_frame::SetSearchText);
}
void main_window::CreateDockWindows()
{
// new mainwindow widget because existing seems to be bugged for now
m_mw = new QMainWindow();
m_gameListFrame = new game_list_frame(guiSettings, m_Render_Creator, m_mw);
m_gameListFrame->setObjectName("gamelist");
m_debuggerFrame = new debugger_frame(guiSettings, m_mw);
m_debuggerFrame->setObjectName("debugger");
m_logFrame = new log_frame(guiSettings, m_mw);
m_logFrame->setObjectName("logger");
m_mw->addDockWidget(Qt::LeftDockWidgetArea, m_gameListFrame);
m_mw->addDockWidget(Qt::LeftDockWidgetArea, m_logFrame);
m_mw->addDockWidget(Qt::RightDockWidgetArea, m_debuggerFrame);
m_mw->setDockNestingEnabled(true);
setCentralWidget(m_mw);
connect(m_logFrame, &log_frame::LogFrameClosed, [=]()
{
if (ui->showLogAct->isChecked())
{
ui->showLogAct->setChecked(false);
guiSettings->SetValue(GUI::mw_logger, false);
}
});
connect(m_debuggerFrame, &debugger_frame::DebugFrameClosed, [=]()
{
if (ui->showDebuggerAct->isChecked())
{
ui->showDebuggerAct->setChecked(false);
guiSettings->SetValue(GUI::mw_debugger, false);
}
});
connect(m_gameListFrame, &game_list_frame::GameListFrameClosed, [=]()
{
if (ui->showGameListAct->isChecked())
{
ui->showGameListAct->setChecked(false);
guiSettings->SetValue(GUI::mw_gamelist, false);
}
});
connect(m_gameListFrame, &game_list_frame::RequestIconPathSet, this, &main_window::SetAppIconFromPath);
connect(m_gameListFrame, &game_list_frame::RequestAddRecentGame, this, &main_window::AddRecentAction);
connect(m_gameListFrame, &game_list_frame::RequestPackageInstall, [this](const QStringList& paths)
{
for (const auto& path : paths)
{
InstallPkg(path);
}
});
connect(m_gameListFrame, &game_list_frame::RequestFirmwareInstall, this, &main_window::InstallPup);
}
void main_window::ConfigureGuiFromSettings(bool configureAll)
{
// Restore GUI state if needed. We need to if they exist.
QByteArray geometry = guiSettings->GetValue(GUI::mw_geometry).toByteArray();
if (geometry.isEmpty() == false)
{
restoreGeometry(geometry);
}
else
{ // By default, set the window to 70% of the screen and the debugger frame is hidden.
m_debuggerFrame->hide();
QSize defaultSize = QDesktopWidget().availableGeometry().size() * 0.7;
resize(defaultSize);
}
restoreState(guiSettings->GetValue(GUI::mw_windowState).toByteArray());
m_mw->restoreState(guiSettings->GetValue(GUI::mw_mwState).toByteArray());
ui->freezeRecentAct->setChecked(guiSettings->GetValue(GUI::rg_freeze).toBool());
m_rg_entries = guiSettings->Var2List(guiSettings->GetValue(GUI::rg_entries));
// clear recent games menu of actions
for (auto act : m_recentGameActs)
{
ui->bootRecentMenu->removeAction(act);
}
m_recentGameActs.clear();
// Fill the recent games menu
for (int i = 0; i < m_rg_entries.count(); i++)
{
// adjust old unformatted entries (avoid duplication)
m_rg_entries[i] = GUI::Recent_Game(m_rg_entries[i].first, m_rg_entries[i].second);
// create new action
QAction* act = CreateRecentAction(m_rg_entries[i], i + 1);
// add action to menu
if (act)
{
m_recentGameActs.append(act);
ui->bootRecentMenu->addAction(act);
}
else
{
i--; // list count is now an entry shorter so we have to repeat the same index in order to load all other entries
}
}
ui->showLogAct->setChecked(guiSettings->GetValue(GUI::mw_logger).toBool());
ui->showGameListAct->setChecked(guiSettings->GetValue(GUI::mw_gamelist).toBool());
ui->showDebuggerAct->setChecked(guiSettings->GetValue(GUI::mw_debugger).toBool());
ui->showToolBarAct->setChecked(guiSettings->GetValue(GUI::mw_toolBarVisible).toBool());
ui->showGameToolBarAct->setChecked(guiSettings->GetValue(GUI::gl_toolBarVisible).toBool());
m_debuggerFrame->setVisible(ui->showDebuggerAct->isChecked());
m_logFrame->setVisible(ui->showLogAct->isChecked());
m_gameListFrame->setVisible(ui->showGameListAct->isChecked());
m_gameListFrame->SetToolBarVisible(ui->showGameToolBarAct->isChecked());
ui->toolBar->setVisible(ui->showToolBarAct->isChecked());
RepaintToolbar();
ui->showCatHDDGameAct->setChecked(guiSettings->GetCategoryVisibility(Category::Non_Disc_Game));
ui->showCatDiscGameAct->setChecked(guiSettings->GetCategoryVisibility(Category::Disc_Game));
ui->showCatHomeAct->setChecked(guiSettings->GetCategoryVisibility(Category::Home));
ui->showCatAudioVideoAct->setChecked(guiSettings->GetCategoryVisibility(Category::Media));
ui->showCatGameDataAct->setChecked(guiSettings->GetCategoryVisibility(Category::Data));
ui->showCatUnknownAct->setChecked(guiSettings->GetCategoryVisibility(Category::Unknown_Cat));
ui->showCatOtherAct->setChecked(guiSettings->GetCategoryVisibility(Category::Others));
int idx = guiSettings->GetValue(GUI::gl_iconSize).toInt();
int index = GUI::gl_max_slider_pos / 4;
if (idx < index) ui->setIconSizeTinyAct->setChecked(true);
else if (idx < index * 2) ui->setIconSizeSmallAct->setChecked(true);
else if (idx < index * 3) ui->setIconSizeMediumAct->setChecked(true);
else ui->setIconSizeLargeAct->setChecked(true);
bool isListMode = guiSettings->GetValue(GUI::gl_listMode).toBool();
if (isListMode) ui->setlistModeListAct->setChecked(true);
else ui->setlistModeGridAct->setChecked(true);
m_categoryVisibleActGroup->setEnabled(isListMode);
if (configureAll)
{
// Handle log settings
m_logFrame->LoadSettings();
// Gamelist
m_gameListFrame->LoadSettings();
}
}
void main_window::keyPressEvent(QKeyEvent *keyEvent)
{
if (((keyEvent->modifiers() & Qt::AltModifier) && keyEvent->key() == Qt::Key_Return) || (isFullScreen() && keyEvent->key() == Qt::Key_Escape))
{
ui->toolbar_fullscreen->trigger();
}
if (keyEvent->modifiers() & Qt::ControlModifier)
{
switch (keyEvent->key())
{
case Qt::Key_E: if (Emu.IsPaused()) Emu.Resume(); else if (Emu.IsReady()) Emu.Run(); return;
case Qt::Key_P: if (Emu.IsRunning()) Emu.Pause(); return;
case Qt::Key_S: if (!Emu.IsStopped()) Emu.Stop(); return;
case Qt::Key_R: if (!Emu.GetPath().empty()) { Emu.Stop(); Emu.Run(); } return;
}
}
}
void main_window::mouseDoubleClickEvent(QMouseEvent *event)
{
if (isFullScreen())
{
if (event->button() == Qt::LeftButton)
{
showNormal();
ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on);
}
}
}
/** Override the Qt close event to have the emulator stop and the application die. May add a warning dialog in future.
*/
void main_window::closeEvent(QCloseEvent* closeEvent)
{
Q_UNUSED(closeEvent);
// Cleanly stop the emulator.
Emu.Stop();
SaveWindowState();
// I need the gui settings to sync, and that means having the destructor called as guiSetting's parent is main_window.
setAttribute(Qt::WA_DeleteOnClose);
QMainWindow::close();
// It's possible to have other windows open, like games. So, force the application to die.
QApplication::quit();
}
| PeterMcteague/rpcs3 | rpcs3/rpcs3qt/main_window.cpp | C++ | gpl-2.0 | 49,565 |
<?php
/**
* Elgg Gifts plugin
* Send gifts to you friends
*
* @package Gifts
* @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2
* @author Christian Heckelmann
* @copyright Christian Heckelmann
* @link http://www.heckelmann.info
*
* updated by iionly (iionly@gmx.de)
*/
// Show your sent gifts
elgg_push_breadcrumb(elgg_echo('gifts:menu'), 'gifts/' . elgg_get_logged_in_user_entity()->username. '/index');
$title = elgg_echo('gifts:sent');
elgg_push_breadcrumb($title);
if (elgg_is_logged_in()) {
elgg_register_menu_item('title', [
'name' => 'sendgift',
'href' => "gifts/" . elgg_get_logged_in_user_entity()->username . "/sendgift",
'text' => elgg_echo('gifts:sendgifts'),
'link_class' => 'elgg-button elgg-button-action',
]);
}
$content = elgg_list_entities([
'type' => 'object',
'subtype' => Gifts::SUBTYPE,
'owner_guid' => elgg_get_logged_in_user_guid(),
'no_results' => elgg_echo('gifts:nogifts'),
]);
// Format page
$body = elgg_view_layout('content', [
'content' => $content,
'filter' => '',
'title' => $title,
]);
// Draw it
echo elgg_view_page($title, $body);
| iionly/gifts | views/default/resources/gifts/sent.php | PHP | gpl-2.0 | 1,189 |
<?php
/**
* Checkout coupon form
*
* @author WooThemes
* @package WooCommerce/Templates
* @version 1.6.4
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
global $woocommerce;
if ( ! WC()->cart->coupons_enabled() )
return;
$info_message = apply_filters( 'woocommerce_checkout_coupon_message', __( 'Have a coupon?', 'woocommerce' ) );
$info_message .= ' <a href="#" class="showcoupon">' . __( 'Click here to enter your code', 'woocommerce' ) . '</a>';
?>
<div class="box woocommerce-box border-box"> <?php echo $info_message;?>
<form class="checkout_coupon brad-woocommerce-form" method="post" style="display:none">
<p class="form-row form-row-first">
<input type="text" name="coupon_code" class="input-text" placeholder="<?php _e( 'Coupon code', 'woocommerce' ); ?>" id="coupon_code" value="" />
</p>
<p class="form-row form-row-last">
<input type="submit" class="button" name="apply_coupon" value="<?php _e( 'Apply Coupon', 'woocommerce' ); ?>" />
</p>
<div class="clear"></div>
</form>
</div>
| diegoschefer/fcp-wp | wp-content/themes/Akal/woocommerce/checkout/form-coupon.php | PHP | gpl-2.0 | 1,068 |
<?php
/**
*
* @package phpBB.de pastebin
* @copyright (c) 2015 phpBB.de, gn#36
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2
*
*/
namespace goztow\edit_has_topicreview\event;
/**
* @ignore
*/
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Event listener
*/
class base_events implements EventSubscriberInterface
{
static public function getSubscribedEvents()
{
return array(
'core.posting_modify_template_vars' => 'edit_topicreview',
);
}
/* @var \phpbb\template\template */
protected $template;
/**
* Constructor
*
* @param \phpbb\controller\helper $helper Controller helper object
* @param \phpbb\template\template $template Template object
*/
public function __construct(\phpbb\template\template $template)
{
$this->template = $template;
}
public function edit_topicreview($event)
{
if ($event['mode'] == 'edit' && topic_review($event['topic_id'], $event['forum_id']))
{
$this->template->assign_var('S_DISPLAY_REVIEW', true);
}
}
}
| goztow/edit_has_topicreview | event/base_events.php | PHP | gpl-2.0 | 1,058 |
<?php
/**
* Custom template tags for this theme
*
* Eventually, some of the functionality here could be replaced by core features.
*
* @package UnlockingSilentHistories
*/
if ( ! function_exists( 'unlockingsilenthistories_posted_on' ) ) :
/**
* Prints HTML with meta information for the current post-date/time and author.
*/
function unlockingsilenthistories_posted_on() {
$time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) {
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
}
$time_string = sprintf( $time_string,
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() ),
esc_attr( get_the_modified_date( 'c' ) ),
esc_html( get_the_modified_date() )
);
$posted_on = sprintf(
/* translators: %s: post date. */
esc_html_x( 'Posted on %s', 'post date', 'unlockingsilenthistories' ),
'<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>'
);
$byline = sprintf(
/* translators: %s: post author. */
esc_html_x( 'by %s', 'post author', 'unlockingsilenthistories' ),
'<span class="author vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . '">' . esc_html( get_the_author() ) . '</a></span>'
);
echo '<span class="posted-on">' . $posted_on . '</span><span class="byline"> ' . $byline . '</span>'; // WPCS: XSS OK.
}
endif;
if ( ! function_exists( 'unlockingsilenthistories_entry_footer' ) ) :
/**
* Prints HTML with meta information for the categories, tags and comments.
*/
function unlockingsilenthistories_entry_footer() {
// Hide category and tag text for pages.
if ( 'post' === get_post_type() ) {
/* translators: used between list items, there is a space after the comma */
$categories_list = get_the_category_list( esc_html__( ', ', 'unlockingsilenthistories' ) );
if ( $categories_list ) {
/* translators: 1: list of categories. */
printf( '<span class="cat-links">' . esc_html__( 'Posted in %1$s', 'unlockingsilenthistories' ) . '</span>', $categories_list ); // WPCS: XSS OK.
}
/* translators: used between list items, there is a space after the comma */
$tags_list = get_the_tag_list( '', esc_html_x( ', ', 'list item separator', 'unlockingsilenthistories' ) );
if ( $tags_list ) {
/* translators: 1: list of tags. */
printf( '<span class="tags-links">' . esc_html__( 'Tagged %1$s', 'unlockingsilenthistories' ) . '</span>', $tags_list ); // WPCS: XSS OK.
}
}
if ( ! is_single() && ! post_password_required() && ( comments_open() || get_comments_number() ) ) {
echo '<span class="comments-link">';
comments_popup_link(
sprintf(
wp_kses(
/* translators: %s: post title */
__( 'Leave a Comment<span class="screen-reader-text"> on %s</span>', 'unlockingsilenthistories' ),
array(
'span' => array(
'class' => array(),
),
)
),
get_the_title()
)
);
echo '</span>';
}
edit_post_link(
sprintf(
wp_kses(
/* translators: %s: Name of current post. Only visible to screen readers */
__( 'Edit <span class="screen-reader-text">%s</span>', 'unlockingsilenthistories' ),
array(
'span' => array(
'class' => array(),
),
)
),
get_the_title()
),
'<span class="edit-link">',
'</span>'
);
}
endif;
| jhyun94/WP-USH | inc/template-tags.php | PHP | gpl-2.0 | 3,526 |
package uq.androidhack.flashspeak;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import uq.androidhack.flashspeak.interfaces.TargetFileListener;
import uq.androidhack.flashspeak.interfaces.TrialFileListener;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link VisualisationFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link VisualisationFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class VisualisationFragment extends Fragment implements TargetFileListener,TrialFileListener{
private OnFragmentInteractionListener mListener;
//Here is your URL defined
String url = "http://vprbbc.streamguys.net/vprbbc24.mp3";
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment VisualisationFragment.
*/
public static VisualisationFragment newInstance() {
VisualisationFragment fragment = new VisualisationFragment();
Bundle args = new Bundle();
//args.putString(ARG_PARAM1, param1);
//args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public VisualisationFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_visualisation, container, false);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onFileChange(String uri) {
File file = new File (uri);
ImageView ogAudioSampleImageView = (ImageView)getView().findViewById(R.id.originalAudioSampleVisualisation);
ogAudioSampleImageView.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath()));
}
@Override
public void onRecording(URI uri) {
ImageView targetAudioSampleImageView = (ImageView)getView().findViewById(R.id.usersAudioSampleVisualisation);
targetAudioSampleImageView.setImageResource(android.R.color.transparent);
}
@Override
public void onFinishProcessing(String b) {
Log.i("VISUALIZER", "in HERE!");
ImageView ogAudioSampleImageView = (ImageView)getView().findViewById(R.id.originalAudioSampleVisualisation);
//ogAudioSampleImageView.setImageURI(new URI(b));
new DownloadImageTask(ogAudioSampleImageView).execute(b);
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
public void onFragmentInteraction(Bitmap uri);
}
}
| andyepx/flashspeak | app/src/main/java/uq/androidhack/flashspeak/VisualisationFragment.java | Java | gpl-2.0 | 5,028 |
using System;
using System.IO;
static class App{
static void PrintRunningGC(int n){
Console.WriteLine("Running GC for generation " + n);
GC.Collect(n);
}
public static void Main(){
//
// Uma instância de FileStream mantém um handle para um recurso nativo, i.e. um ficheiro.
//
FileStream fs = new FileStream("out.txt", FileMode.Create);
// Wait for user to hit <Enter>
Console.WriteLine("Wait for user to hit <Enter>");
Console.ReadLine();
PrintRunningGC(0);
Console.WriteLine("Wait for user to hit <Enter>");
Console.ReadLine();
}
}
| isel-leic-ave/ave-2015-16-sem1-i41n | aula34-gc/Finalization01.cs | C# | gpl-2.0 | 655 |
package jrpsoft;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Ellipse2D;
import java.util.Random;
public class Fantasma extends Actor {
protected static final int FANTASMA_SPEED = 1;
public boolean up, down, right, left;
static Boolean[] dir = new Boolean[4];
int avazarA = 0;
Random random;
public Fantasma(Point puntoIncio, Color colorPrincipal) {
super(puntoIncio, colorPrincipal);
random = new Random();
}
public Point getPoint() {
return p;
}
public void paint(Graphics2D g2) {
g2.setColor(color);
Point pixelPoint = Director.getPxOfCell(p);
Ellipse2D fantasma = new Ellipse2D.Float(pixelPoint.x, pixelPoint.y,
diametro, diametro);
g2.fill(fantasma);
g2.fill(new Ellipse2D.Float(pixelPoint.x - 1, pixelPoint.y + 12, diametro / 2, diametro / 2));
g2.fill(new Ellipse2D.Float(pixelPoint.x + 5, pixelPoint.y + 12, diametro / 2, diametro / 2));
g2.fill(new Ellipse2D.Float(pixelPoint.x + 11, pixelPoint.y + 12, diametro / 2, diametro / 2));
}
public void mover(Pacman pacman, Tablero tablero) {
/*
* System.out.println("ee "+(random.nextInt(5)));
* if(random.nextInt(5)==0){ avanzar((random.nextInt(4)+1),tablero); }
*/
// avazarA=movAleatorio(tablero);
//System.err.println(p);
// avazarA=0;
Astar.getAstar().getPath(p, pacman.p);
Point nextPoint=Astar.getAstar().getNextPoint();
avanzar(getDirToPoint(nextPoint), tablero);
}
/*@SuppressWarnings("unused")
private int movAleatorio(Tablero tablero) {
Point aux = (Point) p.clone();
int randDir = 0;
do {
aux = reverseTranslateDir(aux, randDir);
randDir = random.nextInt(4) + 1;
translateDir(aux, randDir);
// System.out.print("\nwhiling"+randDir+" px:"+aux.x+" py:"+aux.y);
} while (!tablero.isWalkable(aux));
return randDir;
}*/
private void avanzar(int dir, Tablero tablero) {
p=translateDir(p,dir);
/*Point anterior = (Point) p.clone();
translateDir(p, dir);
if (!tablero.isWalkable(p)) {
p = anterior;
}*/
}
public Point translateDir(Point p, int dir) {
switch (dir) {
case DUP:
p.y += UP;
break;
case DDOWN:
p.y += DOWN;
break;
case DLEFT:
p.x += LEFT;
break;
case DRIGHT:
p.x += RIGHT;
break;
default:
break;
}
return p;
}
/*
public Point reverseTranslateDir(Point p, int dir) {
switch (dir) {
case DUP:
p.y -= UP;
break;
case DDOWN:
p.y -= DOWN;
break;
case DLEFT:
p.x -= LEFT;
break;
case DRIGHT:
p.x -= RIGHT;
break;
default:
break;
}
return p;
}
*/
}
| jesusnoseq/JComococos | src/jrpsoft/Fantasma.java | Java | gpl-2.0 | 2,570 |
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the Graphics Dojo project on Qt Labs.
**
** This file may be used under the terms of the GNU General Public
** License version 2.0 or 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of
** this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
#include <QtGui>
#include <QtWidgets>
#include <QtNetwork>
#include <iostream>
// for the explanation of the trick, check out:
// http://www.virtualdub.org/blog/pivot/entry.php?id=116
// http://www.compuphase.com/graphic/scale3.htm
#define AVG(a,b) ( ((((a)^(b)) & 0xfefefefeUL) >> 1) + ((a)&(b)) )
QImage halfSized(const QImage &source)
{
QImage dest(source.size() * 0.5, QImage::Format_ARGB32_Premultiplied);
const quint32 *src = reinterpret_cast<const quint32*>(source.bits());
int sx = source.bytesPerLine() >> 2;
int sx2 = sx << 1;
quint32 *dst = reinterpret_cast<quint32*>(dest.bits());
int dx = dest.bytesPerLine() >> 2;
int ww = dest.width();
int hh = dest.height();
for (int y = hh; y; --y, dst += dx, src += sx2) {
const quint32 *p1 = src;
const quint32 *p2 = src + sx;
quint32 *q = dst;
for (int x = ww; x; --x, q++, p1 += 2, p2 += 2)
* q = AVG(AVG(p1[0], p1[1]), AVG(p2[0], p2[1]));
}
return dest;
}
class HalfScaler: public QWidget
{
Q_OBJECT
private:
int m_method;
QNetworkAccessManager m_manager;
QImage m_fastScaled;
QImage m_smoothScaled;
QImage m_optimizedScaled;
public:
HalfScaler(): QWidget(), m_method(0) {
setAcceptDrops(true);
connect(&m_manager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(handleNetworkData(QNetworkReply*)));
setWindowTitle("Drag and drop an image here!");
resize(512, 256);
}
void loadImage(const QImage &image) {
QImage img = image.convertToFormat(QImage::Format_ARGB32_Premultiplied);
if (img.isNull()) {
resize(512, 256);
setWindowTitle("Can't load the image. Please drag and drop an new image.");
} else {
// we crop the image so that the width and height are even
int ww = img.width() >> 1;
int hh = img.height() >> 1;
img = img.copy(0, 0, ww << 1, hh << 1);
m_fastScaled = img.scaled(ww, hh, Qt::IgnoreAspectRatio, Qt::FastTransformation);
m_smoothScaled = img.scaled(ww, hh, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
m_optimizedScaled = halfSized(img);
resize(20 + ww * 2 + 50, hh * 2 + 30 + 2 * 40);
}
update();
}
public slots:
void handleNetworkData(QNetworkReply *networkReply) {
m_fastScaled = QImage();
m_smoothScaled = QImage();
m_optimizedScaled = QImage();
QUrl url = networkReply->url();
if (networkReply->error()) {
setWindowTitle(QString("Can't download %1: %2").arg(url.toString()).arg(networkReply->errorString()));
} else {
QImage image;
image.load(networkReply, 0);
QString fileName = QFileInfo(url.path()).fileName();
setWindowTitle(QString("%1 - press a key to switch the scaling method").arg(fileName));
loadImage(image);
}
networkReply->deleteLater();
}
protected:
void dragEnterEvent(QDragEnterEvent *event) {
if (event->mimeData()->hasFormat("text/uri-list"))
event->acceptProposedAction();
}
void dropEvent(QDropEvent *event) {
QList<QUrl> urls = event->mimeData()->urls();
if (urls.count()) {
QUrl url = urls[0];
if (event->mimeData()->hasImage()) {
QImage img = qvariant_cast<QImage>(event->mimeData()->imageData());
QString fileName = QFileInfo(url.path()).fileName();
setWindowTitle(QString("%1 - press a key to switch the scaling method").arg(fileName));
loadImage(img);
} else {
m_manager.get(QNetworkRequest(url));
setWindowTitle(QString("Loading %1...").arg(url.toString()));
}
event->acceptProposedAction();
}
}
void keyPressEvent(QKeyEvent*) {
m_method = (m_method + 1) % 3;
update();
}
void paintEvent(QPaintEvent*) {
if (m_fastScaled.isNull())
return;
int w = m_fastScaled.width();
int h = m_optimizedScaled.height();
QPainter painter;
painter.begin(this);
// top left image: fast
painter.translate(10, 40);
painter.setPen(Qt::black);
painter.drawText(0, -40, w, 40, Qt::AlignCenter, "Qt::FastTransformation");
if (m_method == 0) {
painter.setPen(QPen(Qt::red, 2));
painter.drawRect(-2, -2, w + 4, h + 4);
painter.drawLine(w + 2, h + 2, w + 50 - 10, h + 50 - 10);
}
painter.drawImage(0, 0, m_fastScaled);
// top right image: smooth
painter.translate(w + 50, 0);
painter.setPen(Qt::black);
painter.drawText(0, -40, w, 40, Qt::AlignCenter, "Qt::SmoothTransformation");
if (m_method == 1) {
painter.setPen(QPen(Qt::red, 2));
painter.drawRect(-2, -2, w + 4, h + 4);
painter.drawLine(w / 2, h + 2, w / 2, h + 50 - 10);
}
painter.drawImage(0, 0, m_smoothScaled);
// bottom left image: optimized
painter.translate(-w - 50, h + 50);
painter.setPen(Qt::black);
painter.drawText(0, -40, w, 40, Qt::AlignCenter, "Optimized");
if (m_method == 2) {
painter.setPen(QPen(Qt::red, 2));
painter.drawRect(-2, -2, w + 4, h + 4);
painter.drawLine(w + 2, h / 2, w + 50 - 10, h / 2);
}
painter.drawImage(0, 0, m_optimizedScaled);
// bottom right image: chosen by the user
QImage img = (m_method == 0) ? m_fastScaled : (m_method == 1) ? m_smoothScaled : m_optimizedScaled;
painter.translate(w + 50, 0);
painter.drawImage(0, 0, img);
painter.end();
}
};
#include "halfscale.moc"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
HalfScaler widget;
widget.show();
return app.exec();
}
| anak10thn/graphics-dojo-qt5 | halfscale/halfscale.cpp | C++ | gpl-2.0 | 7,095 |
<?php
defined('_JEXEC') or die();
/**
*
* Description
*
* @package VirtueMart
* @subpackage Calculation tool
* @author Max Milbers
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* @version $Id: default.php 6475 2012-09-21 11:54:21Z Milbo $
*/
// Check to ensure this file is included in Joomla!
?>
<form action="index.php" method="post" name="adminForm" id="adminForm">
<?php AdminUIHelper::startAdminArea(); ?>
<div id="filter-bar" class="btn-toolbar">
<?php echo $this->displayDefaultViewSearch() ?>
</div>
<div class="clearfix"> </div>
<div id="results">
<?php
// split to use ajax search
echo $this->loadTemplate('results'); ?>
</div>
<?php AdminUIHelper::endAdminArea(true); ?>
</form>
| cuongnd/test_pro | administrator/components/com_virtuemart1/views/calc/tmpl/default.php | PHP | gpl-2.0 | 1,115 |
#!/usr/bin/env python
"""
Grid time
=============
"""
from datetime import timedelta
import numpy as np
from opendrift.readers import reader_global_landmask
from opendrift.readers import reader_netCDF_CF_generic
from opendrift.models.oceandrift import OceanDrift
# Seeding at a grid at regular interval
o = OceanDrift(loglevel=20) # Set loglevel to 0 for debug information
reader_norkyst = reader_netCDF_CF_generic.Reader(o.test_data_folder() +
'16Nov2015_NorKyst_z_surface/norkyst800_subset_16Nov2015.nc')
#%%
# Landmask
reader_landmask = reader_global_landmask.Reader(
extent=[4.0, 5.5, 59.9, 61.2])
o.add_reader([reader_landmask, reader_norkyst])
#%%
# Seeding some particles
lons = np.linspace(4.4, 4.6, 10)
lats = np.linspace(60.0, 60.1, 10)
lons, lats = np.meshgrid(lons, lats)
lons = lons.ravel()
lats = lats.ravel()
#%%
# Seed oil elements on a grid at regular time interval
start_time = reader_norkyst.start_time
time_step = timedelta(hours=6)
num_steps = 10
for i in range(num_steps+1):
o.seed_elements(lons, lats, radius=0, number=100,
time=start_time + i*time_step)
#%%
# Running model for 60 hours
o.run(steps=60*4, time_step=900, time_step_output=3600)
#%%
# Print and plot results
print(o)
o.animation(fast=True)
#%%
# .. image:: /gallery/animations/example_grid_time_0.gif
| OpenDrift/opendrift | examples/example_grid_time.py | Python | gpl-2.0 | 1,348 |
//
// C++ Implementation: Audio::OggStream
//
#include "config.h"
#ifdef HAVE_OGG
#include "OggStream.h"
#include "OggData.h"
#include "config.h"
#include <utility>
#include <limits>
#include <stdlib.h>
#include <vorbis/vorbisfile.h>
#include "vsfilesystem.h"
#ifndef OGG_BUFFER_SIZE
#define OGG_BUFFER_SIZE 4096*2*2
#endif
namespace Audio {
OggStream::OggStream(const std::string& path, VSFileSystem::VSFileType type) throw(Exception)
: Stream(path)
{
if ( file.OpenReadOnly(path, type) <= VSFileSystem::Ok )
throw FileOpenException("Error opening file \"" + path + "\"");
oggData = new __impl::OggData(file, getFormatInternal(), 0);
// Cache duration in case ov_time_total gets expensive
duration = ov_time_total( &oggData->vorbisFile, oggData->streamIndex );
// Allocate read buffer
readBufferSize = OGG_BUFFER_SIZE;
readBufferAvail = 0;
readBuffer = malloc(readBufferSize);
}
OggStream::~OggStream()
{
// destructor closes the file already
delete oggData;
}
double OggStream::getLengthImpl() const throw(Exception)
{
return duration;
}
double OggStream::getPositionImpl() const throw()
{
return ov_time_tell( &oggData->vorbisFile );
}
void OggStream::seekImpl(double position) throw(Exception)
{
if (position >= duration)
throw EndOfStreamException();
readBufferAvail = 0;
switch (ov_time_seek(&oggData->vorbisFile, position)) {
case 0: break;
case OV_ENOSEEK: throw Exception("Stream not seekable");
case OV_EINVAL: throw Exception("Invalid argument or state");
case OV_EREAD: throw Exception("Read error");
case OV_EFAULT: throw Exception("Internal logic fault, bug or heap/stack corruption");
case OV_EBADLINK:throw CorruptStreamException(false);
default: throw Exception("Unidentified error code");
}
}
void OggStream::getBufferImpl(void *&buffer, unsigned int &bufferSize) throw(Exception)
{
if (readBufferAvail == 0)
throw NoBufferException();
buffer = readBuffer;
bufferSize = readBufferAvail;
}
void OggStream::nextBufferImpl() throw(Exception)
{
int curStream = oggData->streamIndex;
long ovr;
switch( ovr = ov_read(&oggData->vorbisFile,
(char*)readBuffer, readBufferSize,
0, 2, 1, &curStream) )
{
case OV_HOLE: throw CorruptStreamException(false);
case OV_EBADLINK: throw CorruptStreamException(false);
case 0: throw EndOfStreamException();
default: readBufferSize = ovr;
}
}
};
#endif // HAVE_OGG
| vinni-au/vega-strike | vegastrike/src/audio/codecs/OggStream.cpp | C++ | gpl-2.0 | 2,896 |
angular.module('component').component('getGit', {
template: `
<section>
<h1>GIT : Repro</h1>
<div class="controller" >
<div git-repro="user : 'gaetanV',repositories :'angular_directive',branch:'master',path:'angular1/directive/gitRepro.directive.js'" > </div>
</div>
</section>
`,
});
| gaetanV/angular_directive | angularJs/app/component/getgit.component.ts | TypeScript | gpl-2.0 | 362 |
//
// begin license header
//
// This file is part of Pixy CMUcam5 or "Pixy" for short
//
// All Pixy source code is provided under the terms of the
// GNU General Public License v2 (http://www.gnu.org/licenses/gpl-2.0.html).
// Those wishing to use Pixy source code, software and/or
// technologies under different licensing terms should contact us at
// cmucam@cs.cmu.edu. Such licensing terms are available for
// all portions of the Pixy codebase presented here.
//
// end license header
//
#include <math.h>
#include "pixy_init.h"
#include "misc.h"
#include "power.h"
static const ProcModule g_module[] =
{
{
"pwr_getVin",
(ProcPtr)pwr_getVin,
{END},
"Get Vin (JP1) voltage"
"@r voltage in millivolts"
},
{
"pwr_get5V",
(ProcPtr)pwr_get5v,
{END},
"Get 5V voltage"
"@r voltage in millivolts"
},
{
"pwr_getVbus",
(ProcPtr)pwr_getVbus,
{END},
"Get USB VBUS voltage"
"@r voltage in millivolts"
},
{
"pwr_USBpowered",
(ProcPtr)pwr_USBpowered,
{END},
"Determine if camera power is from USB host."
"@r 0 if power is from Vin (JP1), nonzero if power is from USB"
},
END
};
uint32_t pwr_getVin()
{
uint32_t vin;
vin = adc_get(VIN_ADCCHAN)*10560/1024 + 330; // 10560 = 3.3*3.2*1000, 330 is diode drop
return vin;
}
uint32_t pwr_get5v()
{
uint32_t v5;
v5 = adc_get(V5_ADCCHAN)*5293/1024; // 5293=3.3*1.604*1000
return v5;
}
uint32_t pwr_getVbus()
{
uint32_t vbus;
vbus = adc_get(VBUS_ADCCHAN)*5293/1024; // 5293=3.3*1.604*1000
return vbus;
}
uint32_t pwr_USBpowered()
{
if (LPC_GPIO_PORT->PIN[5]&0x0100)
return 1;
else
return 0;
}
void pwr_init()
{
LPC_GPIO_PORT->DIR[5] |= 0x0100;
// choose USB power or vin
if (pwr_getVin()>6430) // 6430=5000+1100(ldo)+330(diode)
LPC_GPIO_PORT->PIN[5] &= ~0x0100;
else // switch usb on
LPC_GPIO_PORT->PIN[5] |= 0x0100;
#if 0 // Undergrad robotics mod, no need for usb shit fuck my ass nigga please
g_chirpUsb->registerModule(g_module);
#endif
}
| Pravuz/AimBot | Pixy/gcc/pixy_m4/src/power.cpp | C++ | gpl-2.0 | 1,975 |
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("CryptoMethods")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HP")]
[assembly: AssemblyProduct("CryptoMethods")]
[assembly: AssemblyCopyright("Copyright © HP 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("6eb617c1-11a2-4074-91bc-b4687444cebf")]
// 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")]
| tmpope/Cryptography | CryptoMethods/CryptoMethods/Properties/AssemblyInfo.cs | C# | gpl-2.0 | 1,406 |
/*
* Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @summary Spliterator traversing and splitting tests
* @library ../stream/bootlib
* @build java.base/java.util.SpliteratorOfIntDataBuilder
* java.base/java.util.SpliteratorTestHelper
* @run testng SpliteratorTraversingAndSplittingTest
* @bug 8020016 8071477 8072784 8169838
*/
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.nio.CharBuffer;
import java.util.AbstractCollection;
import java.util.AbstractList;
import java.util.AbstractSet;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.RandomAccess;
import java.util.Set;
import java.util.SortedSet;
import java.util.Spliterator;
import java.util.SpliteratorOfIntDataBuilder;
import java.util.SpliteratorTestHelper;
import java.util.Spliterators;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.WeakHashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import java.util.function.Function;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
public class SpliteratorTraversingAndSplittingTest extends SpliteratorTestHelper {
private static final List<Integer> SIZES = Arrays.asList(0, 1, 10, 42);
private static final String LOW = new String(new char[] {Character.MIN_LOW_SURROGATE});
private static final String HIGH = new String(new char[] {Character.MIN_HIGH_SURROGATE});
private static final String HIGH_LOW = HIGH + LOW;
private static final String CHAR_HIGH_LOW = "A" + HIGH_LOW;
private static final String HIGH_LOW_CHAR = HIGH_LOW + "A";
private static final String CHAR_HIGH_LOW_CHAR = "A" + HIGH_LOW + "A";
private static final List<String> STRINGS = generateTestStrings();
private static List<String> generateTestStrings() {
List<String> strings = new ArrayList<>();
for (int n : Arrays.asList(1, 2, 3, 16, 17)) {
strings.add(generate("A", n));
strings.add(generate(LOW, n));
strings.add(generate(HIGH, n));
strings.add(generate(HIGH_LOW, n));
strings.add(generate(CHAR_HIGH_LOW, n));
strings.add(generate(HIGH_LOW_CHAR, n));
strings.add(generate(CHAR_HIGH_LOW_CHAR, n));
}
return strings;
}
private static String generate(String s, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(s);
}
return sb.toString();
}
private static class SpliteratorDataBuilder<T> {
List<Object[]> data;
List<T> exp;
Map<T, T> mExp;
SpliteratorDataBuilder(List<Object[]> data, List<T> exp) {
this.data = data;
this.exp = exp;
this.mExp = createMap(exp);
}
Map<T, T> createMap(List<T> l) {
Map<T, T> m = new LinkedHashMap<>();
for (T t : l) {
m.put(t, t);
}
return m;
}
void add(String description, Collection<?> expected, Supplier<Spliterator<?>> s) {
description = joiner(description).toString();
data.add(new Object[]{description, expected, s});
}
void add(String description, Supplier<Spliterator<?>> s) {
add(description, exp, s);
}
void addCollection(Function<Collection<T>, ? extends Collection<T>> c) {
add("new " + c.apply(Collections.<T>emptyList()).getClass().getName() + ".spliterator()",
() -> c.apply(exp).spliterator());
}
void addList(Function<Collection<T>, ? extends List<T>> l) {
addCollection(l);
addCollection(l.andThen(list -> list.subList(0, list.size())));
}
void addMap(Function<Map<T, T>, ? extends Map<T, T>> m) {
String description = "new " + m.apply(Collections.<T, T>emptyMap()).getClass().getName();
addMap(m, description);
}
void addMap(Function<Map<T, T>, ? extends Map<T, T>> m, String description) {
add(description + ".keySet().spliterator()", () -> m.apply(mExp).keySet().spliterator());
add(description + ".values().spliterator()", () -> m.apply(mExp).values().spliterator());
add(description + ".entrySet().spliterator()", mExp.entrySet(), () -> m.apply(mExp).entrySet().spliterator());
}
StringBuilder joiner(String description) {
return new StringBuilder(description).
append(" {").
append("size=").append(exp.size()).
append("}");
}
}
static Object[][] spliteratorDataProvider;
@DataProvider(name = "Spliterator<Integer>")
public static Object[][] spliteratorDataProvider() {
if (spliteratorDataProvider != null) {
return spliteratorDataProvider;
}
List<Object[]> data = new ArrayList<>();
for (int size : SIZES) {
List<Integer> exp = listIntRange(size);
SpliteratorDataBuilder<Integer> db = new SpliteratorDataBuilder<>(data, exp);
// Direct spliterator methods
db.add("Spliterators.spliterator(Collection, ...)",
() -> Spliterators.spliterator(exp, 0));
db.add("Spliterators.spliterator(Iterator, ...)",
() -> Spliterators.spliterator(exp.iterator(), exp.size(), 0));
db.add("Spliterators.spliteratorUnknownSize(Iterator, ...)",
() -> Spliterators.spliteratorUnknownSize(exp.iterator(), 0));
db.add("Spliterators.spliterator(Spliterators.iteratorFromSpliterator(Spliterator ), ...)",
() -> Spliterators.spliterator(Spliterators.iterator(exp.spliterator()), exp.size(), 0));
db.add("Spliterators.spliterator(T[], ...)",
() -> Spliterators.spliterator(exp.toArray(new Integer[0]), 0));
db.add("Arrays.spliterator(T[], ...)",
() -> Arrays.spliterator(exp.toArray(new Integer[0])));
class SpliteratorFromIterator extends Spliterators.AbstractSpliterator<Integer> {
Iterator<Integer> it;
SpliteratorFromIterator(Iterator<Integer> it, long est) {
super(est, Spliterator.SIZED);
this.it = it;
}
@Override
public boolean tryAdvance(Consumer<? super Integer> action) {
if (action == null)
throw new NullPointerException();
if (it.hasNext()) {
action.accept(it.next());
return true;
}
else {
return false;
}
}
}
db.add("new Spliterators.AbstractSpliterator()",
() -> new SpliteratorFromIterator(exp.iterator(), exp.size()));
// Collections
// default method implementations
class AbstractCollectionImpl extends AbstractCollection<Integer> {
Collection<Integer> c;
AbstractCollectionImpl(Collection<Integer> c) {
this.c = c;
}
@Override
public Iterator<Integer> iterator() {
return c.iterator();
}
@Override
public int size() {
return c.size();
}
}
db.addCollection(
c -> new AbstractCollectionImpl(c));
class AbstractListImpl extends AbstractList<Integer> {
List<Integer> l;
AbstractListImpl(Collection<Integer> c) {
this.l = new ArrayList<>(c);
}
@Override
public Integer get(int index) {
return l.get(index);
}
@Override
public int size() {
return l.size();
}
}
db.addCollection(
c -> new AbstractListImpl(c));
class AbstractSetImpl extends AbstractSet<Integer> {
Set<Integer> s;
AbstractSetImpl(Collection<Integer> c) {
this.s = new HashSet<>(c);
}
@Override
public Iterator<Integer> iterator() {
return s.iterator();
}
@Override
public int size() {
return s.size();
}
}
db.addCollection(
c -> new AbstractSetImpl(c));
class AbstractSortedSetImpl extends AbstractSet<Integer> implements SortedSet<Integer> {
SortedSet<Integer> s;
AbstractSortedSetImpl(Collection<Integer> c) {
this.s = new TreeSet<>(c);
}
@Override
public Iterator<Integer> iterator() {
return s.iterator();
}
@Override
public int size() {
return s.size();
}
@Override
public Comparator<? super Integer> comparator() {
return s.comparator();
}
@Override
public SortedSet<Integer> subSet(Integer fromElement, Integer toElement) {
return s.subSet(fromElement, toElement);
}
@Override
public SortedSet<Integer> headSet(Integer toElement) {
return s.headSet(toElement);
}
@Override
public SortedSet<Integer> tailSet(Integer fromElement) {
return s.tailSet(fromElement);
}
@Override
public Integer first() {
return s.first();
}
@Override
public Integer last() {
return s.last();
}
@Override
public Spliterator<Integer> spliterator() {
return SortedSet.super.spliterator();
}
}
db.addCollection(
c -> new AbstractSortedSetImpl(c));
class IterableWrapper implements Iterable<Integer> {
final Iterable<Integer> it;
IterableWrapper(Iterable<Integer> it) {
this.it = it;
}
@Override
public Iterator<Integer> iterator() {
return it.iterator();
}
}
db.add("new Iterable.spliterator()",
() -> new IterableWrapper(exp).spliterator());
//
db.add("Arrays.asList().spliterator()",
() -> Spliterators.spliterator(Arrays.asList(exp.toArray(new Integer[0])), 0));
db.addList(ArrayList::new);
db.addList(LinkedList::new);
db.addList(Vector::new);
class AbstractRandomAccessListImpl extends AbstractList<Integer> implements RandomAccess {
Integer[] ia;
AbstractRandomAccessListImpl(Collection<Integer> c) {
this.ia = c.toArray(new Integer[c.size()]);
}
@Override
public Integer get(int index) {
return ia[index];
}
@Override
public int size() {
return ia.length;
}
}
db.addList(AbstractRandomAccessListImpl::new);
class RandomAccessListImpl implements List<Integer>, RandomAccess {
Integer[] ia;
List<Integer> l;
RandomAccessListImpl(Collection<Integer> c) {
this.ia = c.toArray(new Integer[c.size()]);
this.l = Arrays.asList(ia);
}
@Override
public Integer get(int index) {
return ia[index];
}
@Override
public Integer set(int index, Integer element) {
throw new UnsupportedOperationException();
}
@Override
public void add(int index, Integer element) {
throw new UnsupportedOperationException();
}
@Override
public Integer remove(int index) {
throw new UnsupportedOperationException();
}
@Override
public int indexOf(Object o) {
return l.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return Arrays.asList(ia).lastIndexOf(o);
}
@Override
public ListIterator<Integer> listIterator() {
return l.listIterator();
}
@Override
public ListIterator<Integer> listIterator(int index) {
return l.listIterator(index);
}
@Override
public List<Integer> subList(int fromIndex, int toIndex) {
return l.subList(fromIndex, toIndex);
}
@Override
public int size() {
return ia.length;
}
@Override
public boolean isEmpty() {
return size() != 0;
}
@Override
public boolean contains(Object o) {
return l.contains(o);
}
@Override
public Iterator<Integer> iterator() {
return l.iterator();
}
@Override
public Object[] toArray() {
return l.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return l.toArray(a);
}
@Override
public boolean add(Integer integer) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> c) {
return l.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends Integer> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(int index, Collection<? extends Integer> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
}
db.addList(RandomAccessListImpl::new);
db.addCollection(HashSet::new);
db.addCollection(LinkedHashSet::new);
db.addCollection(TreeSet::new);
db.addCollection(c -> { Stack<Integer> s = new Stack<>(); s.addAll(c); return s;});
db.addCollection(PriorityQueue::new);
db.addCollection(ArrayDeque::new);
db.addCollection(ConcurrentSkipListSet::new);
if (size > 0) {
db.addCollection(c -> {
ArrayBlockingQueue<Integer> abq = new ArrayBlockingQueue<>(size);
abq.addAll(c);
return abq;
});
}
db.addCollection(PriorityBlockingQueue::new);
db.addCollection(LinkedBlockingQueue::new);
db.addCollection(LinkedTransferQueue::new);
db.addCollection(ConcurrentLinkedQueue::new);
db.addCollection(LinkedBlockingDeque::new);
db.addCollection(CopyOnWriteArrayList::new);
db.addCollection(CopyOnWriteArraySet::new);
if (size == 0) {
db.addCollection(c -> Collections.<Integer>emptySet());
db.addList(c -> Collections.<Integer>emptyList());
}
else if (size == 1) {
db.addCollection(c -> Collections.singleton(exp.get(0)));
db.addCollection(c -> Collections.singletonList(exp.get(0)));
}
{
Integer[] ai = new Integer[size];
Arrays.fill(ai, 1);
db.add(String.format("Collections.nCopies(%d, 1)", exp.size()),
Arrays.asList(ai),
() -> Collections.nCopies(exp.size(), 1).spliterator());
}
// Collections.synchronized/unmodifiable/checked wrappers
db.addCollection(Collections::unmodifiableCollection);
db.addCollection(c -> Collections.unmodifiableSet(new HashSet<>(c)));
db.addCollection(c -> Collections.unmodifiableSortedSet(new TreeSet<>(c)));
db.addList(c -> Collections.unmodifiableList(new ArrayList<>(c)));
db.addMap(Collections::unmodifiableMap);
db.addMap(m -> Collections.unmodifiableSortedMap(new TreeMap<>(m)));
db.addCollection(Collections::synchronizedCollection);
db.addCollection(c -> Collections.synchronizedSet(new HashSet<>(c)));
db.addCollection(c -> Collections.synchronizedSortedSet(new TreeSet<>(c)));
db.addList(c -> Collections.synchronizedList(new ArrayList<>(c)));
db.addMap(Collections::synchronizedMap);
db.addMap(m -> Collections.synchronizedSortedMap(new TreeMap<>(m)));
db.addCollection(c -> Collections.checkedCollection(c, Integer.class));
db.addCollection(c -> Collections.checkedQueue(new ArrayDeque<>(c), Integer.class));
db.addCollection(c -> Collections.checkedSet(new HashSet<>(c), Integer.class));
db.addCollection(c -> Collections.checkedSortedSet(new TreeSet<>(c), Integer.class));
db.addList(c -> Collections.checkedList(new ArrayList<>(c), Integer.class));
db.addMap(c -> Collections.checkedMap(c, Integer.class, Integer.class));
db.addMap(m -> Collections.checkedSortedMap(new TreeMap<>(m), Integer.class, Integer.class));
// Maps
db.addMap(HashMap::new);
db.addMap(m -> {
// Create a Map ensuring that for large sizes
// buckets will contain 2 or more entries
HashMap<Integer, Integer> cm = new HashMap<>(1, m.size() + 1);
// Don't use putAll which inflates the table by
// m.size() * loadFactor, thus creating a very sparse
// map for 1000 entries defeating the purpose of this test,
// in addition it will cause the split until null test to fail
// because the number of valid splits is larger than the
// threshold
for (Map.Entry<Integer, Integer> e : m.entrySet())
cm.put(e.getKey(), e.getValue());
return cm;
}, "new java.util.HashMap(1, size + 1)");
db.addMap(LinkedHashMap::new);
db.addMap(IdentityHashMap::new);
db.addMap(WeakHashMap::new);
db.addMap(m -> {
// Create a Map ensuring that for large sizes
// buckets will be consist of 2 or more entries
WeakHashMap<Integer, Integer> cm = new WeakHashMap<>(1, m.size() + 1);
for (Map.Entry<Integer, Integer> e : m.entrySet())
cm.put(e.getKey(), e.getValue());
return cm;
}, "new java.util.WeakHashMap(1, size + 1)");
// @@@ Descending maps etc
db.addMap(TreeMap::new);
db.addMap(ConcurrentHashMap::new);
db.addMap(ConcurrentSkipListMap::new);
if (size == 0) {
db.addMap(m -> Collections.<Integer, Integer>emptyMap());
}
else if (size == 1) {
db.addMap(m -> Collections.singletonMap(exp.get(0), exp.get(0)));
}
}
return spliteratorDataProvider = data.toArray(new Object[0][]);
}
private static List<Integer> listIntRange(int upTo) {
List<Integer> exp = new ArrayList<>();
for (int i = 0; i < upTo; i++)
exp.add(i);
return Collections.unmodifiableList(exp);
}
@Test(dataProvider = "Spliterator<Integer>")
public void testNullPointerException(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining(null));
executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance(null));
}
@Test(dataProvider = "Spliterator<Integer>")
public void testForEach(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testForEach(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testTryAdvance(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testTryAdvance(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testMixedTryAdvanceForEach(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testMixedTryAdvanceForEach(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testMixedTraverseAndSplit(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testMixedTraverseAndSplit(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testSplitAfterFullTraversal(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testSplitAfterFullTraversal(s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testSplitOnce(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testSplitOnce(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testSplitSixDeep(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testSplitSixDeep(exp, s, UnaryOperator.identity());
}
@Test(dataProvider = "Spliterator<Integer>")
public void testSplitUntilNull(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
testSplitUntilNull(exp, s, UnaryOperator.identity());
}
//
private static class SpliteratorOfIntCharDataBuilder {
List<Object[]> data;
String s;
List<Integer> expChars;
List<Integer> expCodePoints;
SpliteratorOfIntCharDataBuilder(List<Object[]> data, String s) {
this.data = data;
this.s = s;
this.expChars = transform(s, false);
this.expCodePoints = transform(s, true);
}
static List<Integer> transform(String s, boolean toCodePoints) {
List<Integer> l = new ArrayList<>();
if (!toCodePoints) {
for (int i = 0; i < s.length(); i++) {
l.add((int) s.charAt(i));
}
}
else {
for (int i = 0; i < s.length();) {
char c1 = s.charAt(i++);
int cp = c1;
if (Character.isHighSurrogate(c1) && i < s.length()) {
char c2 = s.charAt(i);
if (Character.isLowSurrogate(c2)) {
i++;
cp = Character.toCodePoint(c1, c2);
}
}
l.add(cp);
}
}
return l;
}
void add(String description, Function<String, CharSequence> f) {
description = description.replace("%s", s);
{
Supplier<Spliterator.OfInt> supplier = () -> f.apply(s).chars().spliterator();
data.add(new Object[]{description + ".chars().spliterator()", expChars, supplier});
}
{
Supplier<Spliterator.OfInt> supplier = () -> f.apply(s).codePoints().spliterator();
data.add(new Object[]{description + ".codePoints().spliterator()", expCodePoints, supplier});
}
}
}
static Object[][] spliteratorOfIntDataProvider;
@DataProvider(name = "Spliterator.OfInt")
public static Object[][] spliteratorOfIntDataProvider() {
if (spliteratorOfIntDataProvider != null) {
return spliteratorOfIntDataProvider;
}
List<Object[]> data = new ArrayList<>();
for (int size : SIZES) {
int exp[] = arrayIntRange(size);
SpliteratorOfIntDataBuilder db = new SpliteratorOfIntDataBuilder(data, listIntRange(size));
db.add("Spliterators.spliterator(int[], ...)",
() -> Spliterators.spliterator(exp, 0));
db.add("Arrays.spliterator(int[], ...)",
() -> Arrays.spliterator(exp));
db.add("Spliterators.spliterator(PrimitiveIterator.OfInt, ...)",
() -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0));
db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfInt, ...)",
() -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0));
class IntSpliteratorFromArray extends Spliterators.AbstractIntSpliterator {
int[] a;
int index = 0;
IntSpliteratorFromArray(int[] a) {
super(a.length, Spliterator.SIZED);
this.a = a;
}
@Override
public boolean tryAdvance(IntConsumer action) {
if (action == null)
throw new NullPointerException();
if (index < a.length) {
action.accept(a[index++]);
return true;
}
else {
return false;
}
}
}
db.add("new Spliterators.AbstractIntAdvancingSpliterator()",
() -> new IntSpliteratorFromArray(exp));
}
// Class for testing default methods
class CharSequenceImpl implements CharSequence {
final String s;
public CharSequenceImpl(String s) {
this.s = s;
}
@Override
public int length() {
return s.length();
}
@Override
public char charAt(int index) {
return s.charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return s.subSequence(start, end);
}
@Override
public String toString() {
return s;
}
}
for (String string : STRINGS) {
SpliteratorOfIntCharDataBuilder cdb = new SpliteratorOfIntCharDataBuilder(data, string);
cdb.add("\"%s\"", s -> s);
cdb.add("new CharSequenceImpl(\"%s\")", CharSequenceImpl::new);
cdb.add("new StringBuilder(\"%s\")", StringBuilder::new);
cdb.add("new StringBuffer(\"%s\")", StringBuffer::new);
cdb.add("CharBuffer.wrap(\"%s\".toCharArray())", s -> CharBuffer.wrap(s.toCharArray()));
}
return spliteratorOfIntDataProvider = data.toArray(new Object[0][]);
}
private static int[] arrayIntRange(int upTo) {
int[] exp = new int[upTo];
for (int i = 0; i < upTo; i++)
exp[i] = i;
return exp;
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntNullPointerException(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((IntConsumer) null));
executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((IntConsumer) null));
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntForEach(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testForEach(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntTryAdvance(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testTryAdvance(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntMixedTryAdvanceForEach(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testMixedTryAdvanceForEach(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntMixedTraverseAndSplit(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testMixedTraverseAndSplit(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntSplitAfterFullTraversal(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitAfterFullTraversal(s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntSplitOnce(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitOnce(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntSplitSixDeep(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitSixDeep(exp, s, intBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfInt")
public void testIntSplitUntilNull(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
testSplitUntilNull(exp, s, intBoxingConsumer());
}
//
private static class SpliteratorOfLongDataBuilder {
List<Object[]> data;
List<Long> exp;
SpliteratorOfLongDataBuilder(List<Object[]> data, List<Long> exp) {
this.data = data;
this.exp = exp;
}
void add(String description, List<Long> expected, Supplier<Spliterator.OfLong> s) {
description = joiner(description).toString();
data.add(new Object[]{description, expected, s});
}
void add(String description, Supplier<Spliterator.OfLong> s) {
add(description, exp, s);
}
StringBuilder joiner(String description) {
return new StringBuilder(description).
append(" {").
append("size=").append(exp.size()).
append("}");
}
}
static Object[][] spliteratorOfLongDataProvider;
@DataProvider(name = "Spliterator.OfLong")
public static Object[][] spliteratorOfLongDataProvider() {
if (spliteratorOfLongDataProvider != null) {
return spliteratorOfLongDataProvider;
}
List<Object[]> data = new ArrayList<>();
for (int size : SIZES) {
long exp[] = arrayLongRange(size);
SpliteratorOfLongDataBuilder db = new SpliteratorOfLongDataBuilder(data, listLongRange(size));
db.add("Spliterators.spliterator(long[], ...)",
() -> Spliterators.spliterator(exp, 0));
db.add("Arrays.spliterator(long[], ...)",
() -> Arrays.spliterator(exp));
db.add("Spliterators.spliterator(PrimitiveIterator.OfLong, ...)",
() -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0));
db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfLong, ...)",
() -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0));
class LongSpliteratorFromArray extends Spliterators.AbstractLongSpliterator {
long[] a;
int index = 0;
LongSpliteratorFromArray(long[] a) {
super(a.length, Spliterator.SIZED);
this.a = a;
}
@Override
public boolean tryAdvance(LongConsumer action) {
if (action == null)
throw new NullPointerException();
if (index < a.length) {
action.accept(a[index++]);
return true;
}
else {
return false;
}
}
}
db.add("new Spliterators.AbstractLongAdvancingSpliterator()",
() -> new LongSpliteratorFromArray(exp));
}
return spliteratorOfLongDataProvider = data.toArray(new Object[0][]);
}
private static List<Long> listLongRange(int upTo) {
List<Long> exp = new ArrayList<>();
for (long i = 0; i < upTo; i++)
exp.add(i);
return Collections.unmodifiableList(exp);
}
private static long[] arrayLongRange(int upTo) {
long[] exp = new long[upTo];
for (int i = 0; i < upTo; i++)
exp[i] = i;
return exp;
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongNullPointerException(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((LongConsumer) null));
executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((LongConsumer) null));
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongForEach(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testForEach(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongTryAdvance(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testTryAdvance(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongMixedTryAdvanceForEach(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testMixedTryAdvanceForEach(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongMixedTraverseAndSplit(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testMixedTraverseAndSplit(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongSplitAfterFullTraversal(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testSplitAfterFullTraversal(s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongSplitOnce(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testSplitOnce(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongSplitSixDeep(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testSplitSixDeep(exp, s, longBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfLong")
public void testLongSplitUntilNull(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
testSplitUntilNull(exp, s, longBoxingConsumer());
}
//
private static class SpliteratorOfDoubleDataBuilder {
List<Object[]> data;
List<Double> exp;
SpliteratorOfDoubleDataBuilder(List<Object[]> data, List<Double> exp) {
this.data = data;
this.exp = exp;
}
void add(String description, List<Double> expected, Supplier<Spliterator.OfDouble> s) {
description = joiner(description).toString();
data.add(new Object[]{description, expected, s});
}
void add(String description, Supplier<Spliterator.OfDouble> s) {
add(description, exp, s);
}
StringBuilder joiner(String description) {
return new StringBuilder(description).
append(" {").
append("size=").append(exp.size()).
append("}");
}
}
static Object[][] spliteratorOfDoubleDataProvider;
@DataProvider(name = "Spliterator.OfDouble")
public static Object[][] spliteratorOfDoubleDataProvider() {
if (spliteratorOfDoubleDataProvider != null) {
return spliteratorOfDoubleDataProvider;
}
List<Object[]> data = new ArrayList<>();
for (int size : SIZES) {
double exp[] = arrayDoubleRange(size);
SpliteratorOfDoubleDataBuilder db = new SpliteratorOfDoubleDataBuilder(data, listDoubleRange(size));
db.add("Spliterators.spliterator(double[], ...)",
() -> Spliterators.spliterator(exp, 0));
db.add("Arrays.spliterator(double[], ...)",
() -> Arrays.spliterator(exp));
db.add("Spliterators.spliterator(PrimitiveIterator.OfDouble, ...)",
() -> Spliterators.spliterator(Spliterators.iterator(Arrays.spliterator(exp)), exp.length, 0));
db.add("Spliterators.spliteratorUnknownSize(PrimitiveIterator.OfDouble, ...)",
() -> Spliterators.spliteratorUnknownSize(Spliterators.iterator(Arrays.spliterator(exp)), 0));
class DoubleSpliteratorFromArray extends Spliterators.AbstractDoubleSpliterator {
double[] a;
int index = 0;
DoubleSpliteratorFromArray(double[] a) {
super(a.length, Spliterator.SIZED);
this.a = a;
}
@Override
public boolean tryAdvance(DoubleConsumer action) {
if (action == null)
throw new NullPointerException();
if (index < a.length) {
action.accept(a[index++]);
return true;
}
else {
return false;
}
}
}
db.add("new Spliterators.AbstractDoubleAdvancingSpliterator()",
() -> new DoubleSpliteratorFromArray(exp));
}
return spliteratorOfDoubleDataProvider = data.toArray(new Object[0][]);
}
private static List<Double> listDoubleRange(int upTo) {
List<Double> exp = new ArrayList<>();
for (double i = 0; i < upTo; i++)
exp.add(i);
return Collections.unmodifiableList(exp);
}
private static double[] arrayDoubleRange(int upTo) {
double[] exp = new double[upTo];
for (int i = 0; i < upTo; i++)
exp[i] = i;
return exp;
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleNullPointerException(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((DoubleConsumer) null));
executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance((DoubleConsumer) null));
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleForEach(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testForEach(exp, s, doubleBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleTryAdvance(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testTryAdvance(exp, s, doubleBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleMixedTryAdvanceForEach(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testMixedTryAdvanceForEach(exp, s, doubleBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleMixedTraverseAndSplit(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testMixedTraverseAndSplit(exp, s, doubleBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleSplitAfterFullTraversal(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testSplitAfterFullTraversal(s, doubleBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleSplitOnce(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testSplitOnce(exp, s, doubleBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleSplitSixDeep(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testSplitSixDeep(exp, s, doubleBoxingConsumer());
}
@Test(dataProvider = "Spliterator.OfDouble")
public void testDoubleSplitUntilNull(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
testSplitUntilNull(exp, s, doubleBoxingConsumer());
}
}
| dmlloyd/openjdk-modules | jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java | Java | gpl-2.0 | 44,814 |
/*
* The ManaPlus Client
* Copyright (C) 2004-2009 The Mana World Development Team
* Copyright (C) 2009-2010 The Mana Developers
* Copyright (C) 2011-2018 The ManaPlus Developers
*
* This file is part of The ManaPlus Client.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "net/eathena/itemrecv.h"
#include "actormanager.h"
#include "itemcolormanager.h"
#include "logger.h"
#include "const/resources/item/cards.h"
#include "net/messagein.h"
#include "debug.h"
extern int packetVersion;
extern bool packets_zero;
namespace EAthena
{
void ItemRecv::processItemDropped(Net::MessageIn &msg)
{
const BeingId id = msg.readBeingId("id");
const int itemId = msg.readItemId("item id");
ItemTypeT itemType = ItemType::Unknown;
if (msg.getVersion() >= 20130000)
itemType = static_cast<ItemTypeT>(msg.readInt16("type"));
const Identified identified = fromInt(
msg.readUInt8("identify"), Identified);
const int x = msg.readInt16("x");
const int y = msg.readInt16("y");
const int subX = CAST_S32(msg.readInt8("subx"));
const int subY = CAST_S32(msg.readInt8("suby"));
const int amount = msg.readInt16("count");
if (packets_zero || packetVersion >= 20180418)
{
msg.readUInt8("show drop effect");
msg.readInt16("show effect mode");
}
if (actorManager != nullptr)
{
actorManager->createItem(id,
itemId,
x, y,
itemType,
amount,
0,
ItemColor_one,
identified,
Damaged_false,
subX, subY,
nullptr);
}
}
void ItemRecv::processItemDropped2(Net::MessageIn &msg)
{
const BeingId id = msg.readBeingId("id");
const int itemId = msg.readInt16("item id"); // +++ need use int32
const ItemTypeT itemType = static_cast<ItemTypeT>(msg.readUInt8("type"));
const Identified identified = fromInt(
msg.readUInt8("identify"), Identified);
const Damaged damaged = fromBool(msg.readUInt8("attribute"), Damaged);
const uint8_t refine = msg.readUInt8("refine");
int cards[maxCards];
for (int f = 0; f < maxCards; f++)
cards[f] = msg.readUInt16("card"); // ++ need use int32
const int x = msg.readInt16("x");
const int y = msg.readInt16("y");
const int amount = msg.readInt16("amount");
const int subX = CAST_S32(msg.readInt8("subx"));
const int subY = CAST_S32(msg.readInt8("suby"));
// +++ probably need add drop effect fields?
if (actorManager != nullptr)
{
actorManager->createItem(id,
itemId,
x, y,
itemType,
amount,
refine,
ItemColorManager::getColorFromCards(&cards[0]),
identified,
damaged,
subX, subY,
&cards[0]);
}
}
void ItemRecv::processItemMvpDropped(Net::MessageIn &msg)
{
UNIMPLEMENTEDPACKET;
msg.readInt16("len");
msg.readUInt8("type");
msg.readItemId("item id");
msg.readUInt8("len");
msg.readString(24, "name");
msg.readUInt8("monster name len");
msg.readString(24, "monster name");
}
void ItemRecv::processItemVisible(Net::MessageIn &msg)
{
const BeingId id = msg.readBeingId("item object id");
const int itemId = msg.readItemId("item id");
const Identified identified = fromInt(
msg.readUInt8("identify"), Identified);
const int x = msg.readInt16("x");
const int y = msg.readInt16("y");
const int amount = msg.readInt16("amount");
const int subX = CAST_S32(msg.readInt8("sub x"));
const int subY = CAST_S32(msg.readInt8("sub y"));
if (actorManager != nullptr)
{
actorManager->createItem(id,
itemId,
x, y,
ItemType::Unknown,
amount,
0,
ItemColor_one,
identified,
Damaged_false,
subX, subY,
nullptr);
}
}
void ItemRecv::processItemVisible2(Net::MessageIn &msg)
{
const BeingId id = msg.readBeingId("item object id");
const int itemId = msg.readInt16("item id"); // +++ need use int32
const ItemTypeT itemType = static_cast<ItemTypeT>(
msg.readUInt8("type"));
const Identified identified = fromInt(
msg.readUInt8("identify"), Identified);
const Damaged damaged = fromBool(msg.readUInt8("attribute"), Damaged);
const uint8_t refine = msg.readUInt8("refine");
int cards[maxCards];
for (int f = 0; f < maxCards; f++)
cards[f] = msg.readUInt16("card"); // +++ need use int32
const int x = msg.readInt16("x");
const int y = msg.readInt16("y");
const int amount = msg.readInt16("amount");
const int subX = CAST_S32(msg.readInt8("sub x"));
const int subY = CAST_S32(msg.readInt8("sub y"));
if (actorManager != nullptr)
{
actorManager->createItem(id,
itemId,
x, y,
itemType,
amount,
refine,
ItemColorManager::getColorFromCards(&cards[0]),
identified,
damaged,
subX, subY,
&cards[0]);
}
}
} // namespace EAthena
| mekolat/ManaPlus | src/net/eathena/itemrecv.cpp | C++ | gpl-2.0 | 5,784 |
/**
* ownCloud Android client application
*
* @author Mario Danic
* Copyright (C) 2017 Mario Danic
* Copyright (C) 2012 Bartek Przybylski
* Copyright (C) 2012-2016 ownCloud Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.fragment;
import android.animation.LayoutTransition;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.owncloud.android.MainApp;
import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.files.SearchOperation;
import com.owncloud.android.ui.ExtendedListView;
import com.owncloud.android.ui.activity.FileDisplayActivity;
import com.owncloud.android.ui.activity.FolderPickerActivity;
import com.owncloud.android.ui.activity.OnEnforceableRefreshListener;
import com.owncloud.android.ui.activity.UploadFilesActivity;
import com.owncloud.android.ui.adapter.FileListListAdapter;
import com.owncloud.android.ui.adapter.LocalFileListAdapter;
import com.owncloud.android.ui.events.SearchEvent;
import org.greenrobot.eventbus.EventBus;
import org.parceler.Parcel;
import java.util.ArrayList;
import third_parties.in.srain.cube.GridViewWithHeaderAndFooter;
import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;
public class ExtendedListFragment extends Fragment
implements OnItemClickListener, OnEnforceableRefreshListener, SearchView.OnQueryTextListener {
protected static final String TAG = ExtendedListFragment.class.getSimpleName();
protected static final String KEY_SAVED_LIST_POSITION = "SAVED_LIST_POSITION";
private static final String KEY_INDEXES = "INDEXES";
private static final String KEY_FIRST_POSITIONS = "FIRST_POSITIONS";
private static final String KEY_TOPS = "TOPS";
private static final String KEY_HEIGHT_CELL = "HEIGHT_CELL";
private static final String KEY_EMPTY_LIST_MESSAGE = "EMPTY_LIST_MESSAGE";
private static final String KEY_IS_GRID_VISIBLE = "IS_GRID_VISIBLE";
protected SwipeRefreshLayout mRefreshListLayout;
private SwipeRefreshLayout mRefreshGridLayout;
protected SwipeRefreshLayout mRefreshEmptyLayout;
protected LinearLayout mEmptyListContainer;
protected TextView mEmptyListMessage;
protected TextView mEmptyListHeadline;
protected ImageView mEmptyListIcon;
protected ProgressBar mEmptyListProgress;
private FloatingActionsMenu mFabMain;
private FloatingActionButton mFabUpload;
private FloatingActionButton mFabMkdir;
private FloatingActionButton mFabUploadFromApp;
// Save the state of the scroll in browsing
private ArrayList<Integer> mIndexes;
private ArrayList<Integer> mFirstPositions;
private ArrayList<Integer> mTops;
private int mHeightCell = 0;
private SwipeRefreshLayout.OnRefreshListener mOnRefreshListener = null;
protected AbsListView mCurrentListView;
private ExtendedListView mListView;
private View mListFooterView;
private GridViewWithHeaderAndFooter mGridView;
private View mGridFooterView;
private BaseAdapter mAdapter;
protected SearchView searchView;
private Handler handler = new Handler();
@Parcel
public enum SearchType {
NO_SEARCH,
REGULAR_FILTER,
FILE_SEARCH,
FAVORITE_SEARCH,
FAVORITE_SEARCH_FILTER,
VIDEO_SEARCH,
VIDEO_SEARCH_FILTER,
PHOTO_SEARCH,
PHOTOS_SEARCH_FILTER,
RECENTLY_MODIFIED_SEARCH,
RECENTLY_MODIFIED_SEARCH_FILTER,
RECENTLY_ADDED_SEARCH,
RECENTLY_ADDED_SEARCH_FILTER,
// not a real filter, but nevertheless
SHARED_FILTER
}
protected void setListAdapter(BaseAdapter listAdapter) {
mAdapter = listAdapter;
mCurrentListView.setAdapter(listAdapter);
mCurrentListView.invalidateViews();
}
protected AbsListView getListView() {
return mCurrentListView;
}
public FloatingActionButton getFabUpload() {
return mFabUpload;
}
public FloatingActionButton getFabUploadFromApp() {
return mFabUploadFromApp;
}
public FloatingActionButton getFabMkdir() {
return mFabMkdir;
}
public FloatingActionsMenu getFabMain() {
return mFabMain;
}
public void switchToGridView() {
if (!isGridEnabled()) {
mListView.setAdapter(null);
mRefreshListLayout.setVisibility(View.GONE);
mRefreshGridLayout.setVisibility(View.VISIBLE);
mCurrentListView = mGridView;
setListAdapter(mAdapter);
}
}
public void switchToListView() {
if (isGridEnabled()) {
mGridView.setAdapter(null);
mRefreshGridLayout.setVisibility(View.GONE);
mRefreshListLayout.setVisibility(View.VISIBLE);
mCurrentListView = mListView;
setListAdapter(mAdapter);
}
}
public boolean isGridEnabled() {
return (mCurrentListView != null && mCurrentListView.equals(mGridView));
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
final MenuItem item = menu.findItem(R.id.action_search);
searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
final Handler handler = new Handler();
DisplayMetrics displaymetrics = new DisplayMetrics();
Activity activity;
if ((activity = getActivity()) != null) {
activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
if (getResources().getConfiguration().orientation == ORIENTATION_LANDSCAPE) {
searchView.setMaxWidth((int) (width * 0.4));
} else {
if (activity instanceof FolderPickerActivity) {
searchView.setMaxWidth((int) (width * 0.8));
} else {
searchView.setMaxWidth((int) (width * 0.7));
}
}
}
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, final boolean hasFocus) {
if (hasFocus) {
mFabMain.collapse();
}
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (getActivity() != null && !(getActivity() instanceof FolderPickerActivity)) {
setFabEnabled(!hasFocus);
boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils.
getCurrentOwnCloudAccount(MainApp.getAppContext()));
if (getResources().getBoolean(R.bool.bottom_toolbar_enabled) && searchSupported) {
BottomNavigationView bottomNavigationView = (BottomNavigationView) getActivity().
findViewById(R.id.bottom_navigation_view);
if (hasFocus) {
bottomNavigationView.setVisibility(View.GONE);
} else {
bottomNavigationView.setVisibility(View.VISIBLE);
}
}
}
}
}, 100);
}
});
final View mSearchEditFrame = searchView
.findViewById(android.support.v7.appcompat.R.id.search_edit_frame);
ViewTreeObserver vto = mSearchEditFrame.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
int oldVisibility = -1;
@Override
public void onGlobalLayout() {
int currentVisibility = mSearchEditFrame.getVisibility();
if (currentVisibility != oldVisibility) {
if (currentVisibility == View.VISIBLE) {
setEmptyListMessage(SearchType.REGULAR_FILTER);
} else {
setEmptyListMessage(SearchType.NO_SEARCH);
}
oldVisibility = currentVisibility;
}
}
});
LinearLayout searchBar = (LinearLayout) searchView.findViewById(R.id.search_bar);
searchBar.setLayoutTransition(new LayoutTransition());
}
public boolean onQueryTextChange(final String query) {
if (getFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT)
instanceof ExtendedListFragment){
performSearch(query, false);
return true;
} else {
return false;
}
}
@Override
public boolean onQueryTextSubmit(String query) {
if (getFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT)
instanceof ExtendedListFragment){
performSearch(query, true);
return true;
} else {
return false;
}
}
private void performSearch(final String query, boolean isSubmit) {
handler.removeCallbacksAndMessages(null);
if (!TextUtils.isEmpty(query)) {
int delay = 500;
if (isSubmit) {
delay = 0;
}
if (mAdapter != null && mAdapter instanceof FileListListAdapter) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (AccountUtils.hasSearchSupport(AccountUtils.
getCurrentOwnCloudAccount(MainApp.getAppContext()))) {
EventBus.getDefault().post(new SearchEvent(query, SearchOperation.SearchType.FILE_SEARCH,
SearchEvent.UnsetType.NO_UNSET));
} else {
FileListListAdapter fileListListAdapter = (FileListListAdapter) mAdapter;
fileListListAdapter.getFilter().filter(query);
}
}
}, delay);
} else if (mAdapter != null && mAdapter instanceof LocalFileListAdapter) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
LocalFileListAdapter localFileListAdapter = (LocalFileListAdapter) mAdapter;
localFileListAdapter.filter(query);
}
}, delay);
}
if (searchView != null && delay == 0) {
searchView.clearFocus();
}
} else {
Activity activity;
if ((activity = getActivity()) != null) {
if (activity instanceof FileDisplayActivity) {
((FileDisplayActivity) activity).refreshListOfFilesFragment(true);
} else if (activity instanceof UploadFilesActivity) {
LocalFileListAdapter localFileListAdapter = (LocalFileListAdapter) mAdapter;
localFileListAdapter.filter(query);
} else if (activity instanceof FolderPickerActivity) {
((FolderPickerActivity) activity).refreshListOfFilesFragment(true);
}
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log_OC.d(TAG, "onCreateView");
View v = inflater.inflate(R.layout.list_fragment, null);
setupEmptyList(v);
mListView = (ExtendedListView) (v.findViewById(R.id.list_root));
mListView.setOnItemClickListener(this);
mListFooterView = inflater.inflate(R.layout.list_footer, null, false);
mGridView = (GridViewWithHeaderAndFooter) (v.findViewById(R.id.grid_root));
mGridView.setNumColumns(GridView.AUTO_FIT);
mGridView.setOnItemClickListener(this);
mGridFooterView = inflater.inflate(R.layout.list_footer, null, false);
// Pull-down to refresh layout
mRefreshListLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_list);
mRefreshGridLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_grid);
mRefreshEmptyLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_containing_empty);
onCreateSwipeToRefresh(mRefreshListLayout);
onCreateSwipeToRefresh(mRefreshGridLayout);
onCreateSwipeToRefresh(mRefreshEmptyLayout);
mListView.setEmptyView(mRefreshEmptyLayout);
mGridView.setEmptyView(mRefreshEmptyLayout);
mFabMain = (FloatingActionsMenu) v.findViewById(R.id.fab_main);
mFabUpload = (FloatingActionButton) v.findViewById(R.id.fab_upload);
mFabMkdir = (FloatingActionButton) v.findViewById(R.id.fab_mkdir);
mFabUploadFromApp = (FloatingActionButton) v.findViewById(R.id.fab_upload_from_app);
boolean searchSupported = AccountUtils.hasSearchSupport(AccountUtils.
getCurrentOwnCloudAccount(MainApp.getAppContext()));
if (getResources().getBoolean(R.bool.bottom_toolbar_enabled) && searchSupported) {
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mFabMain.getLayoutParams();
final float scale = v.getResources().getDisplayMetrics().density;
BottomNavigationView bottomNavigationView = (BottomNavigationView)
v.findViewById(R.id.bottom_navigation_view);
// convert the DP into pixel
int pixel = (int) (32 * scale + 0.5f);
layoutParams.setMargins(0, 0, pixel / 2, bottomNavigationView.getMeasuredHeight() + pixel * 2);
}
mCurrentListView = mListView; // list by default
if (savedInstanceState != null) {
if (savedInstanceState.getBoolean(KEY_IS_GRID_VISIBLE, false)) {
switchToGridView();
}
int referencePosition = savedInstanceState.getInt(KEY_SAVED_LIST_POSITION);
if (isGridEnabled()) {
Log_OC.v(TAG, "Setting grid position " + referencePosition);
mGridView.setSelection(referencePosition);
} else {
Log_OC.v(TAG, "Setting and centering around list position " + referencePosition);
mListView.setAndCenterSelection(referencePosition);
}
}
return v;
}
protected void setupEmptyList(View view) {
mEmptyListContainer = (LinearLayout) view.findViewById(R.id.empty_list_view);
mEmptyListMessage = (TextView) view.findViewById(R.id.empty_list_view_text);
mEmptyListHeadline = (TextView) view.findViewById(R.id.empty_list_view_headline);
mEmptyListIcon = (ImageView) view.findViewById(R.id.empty_list_icon);
mEmptyListProgress = (ProgressBar) view.findViewById(R.id.empty_list_progress);
}
/**
* {@inheritDoc}
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mIndexes = savedInstanceState.getIntegerArrayList(KEY_INDEXES);
mFirstPositions = savedInstanceState.getIntegerArrayList(KEY_FIRST_POSITIONS);
mTops = savedInstanceState.getIntegerArrayList(KEY_TOPS);
mHeightCell = savedInstanceState.getInt(KEY_HEIGHT_CELL);
setMessageForEmptyList(savedInstanceState.getString(KEY_EMPTY_LIST_MESSAGE));
} else {
mIndexes = new ArrayList<>();
mFirstPositions = new ArrayList<>();
mTops = new ArrayList<>();
mHeightCell = 0;
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log_OC.d(TAG, "onSaveInstanceState()");
savedInstanceState.putBoolean(KEY_IS_GRID_VISIBLE, isGridEnabled());
savedInstanceState.putInt(KEY_SAVED_LIST_POSITION, getReferencePosition());
savedInstanceState.putIntegerArrayList(KEY_INDEXES, mIndexes);
savedInstanceState.putIntegerArrayList(KEY_FIRST_POSITIONS, mFirstPositions);
savedInstanceState.putIntegerArrayList(KEY_TOPS, mTops);
savedInstanceState.putInt(KEY_HEIGHT_CELL, mHeightCell);
savedInstanceState.putString(KEY_EMPTY_LIST_MESSAGE, getEmptyViewText());
}
/**
* Calculates the position of the item that will be used as a reference to
* reposition the visible items in the list when the device is turned to
* other position.
*
* The current policy is take as a reference the visible item in the center
* of the screen.
*
* @return The position in the list of the visible item in the center of the
* screen.
*/
protected int getReferencePosition() {
if (mCurrentListView != null) {
return (mCurrentListView.getFirstVisiblePosition() +
mCurrentListView.getLastVisiblePosition()) / 2;
} else {
return 0;
}
}
/*
* Restore index and position
*/
protected void restoreIndexAndTopPosition() {
if (mIndexes.size() > 0) {
// needs to be checked; not every browse-up had a browse-down before
int index = mIndexes.remove(mIndexes.size() - 1);
final int firstPosition = mFirstPositions.remove(mFirstPositions.size() - 1);
int top = mTops.remove(mTops.size() - 1);
Log_OC.v(TAG, "Setting selection to position: " + firstPosition + "; top: "
+ top + "; index: " + index);
if (mCurrentListView != null && mCurrentListView.equals(mListView)) {
if (mHeightCell * index <= mListView.getHeight()) {
mListView.setSelectionFromTop(firstPosition, top);
} else {
mListView.setSelectionFromTop(index, 0);
}
} else {
if (mHeightCell * index <= mGridView.getHeight()) {
mGridView.setSelection(firstPosition);
//mGridView.smoothScrollToPosition(firstPosition);
} else {
mGridView.setSelection(index);
//mGridView.smoothScrollToPosition(index);
}
}
}
}
/*
* Save index and top position
*/
protected void saveIndexAndTopPosition(int index) {
mIndexes.add(index);
int firstPosition = mCurrentListView.getFirstVisiblePosition();
mFirstPositions.add(firstPosition);
View view = mCurrentListView.getChildAt(0);
int top = (view == null) ? 0 : view.getTop();
mTops.add(top);
// Save the height of a cell
mHeightCell = (view == null || mHeightCell != 0) ? mHeightCell : view.getHeight();
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// to be @overriden
}
@Override
public void onRefresh() {
if (searchView != null) {
searchView.onActionViewCollapsed();
Activity activity;
if ((activity = getActivity()) != null && activity instanceof FileDisplayActivity) {
FileDisplayActivity fileDisplayActivity = (FileDisplayActivity) activity;
fileDisplayActivity.setDrawerIndicatorEnabled(fileDisplayActivity.isDrawerIndicatorAvailable());
}
}
mRefreshListLayout.setRefreshing(false);
mRefreshGridLayout.setRefreshing(false);
mRefreshEmptyLayout.setRefreshing(false);
if (mOnRefreshListener != null) {
mOnRefreshListener.onRefresh();
}
}
public void setOnRefreshListener(OnEnforceableRefreshListener listener) {
mOnRefreshListener = listener;
}
/**
* Disables swipe gesture.
*
* Sets the 'enabled' state of the refresh layouts contained in the fragment.
*
* When 'false' is set, prevents user gestures but keeps the option to refresh programatically,
*
* @param enabled Desired state for capturing swipe gesture.
*/
public void setSwipeEnabled(boolean enabled) {
mRefreshListLayout.setEnabled(enabled);
mRefreshGridLayout.setEnabled(enabled);
mRefreshEmptyLayout.setEnabled(enabled);
}
/**
* Sets the 'visibility' state of the FAB contained in the fragment.
*
* When 'false' is set, FAB visibility is set to View.GONE programmatically,
*
* @param enabled Desired visibility for the FAB.
*/
public void setFabEnabled(boolean enabled) {
if (enabled) {
mFabMain.setVisibility(View.VISIBLE);
} else {
mFabMain.setVisibility(View.GONE);
}
}
/**
* Set message for empty list view.
*/
public void setMessageForEmptyList(String message) {
if (mEmptyListContainer != null && mEmptyListMessage != null) {
mEmptyListMessage.setText(message);
}
}
/**
* displays an empty list information with a headline, a message and an icon.
*
* @param headline the headline
* @param message the message
* @param icon the icon to be shown
*/
public void setMessageForEmptyList(@StringRes final int headline, @StringRes final int message, @DrawableRes final int icon) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (mEmptyListContainer != null && mEmptyListMessage != null) {
mEmptyListHeadline.setText(headline);
mEmptyListMessage.setText(message);
mEmptyListIcon.setImageResource(icon);
mEmptyListIcon.setVisibility(View.VISIBLE);
mEmptyListProgress.setVisibility(View.GONE);
}
}
});
}
public void setEmptyListMessage(final SearchType searchType) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (searchType == SearchType.NO_SEARCH) {
setMessageForEmptyList(
R.string.file_list_empty_headline,
R.string.file_list_empty,
R.drawable.ic_list_empty_folder
);
} else if (searchType == SearchType.FILE_SEARCH) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search,
R.string.file_list_empty, R.drawable.ic_search_light_grey);
} else if (searchType == SearchType.FAVORITE_SEARCH) {
setMessageForEmptyList(R.string.file_list_empty_favorite_headline,
R.string.file_list_empty_favorites_filter_list, R.drawable.ic_star_light_grey);
} else if (searchType == SearchType.VIDEO_SEARCH) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search_videos,
R.string.file_list_empty_text_videos, R.drawable.ic_list_empty_video);
} else if (searchType == SearchType.PHOTO_SEARCH) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search_photos,
R.string.file_list_empty_text_photos, R.drawable.ic_list_empty_image);
} else if (searchType == SearchType.RECENTLY_MODIFIED_SEARCH) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search,
R.string.file_list_empty_recently_modified, R.drawable.ic_list_empty_recent);
} else if (searchType == SearchType.RECENTLY_ADDED_SEARCH) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search,
R.string.file_list_empty_recently_added, R.drawable.ic_list_empty_recent);
} else if (searchType == SearchType.REGULAR_FILTER) {
setMessageForEmptyList(R.string.file_list_empty_headline_search,
R.string.file_list_empty_search, R.drawable.ic_search_light_grey);
} else if (searchType == SearchType.FAVORITE_SEARCH_FILTER) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search,
R.string.file_list_empty_favorites_filter, R.drawable.ic_star_light_grey);
} else if (searchType == SearchType.VIDEO_SEARCH_FILTER) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search_videos,
R.string.file_list_empty_text_videos_filter, R.drawable.ic_list_empty_video);
} else if (searchType == SearchType.PHOTOS_SEARCH_FILTER) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search_photos,
R.string.file_list_empty_text_photos_filter, R.drawable.ic_list_empty_image);
} else if (searchType == SearchType.RECENTLY_MODIFIED_SEARCH_FILTER) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search,
R.string.file_list_empty_recently_modified_filter, R.drawable.ic_list_empty_recent);
} else if (searchType == SearchType.RECENTLY_ADDED_SEARCH_FILTER) {
setMessageForEmptyList(R.string.file_list_empty_headline_server_search,
R.string.file_list_empty_recently_added_filter, R.drawable.ic_list_empty_recent);
} else if (searchType == SearchType.SHARED_FILTER) {
setMessageForEmptyList(R.string.file_list_empty_shared_headline,
R.string.file_list_empty_shared, R.drawable.ic_list_empty_shared);
}
}
});
}
/**
* Set message for empty list view.
*/
public void setEmptyListLoadingMessage() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (mEmptyListContainer != null && mEmptyListMessage != null) {
mEmptyListHeadline.setText(R.string.file_list_loading);
mEmptyListMessage.setText("");
mEmptyListIcon.setVisibility(View.GONE);
mEmptyListProgress.setVisibility(View.VISIBLE);
}
}
});
}
/**
* Get the text of EmptyListMessage TextView.
*
* @return String empty text view text-value
*/
public String getEmptyViewText() {
return (mEmptyListContainer != null && mEmptyListMessage != null) ? mEmptyListMessage.getText().toString() : "";
}
protected void onCreateSwipeToRefresh(SwipeRefreshLayout refreshLayout) {
// Colors in animations
refreshLayout.setColorSchemeResources(R.color.color_accent, R.color.primary, R.color.primary_dark);
refreshLayout.setOnRefreshListener(this);
}
@Override
public void onRefresh(boolean ignoreETag) {
mRefreshListLayout.setRefreshing(false);
mRefreshGridLayout.setRefreshing(false);
mRefreshEmptyLayout.setRefreshing(false);
if (mOnRefreshListener != null) {
mOnRefreshListener.onRefresh();
}
}
protected void setChoiceMode(int choiceMode) {
mListView.setChoiceMode(choiceMode);
mGridView.setChoiceMode(choiceMode);
}
protected void setMultiChoiceModeListener(AbsListView.MultiChoiceModeListener listener) {
mListView.setMultiChoiceModeListener(listener);
mGridView.setMultiChoiceModeListener(listener);
}
/**
* TODO doc
* To be called before setAdapter, or GridViewWithHeaderAndFooter will throw an exception
*
* @param enabled flag if footer should be shown/calculated
*/
protected void setFooterEnabled(boolean enabled) {
if (enabled) {
if (mGridView.getFooterViewCount() == 0 && mGridView.isCorrectAdapter()) {
if (mGridFooterView.getParent() != null) {
((ViewGroup) mGridFooterView.getParent()).removeView(mGridFooterView);
}
mGridView.addFooterView(mGridFooterView, null, false);
}
mGridFooterView.invalidate();
if (mListView.getFooterViewsCount() == 0) {
if (mListFooterView.getParent() != null) {
((ViewGroup) mListFooterView.getParent()).removeView(mListFooterView);
}
mListView.addFooterView(mListFooterView, null, false);
}
mListFooterView.invalidate();
} else {
mGridView.removeFooterView(mGridFooterView);
mListView.removeFooterView(mListFooterView);
}
}
/**
* set the list/grid footer text.
*
* @param text the footer text
*/
protected void setFooterText(String text) {
if (text != null && text.length() > 0) {
((TextView) mListFooterView.findViewById(R.id.footerText)).setText(text);
((TextView) mGridFooterView.findViewById(R.id.footerText)).setText(text);
setFooterEnabled(true);
} else {
setFooterEnabled(false);
}
}
}
| aleister09/android | src/main/java/com/owncloud/android/ui/fragment/ExtendedListFragment.java | Java | gpl-2.0 | 31,646 |
/*
* Copyright (C) 2001-2006 Jacek Sieka, arnetheduck on gmail point com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "stdinc.h"
#include "DCPlusPlus.h"
#include "ZUtils.h"
#include "Exception.h"
#include "ResourceManager.h"
const double ZFilter::MIN_COMPRESSION_LEVEL = 0.9;
ZFilter::ZFilter() : totalIn(0), totalOut(0), compressing(true) {
memset(&zs, 0, sizeof(zs));
if(deflateInit(&zs, 3) != Z_OK) {
throw Exception(STRING(COMPRESSION_ERROR));
}
}
ZFilter::~ZFilter() {
dcdebug("ZFilter end, %ld/%ld = %.04f\n", zs.total_out, zs.total_in, (float)zs.total_out / max((float)zs.total_in, (float)1));
deflateEnd(&zs);
}
bool ZFilter::operator()(const void* in, size_t& insize, void* out, size_t& outsize) {
if(outsize == 0)
return false;
zs.next_in = (Bytef*)in;
zs.next_out = (Bytef*)out;
// Check if there's any use compressing; if not, save some cpu...
if(compressing && insize > 0 && outsize > 16 && (totalIn > (64*1024)) && ((static_cast<double>(totalOut) / totalIn) > 0.95)) {
zs.avail_in = 0;
zs.avail_out = outsize;
if(deflateParams(&zs, 0, Z_DEFAULT_STRATEGY) != Z_OK) {
throw Exception(STRING(COMPRESSION_ERROR));
}
zs.avail_in = insize;
compressing = false;
dcdebug("Dynamically disabled compression");
// Check if we ate all space already...
if(zs.avail_out == 0) {
outsize = outsize - zs.avail_out;
insize = insize - zs.avail_in;
totalOut += outsize;
totalIn += insize;
return true;
}
} else {
zs.avail_in = insize;
zs.avail_out = outsize;
}
if(insize == 0) {
int err = ::deflate(&zs, Z_FINISH);
if(err != Z_OK && err != Z_STREAM_END)
throw Exception(STRING(COMPRESSION_ERROR));
outsize = outsize - zs.avail_out;
insize = insize - zs.avail_in;
totalOut += outsize;
totalIn += insize;
return err == Z_OK;
} else {
int err = ::deflate(&zs, Z_NO_FLUSH);
if(err != Z_OK)
throw Exception(STRING(COMPRESSION_ERROR));
outsize = outsize - zs.avail_out;
insize = insize - zs.avail_in;
totalOut += outsize;
totalIn += insize;
return true;
}
}
UnZFilter::UnZFilter() {
memset(&zs, 0, sizeof(zs));
if(inflateInit(&zs) != Z_OK)
throw Exception(STRING(DECOMPRESSION_ERROR));
}
UnZFilter::~UnZFilter() {
dcdebug("UnZFilter end, %ld/%ld = %.04f\n", zs.total_out, zs.total_in, (float)zs.total_out / max((float)zs.total_in, (float)1));
inflateEnd(&zs);
}
bool UnZFilter::operator()(const void* in, size_t& insize, void* out, size_t& outsize) {
if(outsize == 0)
return 0;
zs.avail_in = insize;
zs.next_in = (Bytef*)in;
zs.avail_out = outsize;
zs.next_out = (Bytef*)out;
int err = ::inflate(&zs, Z_NO_FLUSH);
// see zlib/contrib/minizip/unzip.c, Z_BUF_ERROR means we should have padded
// with a dummy byte if at end of stream - since we don't do this it's not a real
// error
if(!(err == Z_OK || err == Z_STREAM_END || (err == Z_BUF_ERROR && in == NULL)))
throw Exception(STRING(DECOMPRESSION_ERROR));
outsize = outsize - zs.avail_out;
insize = insize - zs.avail_in;
return err == Z_OK;
}
| NareshPS/FBLinuxDCPP | client/ZUtils.cpp | C++ | gpl-2.0 | 3,708 |
/* Copyright (C) 2007 The SpringLobby Team. All rights reserved. */
//
#ifndef NO_TORRENT_SYSTEM
#ifdef _MSC_VER
#ifndef NOMINMAX
#define NOMINMAX
#endif // NOMINMAX
#include <winsock2.h>
#endif // _MSC_VER
#include <wx/stattext.h>
#include <wx/sizer.h>
#include <wx/textctrl.h>
#include <wx/intl.h>
#include <wx/choice.h>
#include <wx/statbox.h>
#include <wx/event.h>
#include <wx/regex.h>
#include <wx/checkbox.h>
#include "filelistfilter.h"
#include "filelistctrl.h"
#include "filelistdialog.h"
#include "../uiutils.h"
#include "../utils/downloader.h"
#include "../torrentwrapper.h"
///////////////////////////////////////////////////////////////////////////
BEGIN_EVENT_TABLE( FileListFilter, wxPanel )
EVT_CHOICE( FILE_FILTER_TYPE_CHOICE, FileListFilter::OnChangeType )
EVT_TEXT( FILE_FILTER_NAME_EDIT , FileListFilter::OnChangeName )
EVT_CHECKBOX( FILE_FILTER_ONDISK , FileListFilter::OnChangeOndisk )
END_EVENT_TABLE()
FileListFilter::FileListFilter( wxWindow* parent, wxWindowID id, FileListDialog* parentBattleListTab, const wxPoint& pos, const wxSize& size, long style )
: wxPanel( parent, id, pos, size, style ),
m_parent_filelistdialog( parentBattleListTab )
{
wxBoxSizer* m_filter_sizer;
m_filter_sizer = new wxBoxSizer( wxVERTICAL );
wxStaticBoxSizer* m_filter_body_sizer;
m_filter_body_sizer = new wxStaticBoxSizer( new wxStaticBox( this, -1, wxEmptyString ), wxVERTICAL );
wxBoxSizer* m_filter_body_row1_sizer;
m_filter_body_row1_sizer = new wxBoxSizer( wxHORIZONTAL );
m_filter_name_text = new wxStaticText( this, wxID_ANY, _( "Filename:" ), wxDefaultPosition, wxSize( -1,-1 ), 0 );
m_filter_name_text->Wrap( -1 );
m_filter_name_text->SetMinSize( wxSize( 90,-1 ) );
m_filter_body_row1_sizer->Add( m_filter_name_text, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
m_filter_name_edit = new wxTextCtrl( this, FILE_FILTER_NAME_EDIT, _T( "" ), wxDefaultPosition, wxSize( -1,-1 ), 0|wxSIMPLE_BORDER );
m_filter_name_edit->SetFont( wxFont( wxNORMAL_FONT->GetPointSize(), 70, 90, 90, false, wxEmptyString ) );
m_filter_name_edit->SetMinSize( wxSize( 220,-1 ) );
m_filter_name_expression = new wxRegEx( m_filter_name_edit->GetValue(),wxRE_ICASE );
m_filter_body_row1_sizer->Add( m_filter_name_edit, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5 );
wxBoxSizer* m_filter_type_sizer;
m_filter_type_sizer = new wxBoxSizer( wxHORIZONTAL );
m_filter_type_text = new wxStaticText( this, wxID_ANY, _( "Filetype:" ), wxDefaultPosition, wxDefaultSize, 0 );
m_filter_type_text->Wrap( -1 );
m_filter_type_sizer->Add( m_filter_type_text, 0, wxALIGN_RIGHT|wxALL|wxALIGN_CENTER_VERTICAL, 5 );
wxBoxSizer* m_filter_ondisk_sizer;
m_filter_ondisk_sizer = new wxBoxSizer( wxHORIZONTAL );
m_filter_ondisk = new wxCheckBox( this, FILE_FILTER_ONDISK, _T( "Filter files already on disk" ) );
m_filter_ondisk_sizer->Add( m_filter_ondisk, 0, wxALIGN_CENTER_VERTICAL );
wxString firstChoice = _T( "Any" );
wxArrayString m_filter_type_choiceChoices;
m_filter_type_choiceChoices.Add( firstChoice );
m_filter_type_choiceChoices.Add( _( "Map" ) );
m_filter_type_choiceChoices.Add( _( "Game" ) );
m_filter_type_choice = new wxChoice( this, FILE_FILTER_TYPE_CHOICE, wxDefaultPosition, wxDefaultSize, m_filter_type_choiceChoices, wxSIMPLE_BORDER );
m_filter_type_sizer->Add( m_filter_type_choice, 0, wxALIGN_RIGHT|wxALL|wxALIGN_CENTER_VERTICAL, 5 );
m_filter_body_row1_sizer->Add( m_filter_type_sizer, 0, wxEXPAND, 5 );
m_filter_body_row1_sizer->Add( m_filter_ondisk_sizer, 0, wxEXPAND|wxALIGN_CENTER_VERTICAL, 5 );
m_filter_body_sizer->Add( m_filter_body_row1_sizer, 1, wxEXPAND, 5 );
m_filter_sizer->Add( m_filter_body_sizer, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL, 5 );
this->SetSizer( m_filter_sizer );
this->Layout();
m_filter_sizer->Fit( this );
delete m_filter_name_expression;
m_filter_name_expression = new wxRegEx( m_filter_name_edit->GetValue(),wxRE_ICASE );
m_filter_type_choice_value = -1;
wxCommandEvent dummy;
OnChange( dummy );
}
bool FileListFilter::DoFilterResource( const PlasmaResourceInfo& /*info*/ )
{
// if(!data.ok())return false;
// if ( data->name.Upper().Find( m_filter_name_edit->GetValue().Upper() ) == wxNOT_FOUND
// && !m_filter_name_expression->Matches( data->name ) )
// return false;
// if ( m_filter_type_choice_value == 0 && data->type != SpringUnitSync::map ) return false;
//
// if ( m_filter_type_choice_value == 1 && data->type != SpringUnitSync::mod ) return false;
//
// if ( m_filter_ondisk->IsChecked() && data->HasFullFileLocal() )
// return false;
return false;
}
void FileListFilter::OnChange( wxCommandEvent& )
{
//needs dummy event data
m_parent_filelistdialog->UpdateList( GlobalEvents::GlobalEventData() );
}
void FileListFilter::OnChangeName( wxCommandEvent& event )
{
delete m_filter_name_expression;
m_filter_name_expression = new wxRegEx( m_filter_name_edit->GetValue(),wxRE_ICASE );
OnChange( event );
}
void FileListFilter::OnChangeType( wxCommandEvent& event )
{
m_filter_type_choice_value = m_filter_type_choice->GetSelection()-1;
OnChange( event );
}
void FileListFilter::OnChangeOndisk( wxCommandEvent& event )
{
OnChange( event );
}
#endif
| N2maniac/springlobby-join-fork | src/filelister/filelistfilter.cpp | C++ | gpl-2.0 | 5,177 |
<?php
//add a button to the content editor, next to the media button
//this button will show a popup that contains inline content
add_action('media_buttons_context', 'add_my_custom_button');
//add some content to the bottom of the page
//This will be shown in the inline modal
if(is_admin()){
add_action('admin_footer', 'add_inline_popup_content');
}
//action to add a custom button to the content editor
function add_my_custom_button($context) {
//path to my icon
$img = get_template_directory_uri() .'/images/shortcode_button.png';
//our popup's title
$title = __('Cosmone Shortcodes','cosmone');
//append the icon
$context .= "<a class='cosmone_shortcodes' title='{$title}'><img src='{$img}' /></a>";
return $context;
}
function add_inline_popup_content() {
global $cosmone_shortcodes ;
?>
<div class="white-popup cosmone_shortcodes_container mfp-with-anim mfp-hide" id="cosmone_shortcodes_container" style="" >
<form>
<h4><?php _e("MageeWP Shortcodes Generator",'cosmone');?></h4>
<ul class="cosmone_shortcodes_list">
<?php if(is_array($cosmone_shortcodes )):foreach($cosmone_shortcodes as $key => $val){
if(in_array($key ,array("testimonial_item","pricing_row",'tab','accordion'))){continue;}
?>
<li><a class='cosmone_shortcode_item <?php echo $key;?>' title='<?php echo ucwords(str_replace("_"," ",$key));?>' data-shortcode="<?php echo $key;?>" href="javascript:;"><?php echo ucwords(str_replace("_"," ",$key));?></a></li>
<?php } ?>
<?php endif;?>
</ul>
<div id="cosmone-shortcodes-settings">
<div id="cosmone-generator-breadcrumbs">
<a title="Click to return to the shortcodes list" class="cosmone-shortcodes-home" href="javascript:void(0);"><?php _e("All shortcodes",'cosmone');?></a> → <span class="current_shortcode"></span>
<div class="clear"></div>
</div>
<div id="cosmone-shortcodes-settings-inner"></div>
<input name="cosmone-shortcode" type="hidden" id="cosmone-shortcode" value="" />
<input name="cosmone-shortcode-textarea" type="hidden" id="cosmone-shortcode-textarea" value="" />
<div class="cosmone-shortcode-actions cosmone-shortcode-clearfix">
<!--<a class="button button-secondary button-large cosmone-shortcode-preview " href="javascript:void(0);"><?php _e("Preview shortcode",'cosmone');?></a>-->
<a class="button button-primary button-large cosmone-shortcode-insert " href="javascript:void(0);"><?php _e("Insert shortcode",'cosmone');?></a>
</div>
<div class="clear"></div>
</div></form>
<div class="clear"></div>
</div>
<div id="cosmone-shortcode-preview" style="display:none;">
</div>
<?php } ?> | emanuelefrasca/emanuelefrasca_local_wp_slideshow | wp-content/themes/cosmone/includes/shortcode-media-button.php | PHP | gpl-2.0 | 2,726 |
/*
* Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/>
* Copyright (C) 2009-2011 MaNGOSZero <https://github.com/mangos/zero>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "MapManager.h"
#include "Log.h"
#include "GridStates.h"
#include "CellImpl.h"
#include "Map.h"
#include "DBCEnums.h"
#include "DBCStores.h"
#include "GridMap.h"
#include "VMapFactory.h"
#include "World.h"
#include "Policies/SingletonImp.h"
#include "Util.h"
char const* MAP_MAGIC = "MAPS";
char const* MAP_VERSION_MAGIC = "10.1";
char const* MAP_AREA_MAGIC = "AREA";
char const* MAP_HEIGHT_MAGIC = "MHGT";
char const* MAP_LIQUID_MAGIC = "MLIQ";
GridMap::GridMap()
{
m_flags = 0;
// Area data
m_gridArea = 0;
m_area_map = NULL;
// Height level data
m_gridHeight = INVALID_HEIGHT_VALUE;
m_gridGetHeight = &GridMap::getHeightFromFlat;
m_V9 = NULL;
m_V8 = NULL;
// Liquid data
m_liquidType = 0;
m_liquid_offX = 0;
m_liquid_offY = 0;
m_liquid_width = 0;
m_liquid_height = 0;
m_liquidLevel = INVALID_HEIGHT_VALUE;
m_liquid_type = NULL;
m_liquid_map = NULL;
}
GridMap::~GridMap()
{
unloadData();
}
bool GridMap::loadData(char *filename)
{
// Unload old data if exist
unloadData();
GridMapFileHeader header;
// Not return error if file not found
FILE *in = fopen(filename, "rb");
if (!in)
return true;
fread(&header, sizeof(header),1,in);
if (header.mapMagic == *((uint32 const*)(MAP_MAGIC)) &&
header.versionMagic == *((uint32 const*)(MAP_VERSION_MAGIC)))
{
// loadup area data
if (header.areaMapOffset && !loadAreaData(in, header.areaMapOffset, header.areaMapSize))
{
sLog.outError("Error loading map area data\n");
fclose(in);
return false;
}
// loadup height data
if (header.heightMapOffset && !loadHeightData(in, header.heightMapOffset, header.heightMapSize))
{
sLog.outError("Error loading map height data\n");
fclose(in);
return false;
}
// loadup liquid data
if (header.liquidMapOffset && !loadGridMapLiquidData(in, header.liquidMapOffset, header.liquidMapSize))
{
sLog.outError("Error loading map liquids data\n");
fclose(in);
return false;
}
fclose(in);
return true;
}
sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.", filename);
fclose(in);
return false;
}
void GridMap::unloadData()
{
if (m_area_map)
delete[] m_area_map;
if (m_V9)
delete[] m_V9;
if (m_V8)
delete[] m_V8;
if (m_liquid_type)
delete[] m_liquid_type;
if (m_liquid_map)
delete[] m_liquid_map;
m_area_map = NULL;
m_V9 = NULL;
m_V8 = NULL;
m_liquid_type = NULL;
m_liquid_map = NULL;
m_gridGetHeight = &GridMap::getHeightFromFlat;
}
bool GridMap::loadAreaData(FILE *in, uint32 offset, uint32 /*size*/)
{
GridMapAreaHeader header;
fseek(in, offset, SEEK_SET);
fread(&header, sizeof(header), 1, in);
if (header.fourcc != *((uint32 const*)(MAP_AREA_MAGIC)))
return false;
m_gridArea = header.gridArea;
if (!(header.flags & MAP_AREA_NO_AREA))
{
m_area_map = new uint16 [16*16];
fread(m_area_map, sizeof(uint16), 16*16, in);
}
return true;
}
bool GridMap::loadHeightData(FILE *in, uint32 offset, uint32 /*size*/)
{
GridMapHeightHeader header;
fseek(in, offset, SEEK_SET);
fread(&header, sizeof(header), 1, in);
if (header.fourcc != *((uint32 const*)(MAP_HEIGHT_MAGIC)))
return false;
m_gridHeight = header.gridHeight;
if (!(header.flags & MAP_HEIGHT_NO_HEIGHT))
{
if ((header.flags & MAP_HEIGHT_AS_INT16))
{
m_uint16_V9 = new uint16 [129*129];
m_uint16_V8 = new uint16 [128*128];
fread(m_uint16_V9, sizeof(uint16), 129*129, in);
fread(m_uint16_V8, sizeof(uint16), 128*128, in);
m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 65535;
m_gridGetHeight = &GridMap::getHeightFromUint16;
}
else if ((header.flags & MAP_HEIGHT_AS_INT8))
{
m_uint8_V9 = new uint8 [129*129];
m_uint8_V8 = new uint8 [128*128];
fread(m_uint8_V9, sizeof(uint8), 129*129, in);
fread(m_uint8_V8, sizeof(uint8), 128*128, in);
m_gridIntHeightMultiplier = (header.gridMaxHeight - header.gridHeight) / 255;
m_gridGetHeight = &GridMap::getHeightFromUint8;
}
else
{
m_V9 = new float [129*129];
m_V8 = new float [128*128];
fread(m_V9, sizeof(float), 129*129, in);
fread(m_V8, sizeof(float), 128*128, in);
m_gridGetHeight = &GridMap::getHeightFromFloat;
}
}
else
m_gridGetHeight = &GridMap::getHeightFromFlat;
return true;
}
bool GridMap::loadGridMapLiquidData(FILE *in, uint32 offset, uint32 /*size*/)
{
GridMapLiquidHeader header;
fseek(in, offset, SEEK_SET);
fread(&header, sizeof(header), 1, in);
if (header.fourcc != *((uint32 const*)(MAP_LIQUID_MAGIC)))
return false;
m_liquidType = header.liquidType;
m_liquid_offX = header.offsetX;
m_liquid_offY = header.offsetY;
m_liquid_width = header.width;
m_liquid_height = header.height;
m_liquidLevel = header.liquidLevel;
if (!(header.flags & MAP_LIQUID_NO_TYPE))
{
m_liquid_type = new uint8 [16*16];
fread(m_liquid_type, sizeof(uint8), 16*16, in);
}
if (!(header.flags & MAP_LIQUID_NO_HEIGHT))
{
m_liquid_map = new float [m_liquid_width*m_liquid_height];
fread(m_liquid_map, sizeof(float), m_liquid_width*m_liquid_height, in);
}
return true;
}
uint16 GridMap::getArea(float x, float y)
{
if (!m_area_map)
return m_gridArea;
x = 16 * (32 - x/SIZE_OF_GRIDS);
y = 16 * (32 - y/SIZE_OF_GRIDS);
int lx = (int)x & 15;
int ly = (int)y & 15;
return m_area_map[lx*16 + ly];
}
float GridMap::getHeightFromFlat(float /*x*/, float /*y*/) const
{
return m_gridHeight;
}
float GridMap::getHeightFromFloat(float x, float y) const
{
if (!m_V8 || !m_V9)
return m_gridHeight;
x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int x_int = (int)x;
int y_int = (int)y;
x -= x_int;
y -= y_int;
x_int &= (MAP_RESOLUTION - 1);
y_int &= (MAP_RESOLUTION - 1);
// Height stored as: h5 - its v8 grid, h1-h4 - its v9 grid
// +--------------> X
// | h1-------h2 Coordinates is:
// | | \ 1 / | h1 0,0
// | | \ / | h2 0,1
// | | 2 h5 3 | h3 1,0
// | | / \ | h4 1,1
// | | / 4 \ | h5 1/2,1/2
// | h3-------h4
// V Y
// For find height need
// 1 - detect triangle
// 2 - solve linear equation from triangle points
// Calculate coefficients for solve h = a*x + b*y + c
float a,b,c;
// Select triangle:
if (x+y < 1)
{
if (x > y)
{
// 1 triangle (h1, h2, h5 points)
float h1 = m_V9[(x_int )*129 + y_int];
float h2 = m_V9[(x_int+1)*129 + y_int];
float h5 = 2 * m_V8[x_int*128 + y_int];
a = h2-h1;
b = h5-h1-h2;
c = h1;
}
else
{
// 2 triangle (h1, h3, h5 points)
float h1 = m_V9[x_int*129 + y_int ];
float h3 = m_V9[x_int*129 + y_int+1];
float h5 = 2 * m_V8[x_int*128 + y_int];
a = h5 - h1 - h3;
b = h3 - h1;
c = h1;
}
}
else
{
if (x > y)
{
// 3 triangle (h2, h4, h5 points)
float h2 = m_V9[(x_int+1)*129 + y_int ];
float h4 = m_V9[(x_int+1)*129 + y_int+1];
float h5 = 2 * m_V8[x_int*128 + y_int];
a = h2 + h4 - h5;
b = h4 - h2;
c = h5 - h4;
}
else
{
// 4 triangle (h3, h4, h5 points)
float h3 = m_V9[(x_int )*129 + y_int+1];
float h4 = m_V9[(x_int+1)*129 + y_int+1];
float h5 = 2 * m_V8[x_int*128 + y_int];
a = h4 - h3;
b = h3 + h4 - h5;
c = h5 - h4;
}
}
// Calculate height
return a * x + b * y + c;
}
float GridMap::getHeightFromUint8(float x, float y) const
{
if (!m_uint8_V8 || !m_uint8_V9)
return m_gridHeight;
x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int x_int = (int)x;
int y_int = (int)y;
x -= x_int;
y -= y_int;
x_int &= (MAP_RESOLUTION - 1);
y_int &= (MAP_RESOLUTION - 1);
int32 a, b, c;
uint8 *V9_h1_ptr = &m_uint8_V9[x_int*128 + x_int + y_int];
if (x+y < 1)
{
if (x > y)
{
// 1 triangle (h1, h2, h5 points)
int32 h1 = V9_h1_ptr[ 0];
int32 h2 = V9_h1_ptr[129];
int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
a = h2-h1;
b = h5-h1-h2;
c = h1;
}
else
{
// 2 triangle (h1, h3, h5 points)
int32 h1 = V9_h1_ptr[0];
int32 h3 = V9_h1_ptr[1];
int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
a = h5 - h1 - h3;
b = h3 - h1;
c = h1;
}
}
else
{
if (x > y)
{
// 3 triangle (h2, h4, h5 points)
int32 h2 = V9_h1_ptr[129];
int32 h4 = V9_h1_ptr[130];
int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
a = h2 + h4 - h5;
b = h4 - h2;
c = h5 - h4;
}
else
{
// 4 triangle (h3, h4, h5 points)
int32 h3 = V9_h1_ptr[ 1];
int32 h4 = V9_h1_ptr[130];
int32 h5 = 2 * m_uint8_V8[x_int*128 + y_int];
a = h4 - h3;
b = h3 + h4 - h5;
c = h5 - h4;
}
}
// Calculate height
return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight;
}
float GridMap::getHeightFromUint16(float x, float y) const
{
if (!m_uint16_V8 || !m_uint16_V9)
return m_gridHeight;
x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int x_int = (int)x;
int y_int = (int)y;
x -= x_int;
y -= y_int;
x_int &= (MAP_RESOLUTION - 1);
y_int &= (MAP_RESOLUTION - 1);
int32 a, b, c;
uint16 *V9_h1_ptr = &m_uint16_V9[x_int*128 + x_int + y_int];
if (x+y < 1)
{
if (x > y)
{
// 1 triangle (h1, h2, h5 points)
int32 h1 = V9_h1_ptr[ 0];
int32 h2 = V9_h1_ptr[129];
int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
a = h2-h1;
b = h5-h1-h2;
c = h1;
}
else
{
// 2 triangle (h1, h3, h5 points)
int32 h1 = V9_h1_ptr[0];
int32 h3 = V9_h1_ptr[1];
int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
a = h5 - h1 - h3;
b = h3 - h1;
c = h1;
}
}
else
{
if (x > y)
{
// 3 triangle (h2, h4, h5 points)
int32 h2 = V9_h1_ptr[129];
int32 h4 = V9_h1_ptr[130];
int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
a = h2 + h4 - h5;
b = h4 - h2;
c = h5 - h4;
}
else
{
// 4 triangle (h3, h4, h5 points)
int32 h3 = V9_h1_ptr[ 1];
int32 h4 = V9_h1_ptr[130];
int32 h5 = 2 * m_uint16_V8[x_int*128 + y_int];
a = h4 - h3;
b = h3 + h4 - h5;
c = h5 - h4;
}
}
// Calculate height
return (float)((a * x) + (b * y) + c)*m_gridIntHeightMultiplier + m_gridHeight;
}
float GridMap::getLiquidLevel(float x, float y)
{
if (!m_liquid_map)
return m_liquidLevel;
x = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
y = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int cx_int = ((int)x & (MAP_RESOLUTION-1)) - m_liquid_offY;
int cy_int = ((int)y & (MAP_RESOLUTION-1)) - m_liquid_offX;
if (cx_int < 0 || cx_int >=m_liquid_height)
return INVALID_HEIGHT_VALUE;
if (cy_int < 0 || cy_int >=m_liquid_width )
return INVALID_HEIGHT_VALUE;
return m_liquid_map[cx_int*m_liquid_width + cy_int];
}
uint8 GridMap::getTerrainType(float x, float y)
{
if (!m_liquid_type)
return (uint8)m_liquidType;
x = 16 * (32 - x/SIZE_OF_GRIDS);
y = 16 * (32 - y/SIZE_OF_GRIDS);
int lx = (int)x & 15;
int ly = (int)y & 15;
return m_liquid_type[lx*16 + ly];
}
// Get water state on map
GridMapLiquidStatus GridMap::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, GridMapLiquidData *data)
{
// Check water type (if no water return)
if (!m_liquid_type && !m_liquidType)
return LIQUID_MAP_NO_WATER;
// Get cell
float cx = MAP_RESOLUTION * (32 - x/SIZE_OF_GRIDS);
float cy = MAP_RESOLUTION * (32 - y/SIZE_OF_GRIDS);
int x_int = (int)cx & (MAP_RESOLUTION-1);
int y_int = (int)cy & (MAP_RESOLUTION-1);
// Check water type in cell
uint8 type = m_liquid_type ? m_liquid_type[(x_int>>3)*16 + (y_int>>3)] : m_liquidType;
if (type == 0)
return LIQUID_MAP_NO_WATER;
// Check req liquid type mask
if (ReqLiquidType && !(ReqLiquidType&type))
return LIQUID_MAP_NO_WATER;
// Check water level:
// Check water height map
int lx_int = x_int - m_liquid_offY;
if (lx_int < 0 || lx_int >=m_liquid_height)
return LIQUID_MAP_NO_WATER;
int ly_int = y_int - m_liquid_offX;
if (ly_int < 0 || ly_int >=m_liquid_width )
return LIQUID_MAP_NO_WATER;
// Get water level
float liquid_level = m_liquid_map ? m_liquid_map[lx_int*m_liquid_width + ly_int] : m_liquidLevel;
// Get ground level (sub 0.2 for fix some errors)
float ground_level = getHeight(x, y);
// Check water level and ground level
if (liquid_level < ground_level || z < ground_level - 2)
return LIQUID_MAP_NO_WATER;
// All ok in water -> store data
if (data)
{
data->type = type;
data->level = liquid_level;
data->depth_level = ground_level;
}
// For speed check as int values
int delta = int((liquid_level - z) * 10);
// Get position delta
if (delta > 20) // Under water
return LIQUID_MAP_UNDER_WATER;
if (delta > 0 ) // In water
return LIQUID_MAP_IN_WATER;
if (delta > -1) // Walk on water
return LIQUID_MAP_WATER_WALK;
// Above water
return LIQUID_MAP_ABOVE_WATER;
}
bool GridMap::ExistMap(uint32 mapid,int gx,int gy)
{
int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
char* tmp = new char[len];
snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),mapid,gx,gy);
FILE *pf=fopen(tmp,"rb");
if(!pf)
{
sLog.outError("Check existing of map file '%s': not exist!",tmp);
delete[] tmp;
return false;
}
GridMapFileHeader header;
fread(&header, sizeof(header), 1, pf);
if (header.mapMagic != *((uint32 const*)(MAP_MAGIC)) ||
header.versionMagic != *((uint32 const*)(MAP_VERSION_MAGIC)))
{
sLog.outError("Map file '%s' is non-compatible version (outdated?). Please, create new using ad.exe program.",tmp);
delete [] tmp;
fclose(pf); //close file before return
return false;
}
delete [] tmp;
fclose(pf);
return true;
}
bool GridMap::ExistVMap(uint32 mapid,int gx,int gy)
{
if(VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager())
{
if(vmgr->isMapLoadingEnabled())
{
// x and y are swapped !! => fixed now
bool exists = vmgr->existsMap((sWorld.GetDataPath()+ "vmaps").c_str(), mapid, gx,gy);
if(!exists)
{
std::string name = vmgr->getDirFileName(mapid,gx,gy);
sLog.outError("VMap file '%s' is missing or point to wrong version vmap file, redo vmaps with latest vmap_assembler.exe program", (sWorld.GetDataPath()+"vmaps/"+name).c_str());
return false;
}
}
}
return true;
}
//////////////////////////////////////////////////////////////////////////
TerrainInfo::TerrainInfo(uint32 mapid) : m_mapId(mapid)
{
for (int k = 0; k < MAX_NUMBER_OF_GRIDS; ++k)
{
for (int i = 0; i < MAX_NUMBER_OF_GRIDS; ++i)
{
m_GridMaps[i][k] = NULL;
m_GridRef[i][k] = 0;
}
}
//clean up GridMap objects every minute
const uint32 iCleanUpInterval = 60;
//schedule start randlomly
const uint32 iRandomStart = urand(20, 40);
i_timer.SetInterval(iCleanUpInterval * 1000);
i_timer.SetCurrent(iRandomStart * 1000);
}
TerrainInfo::~TerrainInfo()
{
for (int k = 0; k < MAX_NUMBER_OF_GRIDS; ++k)
for (int i = 0; i < MAX_NUMBER_OF_GRIDS; ++i)
delete m_GridMaps[i][k];
VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(m_mapId);
}
GridMap * TerrainInfo::Load(const uint32 x, const uint32 y)
{
MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS);
MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS);
//reference grid as a first step
RefGrid(x, y);
//quick check if GridMap already loaded
GridMap * pMap = m_GridMaps[x][y];
if(!pMap)
pMap = LoadMapAndVMap(x, y);
return pMap;
}
//schedule lazy GridMap object cleanup
void TerrainInfo::Unload(const uint32 x, const uint32 y)
{
MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS);
MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS);
if(m_GridMaps[x][y])
{
//decrease grid reference count...
if(UnrefGrid(x, y) == 0)
{
//TODO: add your additional logic here
}
}
}
//call this method only
void TerrainInfo::CleanUpGrids(const uint32 diff)
{
i_timer.Update(diff);
if( !i_timer.Passed() )
return;
for (int y = 0; y < MAX_NUMBER_OF_GRIDS; ++y)
{
for (int x = 0; x < MAX_NUMBER_OF_GRIDS; ++x)
{
const int16& iRef = m_GridRef[x][y];
GridMap * pMap = m_GridMaps[x][y];
//delete those GridMap objects which have refcount = 0
if(pMap && iRef == 0 )
{
m_GridMaps[x][y] = NULL;
//delete grid data if reference count == 0
pMap->unloadData();
delete pMap;
//unload VMAPS...
VMAP::VMapFactory::createOrGetVMapManager()->unloadMap(m_mapId, x, y);
}
}
}
i_timer.Reset();
}
int TerrainInfo::RefGrid(const uint32& x, const uint32& y)
{
MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS);
MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS);
LOCK_GUARD _lock(m_refMutex);
return (m_GridRef[x][y] += 1);
}
int TerrainInfo::UnrefGrid(const uint32& x, const uint32& y)
{
MANGOS_ASSERT(x < MAX_NUMBER_OF_GRIDS);
MANGOS_ASSERT(y < MAX_NUMBER_OF_GRIDS);
int16& iRef = m_GridRef[x][y];
LOCK_GUARD _lock(m_refMutex);
if(iRef > 0)
return (iRef -= 1);
return 0;
}
float TerrainInfo::GetHeight(float x, float y, float z, bool pUseVmaps, float maxSearchDist) const
{
// find raw .map surface under Z coordinates
float mapHeight;
float z2 = z + 2.f;
if (GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y))
{
float _mapheight = gmap->getHeight(x,y);
// look from a bit higher pos to find the floor, ignore under surface case
if (z2 > _mapheight)
mapHeight = _mapheight;
else
mapHeight = VMAP_INVALID_HEIGHT_VALUE;
}
else
mapHeight = VMAP_INVALID_HEIGHT_VALUE;
float vmapHeight;
if (pUseVmaps)
{
VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
if (vmgr->isHeightCalcEnabled())
{
// if mapHeight has been found search vmap height at least until mapHeight point
// this prevent case when original Z "too high above ground and vmap height search fail"
// this will not affect most normal cases (no map in instance, or stay at ground at continent)
if (mapHeight > INVALID_HEIGHT && z2 - mapHeight > maxSearchDist)
maxSearchDist = z2 - mapHeight + 1.0f; // 1.0 make sure that we not fail for case when map height near but above for vamp height
// look from a bit higher pos to find the floor
vmapHeight = vmgr->getHeight(GetMapId(), x, y, z2, maxSearchDist);
}
else
vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
}
else
vmapHeight = VMAP_INVALID_HEIGHT_VALUE;
// mapHeight set for any above raw ground Z or <= INVALID_HEIGHT
// vmapheight set for any under Z value or <= INVALID_HEIGHT
if (vmapHeight > INVALID_HEIGHT)
{
if (mapHeight > INVALID_HEIGHT)
{
// we have mapheight and vmapheight and must select more appropriate
// we are already under the surface or vmap height above map heigt
// or if the distance of the vmap height is less the land height distance
if (z < mapHeight || vmapHeight > mapHeight || fabs(mapHeight-z) > fabs(vmapHeight-z))
return vmapHeight;
else
return mapHeight; // better use .map surface height
}
else
return vmapHeight; // we have only vmapHeight (if have)
}
return mapHeight;
}
inline bool IsOutdoorWMO(uint32 mogpFlags)
{
return mogpFlags & 0x8008;
}
bool TerrainInfo::IsOutdoors(float x, float y, float z) const
{
uint32 mogpFlags;
int32 adtId, rootId, groupId;
// no wmo found? -> outside by default
if(!GetAreaInfo(x, y, z, mogpFlags, adtId, rootId, groupId))
return true;
return IsOutdoorWMO(mogpFlags);
}
bool TerrainInfo::GetAreaInfo(float x, float y, float z, uint32 &flags, int32 &adtId, int32 &rootId, int32 &groupId) const
{
float vmap_z = z;
VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
if (vmgr->getAreaInfo(GetMapId(), x, y, vmap_z, flags, adtId, rootId, groupId))
{
// check if there's terrain between player height and object height
if(GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y))
{
float _mapheight = gmap->getHeight(x,y);
// z + 2.0f condition taken from GetHeight(), not sure if it's such a great choice...
if(z + 2.0f > _mapheight && _mapheight > vmap_z)
return false;
}
return true;
}
return false;
}
uint16 TerrainInfo::GetAreaFlag(float x, float y, float z, bool *isOutdoors) const
{
uint32 mogpFlags;
int32 adtId, rootId, groupId;
WMOAreaTableEntry const* wmoEntry = 0;
AreaTableEntry const* atEntry = 0;
bool haveAreaInfo = false;
if(GetAreaInfo(x, y, z, mogpFlags, adtId, rootId, groupId))
{
haveAreaInfo = true;
wmoEntry = GetWMOAreaTableEntryByTripple(rootId, adtId, groupId);
if(wmoEntry)
atEntry = GetAreaEntryByAreaID(wmoEntry->areaId);
}
uint16 areaflag;
if (atEntry)
areaflag = atEntry->exploreFlag;
else
{
if(GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y))
areaflag = gmap->getArea(x, y);
// this used while not all *.map files generated (instances)
else
areaflag = GetAreaFlagByMapId(GetMapId());
}
if (isOutdoors)
{
if (haveAreaInfo)
*isOutdoors = IsOutdoorWMO(mogpFlags);
else
*isOutdoors = true;
}
return areaflag;
}
uint8 TerrainInfo::GetTerrainType(float x, float y ) const
{
if(GridMap *gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y))
return gmap->getTerrainType(x, y);
else
return 0;
}
uint32 TerrainInfo::GetAreaId(float x, float y, float z) const
{
return TerrainManager::GetAreaIdByAreaFlag(GetAreaFlag(x,y,z),m_mapId);
}
uint32 TerrainInfo::GetZoneId(float x, float y, float z) const
{
return TerrainManager::GetZoneIdByAreaFlag(GetAreaFlag(x,y,z),m_mapId);
}
void TerrainInfo::GetZoneAndAreaId(uint32& zoneid, uint32& areaid, float x, float y, float z) const
{
TerrainManager::GetZoneAndAreaIdByAreaFlag(zoneid,areaid,GetAreaFlag(x,y,z),m_mapId);
}
GridMapLiquidStatus TerrainInfo::getLiquidStatus(float x, float y, float z, uint8 ReqLiquidType, GridMapLiquidData *data) const
{
GridMapLiquidStatus result = LIQUID_MAP_NO_WATER;
VMAP::IVMapManager* vmgr = VMAP::VMapFactory::createOrGetVMapManager();
float liquid_level, ground_level = INVALID_HEIGHT_VALUE;
uint32 liquid_type;
if (vmgr->GetLiquidLevel(GetMapId(), x, y, z, ReqLiquidType, liquid_level, ground_level, liquid_type))
{
DEBUG_LOG("getLiquidStatus(): vmap liquid level: %f ground: %f type: %u", liquid_level, ground_level, liquid_type);
// Check water level and ground level
if (liquid_level > ground_level && z > ground_level - 2)
{
// All ok in water -> store data
if (data)
{
data->type = liquid_type;
data->level = liquid_level;
data->depth_level = ground_level;
}
// For speed check as int values
int delta = int((liquid_level - z) * 10);
// Get position delta
if (delta > 20) // Under water
return LIQUID_MAP_UNDER_WATER;
if (delta > 0 ) // In water
return LIQUID_MAP_IN_WATER;
if (delta > -1) // Walk on water
return LIQUID_MAP_WATER_WALK;
result = LIQUID_MAP_ABOVE_WATER;
}
}
if(GridMap* gmap = const_cast<TerrainInfo*>(this)->GetGrid(x, y))
{
GridMapLiquidData map_data;
GridMapLiquidStatus map_result = gmap->getLiquidStatus(x, y, z, ReqLiquidType, &map_data);
// Not override LIQUID_MAP_ABOVE_WATER with LIQUID_MAP_NO_WATER:
if (map_result != LIQUID_MAP_NO_WATER && (map_data.level > ground_level))
{
if (data)
*data = map_data;
return map_result;
}
}
return result;
}
bool TerrainInfo::IsInWater(float x, float y, float pZ, GridMapLiquidData *data) const
{
// Check surface in x, y point for liquid
if (const_cast<TerrainInfo*>(this)->GetGrid(x, y))
{
GridMapLiquidData liquid_status;
GridMapLiquidData *liquid_ptr = data ? data : &liquid_status;
if (getLiquidStatus(x, y, pZ, MAP_ALL_LIQUIDS, liquid_ptr))
{
//if (liquid_prt->level - liquid_prt->depth_level > 2) //???
return true;
}
}
return false;
}
bool TerrainInfo::IsUnderWater(float x, float y, float z) const
{
if (const_cast<TerrainInfo*>(this)->GetGrid(x, y))
{
if (getLiquidStatus(x, y, z, MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN)&LIQUID_MAP_UNDER_WATER)
return true;
}
return false;
}
/**
* Function find higher form water or ground height for current floor
*
* @param x, y, z Coordinates original point at floor level
*
* @param pGround optional arg for retrun calculated by function work ground height, it let avoid in caller code recalculate height for point if it need
*
* @param swim z coordinate can be calculated for select above/at or under z coordinate (for fly or swim/walking by bottom)
* in last cases for in water returned under water height for avoid client set swimming unit as saty at water.
*
* @return calculated z coordinate
*/
float TerrainInfo::GetWaterOrGroundLevel(float x, float y, float z, float* pGround /*= NULL*/, bool swim /*= false*/) const
{
if (const_cast<TerrainInfo*>(this)->GetGrid(x, y))
{
// we need ground level (including grid height version) for proper return water level in point
float ground_z = GetHeight(x, y, z, true, DEFAULT_WATER_SEARCH);
if (pGround)
*pGround = ground_z + 0.05f;
GridMapLiquidData liquid_status;
GridMapLiquidStatus res = getLiquidStatus(x, y, ground_z, MAP_ALL_LIQUIDS, &liquid_status);
return res ? ( swim ? liquid_status.level - 2.0f : liquid_status.level) : ground_z + 0.05f;
}
return VMAP_INVALID_HEIGHT_VALUE;
}
GridMap * TerrainInfo::GetGrid( const float x, const float y )
{
// half opt method
int gx=(int)(32-x/SIZE_OF_GRIDS); //grid x
int gy=(int)(32-y/SIZE_OF_GRIDS); //grid y
//quick check if GridMap already loaded
GridMap * pMap = m_GridMaps[gx][gy];
if(!pMap)
pMap = LoadMapAndVMap(gx, gy);
return pMap;
}
GridMap * TerrainInfo::LoadMapAndVMap( const uint32 x, const uint32 y )
{
//double checked lock pattern
if(!m_GridMaps[x][y])
{
LOCK_GUARD lock(m_mutex);
if(!m_GridMaps[x][y])
{
GridMap * map = new GridMap();
// map file name
char *tmp=NULL;
int len = sWorld.GetDataPath().length()+strlen("maps/%03u%02u%02u.map")+1;
tmp = new char[len];
snprintf(tmp, len, (char *)(sWorld.GetDataPath()+"maps/%03u%02u%02u.map").c_str(),m_mapId, x, y);
sLog.outDetail("Loading map %s",tmp);
if(!map->loadData(tmp))
{
sLog.outError("Error load map file: \n %s\n", tmp);
//ASSERT(false);
}
delete [] tmp;
m_GridMaps[x][y] = map;
//load VMAPs for current map/grid...
const MapEntry * i_mapEntry = sMapStore.LookupEntry(m_mapId);
const char* mapName = i_mapEntry ? i_mapEntry->name[sWorld.GetDefaultDbcLocale()] : "UNNAMEDMAP\x0";
int vmapLoadResult = VMAP::VMapFactory::createOrGetVMapManager()->loadMap((sWorld.GetDataPath()+ "vmaps").c_str(), m_mapId, x, y);
switch(vmapLoadResult)
{
case VMAP::VMAP_LOAD_RESULT_OK:
sLog.outDetail("VMAP loaded name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", mapName, m_mapId, x,y,x,y);
break;
case VMAP::VMAP_LOAD_RESULT_ERROR:
sLog.outDetail("Could not load VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", mapName, m_mapId, x,y,x,y);
break;
case VMAP::VMAP_LOAD_RESULT_IGNORED:
DEBUG_LOG("Ignored VMAP name:%s, id:%d, x:%d, y:%d (vmap rep.: x:%d, y:%d)", mapName, m_mapId, x,y,x,y);
break;
}
}
}
return m_GridMaps[x][y];
}
float TerrainInfo::GetWaterLevel(float x, float y, float z, float* pGround /*= NULL*/) const
{
if (const_cast<TerrainInfo*>(this)->GetGrid(x, y))
{
// we need ground level (including grid height version) for proper return water level in point
float ground_z = GetHeight(x, y, z, true, DEFAULT_WATER_SEARCH);
if (pGround)
*pGround = ground_z;
GridMapLiquidData liquid_status;
GridMapLiquidStatus res = getLiquidStatus(x, y, ground_z, MAP_ALL_LIQUIDS, &liquid_status);
if (!res)
return VMAP_INVALID_HEIGHT_VALUE;
return liquid_status.level;
}
return VMAP_INVALID_HEIGHT_VALUE;
}
//////////////////////////////////////////////////////////////////////////
#define CLASS_LOCK MaNGOS::ClassLevelLockable<TerrainManager, ACE_Thread_Mutex>
INSTANTIATE_SINGLETON_2(TerrainManager, CLASS_LOCK);
INSTANTIATE_CLASS_MUTEX(TerrainManager, ACE_Thread_Mutex);
TerrainManager::TerrainManager()
{
}
TerrainManager::~TerrainManager()
{
for (TerrainDataMap::iterator it = i_TerrainMap.begin(); it != i_TerrainMap.end(); ++it)
delete it->second;
}
TerrainInfo * TerrainManager::LoadTerrain(const uint32 mapId)
{
Guard _guard(*this);
TerrainInfo * ptr = NULL;
TerrainDataMap::const_iterator iter = i_TerrainMap.find(mapId);
if(iter == i_TerrainMap.end())
{
ptr = new TerrainInfo(mapId);
i_TerrainMap[mapId] = ptr;
}
else
ptr = (*iter).second;
return ptr;
}
void TerrainManager::UnloadTerrain(const uint32 mapId)
{
if(sWorld.getConfig(CONFIG_BOOL_GRID_UNLOAD) == 0)
return;
Guard _guard(*this);
TerrainDataMap::iterator iter = i_TerrainMap.find(mapId);
if(iter != i_TerrainMap.end())
{
TerrainInfo * ptr = (*iter).second;
//lets check if this object can be actually freed
if(ptr->IsReferenced() == false)
{
i_TerrainMap.erase(iter);
delete ptr;
}
}
}
void TerrainManager::Update(const uint32 diff)
{
//global garbage collection for GridMap objects and VMaps
for (TerrainDataMap::iterator iter = i_TerrainMap.begin(); iter != i_TerrainMap.end(); ++iter)
iter->second->CleanUpGrids(diff);
}
void TerrainManager::UnloadAll()
{
for (TerrainDataMap::iterator it = i_TerrainMap.begin(); it != i_TerrainMap.end(); ++it)
delete it->second;
i_TerrainMap.clear();
}
uint32 TerrainManager::GetAreaIdByAreaFlag(uint16 areaflag,uint32 map_id)
{
AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
if (entry)
return entry->ID;
else
return 0;
}
uint32 TerrainManager::GetZoneIdByAreaFlag(uint16 areaflag,uint32 map_id)
{
AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
if( entry )
return ( entry->zone != 0 ) ? entry->zone : entry->ID;
else
return 0;
}
void TerrainManager::GetZoneAndAreaIdByAreaFlag(uint32& zoneid, uint32& areaid, uint16 areaflag,uint32 map_id)
{
AreaTableEntry const *entry = GetAreaEntryByAreaFlagAndMap(areaflag,map_id);
areaid = entry ? entry->ID : 0;
zoneid = entry ? (( entry->zone != 0 ) ? entry->zone : entry->ID) : 0;
}
| vanilla-wow/MaNGOSZero | src/game/GridMap.cpp | C++ | gpl-2.0 | 35,544 |
<?php declare(strict_types=1);
namespace mglaman\PHPStanDrupal\Rules\Drupal;
use Drupal\Core\Extension\ModuleHandlerInterface;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\ShouldNotHappenException;
use PHPStan\Type\ObjectType;
class LoadIncludes extends LoadIncludeBase
{
public function getNodeType(): string
{
return Node\Expr\MethodCall::class;
}
public function processNode(Node $node, Scope $scope): array
{
assert($node instanceof Node\Expr\MethodCall);
if (!$node->name instanceof Node\Identifier) {
return [];
}
$method_name = $node->name->toString();
if ($method_name !== 'loadInclude') {
return [];
}
$args = $node->getArgs();
if (\count($args) < 2) {
return [];
}
$variable = $node->var;
if (!$variable instanceof Node\Expr\Variable) {
return [];
}
$var_name = $variable->name;
if (!is_string($var_name)) {
throw new ShouldNotHappenException(sprintf('Expected string for variable in %s, please open an issue on GitHub https://github.com/mglaman/phpstan-drupal/issues', static::class));
}
$moduleHandlerInterfaceType = new ObjectType(ModuleHandlerInterface::class);
$variableType = $scope->getVariableType($var_name);
if (!$variableType->isSuperTypeOf($moduleHandlerInterfaceType)->yes()) {
return [];
}
try {
// Try to invoke it similarly as the module handler itself.
[$moduleName, $filename] = $this->parseLoadIncludeArgs($args[0], $args[1], $args[2] ?? null, $scope);
$module = $this->extensionMap->getModule($moduleName);
if ($module === null) {
return [
RuleErrorBuilder::message(sprintf(
'File %s could not be loaded from %s::loadInclude because %s module is not found.',
$filename,
ModuleHandlerInterface::class,
$moduleName
))
->line($node->getLine())
->build()
];
}
$file = $module->getAbsolutePath() . DIRECTORY_SEPARATOR . $filename;
if (is_file($file)) {
require_once $file;
return [];
}
return [
RuleErrorBuilder::message(sprintf(
'File %s could not be loaded from %s::loadInclude',
$module->getPath() . DIRECTORY_SEPARATOR . $filename,
ModuleHandlerInterface::class
))
->line($node->getLine())
->build()
];
} catch (\Throwable $e) {
return [
RuleErrorBuilder::message(sprintf(
'A file could not be loaded from %s::loadInclude',
ModuleHandlerInterface::class
))
->line($node->getLine())
->build()
];
}
}
}
| mamont77/easydrupal | vendor/mglaman/phpstan-drupal/src/Rules/Drupal/LoadIncludes.php | PHP | gpl-2.0 | 3,204 |
/*
* Animation plugin for compiz/beryl
*
* animation.c
*
* Copyright : (C) 2006 Erkin Bahceci
* E-mail : erkinbah@gmail.com
*
* Based on Wobbly and Minimize plugins by
* : David Reveman
* E-mail : davidr@novell.com>
*
* Particle system added by : (C) 2006 Dennis Kasprzyk
* E-mail : onestone@beryl-project.org
*
* Beam-Up added by : Florencio Guimaraes
* E-mail : florencio@nexcorp.com.br
*
* Hexagon tessellator added by : Mike Slegeir
* E-mail : mikeslegeir@mail.utexas.edu>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "private.h"
// ===================== Effect: Leaf Spread =========================
const float LeafSpreadAnim::kDurationFactor = 1.67;
LeafSpreadAnim::LeafSpreadAnim (CompWindow *w,
WindowEvent curWindowEvent,
float duration,
const AnimEffect info,
const CompRect &icon) :
Animation::Animation (w, curWindowEvent, kDurationFactor * duration, info,
icon),
PolygonAnim::PolygonAnim (w, curWindowEvent, kDurationFactor * duration,
info, icon)
{
mDoDepthTest = true;
mDoLighting = true;
mCorrectPerspective = CorrectPerspectivePolygon;
}
void
LeafSpreadAnim::init ()
{
if (!tessellateIntoRectangles (20, 14, 15.0f))
return;
CompRect outRect (mAWindow->savedRectsValid () ?
mAWindow->savedOutRect () :
mWindow->outputRect ());
float fadeDuration = 0.26;
float life = 0.4;
float spreadFac = 3.5;
float randYMax = 0.07;
float winFacX = outRect.width () / 800.0;
float winFacY = outRect.height () / 800.0;
float winFacZ = (outRect.height () + outRect.width ()) / 2.0 / 800.0;
float screenSizeFactor = (0.8 * DEFAULT_Z_CAMERA * ::screen->width ());
foreach (PolygonObject *p, mPolygons)
{
p->rotAxis.set (RAND_FLOAT (), RAND_FLOAT (), RAND_FLOAT ());
float speed = screenSizeFactor / 10 * (0.2 + RAND_FLOAT ());
float xx = 2 * (p->centerRelPos.x () - 0.5);
float yy = 2 * (p->centerRelPos.y () - 0.5);
float x = speed * winFacX * spreadFac * (xx +
0.5 * (RAND_FLOAT () - 0.5));
float y = speed * winFacY * spreadFac * (yy +
0.5 * (RAND_FLOAT () - 0.5));
float z = speed * winFacZ * 7 * ((RAND_FLOAT () - 0.5) / 0.5);
p->finalRelPos.set (x, y, z);
p->moveStartTime =
p->centerRelPos.y () * (1 - fadeDuration - randYMax) +
randYMax * RAND_FLOAT ();
p->moveDuration = 1;
p->fadeStartTime = p->moveStartTime + life;
if (p->fadeStartTime > 1 - fadeDuration)
p->fadeStartTime = 1 - fadeDuration;
p->fadeDuration = fadeDuration;
p->finalRotAng = 150;
}
}
| hedmo/compiz-plugins-extra | animationaddon/src/leafspread.cpp | C++ | gpl-2.0 | 3,316 |
<?php
/**
* Sets the body-tag class attribute.
*
* Adds 'sidebar-left', 'sidebar-right' or 'sidebars' classes as needed.
*/
function phptemplate_body_class($left, $right) {
if ($left != '' && $right != '') {
$class = 'sidebars';
}
else {
if ($left != '') {
$class = 'sidebar-left';
}
if ($right != '') {
$class = 'sidebar-right';
}
}
if (isset($class)) {
print ' class="'. $class .'"';
}
}
/**
* Return a themed breadcrumb trail.
*
* @param $breadcrumb
* An array containing the breadcrumb links.
* @return a string containing the breadcrumb output.
*/
function phptemplate_breadcrumb($breadcrumb) {
if (!empty($breadcrumb)) {
return '<div class="breadcrumb">'. implode(' › ', $breadcrumb) .'</div>';
}
}
/**
* Override or insert PHPTemplate variables into the templates.
*/
function phptemplate_preprocess_page(&$vars) {
$vars['tabs2'] = menu_secondary_local_tasks();
// Hook into color.module
if (module_exists('color')) {
_color_page_alter($vars);
}
}
/**
* Add a "Comments" heading above comments except on forum pages.
*/
function tiki_preprocess_comment_wrapper(&$vars) {
if ($vars['content'] && $vars['node']->type != 'forum') {
$vars['content'] = '<h2 class="comments">'. t('Comments') .'</h2>'. $vars['content'];
}
}
/**
* Returns the rendered local tasks. The default implementation renders
* them as tabs. Overridden to split the secondary tasks.
*
* @ingroup themeable
*/
function phptemplate_menu_local_tasks() {
return menu_primary_local_tasks();
}
/**
* Returns the themed submitted-by string for the comment.
*/
function phptemplate_comment_submitted($comment) {
return t('!datetime — !username',
array(
'!username' => theme('username', $comment),
'!datetime' => format_date($comment->timestamp)
));
}
/**
* Returns the themed submitted-by string for the node.
*/
function phptemplate_node_submitted($node) {
return t('!datetime — !username',
array(
'!username' => theme('username', $node),
'!datetime' => format_date($node->created),
));
}
/**
* Generates IE CSS links for LTR and RTL languages.
*/
function phptemplate_get_ie_styles() {
global $language;
$iecss = '<link type="text/css" rel="stylesheet" media="all" href="'. base_path() . path_to_theme() .'/fix-ie.css" />';
if ($language->direction == LANGUAGE_RTL) {
$iecss .= '<style type="text/css" media="all">@import "'. base_path() . path_to_theme() .'/fix-ie-rtl.css";</style>';
}
return $iecss;
}
| Onenix/360kpop-shop | themes/tiki/template.php | PHP | gpl-2.0 | 2,556 |
/*
* TrxFormController.java
*
* Created on Jan 9, 2010 8:22:32 PM
*
* Copyright (c) 2002 - 2010 : Swayam Inc.
*
* P R O P R I E T A R Y & C O N F I D E N T I A L
*
* The copyright of this document is vested in Swayam Inc. without
* whose prior written permission its contents must not be published,
* adapted or reproduced in any form or disclosed or
* issued to any third party.
*/
package com.swayam.ims.webapp.controller.trx;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
/**
*
* @author paawak
*/
public abstract class TrxFormController implements Controller {
final TrxModeIndicator modeIndicator;
private String formView;
public TrxFormController(TrxModeIndicator modeIndicator) {
this.modeIndicator = modeIndicator;
}
public final void setFormView(String formView) {
this.formView = formView;
}
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView modelNView = new ModelAndView(formView);
modelNView.addObject("isPurchaseMode", modeIndicator.isPurchaseMode());
return modelNView;
}
}
| paawak/blog | code/SpringMVCWithFlex/ims-web/src/main/java/com/swayam/ims/webapp/controller/trx/TrxFormController.java | Java | gpl-2.0 | 1,332 |
<?php
if ( !defined( 'ABSPATH' ) ) {
exit;
}
$rowWidth = 0;
foreach ( $cells as $cell ) {
$rowWidth += (int)$cell['width'];
}
if ( $rows ) { ?>
<table class="mscrm-listview table">
<thead>
<tr>
<?php foreach ( current( $rows ) as $cellName => $cell ) {
$cellWidth = $cells[$cellName]['width'];
?>
<th style="width:<?php echo round( ( $cellWidth / $rowWidth * 100 ), 3 ); ?>%;"><?php echo $cell["head"]; ?></th>
<?php } ?>
</tr>
</thead>
<tbody>
<?php foreach ( $rows as $row ) { ?>
<tr>
<?php foreach ( $row as $key => $cell ) : ?>
<td><?php wordpresscrm_view_field( $cell ); ?></td>
<?php endforeach; ?>
</tr>
<?php } ?>
</tbody>
<?php
if ( array_key_exists( 'count', $attributes ) && (int)$attributes['count'] > 0 ) {
$currentPage = 1;
if ( array_key_exists( 'viewPage', $_GET ) && (int)$_GET['viewPage'] > 0 ) {
$currentPage = (int)$_GET['viewPage'];
}
?><tfoot>
<tr>
<td colspan="<?php echo esc_attr( count( $cells ) ); ?>">
<?php if ( $currentPage > 1 ) {
$queryParams = ACRM()->request->query->all();
unset( $queryParams['viewPage'] );
if ( $currentPage > 2 ) {
$queryParams[ 'viewPage'] = $currentPage - 1;
}
$url = \Symfony\Component\HttpFoundation\Request::create(
ACRM()->request->getPathInfo(),
'GET',
$queryParams
);
?><a href="<?php echo esc_attr( $url->getRequestUri() ); ?>" class="btn btn-outline-primary"><?php _e( '← Previous', 'integration-dynamics' ); ?></a> <?php /* the prepended space is purposeful */
}
if ( $entities->MoreRecords ) {
$url = \Symfony\Component\HttpFoundation\Request::create(
ACRM()->request->getPathInfo(),
'GET',
array_merge( ACRM()->request->query->all(), [ 'viewPage' => $currentPage + 1 ] )
);
?><a href="<?php echo esc_attr( $url->getRequestUri() ); ?>" class="btn btn-outline-primary"><?php _e( 'Next →', 'integration-dynamics' ); ?></a><?php
}
?>
</td>
</tr>
</tfoot>
<?php } ?>
</table>
<?php } else {
echo apply_filters( "wordpresscrm_no_results_view", __( "<p>No results</p>", 'integration-dynamics' ), $attributes["entity"], $attributes["name"] );
} ?>
| AlexaCRM/integration-dynamics | templates/view/view.php | PHP | gpl-2.0 | 2,942 |
<?php
/**
* Options for the bibtex plugin
*
* @author Till Biskup <till@till-biskup>
*/
$meta['_basic'] = array('fieldset');
$meta['sqlite'] = array('onoff');
$meta['citetype'] = array('multichoice','_choices' => array('alpha','apa','authordate','numeric'));
$meta['file'] = array('string');
$meta['pdfdir'] = array('string');
$meta['sort'] = array('onoff');
$meta['_formatstrings'] = array('fieldset');
$meta['fmtstr_article'] = array('string');
$meta['fmtstr_book'] = array('string');
$meta['fmtstr_booklet'] = array('string');
$meta['fmtstr_conference'] = array('string');
$meta['fmtstr_inbook'] = array('string');
$meta['fmtstr_incollection'] = array('string');
$meta['fmtstr_inproceedings'] = array('string');
$meta['fmtstr_manual'] = array('string');
$meta['fmtstr_mastersthesis'] = array('string');
$meta['fmtstr_misc'] = array('string');
$meta['fmtstr_phdthesis'] = array('string');
$meta['fmtstr_proceedings'] = array('string');
$meta['fmtstr_techreport'] = array('string');
$meta['fmtstr_unpublished'] = array('string');
| tillbiskup/dokuwiki-bibtex | conf/metadata.php | PHP | gpl-2.0 | 1,037 |
<?php
/**
* Suomi.fi authentication module.
*
* PHP version 7
*
* Copyright (C) The National Library of Finland 2019.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Authentication
* @author Samuli Sillanpää <samuli.sillanpaa@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
namespace Finna\Auth;
use VuFind\Exception\Auth as AuthException;
/**
* Suomi.fi authentication module.
*
* @category VuFind
* @package Authentication
* @author Samuli Sillanpää <samuli.sillanpaa@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
class Suomifi extends Shibboleth
{
/**
* Set configuration.
*
* @param \Zend\Config\Config $config Configuration to set
*
* @return void
*/
public function setConfig($config)
{
// Replace Shibboleth config section with Shibboleth_suomifi
$data = $config->toArray();
$data['Shibboleth'] = $data['Shibboleth_suomifi'];
$config = new \Zend\Config\Config($data);
parent::setConfig($config);
}
/**
* Get the URL to establish a session (needed when the internal VuFind login
* form is inadequate). Returns false when no session initiator is needed.
*
* @param string $target Full URL where external authentication method should
* send user after login (some drivers may override this).
*
* @return bool|string
*/
public function getSessionInitiator($target)
{
$url = parent::getSessionInitiator($target);
if (!$url) {
return $url;
}
// Set 'auth_method' to Suomifi
$url = str_replace(
'auth_method%3DShibboleth', 'auth_method%3DSuomifi', $url
);
return $url;
}
/**
* Get a server parameter taking into account any environment variables
* redirected by Apache mod_rewrite.
*
* @param \Zend\Http\PhpEnvironment\Request $request Request object containing
* account credentials.
* @param string $param Parameter name
*
* @throws AuthException
* @return mixed
*/
protected function getServerParam($request, $param)
{
$val = parent::getServerParam($request, $param);
$config = $this->getConfig()->Shibboleth;
if ($param === $config->username
&& ((bool)$config->hash_username ?? false)
) {
$secret = $config->hash_secret ?? null;
if (empty($secret)) {
throw new AuthException('hash_secret not configured');
}
$val = hash_hmac('sha256', $val, $secret, false);
}
return $val;
}
}
| arto70/NDL-VuFind2 | module/Finna/src/Finna/Auth/Suomifi.php | PHP | gpl-2.0 | 3,484 |
// clang-format off
/* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
https://www.lammps.org/, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing authors: Jim Shepherd (GA Tech) added SGI SCSL support
Axel Kohlmeyer (Temple U) added support for
FFTW3, KISS FFT, Dfti/MKL, and ACML
Phil Blood (PSC) added single precision FFTs
Paul Coffman (IBM) added MPI collectives remap
------------------------------------------------------------------------- */
#include "fft3d.h"
#include "remap.h"
#include <cstdlib>
#include <cmath>
#if defined(_OPENMP)
#include <omp.h>
#endif
#ifdef FFT_KISS
/* include kissfft implementation */
#include "kissfft.h"
#endif
#define MIN(A,B) ((A) < (B) ? (A) : (B))
#define MAX(A,B) ((A) > (B) ? (A) : (B))
/* ----------------------------------------------------------------------
Data layout for 3d FFTs:
data set of Nfast x Nmid x Nslow elements is owned by P procs
on input, each proc owns a subsection of the elements
on output, each proc will own a (possibly different) subsection
my subsection must not overlap with any other proc's subsection,
i.e. the union of all proc's input (or output) subsections must
exactly tile the global Nfast x Nmid x Nslow data set
when called from C, all subsection indices are
C-style from 0 to N-1 where N = Nfast or Nmid or Nslow
when called from F77, all subsection indices are
F77-style from 1 to N where N = Nfast or Nmid or Nslow
a proc can own 0 elements on input or output
by specifying hi index < lo index
on both input and output, data is stored contiguously on a processor
with a fast-varying, mid-varying, and slow-varying index
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Perform 3d FFT
Arguments:
in starting address of input data on this proc
out starting address of where output data for this proc
will be placed (can be same as in)
flag 1 for forward FFT, -1 for backward FFT
plan plan returned by previous call to fft_3d_create_plan
------------------------------------------------------------------------- */
void fft_3d(FFT_DATA *in, FFT_DATA *out, int flag, struct fft_plan_3d *plan)
{
FFT_SCALAR norm;
#if defined(FFT_FFTW3)
FFT_SCALAR *out_ptr;
#endif
FFT_DATA *data,*copy;
// system specific constants
#if defined(FFT_FFTW3)
FFTW_API(plan) theplan;
#else
// nothing to do for other FFTs
#endif
// pre-remap to prepare for 1st FFTs if needed
// copy = loc for remap result
if (plan->pre_plan) {
if (plan->pre_target == 0) copy = out;
else copy = plan->copy;
remap_3d((FFT_SCALAR *) in, (FFT_SCALAR *) copy,
(FFT_SCALAR *) plan->scratch, plan->pre_plan);
data = copy;
}
else
data = in;
// 1d FFTs along fast axis
#if defined(FFT_MKL)
if (flag == 1)
DftiComputeForward(plan->handle_fast,data);
else
DftiComputeBackward(plan->handle_fast,data);
#elif defined(FFT_FFTW3)
if (flag == 1)
theplan=plan->plan_fast_forward;
else
theplan=plan->plan_fast_backward;
FFTW_API(execute_dft)(theplan,data,data);
#else
int total = plan->total1;
int length = plan->length1;
if (flag == 1)
for (int offset = 0; offset < total; offset += length)
kiss_fft(plan->cfg_fast_forward,&data[offset],&data[offset]);
else
for (int offset = 0; offset < total; offset += length)
kiss_fft(plan->cfg_fast_backward,&data[offset],&data[offset]);
#endif
// 1st mid-remap to prepare for 2nd FFTs
// copy = loc for remap result
if (plan->mid1_target == 0) copy = out;
else copy = plan->copy;
remap_3d((FFT_SCALAR *) data, (FFT_SCALAR *) copy,
(FFT_SCALAR *) plan->scratch, plan->mid1_plan);
data = copy;
// 1d FFTs along mid axis
#if defined(FFT_MKL)
if (flag == 1)
DftiComputeForward(plan->handle_mid,data);
else
DftiComputeBackward(plan->handle_mid,data);
#elif defined(FFT_FFTW3)
if (flag == 1)
theplan=plan->plan_mid_forward;
else
theplan=plan->plan_mid_backward;
FFTW_API(execute_dft)(theplan,data,data);
#else
total = plan->total2;
length = plan->length2;
if (flag == 1)
for (int offset = 0; offset < total; offset += length)
kiss_fft(plan->cfg_mid_forward,&data[offset],&data[offset]);
else
for (int offset = 0; offset < total; offset += length)
kiss_fft(plan->cfg_mid_backward,&data[offset],&data[offset]);
#endif
// 2nd mid-remap to prepare for 3rd FFTs
// copy = loc for remap result
if (plan->mid2_target == 0) copy = out;
else copy = plan->copy;
remap_3d((FFT_SCALAR *) data, (FFT_SCALAR *) copy,
(FFT_SCALAR *) plan->scratch, plan->mid2_plan);
data = copy;
// 1d FFTs along slow axis
#if defined(FFT_MKL)
if (flag == 1)
DftiComputeForward(plan->handle_slow,data);
else
DftiComputeBackward(plan->handle_slow,data);
#elif defined(FFT_FFTW3)
if (flag == 1)
theplan=plan->plan_slow_forward;
else
theplan=plan->plan_slow_backward;
FFTW_API(execute_dft)(theplan,data,data);
#else
total = plan->total3;
length = plan->length3;
if (flag == 1)
for (int offset = 0; offset < total; offset += length)
kiss_fft(plan->cfg_slow_forward,&data[offset],&data[offset]);
else
for (int offset = 0; offset < total; offset += length)
kiss_fft(plan->cfg_slow_backward,&data[offset],&data[offset]);
#endif
// post-remap to put data in output format if needed
// destination is always out
if (plan->post_plan)
remap_3d((FFT_SCALAR *) data, (FFT_SCALAR *) out,
(FFT_SCALAR *) plan->scratch, plan->post_plan);
// scaling if required
if (flag == -1 && plan->scaled) {
norm = plan->norm;
const int num = plan->normnum;
#if defined(FFT_FFTW3)
out_ptr = (FFT_SCALAR *)out;
#endif
for (int i = 0; i < num; i++) {
#if defined(FFT_FFTW3)
*(out_ptr++) *= norm;
*(out_ptr++) *= norm;
#elif defined(FFT_MKL)
out[i] *= norm;
#else /* FFT_KISS */
out[i].re *= norm;
out[i].im *= norm;
#endif
}
}
}
/* ----------------------------------------------------------------------
Create plan for performing a 3d FFT
Arguments:
comm MPI communicator for the P procs which own the data
nfast,nmid,nslow size of global 3d matrix
in_ilo,in_ihi input bounds of data I own in fast index
in_jlo,in_jhi input bounds of data I own in mid index
in_klo,in_khi input bounds of data I own in slow index
out_ilo,out_ihi output bounds of data I own in fast index
out_jlo,out_jhi output bounds of data I own in mid index
out_klo,out_khi output bounds of data I own in slow index
scaled 0 = no scaling of result, 1 = scaling
permute permutation in storage order of indices on output
0 = no permutation
1 = permute once = mid->fast, slow->mid, fast->slow
2 = permute twice = slow->fast, fast->mid, mid->slow
nbuf returns size of internal storage buffers used by FFT
usecollective use collective MPI operations for remapping data
------------------------------------------------------------------------- */
struct fft_plan_3d *fft_3d_create_plan(
MPI_Comm comm, int nfast, int nmid, int nslow,
int in_ilo, int in_ihi, int in_jlo, int in_jhi,
int in_klo, int in_khi,
int out_ilo, int out_ihi, int out_jlo, int out_jhi,
int out_klo, int out_khi,
int scaled, int permute, int *nbuf, int usecollective)
{
struct fft_plan_3d *plan;
int me,nprocs,nthreads;
int flag,remapflag;
int first_ilo,first_ihi,first_jlo,first_jhi,first_klo,first_khi;
int second_ilo,second_ihi,second_jlo,second_jhi,second_klo,second_khi;
int third_ilo,third_ihi,third_jlo,third_jhi,third_klo,third_khi;
int out_size,first_size,second_size,third_size,copy_size,scratch_size;
int np1,np2,ip1,ip2;
// query MPI info
MPI_Comm_rank(comm,&me);
MPI_Comm_size(comm,&nprocs);
#if defined(_OPENMP)
// query OpenMP info.
// should have been initialized systemwide in Comm class constructor
nthreads = omp_get_max_threads();
#else
nthreads = 1;
#endif
// compute division of procs in 2 dimensions not on-processor
bifactor(nprocs,&np1,&np2);
ip1 = me % np1;
ip2 = me/np1;
// allocate memory for plan data struct
plan = (struct fft_plan_3d *) malloc(sizeof(struct fft_plan_3d));
if (plan == nullptr) return nullptr;
// remap from initial distribution to layout needed for 1st set of 1d FFTs
// not needed if all procs own entire fast axis initially
// first indices = distribution after 1st set of FFTs
if (in_ilo == 0 && in_ihi == nfast-1)
flag = 0;
else
flag = 1;
MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm);
if (remapflag == 0) {
first_ilo = in_ilo;
first_ihi = in_ihi;
first_jlo = in_jlo;
first_jhi = in_jhi;
first_klo = in_klo;
first_khi = in_khi;
plan->pre_plan = nullptr;
} else {
first_ilo = 0;
first_ihi = nfast - 1;
first_jlo = ip1*nmid/np1;
first_jhi = (ip1+1)*nmid/np1 - 1;
first_klo = ip2*nslow/np2;
first_khi = (ip2+1)*nslow/np2 - 1;
plan->pre_plan =
remap_3d_create_plan(comm,in_ilo,in_ihi,in_jlo,in_jhi,in_klo,in_khi,
first_ilo,first_ihi,first_jlo,first_jhi,
first_klo,first_khi,2,0,0,FFT_PRECISION,0);
if (plan->pre_plan == nullptr) return nullptr;
}
// 1d FFTs along fast axis
plan->length1 = nfast;
plan->total1 = nfast * (first_jhi-first_jlo+1) * (first_khi-first_klo+1);
// remap from 1st to 2nd FFT
// choose which axis is split over np1 vs np2 to minimize communication
// second indices = distribution after 2nd set of FFTs
second_ilo = ip1*nfast/np1;
second_ihi = (ip1+1)*nfast/np1 - 1;
second_jlo = 0;
second_jhi = nmid - 1;
second_klo = ip2*nslow/np2;
second_khi = (ip2+1)*nslow/np2 - 1;
plan->mid1_plan =
remap_3d_create_plan(comm,
first_ilo,first_ihi,first_jlo,first_jhi,
first_klo,first_khi,
second_ilo,second_ihi,second_jlo,second_jhi,
second_klo,second_khi,2,1,0,FFT_PRECISION,
usecollective);
if (plan->mid1_plan == nullptr) return nullptr;
// 1d FFTs along mid axis
plan->length2 = nmid;
plan->total2 = (second_ihi-second_ilo+1) * nmid * (second_khi-second_klo+1);
// remap from 2nd to 3rd FFT
// if final distribution is permute=2 with all procs owning entire slow axis
// then this remapping goes directly to final distribution
// third indices = distribution after 3rd set of FFTs
if (permute == 2 && out_klo == 0 && out_khi == nslow-1)
flag = 0;
else
flag = 1;
MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm);
if (remapflag == 0) {
third_ilo = out_ilo;
third_ihi = out_ihi;
third_jlo = out_jlo;
third_jhi = out_jhi;
third_klo = out_klo;
third_khi = out_khi;
} else {
third_ilo = ip1*nfast/np1;
third_ihi = (ip1+1)*nfast/np1 - 1;
third_jlo = ip2*nmid/np2;
third_jhi = (ip2+1)*nmid/np2 - 1;
third_klo = 0;
third_khi = nslow - 1;
}
plan->mid2_plan =
remap_3d_create_plan(comm,
second_jlo,second_jhi,second_klo,second_khi,
second_ilo,second_ihi,
third_jlo,third_jhi,third_klo,third_khi,
third_ilo,third_ihi,2,1,0,FFT_PRECISION,usecollective);
if (plan->mid2_plan == nullptr) return nullptr;
// 1d FFTs along slow axis
plan->length3 = nslow;
plan->total3 = (third_ihi-third_ilo+1) * (third_jhi-third_jlo+1) * nslow;
// remap from 3rd FFT to final distribution
// not needed if permute = 2 and third indices = out indices on all procs
if (permute == 2 &&
out_ilo == third_ilo && out_ihi == third_ihi &&
out_jlo == third_jlo && out_jhi == third_jhi &&
out_klo == third_klo && out_khi == third_khi)
flag = 0;
else
flag = 1;
MPI_Allreduce(&flag,&remapflag,1,MPI_INT,MPI_MAX,comm);
if (remapflag == 0)
plan->post_plan = nullptr;
else {
plan->post_plan =
remap_3d_create_plan(comm,
third_klo,third_khi,third_ilo,third_ihi,
third_jlo,third_jhi,
out_klo,out_khi,out_ilo,out_ihi,
out_jlo,out_jhi,2,(permute+1)%3,0,FFT_PRECISION,0);
if (plan->post_plan == nullptr) return nullptr;
}
// configure plan memory pointers and allocate work space
// out_size = amount of memory given to FFT by user
// first/second/third_size =
// amount of memory needed after pre,mid1,mid2 remaps
// copy_size = amount needed internally for extra copy of data
// scratch_size = amount needed internally for remap scratch space
// for each remap:
// out space used for result if big enough, else require copy buffer
// accumulate largest required remap scratch space
out_size = (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) * (out_khi-out_klo+1);
first_size = (first_ihi-first_ilo+1) * (first_jhi-first_jlo+1) *
(first_khi-first_klo+1);
second_size = (second_ihi-second_ilo+1) * (second_jhi-second_jlo+1) *
(second_khi-second_klo+1);
third_size = (third_ihi-third_ilo+1) * (third_jhi-third_jlo+1) *
(third_khi-third_klo+1);
copy_size = 0;
scratch_size = 0;
if (plan->pre_plan) {
if (first_size <= out_size)
plan->pre_target = 0;
else {
plan->pre_target = 1;
copy_size = MAX(copy_size,first_size);
}
scratch_size = MAX(scratch_size,first_size);
}
if (plan->mid1_plan) {
if (second_size <= out_size)
plan->mid1_target = 0;
else {
plan->mid1_target = 1;
copy_size = MAX(copy_size,second_size);
}
scratch_size = MAX(scratch_size,second_size);
}
if (plan->mid2_plan) {
if (third_size <= out_size)
plan->mid2_target = 0;
else {
plan->mid2_target = 1;
copy_size = MAX(copy_size,third_size);
}
scratch_size = MAX(scratch_size,third_size);
}
if (plan->post_plan)
scratch_size = MAX(scratch_size,out_size);
*nbuf = copy_size + scratch_size;
if (copy_size) {
plan->copy = (FFT_DATA *) malloc(copy_size*sizeof(FFT_DATA));
if (plan->copy == nullptr) return nullptr;
}
else plan->copy = nullptr;
if (scratch_size) {
plan->scratch = (FFT_DATA *) malloc(scratch_size*sizeof(FFT_DATA));
if (plan->scratch == nullptr) return nullptr;
}
else plan->scratch = nullptr;
// system specific pre-computation of 1d FFT coeffs
// and scaling normalization
#if defined(FFT_MKL)
DftiCreateDescriptor( &(plan->handle_fast), FFT_MKL_PREC, DFTI_COMPLEX, 1,
(MKL_LONG)nfast);
DftiSetValue(plan->handle_fast, DFTI_NUMBER_OF_TRANSFORMS,
(MKL_LONG)plan->total1/nfast);
DftiSetValue(plan->handle_fast, DFTI_PLACEMENT,DFTI_INPLACE);
DftiSetValue(plan->handle_fast, DFTI_INPUT_DISTANCE, (MKL_LONG)nfast);
DftiSetValue(plan->handle_fast, DFTI_OUTPUT_DISTANCE, (MKL_LONG)nfast);
#if defined(FFT_MKL_THREADS)
DftiSetValue(plan->handle_fast, DFTI_NUMBER_OF_USER_THREADS, nthreads);
#endif
DftiCommitDescriptor(plan->handle_fast);
DftiCreateDescriptor( &(plan->handle_mid), FFT_MKL_PREC, DFTI_COMPLEX, 1,
(MKL_LONG)nmid);
DftiSetValue(plan->handle_mid, DFTI_NUMBER_OF_TRANSFORMS,
(MKL_LONG)plan->total2/nmid);
DftiSetValue(plan->handle_mid, DFTI_PLACEMENT,DFTI_INPLACE);
DftiSetValue(plan->handle_mid, DFTI_INPUT_DISTANCE, (MKL_LONG)nmid);
DftiSetValue(plan->handle_mid, DFTI_OUTPUT_DISTANCE, (MKL_LONG)nmid);
#if defined(FFT_MKL_THREADS)
DftiSetValue(plan->handle_mid, DFTI_NUMBER_OF_USER_THREADS, nthreads);
#endif
DftiCommitDescriptor(plan->handle_mid);
DftiCreateDescriptor( &(plan->handle_slow), FFT_MKL_PREC, DFTI_COMPLEX, 1,
(MKL_LONG)nslow);
DftiSetValue(plan->handle_slow, DFTI_NUMBER_OF_TRANSFORMS,
(MKL_LONG)plan->total3/nslow);
DftiSetValue(plan->handle_slow, DFTI_PLACEMENT,DFTI_INPLACE);
DftiSetValue(plan->handle_slow, DFTI_INPUT_DISTANCE, (MKL_LONG)nslow);
DftiSetValue(plan->handle_slow, DFTI_OUTPUT_DISTANCE, (MKL_LONG)nslow);
#if defined(FFT_MKL_THREADS)
DftiSetValue(plan->handle_slow, DFTI_NUMBER_OF_USER_THREADS, nthreads);
#endif
DftiCommitDescriptor(plan->handle_slow);
#elif defined(FFT_FFTW3)
#if defined(FFT_FFTW_THREADS)
if (nthreads > 1) {
FFTW_API(init_threads)();
FFTW_API(plan_with_nthreads)(nthreads);
}
#endif
plan->plan_fast_forward =
FFTW_API(plan_many_dft)(1, &nfast,plan->total1/plan->length1,
nullptr,&nfast,1,plan->length1,
nullptr,&nfast,1,plan->length1,
FFTW_FORWARD,FFTW_ESTIMATE);
plan->plan_fast_backward =
FFTW_API(plan_many_dft)(1, &nfast,plan->total1/plan->length1,
nullptr,&nfast,1,plan->length1,
nullptr,&nfast,1,plan->length1,
FFTW_BACKWARD,FFTW_ESTIMATE);
plan->plan_mid_forward =
FFTW_API(plan_many_dft)(1, &nmid,plan->total2/plan->length2,
nullptr,&nmid,1,plan->length2,
nullptr,&nmid,1,plan->length2,
FFTW_FORWARD,FFTW_ESTIMATE);
plan->plan_mid_backward =
FFTW_API(plan_many_dft)(1, &nmid,plan->total2/plan->length2,
nullptr,&nmid,1,plan->length2,
nullptr,&nmid,1,plan->length2,
FFTW_BACKWARD,FFTW_ESTIMATE);
plan->plan_slow_forward =
FFTW_API(plan_many_dft)(1, &nslow,plan->total3/plan->length3,
nullptr,&nslow,1,plan->length3,
nullptr,&nslow,1,plan->length3,
FFTW_FORWARD,FFTW_ESTIMATE);
plan->plan_slow_backward =
FFTW_API(plan_many_dft)(1, &nslow,plan->total3/plan->length3,
nullptr,&nslow,1,plan->length3,
nullptr,&nslow,1,plan->length3,
FFTW_BACKWARD,FFTW_ESTIMATE);
#else /* FFT_KISS */
plan->cfg_fast_forward = kiss_fft_alloc(nfast,0,nullptr,nullptr);
plan->cfg_fast_backward = kiss_fft_alloc(nfast,1,nullptr,nullptr);
if (nmid == nfast) {
plan->cfg_mid_forward = plan->cfg_fast_forward;
plan->cfg_mid_backward = plan->cfg_fast_backward;
}
else {
plan->cfg_mid_forward = kiss_fft_alloc(nmid,0,nullptr,nullptr);
plan->cfg_mid_backward = kiss_fft_alloc(nmid,1,nullptr,nullptr);
}
if (nslow == nfast) {
plan->cfg_slow_forward = plan->cfg_fast_forward;
plan->cfg_slow_backward = plan->cfg_fast_backward;
}
else if (nslow == nmid) {
plan->cfg_slow_forward = plan->cfg_mid_forward;
plan->cfg_slow_backward = plan->cfg_mid_backward;
}
else {
plan->cfg_slow_forward = kiss_fft_alloc(nslow,0,nullptr,nullptr);
plan->cfg_slow_backward = kiss_fft_alloc(nslow,1,nullptr,nullptr);
}
#endif
if (scaled == 0)
plan->scaled = 0;
else {
plan->scaled = 1;
plan->norm = 1.0/(nfast*nmid*nslow);
plan->normnum = (out_ihi-out_ilo+1) * (out_jhi-out_jlo+1) *
(out_khi-out_klo+1);
}
return plan;
}
/* ----------------------------------------------------------------------
Destroy a 3d fft plan
------------------------------------------------------------------------- */
void fft_3d_destroy_plan(struct fft_plan_3d *plan)
{
if (plan->pre_plan) remap_3d_destroy_plan(plan->pre_plan);
if (plan->mid1_plan) remap_3d_destroy_plan(plan->mid1_plan);
if (plan->mid2_plan) remap_3d_destroy_plan(plan->mid2_plan);
if (plan->post_plan) remap_3d_destroy_plan(plan->post_plan);
if (plan->copy) free(plan->copy);
if (plan->scratch) free(plan->scratch);
#if defined(FFT_MKL)
DftiFreeDescriptor(&(plan->handle_fast));
DftiFreeDescriptor(&(plan->handle_mid));
DftiFreeDescriptor(&(plan->handle_slow));
#elif defined(FFT_FFTW3)
FFTW_API(destroy_plan)(plan->plan_slow_forward);
FFTW_API(destroy_plan)(plan->plan_slow_backward);
FFTW_API(destroy_plan)(plan->plan_mid_forward);
FFTW_API(destroy_plan)(plan->plan_mid_backward);
FFTW_API(destroy_plan)(plan->plan_fast_forward);
FFTW_API(destroy_plan)(plan->plan_fast_backward);
#if defined(FFT_FFTW_THREADS)
FFTW_API(cleanup_threads)();
#endif
#else
if (plan->cfg_slow_forward != plan->cfg_fast_forward &&
plan->cfg_slow_forward != plan->cfg_mid_forward) {
free(plan->cfg_slow_forward);
free(plan->cfg_slow_backward);
}
if (plan->cfg_mid_forward != plan->cfg_fast_forward) {
free(plan->cfg_mid_forward);
free(plan->cfg_mid_backward);
}
free(plan->cfg_fast_forward);
free(plan->cfg_fast_backward);
#endif
free(plan);
}
/* ----------------------------------------------------------------------
recursively divide n into small factors, return them in list
------------------------------------------------------------------------- */
void factor(int n, int *num, int *list)
{
if (n == 1) {
return;
} else if (n % 2 == 0) {
*list = 2;
(*num)++;
factor(n/2,num,list+1);
} else if (n % 3 == 0) {
*list = 3;
(*num)++;
factor(n/3,num,list+1);
} else if (n % 5 == 0) {
*list = 5;
(*num)++;
factor(n/5,num,list+1);
} else if (n % 7 == 0) {
*list = 7;
(*num)++;
factor(n/7,num,list+1);
} else if (n % 11 == 0) {
*list = 11;
(*num)++;
factor(n/11,num,list+1);
} else if (n % 13 == 0) {
*list = 13;
(*num)++;
factor(n/13,num,list+1);
} else {
*list = n;
(*num)++;
return;
}
}
/* ----------------------------------------------------------------------
divide n into 2 factors of as equal size as possible
------------------------------------------------------------------------- */
void bifactor(int n, int *factor1, int *factor2)
{
int n1,n2,facmax;
facmax = static_cast<int> (sqrt((double) n));
for (n1 = facmax; n1 > 0; n1--) {
n2 = n/n1;
if (n1*n2 == n) {
*factor1 = n1;
*factor2 = n2;
return;
}
}
}
/* ----------------------------------------------------------------------
perform just the 1d FFTs needed by a 3d FFT, no data movement
used for timing purposes
Arguments:
in starting address of input data on this proc, all set to 0.0
nsize size of in
flag 1 for forward FFT, -1 for backward FFT
plan plan returned by previous call to fft_3d_create_plan
------------------------------------------------------------------------- */
void fft_1d_only(FFT_DATA *data, int nsize, int flag, struct fft_plan_3d *plan)
{
int i,num;
FFT_SCALAR norm;
#if defined(FFT_FFTW3)
FFT_SCALAR *data_ptr;
#endif
// total = size of data needed in each dim
// length = length of 1d FFT in each dim
// total/length = # of 1d FFTs in each dim
// if total > nsize, limit # of 1d FFTs to available size of data
int total1 = plan->total1;
int length1 = plan->length1;
int total2 = plan->total2;
int length2 = plan->length2;
int total3 = plan->total3;
int length3 = plan->length3;
// fftw3 and Dfti in MKL encode the number of transforms
// into the plan, so we cannot operate on a smaller data set
#if defined(FFT_MKL) || defined(FFT_FFTW3)
if ((total1 > nsize) || (total2 > nsize) || (total3 > nsize))
return;
#endif
if (total1 > nsize) total1 = (nsize/length1) * length1;
if (total2 > nsize) total2 = (nsize/length2) * length2;
if (total3 > nsize) total3 = (nsize/length3) * length3;
// perform 1d FFTs in each of 3 dimensions
// data is just an array of 0.0
#if defined(FFT_MKL)
if (flag == 1) {
DftiComputeForward(plan->handle_fast,data);
DftiComputeForward(plan->handle_mid,data);
DftiComputeForward(plan->handle_slow,data);
} else {
DftiComputeBackward(plan->handle_fast,data);
DftiComputeBackward(plan->handle_mid,data);
DftiComputeBackward(plan->handle_slow,data);
}
#elif defined(FFT_FFTW3)
FFTW_API(plan) theplan;
if (flag == 1)
theplan=plan->plan_fast_forward;
else
theplan=plan->plan_fast_backward;
FFTW_API(execute_dft)(theplan,data,data);
if (flag == 1)
theplan=plan->plan_mid_forward;
else
theplan=plan->plan_mid_backward;
FFTW_API(execute_dft)(theplan,data,data);
if (flag == 1)
theplan=plan->plan_slow_forward;
else
theplan=plan->plan_slow_backward;
FFTW_API(execute_dft)(theplan,data,data);
#else
if (flag == 1) {
for (int offset = 0; offset < total1; offset += length1)
kiss_fft(plan->cfg_fast_forward,&data[offset],&data[offset]);
for (int offset = 0; offset < total2; offset += length2)
kiss_fft(plan->cfg_mid_forward,&data[offset],&data[offset]);
for (int offset = 0; offset < total3; offset += length3)
kiss_fft(plan->cfg_slow_forward,&data[offset],&data[offset]);
} else {
for (int offset = 0; offset < total1; offset += length1)
kiss_fft(plan->cfg_fast_backward,&data[offset],&data[offset]);
for (int offset = 0; offset < total2; offset += length2)
kiss_fft(plan->cfg_mid_backward,&data[offset],&data[offset]);
for (int offset = 0; offset < total3; offset += length3)
kiss_fft(plan->cfg_slow_backward,&data[offset],&data[offset]);
}
#endif
// scaling if required
// limit num to size of data
if (flag == -1 && plan->scaled) {
norm = plan->norm;
num = MIN(plan->normnum,nsize);
#if defined(FFT_FFTW3)
data_ptr = (FFT_SCALAR *)data;
#endif
for (i = 0; i < num; i++) {
#if defined(FFT_FFTW3)
*(data_ptr++) *= norm;
*(data_ptr++) *= norm;
#elif defined(FFT_MKL)
data[i] *= norm;
#else
data[i].re *= norm;
data[i].im *= norm;
#endif
}
}
}
| jeremiahyan/lammps | src/KSPACE/fft3d.cpp | C++ | gpl-2.0 | 26,711 |
/*
Copyright (C) 2007 Volker Berlin
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jeroen Frijters
jeroen@frijters.net
*/
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using java.awt.peer;
using java.awt.@event;
namespace ikvm.awt
{
internal class WindowsRobot : RobotPeer
{
Screen screen;
internal WindowsRobot(java.awt.GraphicsDevice device)
{
screen = ((NetGraphicsDevice)device).screen;
}
public void dispose()
{
}
public int getRGBPixel(int x, int y)
{
Bitmap bitmap = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(bitmap);
g.CopyFromScreen( x, y, 0, 0, new Size(1,1));
g.Dispose();
Color color = bitmap.GetPixel(0,0);
bitmap.Dispose();
return color.ToArgb();
}
public int[] getRGBPixels(java.awt.Rectangle r)
{
int width = r.width;
int height = r.height;
Bitmap bitmap = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bitmap);
g.CopyFromScreen(r.x, r.y, 0, 0, new Size(width, height));
g.Dispose();
int[] pixels = new int[width * height];
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
pixels[i+j*width] = bitmap.GetPixel(i, j).ToArgb();
}
}
bitmap.Dispose();
return pixels;
}
private byte MapKeyCode(int keyCode)
{
//TODO there need a keymap for some special chars
//http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/UserInput/VirtualKeyCodes.asp
switch (keyCode)
{
case KeyEvent.VK_DELETE:
return VK_DELETE;
default:
return (byte)keyCode;
}
}
public void keyPress(int keycode)
{
keybd_event(MapKeyCode(keycode), 0, KEYEVENTF_KEYDOWN, IntPtr.Zero);
}
public void keyRelease(int keycode)
{
keybd_event(MapKeyCode(keycode), 0, KEYEVENTF_KEYUP, IntPtr.Zero);
}
public void mouseMove(int x, int y)
{
Cursor.Position = new Point(x,y);
}
public void mousePress(int button)
{
int dwFlags = 0;
switch (button)
{
case InputEvent.BUTTON1_MASK:
dwFlags |= MOUSEEVENTF_LEFTDOWN;
break;
case InputEvent.BUTTON2_MASK:
dwFlags |= MOUSEEVENTF_MIDDLEDOWN;
break;
case InputEvent.BUTTON3_MASK:
dwFlags |= MOUSEEVENTF_RIGHTDOWN;
break;
}
mouse_event(dwFlags, 0, 0, 0, IntPtr.Zero);
}
public void mouseRelease(int button)
{
int dwFlags = 0;
switch (button)
{
case InputEvent.BUTTON1_MASK:
dwFlags |= MOUSEEVENTF_LEFTUP;
break;
case InputEvent.BUTTON2_MASK:
dwFlags |= MOUSEEVENTF_MIDDLEUP;
break;
case InputEvent.BUTTON3_MASK:
dwFlags |= MOUSEEVENTF_RIGHTUP;
break;
}
mouse_event(dwFlags, 0, 0, 0, IntPtr.Zero);
}
public void mouseWheel(int wheel)
{
mouse_event(0, 0, 0, wheel, IntPtr.Zero);
}
[DllImport("user32.dll")]
private static extern void keybd_event(byte vk, byte scan, int flags, IntPtr extrainfo);
private const int KEYEVENTF_KEYDOWN = 0x0000;
private const int KEYEVENTF_KEYUP = 0x0002;
[DllImport("user32.dll")]
private static extern void mouse_event(
int dwFlags, // motion and click options
int dx, // horizontal position or change
int dy, // vertical position or change
int dwData, // wheel movement
IntPtr dwExtraInfo // application-defined information
);
private const int MOUSEEVENTF_LEFTDOWN = 0x0002;
private const int MOUSEEVENTF_LEFTUP = 0x0004;
private const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
private const int MOUSEEVENTF_RIGHTUP = 0x0010;
private const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
private const int MOUSEEVENTF_MIDDLEUP = 0x0040;
private const int VK_BACK = 0x08;
private const int VK_TAB = 0x09;
/*
* 0x0A - 0x0B : reserved
*/
private const int VK_CLEAR = 0x0C;
private const int VK_RETURN = 0x0D;
private const int VK_SHIFT = 0x10;
private const int VK_CONTROL = 0x11;
private const int VK_MENU = 0x12;
private const int VK_PAUSE = 0x13;
private const int VK_CAPITAL = 0x14;
private const int VK_KANA = 0x15;
private const int VK_HANGEUL = 0x15; /* old name - should be here for compatibility */
private const int VK_HANGUL = 0x15;
private const int VK_JUNJA = 0x17;
private const int VK_FINAL = 0x18;
private const int VK_HANJA = 0x19;
private const int VK_KANJI = 0x19;
private const int VK_ESCAPE = 0x1B;
private const int VK_CONVERT = 0x1C;
private const int VK_NONCONVERT = 0x1D;
private const int VK_ACCEPT = 0x1E;
private const int VK_MODECHANGE = 0x1F;
private const int VK_SPACE = 0x20;
private const int VK_PRIOR = 0x21;
private const int VK_NEXT = 0x22;
private const int VK_END = 0x23;
private const int VK_HOME = 0x24;
private const int VK_LEFT = 0x25;
private const int VK_UP = 0x26;
private const int VK_RIGHT = 0x27;
private const int VK_DOWN = 0x28;
private const int VK_SELECT = 0x29;
private const int VK_PRINT = 0x2A;
private const int VK_EXECUTE = 0x2B;
private const int VK_SNAPSHOT = 0x2C;
private const int VK_INSERT = 0x2D;
private const int VK_DELETE = 0x2E;
private const int VK_HELP = 0x2F;
/*
* VK_0 - VK_9 are the same as ASCII '0' - '9' (0x30 - 0x39)
* 0x40 : unassigned
* VK_A - VK_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A)
*/
private const int VK_LWIN = 0x5B;
private const int VK_RWIN = 0x5C;
private const int VK_APPS = 0x5D;
/*
* 0x5E : reserved
*/
private const int VK_SLEEP = 0x5F;
private const int VK_NUMPAD0 = 0x60;
private const int VK_NUMPAD1 = 0x61;
private const int VK_NUMPAD2 = 0x62;
private const int VK_NUMPAD3 = 0x63;
private const int VK_NUMPAD4 = 0x64;
private const int VK_NUMPAD5 = 0x65;
private const int VK_NUMPAD6 = 0x66;
private const int VK_NUMPAD7 = 0x67;
private const int VK_NUMPAD8 = 0x68;
private const int VK_NUMPAD9 = 0x69;
private const int VK_MULTIPLY = 0x6A;
private const int VK_ADD = 0x6B;
private const int VK_SEPARATOR = 0x6C;
private const int VK_SUBTRACT = 0x6D;
private const int VK_DECIMAL = 0x6E;
private const int VK_DIVIDE = 0x6F;
private const int VK_F1 = 0x70;
private const int VK_F2 = 0x71;
private const int VK_F3 = 0x72;
private const int VK_F4 = 0x73;
private const int VK_F5 = 0x74;
private const int VK_F6 = 0x75;
private const int VK_F7 = 0x76;
private const int VK_F8 = 0x77;
private const int VK_F9 = 0x78;
private const int VK_F10 = 0x79;
private const int VK_F11 = 0x7A;
private const int VK_F12 = 0x7B;
private const int VK_F13 = 0x7C;
private const int VK_F14 = 0x7D;
private const int VK_F15 = 0x7E;
private const int VK_F16 = 0x7F;
private const int VK_F17 = 0x80;
private const int VK_F18 = 0x81;
private const int VK_F19 = 0x82;
private const int VK_F20 = 0x83;
private const int VK_F21 = 0x84;
private const int VK_F22 = 0x85;
private const int VK_F23 = 0x86;
private const int VK_F24 = 0x87;
/*
* 0x88 - 0x8F : unassigned
*/
private const int VK_NUMLOCK = 0x90;
private const int VK_SCROLL = 0x91;
/*
* NEC PC-9800 kbd definitions
*/
private const int VK_OEM_NEC_EQUAL = 0x92; // '=' key on numpad
/*
* Fujitsu/OASYS kbd definitions
*/
private const int VK_OEM_FJ_JISHO = 0x92; // 'Dictionary' key
private const int VK_OEM_FJ_MASSHOU= 0x93; // 'Unregister word' key
private const int VK_OEM_FJ_TOUROKU= 0x94; // 'Register word' key
private const int VK_OEM_FJ_LOYA = 0x95; // 'Left OYAYUBI' key
private const int VK_OEM_FJ_ROYA = 0x96; // 'Right OYAYUBI' key
/*
* 0x97 - 0x9F : unassigned
*/
/*
* VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys.
* Used only as parameters to GetAsyncKeyState() and GetKeyState().
* No other API or message will distinguish left and right keys in this way.
*/
private const int VK_LSHIFT = 0xA0;
private const int VK_RSHIFT = 0xA1;
private const int VK_LCONTROL = 0xA2;
private const int VK_RCONTROL = 0xA3;
private const int VK_LMENU = 0xA4;
private const int VK_RMENU = 0xA5;
private const int VK_BROWSER_BACK = 0xA6;
private const int VK_BROWSER_FORWARD = 0xA7;
private const int VK_BROWSER_REFRESH = 0xA8;
private const int VK_BROWSER_STOP = 0xA9;
private const int VK_BROWSER_SEARCH = 0xAA;
private const int VK_BROWSER_FAVORITES = 0xAB;
private const int VK_BROWSER_HOME = 0xAC;
private const int VK_VOLUME_MUTE = 0xAD;
private const int VK_VOLUME_DOWN = 0xAE;
private const int VK_VOLUME_UP = 0xAF;
private const int VK_MEDIA_NEXT_TRACK = 0xB0;
private const int VK_MEDIA_PREV_TRACK = 0xB1;
private const int VK_MEDIA_STOP = 0xB2;
private const int VK_MEDIA_PLAY_PAUSE = 0xB3;
private const int VK_LAUNCH_MAIL = 0xB4;
private const int VK_LAUNCH_MEDIA_SELECT= 0xB5;
private const int VK_LAUNCH_APP1 = 0xB6;
private const int VK_LAUNCH_APP2 = 0xB7;
/*
* 0xB8 - 0xB9 : reserved
*/
private const int VK_OEM_1 = 0xBA; // ';:' for US
private const int VK_OEM_PLUS = 0xBB; // '+' any country
private const int VK_OEM_COMMA = 0xBC; // ',' any country
private const int VK_OEM_MINUS = 0xBD; // '-' any country
private const int VK_OEM_PERIOD = 0xBE; // '.' any country
private const int VK_OEM_2 = 0xBF; // '/?' for US
private const int VK_OEM_3 = 0xC0; // '`~' for US
/*
* 0xC1 - 0xD7 : reserved
*/
/*
* 0xD8 - 0xDA : unassigned
*/
private const int VK_OEM_4 = 0xDB; // '[{' for US
private const int VK_OEM_5 = 0xDC; // '\|' for US
private const int VK_OEM_6 = 0xDD; // ']}' for US
private const int VK_OEM_7 = 0xDE; // ''"' for US
private const int VK_OEM_8 = 0xDF;
/*
* 0xE0 : reserved
*/
/*
* Various extended or enhanced keyboards
*/
private const int VK_OEM_AX = 0xE1; // 'AX' key on Japanese AX kbd
private const int VK_OEM_102 = 0xE2; // "<>" or "\|" on RT 102-key kbd.
private const int VK_ICO_HELP = 0xE3; // Help key on ICO
private const int VK_ICO_00 = 0xE4; // 00 key on ICO
/*
* 0xE8 : unassigned
*/
/*
* Nokia/Ericsson definitions
*/
private const int VK_OEM_RESET = 0xE9;
private const int VK_OEM_JUMP = 0xEA;
private const int VK_OEM_PA1 = 0xEB;
private const int VK_OEM_PA2 = 0xEC;
private const int VK_OEM_PA3 = 0xED;
private const int VK_OEM_WSCTRL = 0xEE;
private const int VK_OEM_CUSEL = 0xEF;
private const int VK_OEM_ATTN = 0xF0;
private const int VK_OEM_FINISH = 0xF1;
private const int VK_OEM_COPY = 0xF2;
private const int VK_OEM_AUTO = 0xF3;
private const int VK_OEM_ENLW = 0xF4;
private const int VK_OEM_BACKTAB = 0xF5;
private const int VK_ATTN = 0xF6;
private const int VK_CRSEL = 0xF7;
private const int VK_EXSEL = 0xF8;
private const int VK_EREOF = 0xF9;
private const int VK_PLAY = 0xFA;
private const int VK_ZOOM = 0xFB;
private const int VK_NONAME = 0xFC;
private const int VK_PA1 = 0xFD;
private const int VK_OEM_CLEAR = 0xFE;
}
} | mdavid/IKVM.NET-cvs-clone | awt/robot.cs | C# | gpl-2.0 | 14,656 |
<?php
class WCML_sensei{
function __construct(){
global $sitepress;
add_action( 'manage_edit-lesson_columns', array( $sitepress, 'add_posts_management_column' ) );
add_action( 'manage_edit-course_columns', array( $sitepress, 'add_posts_management_column' ) );
add_action( 'save_post', array( $this, 'save_post_actions' ), 100, 2 );
add_action( 'sensei_log_activity_after', array( $this, 'log_activity_after' ), 10, 3 );
add_filter( 'sensei_bought_product_id', array( $this, 'filter_bought_product_id' ), 10, 2 );
add_action( 'delete_comment', array( $this, 'delete_user_activity' ) );
add_action( 'pre_get_comments', array( $this, 'pre_get_comments') );
}
function save_post_actions( $post_id, $post ){
global $sitepress;
// skip not related post types
if ( !in_array( $post->post_type , array( 'lesson', 'course', 'quiz' ) ) ) {
return;
}
// skip auto-drafts
if ( $post->post_status == 'auto-draft' ) {
return;
}
// skip autosave
if ( isset( $_POST[ 'autosave' ] ) ) {
return;
}
if( $post->post_type == 'quiz' && isset( $_POST[ 'ID' ] ) ){
$this->save_post_actions( $_POST[ 'ID' ], get_post( $_POST[ 'ID' ] ) );
}
// sync fields from original
$trid = $sitepress->get_element_trid( $post_id, 'post_' . $post->post_type );
$translations = $sitepress->get_element_translations( $trid, 'post_' . $post->post_type );
if ( !empty( $translations ) ) {
$original_post_id = false;
foreach ( $translations as $t ) {
if ( $t->original ) {
$original_post_id = $t->element_id;
break;
}
}
if ( $post_id != $original_post_id ) {
$this->sync_custom_fields( $original_post_id, $post_id, $post->post_type );
} else {
foreach ( $translations as $t ) {
if ( $original_post_id != $t->element_id ) {
$this->sync_custom_fields( $original_post_id, $t->element_id, $post->post_type );
}
}
}
}
}
function sync_custom_fields ( $original_post_id, $post_id, $post_type ){
global $sitepress;
$language = $sitepress->get_language_for_element( $post_id, 'post_'.$post_type );
if( $post_type == 'quiz' ){
//sync quiz lesson
$lesson_id = get_post_meta( $original_post_id, '_quiz_lesson', true );
if( $lesson_id ){
$tr_lesson_id = apply_filters( 'translate_object_id', $lesson_id, 'post_lesson', false, $language );
if( !is_null( $tr_lesson_id ) ){
update_post_meta( $post_id, '_quiz_lesson', $tr_lesson_id );
}
}else{
delete_post_meta( $post_id, '_quiz_lesson' );
}
} elseif( $post_type == 'lesson' ){
//sync lesson course
$course_id = get_post_meta( $original_post_id, '_lesson_course', true );
if( $course_id ){
$tr_course_id = apply_filters( 'translate_object_id', $course_id, 'post_course', false, $language );
if( !is_null( $tr_course_id ) ){
update_post_meta( $post_id, '_lesson_course', $tr_course_id );
}
}else{
delete_post_meta( $post_id, '_lesson_course' );
}
//sync lesson prerequisite
$lesson_id = get_post_meta( $original_post_id, '_lesson_prerequisite', true );
if( $lesson_id ){
$tr_lesson_id = apply_filters( 'translate_object_id', $lesson_id, 'post_lesson', false, $language );
if( !is_null( $tr_lesson_id ) ){
update_post_meta( $post_id, '_lesson_prerequisite', $tr_lesson_id );
}
}else{
delete_post_meta( $post_id, '_lesson_prerequisite' );
}
}else{
//sync course woocommerce_product
$product_id = get_post_meta( $original_post_id, '_course_woocommerce_product', true );
if( $product_id ){
$tr_product_id = apply_filters( 'translate_object_id', $product_id, 'post_product', false, $language );
if( !is_null( $tr_product_id ) ){
update_post_meta( $post_id, '_course_woocommerce_product', $tr_product_id );
}
}else{
delete_post_meta( $post_id, '_course_woocommerce_product' );
}
//sync course prerequisite
$course_id = get_post_meta( $original_post_id, '_course_prerequisite', true );
if( $course_id ){
$tr_course_id = apply_filters( 'translate_object_id', $course_id, 'post_course', false, $language );
if( !is_null( $tr_course_id ) ){
update_post_meta( $post_id, '_course_prerequisite', $tr_course_id );
}
}else{
delete_post_meta( $post_id, '_course_prerequisite' );
}
}
}
function log_activity_after ( $args, $data, $comment_id ){
global $sitepress;
$comment_post_id = $data['comment_post_ID'];
$trid = $sitepress->get_element_trid( $comment_post_id, 'post_'.get_post_type( $comment_post_id ) );
$translations = $sitepress->get_element_translations( $trid, 'post_'.get_post_type( $comment_post_id ) );
foreach($translations as $translation){
if( $comment_post_id != $translation->element_id ){
$data['comment_post_ID'] = $translation->element_id;
$trid = $sitepress->get_element_trid( $comment_id, 'comment' );
$tr_comment_id = apply_filters( 'translate_object_id', $comment_id, 'comment', false, $translation->language_code );
if ( isset( $args['action'] ) && 'update' == $args['action'] && !is_null( $tr_comment_id ) && get_comment( $tr_comment_id ) ) {
$data['comment_ID'] = $tr_comment_id;
$tr_comment_id = wp_update_comment( $data );
}else{
$tr_comment_id = wp_insert_comment( $data );
$sitepress->set_element_language_details( $tr_comment_id, 'comment', $trid, $translation->language_code );
}
}
}
}
function filter_bought_product_id( $product_id, $order ){
$order_language = get_post_meta( $order->id, 'wpml_language', true );
$tr_product_id = apply_filters( 'translate_object_id', $product_id, 'post_'.get_post_type( $product_id ), false, $order_language );
if( !is_null( $tr_product_id ) ){
return $tr_product_id;
}else{
return $product_id;
}
}
function delete_user_activity ( $comment_id ){
global $sitepress;
$comment_type = get_comment_type( $comment_id );
if( strstr( $comment_type, "sensei" ) ){
$trid = $sitepress->get_element_trid( $comment_id, 'comment' );
$translations = $sitepress->get_element_translations( $trid, 'comment' );
remove_action( 'delete_comment', array ( $this, 'delete_user_activity' ) );
foreach ( $translations as $translation ){
if( $comment_id != $translation->element_id ){
wp_delete_comment( $translation->element_id, true );
}
}
}
}
function pre_get_comments($obj){
global $sitepress;
if( $obj->query_vars[ 'type' ] == 'sensei_course_start' ){
remove_filter( 'comments_clauses', array( $sitepress, 'comments_clauses' ), 10, 2 );
}
}
}
| SasaKlepikov/Syberg.eu | wp-content/plugins/woocommerce-multilingual/compatibility/wc_sensei.class.php | PHP | gpl-2.0 | 7,952 |
<?php namespace Iiigel\Controller;
class Iiigel extends \Iiigel\Controller\StaticPage {
const DEFAULT_ACTION = 'show';
protected $sRawOutput = NULL;
protected $oCloud = NULL;
protected $oInterpreter = NULL;
protected $oChapter = NULL;
protected $oModule = NULL;
public function __construct() {
if(!isset($GLOBALS['oUserLogin'])) {
throw new \Exception(_('error.permission'));
}
parent::__construct();
$this->oCloud = new \Iiigel\Model\Cloud();
}
/**
* Loads an environment (= module, chapter and interpreter) based on a given hash (either module hash or chapter hash).
*
* @param string [$_sHashId = ''] module or chapter hashed ID
* @return boolean true if successfully loaded
*/
protected function loadEnvironment($_sHashId = '') {
$this->oChapter = $this->oModule = NULL;
if($_sHashId{0} == 'm') {
$this->oModule = new \Iiigel\Model\Module($_sHashId);
$nCurrentChapter = $this->oModule->nCurrentChapter;
if ($nCurrentChapter == 0) {
$this->oChapter = new \Iiigel\Model\Chapter();
$oResult = $this->oChapter->getList($this->oModule->nId);
if(($aRow = $GLOBALS['oDb']->get($oResult))) {
$this->oChapter = new \Iiigel\Model\Chapter($aRow['sHashId']);
} else {
$this->oChapter = NULL;
}
} else {
$this->oChapter = new \Iiigel\Model\Chapter($nCurrentChapter);
}
} else {
$aTemp = array();
foreach ($this->oView->aCheckedHandins as $oRow) {
if ($oRow['sLearn'] !== $_sHashId) {
$aTemp[] = $oRow;
}
}
$this->oView->aCheckedHandins = $aTemp;
$this->oChapter = new \Iiigel\Model\Chapter($_sHashId);
$this->oModule = new \Iiigel\Model\Module(intval($this->oChapter->nIdModule));
}
if($this->oModule->nId > 0 && $this->oChapter !== NULL) {
if($this->oChapter->sInterpreter !== NULL) {
$sInterpreter = '\\Iiigel\\View\\Interpreter\\'.$this->oChapter->sInterpreter;
if(class_exists($sInterpreter)) {
$this->oInterpreter = new $sInterpreter($this->oCloud);
} else {
$this->oInterpreter = new \Iiigel\View\Interpreter\File($this->oCloud);
}
}
return TRUE;
} else {
return FALSE;
}
}
/**
* Output rendered static HTML page.
*
* @return string HTML code
*/
public function output() {
return ($GLOBALS['bAjax'] && $this->sRawOutput !== NULL) ? $this->sRawOutput : $this->oView->render();
}
/**
* Display the main module training view.
*
* @param string $_sHashId if module ID, first chapter of this module is shown; if chapter ID, this chapter is shown
*/
public function show($_sHashId = '') {
if($this->loadEnvironment($_sHashId)) {
//check if current user is in this module
//load module data (incl. chapter)
$this->oView->oModule = $this->oModule;
$this->oChapter->sText = $this->oChapter->replaceTags( $this->oChapter->sText);
$this->oView->oChapter = $this->oChapter;
$this->oView->nEditorWaitTime = $GLOBALS['aConfig']['nEditorWaitTime'];
$this->oView->bHandin = FALSE;
$this->oView->oHandin = NULL;
$this->oView->icurrentuserprogress = $this->oModule->getCurrentChapterProgressOrder($GLOBALS['oUserLogin']->nId);
$this->loadFile('iiigel');
} else {
throw new \Exception(sprintf(_('error.objectload'), $_sHashId));
}
}
public function lookAtHandin($_sHashId) {
$aTemp = array();
foreach ($this->oView->aReviewHandins as $oRow) {
if ($oRow['sHashId'] !== $_sHashId) {
$aTemp[] = $oRow;
}
}
$this->oView->aReviewHandins = $aTemp;
$oHandin = new \Iiigel\Model\Handin($_sHashId);
$oGroup = new \Iiigel\Model\Group(intval($oHandin->nIdGroup));
if ($this->hasGroupEditPermission($oGroup->sHashId)) {
$this->oCloud = new \Iiigel\Model\Cloud(intval($oHandin->nIdCreator));
$this->oChapter = new \Iiigel\Model\Chapter(intval($oHandin->nIdChapter));
$this->oModule = new \Iiigel\Model\Module(intval($this->oChapter->nIdModule));
if($oHandin->sInterpreter !== NULL) {
$sInterpreter = '\\Iiigel\\View\\Interpreter\\'.$oHandin->sInterpreter;
if(class_exists($sInterpreter)) {
$this->oInterpreter = new $sInterpreter($this->oCloud);
} else {
$this->oInterpreter = new \Iiigel\View\Interpreter\File($this->oCloud);
}
$this->oView->oModule = $this->oModule;
$this->oChapter->sText = $this->oChapter->replaceTags( $this->oChapter->sText);
$this->oView->oChapter = $this->oChapter;
$this->oView->nEditorWaitTime = $GLOBALS['aConfig']['nEditorWaitTime'];
$this->oView->bHandin = TRUE;
$this->oView->oHandin = $oHandin;
$this->loadFile('iiigel');
} else {
throw new \Exception(sprintf(_('error.objectload'), $_sHashId));
}
} else {
throw new \Exception(_('error.permission'));
}
}
/**
* Loads cloud and sets ->sRawOutput accordingly.
*/
public function cloud() {
$this->sRawOutput = json_encode($this->oCloud->get());
}
/**
* Interpretes a specific file within a specific chapter. Sets any (HTML) output into ->sRawOutput (without doctype, html, head, body tags).
*
* @param string $_sHashIdFile hash ID of element to interpret
* @param string $_sHashIdChapter hash ID of chapter to be interpreted in (important for correct interpreter)
* @param string $_sHashIdHandin hash ID of handin to set interpreter and finding file-content
*/
public function interpret($_sHashIdFile, $_sHashIdChapter, $_sHashIdHandin = '') {
if (strlen($_sHashIdChapter) > 0) {
if($this->loadEnvironment($_sHashIdChapter)) {
if(($oFile = $this->oCloud->loadFile($_sHashIdFile))) {
$this->sRawOutput = $this->oInterpreter->interpret($oFile);
return;
}
} else {
throw new \Exception($_sHashIdFile." - ".$_sHashIdChapter);
}
} else
if (strlen($_sHashIdHandin) > 0) {
$oHandin = new \Iiigel\Model\Handin($_sHashIdHandin);
$this->oCloud = new \Iiigel\Model\Cloud(intval($oHandin->nIdCreator));
$this->oChapter = new \Iiigel\Model\Chapter(intval($oHandin->nIdChapter));
$this->oModule = new \Iiigel\Model\Module(intval($this->oChapter->nIdModule));
if($oHandin->sInterpreter !== NULL) {
$sInterpreter = '\\Iiigel\\View\\Interpreter\\'.$oHandin->sInterpreter;
if(class_exists($sInterpreter)) {
$this->oInterpreter = new $sInterpreter($this->oCloud);
} else {
$this->oInterpreter = new \Iiigel\View\Interpreter\File($this->oCloud);
}
if(($oFile = $this->oCloud->loadFile($_sHashIdFile))) {
$this->sRawOutput = $this->oInterpreter->interpret($oFile);
return;
}
} else {
throw new \Exception($_sHashIdFile." - ".$_sHashIdHandin);
}
}
throw new \Exception(_('error.filenotfound'));
}
/**
* Open a specific file. Sets File() object to ->sRawOutput, allowing to manually redirect in case the MIME type is not text/...
*
* @param string $_sHashId hash ID of element to open
*/
public function open($_sHashId) {
$this->sRawOutput = json_encode($this->oCloud->loadFile($_sHashId)->getCompleteEntry(TRUE));
}
/**
* Closes file.
*
* @param string $_sHashId hash ID of element to close
*/
public function close($_sHashId) {
$this->sRawOutput = $this->oCloud->closeFile($_sHashId);
}
/**
* Save a file's new contents. Does output TRUE on success.
*
* @param string $_sHashId hash ID of element to be updated
* @param string $_sContent new contents
*/
public function update($_sHashId, $_sContent) {
$oFile = $this->oCloud->loadFile($_sHashId);
$oFile->sFile = $_sContent;
$this->sRawOutput = $oFile->update();
}
/**
* Create a new file (empty) and returns the new cloud structure.
*
* @param string $_sHashIdParent hash ID of parent element, if invalid/NULL/empty, element is put to root element
* @param string $_sName new file's name
*/
public function createFile($_sHashIdParent, $_sName) {
if($this->oCloud->createFile($_sName, new \Iiigel\Model\Folder($_sHashIdParent, $this->oCloud))) {
$this->sRawOutput = json_encode($this->oCloud->get());
} else {
$this->sRawOutput = _('error.create');
}
}
/**
* Create a new directory (empty) and returns the new cloud structure.
*
* @param string $_sHashIdParent hash ID of parent element, if invalid/NULL/empty, element is put to root element
* @param string $_sName new folder's name
*/
public function createDir($_sHashIdParent, $_sName) {
if($this->oCloud->createFolder($_sName, new \Iiigel\Model\Folder($_sHashIdParent, $this->oCloud))) {
$this->sRawOutput = json_encode($this->oCloud->get());
} else {
$this->sRawOutput = _('error.create');
}
}
/**
* Renames any element (either file or folder). Returns new cloud structure.
*
* @param string $_sHashId hash ID of element to be renamed
* @param string $_sNewName new name
*/
public function rename($_sHashId, $_sNewName) {
if($this->oCloud->rename($_sHashId, $_sNewName)) {
$this->sRawOutput = json_encode($this->oCloud->get());
} else {
$this->sRawOutput = _('error.update');
}
}
/**
* Deletes any element (either file or folder). If folder, all child elements are deleted as well. Returns new cloud structure.
*
* @param string $_sHashId hash ID of element to be deleted
*/
public function delete($_sHashId) {
if($this->oCloud->delete($_sHashId)) {
$this->sRawOutput = json_encode($this->oCloud->get());
} else {
$this->sRawOutput = sprintf(_('error.delete'), 'Cloud', $_sHashId);
}
}
/**
* Presents a file/folder for download. Uses HTTP headers and dies afterwards.
* If element to be downloaded is a folder, this folder gets zip'ed and presented for download.
*
* @param string $_sHashId hash ID of element to download
*/
public function download($_sHashId) {
//DOWNLOAD a file (presented as download) or ZIP&DOWNLOAD a folder (presented as download)
//die() afterwards
$oFile = $this->oCloud->loadFile($_sHashId);
if ($oFile !== NULL) {
$aEntry = $oFile->getCompleteEntry(TRUE);
$this->oCloud->closeFile($_sHashId);
if ($aEntry['bFilesystem']) {
if ($aEntry['sType'] === 'folder') {
// ... ZIP
} else
if (strpos($aEntry['sType'], 'text') !== 0) {
$this->redirect($aEntry['sFile'].'?a=download');
}
}
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Content-Type: '.$aEntry['sType']);
header('Content-Length: '.strlen($aEntry['sFile']));
header('Content-Disposition: attachment; filename="'.$aEntry['sName'].'"');
die($aEntry['sFile']);
}
}
/**
* Upload a file from the local machine.
*
* @param string $_sHashId hash ID of folder into which files should be loaded
*/
public function uploadFromHost($_sHashId) {
$oUpload = new \Iiigel\Generic\Upload();
foreach ($oUpload->getFiles() as $sKey => $aFile) {
$this->oCloud->uploadFile($aFile, new \Iiigel\Model\Folder($_sHashId, $this->oCloud));
}
$this->sRawOutput = json_encode($this->oCloud->get());
}
/**
* Upload a file from the web.
*
* @param string $_sHashId hash ID of folder into which files should be loaded
* @param string $_sUrl URL to be included
*/
public function uploadFromUrl($_sHashId, $_sUrl) {
//PUSH file_get_contents or curl into cloud from current folder
$this->sRawOutput = json_encode($this->oCloud->get());
}
/**
* Submit a handin for the current chapter.
*/
public function submit($_sHashIdChapter) {
if ($this->loadEnvironment($_sHashIdChapter)) {
$sState = $this->oCloud->getCurrentState();
$nIdUser = $GLOBALS['oDb']->escape($GLOBALS['oUserLogin']->nId);
$nIdModule = $GLOBALS['oDb']->escape($this->oModule->nId);
$nIdChapter = $GLOBALS['oDb']->escape($this->oChapter->nId);
$oResult = $GLOBALS['oDb']->query('SELECT user2group.nIdGroup AS nIdGroup FROM user2group, chapter WHERE NOT user2group.bDeleted AND user2group.nIdUser = '.$nIdUser.' AND user2group.nIdModule = '.$nIdModule.' AND user2group.nIdChapter = chapter.nId AND chapter.nId = '.$nIdChapter.' ORDER BY chapter.nOrder DESC LIMIT 1;');
if ($GLOBALS['oDb']->count($oResult) > 0) {
if ($aRow = $GLOBALS['oDb']->get($oResult)) {
$oResult = $GLOBALS['oDb']->query('SELECT * FROM handin WHERE
nIdCreator = '.$nIdUser.' AND
nIdGroup = '.$GLOBALS['oDb']->escape($aRow['nIdGroup']).' AND
nIdChapter = '.$nIdChapter.'
LIMIT 1;');
if ($GLOBALS['oDb']->count($oResult) > 0) {
$oHandin = new \Iiigel\Model\Handin($GLOBALS['oDb']->get($oResult));
$oHandin->bCurrentlyUnderReview = !$oHandin->bCurrentlyUnderReview;
if ($oHandin->update()) {
$this->sRawOutput = $sState;
}
} else {
$oHandin = new \Iiigel\Model\Handin(array(
"nIdGroup" => $aRow['nIdGroup'],
"nIdChapter" => $this->oChapter->nId,
"sInterpreter" => $this->oChapter->sInterpreter,
"sCloud" => $sState
));
if ($oHandin->create() !== NULL) {
$this->sRawOutput = $sState;
}
}
}
}
}
}
/**
* Accepts a handin for the current chapter.
*/
public function accept($_sHashId) {
$oHandin = new \Iiigel\Model\Handin($_sHashId);
$oGroup = new \Iiigel\Model\Group(intval($oHandin->nIdGroup));
if ($this->hasGroupEditPermission($oGroup->sHashId)) {
$oChapter = new \Iiigel\Model\Chapter(intval($oHandin->nIdChapter));
$nOrder = $GLOBALS['oDb']->escape($oChapter->nOrder);
$nIdModule = $GLOBALS['oDb']->escape($oChapter->nIdModule);
$nIdUser = $GLOBALS['oDb']->escape($oHandin->nIdCreator);
$nIdGroup = $GLOBALS['oDb']->escape($oGroup->nId);
$GLOBALS['oDb']->query('UPDATE `user2group` SET `nIdChapter` = (SELECT `nId` FROM `chapter` WHERE NOT `bDeleted` AND `bLive` AND `nOrder` > '.$nOrder.' AND `nIdModule` = '.$nIdModule.' ORDER BY `nOrder` ASC LIMIT 1) WHERE NOT `bDeleted` AND `nIdUser` = '.$nIdUser.' AND `nIdGroup` = '.$nIdGroup.';');
$this->sRawOutput = ($oHandin->delete()? 'y' : 'n');
} else {
throw new \Exception(_('error.permission'));
}
}
/**
* Denies a handin for the current chapter.
*/
public function deny($_sHashId) {
$oHandin = new \Iiigel\Model\Handin($_sHashId);
$oGroup = new \Iiigel\Model\Group(intval($oHandin->nIdGroup));
if ($this->hasGroupEditPermission($oGroup->sHashId)) {
$oHandin->bCurrentlyUnderReview = !$oHandin->bCurrentlyUnderReview;
$oHandin->nRound += 1;
$this->sRawOutput = ($oHandin->update()? 'y' : 'n');
} else {
throw new \Exception(_('error.permission'));
}
}
}
?>
| MarHai/iiigel | src/Controller/Iiigel.php | PHP | gpl-2.0 | 16,286 |
<?
/**[N]**
* JIBAS Education Community
* Jaringan Informasi Bersama Antar Sekolah
*
* @version: 3.2 (September 03, 2013)
* @notes: JIBAS Education Community will be managed by Yayasan Indonesia Membaca (http://www.indonesiamembaca.net)
*
* Copyright (C) 2009 Yayasan Indonesia Membaca (http://www.indonesiamembaca.net)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
**[N]**/ ?>
<?
require_once('../include/errorhandler.php');
require_once('../include/sessioninfo.php');
require_once('../include/common.php');
require_once('../include/config.php');
require_once('../include/db_functions.php');
require_once('../library/departemen.php');
require_once('../include/getheader.php');
$departemen=$_REQUEST['departemen'];
$tahunawal=$_REQUEST['tahunawal'];
$tahunakhir=$_REQUEST['tahunakhir'];
OpenDb();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="../style/style.css" rel="stylesheet" type="text/css">
<style type="text/css">
<!--
.style2 {
font-size: 24px;
font-weight: bold;
}
-->
</style><script language="javascript" src="../script/tables.js"></script></head>
<body>
<table width="100%" border="0">
<tr>
<td><?=getHeader($departemen)?></td>
</tr>
<tr>
<td>
<p align="center"><strong>STATISTIK MUTASI SISWA</strong><br>
<strong>TAHUN :
<?=$tahunawal?>
s/d
<?=$tahunakhir?>
</strong><br>
<br>
<img src="gambar_statistik.php?departemen=<?=$departemen?>&tahunakhir=<?=$tahunakhir?>&tahunawal=<?=$tahunawal?>" ></p>
<table width="100%" border="1" align="center" cellpadding="3" cellspacing="0" class="tab" bordercolor="#000000">
<tr class="header">
<td width="5" height="30" align="center">No</td>
<td width="54%" height="30" align="center">Jenis Mutasi</td>
<td width="31%" height="30">Jumlah </td>
</tr>
<?
$sql1="SELECT * FROM jbsakad.jenismutasi ORDER BY replid";
$result1=QueryDb($sql1);
$cnt=1;
while ($row1=@mysql_fetch_array($result1)){
$sql2="SELECT COUNT(*) FROM jbsakad.mutasisiswa m,jbsakad.siswa s,jbsakad.kelas k,jbsakad.tahunajaran ta,jbsakad.tingkat ti WHERE s.idkelas=k.replid AND k.idtahunajaran=ta.replid AND k.idtingkat=ti.replid AND ti.departemen='$departemen' AND ta.departemen='$departemen' AND s.statusmutasi='$row1[replid]' AND m.jenismutasi='$row1[replid]' AND s.statusmutasi=m.jenismutasi AND m.nis=s.nis";
$result2=QueryDb($sql2);
$row2=@mysql_fetch_row($result2);
?>
<tr><td><?=$cnt?></td><td><?=$row1[jenismutasi]?></td><td><?=$row2[0]?> siswa</td></tr>
<?
$sql3="SELECT COUNT(*),YEAR(m.tglmutasi) FROM mutasisiswa m,siswa s,kelas k,tingkat ti,tahunajaran ta WHERE m.jenismutasi='$row1[replid]' AND YEAR(m.tglmutasi)<='$tahunakhir' AND YEAR(m.tglmutasi)>='$tahunawal' AND m.nis=s.nis AND k.idtahunajaran=ta.replid AND k.idtingkat=ti.replid AND s.idkelas=k.replid AND ta.departemen='$departemen' AND ti.departemen='$departemen' GROUP BY YEAR(m.tglmutasi)";
$result3=QueryDb($sql3);
while ($row3=@mysql_fetch_row($result3)){
?>
<tr><td> </td><td>- <?=$row3[1]?></td><td><?=$row3[0]?> siswa</td></tr>
<?
}
$cnt++;
}
?>
</table>
</td>
</tr>
</table>
<script language="javascript">
window.print();
</script>
</body>
</html> | nurulimamnotes/sistem-informasi-sekolah | jibas/akademik/mutasi/cetak_statistik_mutasi.php | PHP | gpl-2.0 | 3,993 |
define(['jquery', 'util.tooltips', 'helper.boxes', 'modules/panel'], function($, tooltips, panel) {
/* Grid */
tourStepsGrid = [
{
beginning: true,
title: 'Welcome to the Blox Visual Editor!',
content: '<p>If this is your first time in the Blox Visual Editor, <strong>we recommend following this tour so you can get the most out of Blox</strong>.</p><p>Or, if you\'re experienced or want to dive in right away, just click the close button in the top right at any time.</p>'
},
{
target: $('li#mode-grid'),
title: 'Mode Selector',
content: '<p>The Blox Visual Editor is split up into 2 modes.</p><p><ul><li><strong>Grid</strong> – Build your layouts</li><li><strong>Design</strong> – Add colors, customize fonts, and more!</li></ul></p>',
position: {
my: 'top left',
at: 'bottom center'
}
},
{
target: $('#layout-selector-select-content'),
title: 'Layout Selector',
content: '<p style="font-size:12px;">Since you may not want every page to be the same, you may use the Layout Selector to select which page, post, or archive to edit.</p><p style="font-size:12px;">The Layout Selector is based off of inheritance. For example, you can customize the "Page" layout and all pages will follow that layout. Plus, you can customize a specific page and it\'ll be different than all other pages.</p><p style="font-size:12px;">The layout selector will allow you to be as precise or broad as you wish. It\'s completely up to you!</p>',
position: {
my: 'top center',
at: 'bottom center'
}
},
{
target: $('div#box-grid-wizard'),
title: 'The Blox Grid',
content: '<p>Now we\'re ready to get started with the Blox Grid. In other words, the good stuff.</p><p>To build your first layout, please select a preset to the right to pre-populate the grid. Or, you may select "Use Empty Grid" to start with a completely blank grid.</p><p>Once you have a preset selected, click "Finish".</p>',
position: {
my: 'right top',
at: 'left center'
},
nextHandler: {
showButton: false,
clickElement: '#grid-wizard-button-preset-use-preset, span.grid-wizard-use-empty-grid',
message: 'Please click <strong>"Finish"</strong> or <strong>"Use Empty Grid"</strong> to continue.'
}
},
{
iframeTarget: 'div.grid-container',
title: 'Adding Blocks',
content: '<p>To add a block, simply place your mouse into the grid then click at where you\'d like the top-left point of the block to be.</p><p>Drag your mouse and the block will appear! Once the block appears, you may choose the block type.</p><p>Hint: Don\'t worry about being precise, you may always move or resize the block.</p>',
position: {
my: 'right top',
at: 'left top',
adjustY: 100
},
maxWidth: 280
},
{
iframeTarget: 'div.grid-container',
title: 'Modifying Blocks',
content: '\
<p style="font-size:12px;">After you\'ve added the desired blocks to your layout, you may move, resize, delete, or change the options of the block at any time.</p>\
<ul style="font-size:12px;">\
<li><strong>Moving Blocks</strong> – Click and drag the block. If you wish to move multiple blocks simultaneously, double-click on a block to enter <em>Mass Block Selection Mode</em>.</li>\
<li><strong>Resizing Blocks</strong> – Grab the border or corner of the block and drag your mouse.</li>\
<li><strong>Block Options (e.g. header image)</strong> – Hover over the block then click the block options icon in the top-right.</li>\
<li><strong>Deleting Blocks</strong> – Move your mouse over the desired block, then click the <em>X</em> icon in the top-right.</li>\
</ul>',
position: {
my: 'right top',
at: 'left top',
adjustY: 100
},
maxWidth: 280
},
{
target: $('#save-button-container'),
title: 'Saving',
content: '<p>Now that you hopefully have a few changes to be saved, you can save using this spiffy Save button.</p><p>For those of you who like hotkeys, use <strong>Ctrl + S</strong> to save.</p>',
position: {
my: 'top right',
at: 'bottom center'
},
tip: 'top right'
},
{
target: $('li#mode-design a'),
title: 'Design Mode',
content: '<p>Thanks for sticking with us!</p><p>Now that you have an understanding of the Grid Mode, we hope you stick with us and head on over to the Design Mode.</p>',
position: {
my: 'top left',
at: 'bottom center',
adjustY: 5
},
tip: 'top left',
buttonText: 'Continue to Design Mode',
buttonCallback: function () {
$.post(Blox.ajaxURL, {
security: Blox.security,
action: 'blox_visual_editor',
method: 'ran_tour',
mode: 'grid',
complete: function () {
Blox.ranTour['grid'] = true;
/* Advance to Design Editor */
$('li#mode-design a').trigger('click');
window.location = $('li#mode-design a').attr('href');
}
});
}
}
];
/* Design */
tourStepsDesign = [
{
beginning: true,
title: 'Welcome to the Blox Design Editor!',
content: "<p>In the <strong>Design Editor</strong>, you can style your elements however you'd like.</p><p>Whether it's fonts, colors, padding, borders, shadows, or rounded corners, you can use the design editor.</p><p>Stick around to learn more!</p>"
},
{
target: '#side-panel-top',
title: 'Element Selector',
content: '<p>The element selector allows you choose which element to edit.</p>',
position: {
my: 'right top',
at: 'left center'
},
callback: function () {
$('li#element-block-header > span.element-name').trigger('click');
}
},
{
target: '#toggle-inspector',
title: 'Inspector',
content: "\
<p>Instead of using the <em>Element Selector</em>, let the Inspector do the work for you.</p>\
<p><strong>Try it out!</strong> Point and right-click on the element you wish to edit and it will become selected!</p>\
",
position: {
my: 'top right',
at: 'bottom center',
adjustX: 10,
adjustY: 5
}
},
{
target: 'window',
title: 'Have fun building with Blox!',
content: '<p>We hope you find Blox to the most powerful and easy-to-use WordPress framework around.</p><p>If you have any questions, please don\'t hesitate to visit the <a href="http://support.bloxtheme.com/?utm_source=visualeditor&utm_medium=blox&utm_campaign=tour" target="_blank">support forums</a>.</p>',
end: true
}
];
return {
start: function () {
if ( Blox.mode == 'grid' ) {
var steps = tourStepsGrid;
hidePanel();
openBox('grid-wizard');
} else if ( Blox.mode == 'design' ) {
var steps = tourStepsDesign;
showPanel();
require(['modules/design/mode-design'], function() {
showDesignEditor();
});
if ( typeof $('div#panel').data('ui-tabs') != 'undefined' )
selectTab('editor-tab', $('div#panel'));
} else {
return;
}
$('<div class="black-overlay"></div>')
.hide()
.attr('id', 'black-overlay-tour')
.css('zIndex', 15)
.appendTo('body')
.fadeIn(500);
$(document.body).qtip({
id: 'tour', // Give it an ID of qtip-tour so we an identify it easily
content: {
text: steps[0].content + '<div id="tour-next-container"><span id="tour-next" class="tour-button button button-blue">Continue Tour <span class="arrow">›</span></span></div>',
title: {
text: steps[0].title, // ...and title
button: 'Skip Tour'
}
},
style: {
classes: 'qtip-tour',
tip: {
width: 18,
height: 10,
mimic: 'center',
offset: 10
}
},
position: {
my: 'center',
at: 'center',
target: $(window), // Also use first steps position target...
viewport: $(window), // ...and make sure it stays on-screen if possible
adjust: {
y: 5,
method: 'shift shift'
}
},
show: {
event: false, // Only show when show() is called manually
ready: true, // Also show on page load,
effect: function () {
$(this).fadeIn(500);
}
},
hide: false, // Don't hide unless we call hide()
events: {
render: function (event, api) {
$('#iframe-notice').remove();
hideIframeOverlay();
openBox('grid-wizard');
// Grab tooltip element
var tooltip = api.elements.tooltip;
// Track the current step in the API
api.step = 0;
// Bind custom custom events we can fire to step forward/back
tooltip.bind('next', function (event) {
/* For some reason trigger window resizing helps tooltip positioning */
$(window).trigger('resize');
// Increase/decrease step depending on the event fired
api.step += 1;
api.step = Math.min(steps.length - 1, Math.max(0, api.step));
// Set new step properties
currentTourStep = steps[api.step];
$('div#black-overlay-tour').fadeOut(100, function () {
$(this).remove();
});
//Run the callback if it exists
if ( typeof currentTourStep.callback === 'function' ) {
currentTourStep.callback.apply(api);
}
if ( currentTourStep.target == 'window' ) {
currentTourStep.target = $(window);
} else if ( typeof currentTourStep.target == 'string' ) {
currentTourStep.target = $(currentTourStep.target);
} else if ( typeof currentTourStep.iframeTarget == 'string' ) {
currentTourStep.target = $i(currentTourStep.iframeTarget).first();
}
api.set('position.target', currentTourStep.target);
if ( typeof currentTourStep.maxWidth !== 'undefined' && window.innerWidth < 1440 ) {
$('.qtip-tour').css('maxWidth', currentTourStep.maxWidth);
} else {
$('.qtip-tour').css('maxWidth', 350);
}
/* Set up button */
var buttonText = 'Next';
if ( typeof currentTourStep.buttonText == 'string' )
var buttonText = currentTourStep.buttonText;
if ( typeof currentTourStep.end !== 'undefined' && currentTourStep.end === true ) {
var button = '<div id="tour-next-container"><span id="tour-finish" class="tour-button button button-blue">Close Tour <span class="arrow">›</span></div>';
} else if ( typeof currentTourStep.nextHandler === 'undefined' || currentTourStep.nextHandler.showButton ) {
var button = '<div id="tour-next-container"><span id="tour-next" class="tour-button button button-blue">' + buttonText + ' <span class="arrow">›</span></div>';
} else {
var button = '<div id="tour-next-container"><p>' + currentTourStep.nextHandler.message + '</p></div>';
}
/* Next Handler Callback... Be able to use something other than the button */
if ( typeof currentTourStep.nextHandler !== 'undefined' && $(currentTourStep.nextHandler.clickElement) ) {
var nextHandlerCallback = function (event) {
$('.qtip-tour').triggerHandler('next');
event.preventDefault();
$(this).unbind('click', nextHandlerCallback);
}
$(currentTourStep.nextHandler.clickElement).bind('click', nextHandlerCallback);
}
/* Set the Content */
api.set('content.text', currentTourStep.content + button);
api.set('content.title', currentTourStep.title);
if ( typeof currentTourStep.end === 'undefined' ) {
/* Position */
if ( typeof currentTourStep.position !== 'undefined' ) {
api.set('position.my', currentTourStep.position.my);
api.set('position.at', currentTourStep.position.at);
/* Offset/Adjust */
if ( typeof currentTourStep.position.adjustX !== 'undefined' ) {
api.set('position.adjust.x', currentTourStep.position.adjustX);
} else {
api.set('position.adjust.x', 0);
}
if ( typeof currentTourStep.position.adjustY !== 'undefined' ) {
api.set('position.adjust.y', currentTourStep.position.adjustY);
} else {
api.set('position.adjust.y', 0);
}
} else {
api.set('position.my', 'top center');
api.set('position.at', 'bottom center');
}
if ( typeof currentTourStep.tip !== 'undefined' )
api.set('style.tip.corner', currentTourStep.tip);
} else {
api.set('position.my', 'center');
api.set('position.at', 'center');
}
});
/* Tour Button Bindings */
$('div.qtip-tour').on('click', 'span#tour-next', function (event) {
/* Callback that fires upon button click... Used for advancing to Design Editor */
if ( typeof currentTourStep == 'object' && typeof currentTourStep.buttonCallback == 'function' )
currentTourStep.buttonCallback.call();
$('.qtip-tour').triggerHandler('next');
event.preventDefault();
});
$('div.qtip-tour').on('click', 'span#tour-finish', function (event) {
$('.qtip-tour').qtip('hide');
});
},
// Destroy the tooltip after it hides as its no longer needed
hide: function (event, api) {
$('div#tour-overlay').remove();
$('div#black-overlay-tour').fadeOut(100, function () {
$(this).remove();
});
$('.qtip-tour').fadeOut(100, function () {
$(this).qtip('destroy');
});
//Tell the DB that the tour has been ran
if ( Blox.ranTour[Blox.mode] == false && Blox.ranTour.legacy != true ) {
$.post(Blox.ajaxURL, {
security: Blox.security,
action: 'blox_visual_editor',
method: 'ran_tour',
mode: Blox.mode
});
Blox.ranTour[Blox.mode] = true;
}
}
}
});
}
}
}); | bloxtheme/BloxTheme | bloxtheme/library/visual-editor/scripts-src/util.tour.js | JavaScript | gpl-2.0 | 13,717 |
using System.Diagnostics;
using System.Xml.Serialization;
namespace IDF.Utilities.ProcLaunch
{
public class ProcInfo
{
[XmlAttribute]
public string Path { get; set; }
[XmlAttribute]
public string WorkingDir { get; set; }
[XmlAttribute]
public string Arguments { get; set; }
[XmlAttribute]
public bool Restart { get; set; }
[XmlIgnore]
public Process ProcessInfo;
[XmlIgnore]
public ProcInfo Parent { get; set; }
}
} | StoneFin/ProcessLauncher | IDFProcLaunch/ProcInfo.cs | C# | gpl-2.0 | 474 |
/**
* Created by inwebo on 05/02/15.
*/
alert('local');
| inwebo/Libre | demos/assets/instances/www.test.fr/themes/default/public/js/demo.js | JavaScript | gpl-2.0 | 58 |
/*++
*
* Kafka Message Queue
*
* DESCRIPTION:
* AUTHOR: NickeyWoo
* DATE: 2014/8/15
*
--*/
#ifndef __KAFKA_PRODUCER_HH__
#define __KAFKA_PRODUCER_HH__
#include <boost/nocopyable.hpp>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/message.h>
#include <google/protobuf/descriptor.h>
class KafkaProducer :
public boost::nocopyable
{
public:
template<typename MessageT>
void Push(std::string strTopic, std::string strGroupId, MessageT* pstMessage)
{
}
private:
};
#endif // define __KAFKA_PRODUCER_HH__
| NickeyWoo/SimpleRPC | Kafka/Kafka/Producer.hh | C++ | gpl-2.0 | 545 |
<?php
namespace Stormpath\Authc\Api;
use Stormpath\Resource\ApiKey;
use Stormpath\Resource\Application;
class AuthenticatorResult
{
protected $application;
protected $apiKey;
protected $accessToken;
public function __construct(Application $application, ApiKey $apiKey, $accessToken = null)
{
$this->application = $application;
$this->apiKey = $apiKey;
if($accessToken) {
$this->accessToken = $accessToken;
}
}
public function getApplication()
{
return $this->application;
}
public function getApiKey()
{
return $this->apiKey;
}
public function getAccessToken()
{
return $this->accessToken;
}
}
| arckinteractive/elgg_stormpath | vendor/stormpath/sdk/src/Stormpath/Authc/Api/AuthenticatorResult.php | PHP | gpl-2.0 | 734 |
<?php
/*
* This file is part of the Eventum (Issue Tracking System) package.
*
* @copyright (c) Eventum Team
* @license GNU General Public License, version 2 or later (GPL-2+)
*
* For the full copyright and license information,
* please see the COPYING and AUTHORS files
* that were distributed with this source code.
*/
namespace Eventum\Controller;
use Auth;
use AuthCookie;
use Eventum\Controller\Helper\MessagesHelper;
use Setup;
use User;
class SignupController extends BaseController
{
/** @var string */
protected $tpl_name = 'signup.tpl.html';
/** @var string */
private $cat;
/**
* {@inheritdoc}
*/
protected function configure()
{
$request = $this->getRequest();
$this->cat = $request->request->get('cat');
}
/**
* {@inheritdoc}
*/
protected function canAccess()
{
// log anonymous users out so they can use the signup form
if (AuthCookie::hasAuthCookie() && Auth::isAnonUser()) {
Auth::logout();
}
return true;
}
/**
* {@inheritdoc}
*/
protected function defaultAction()
{
if ($this->cat == 'signup') {
$this->createVisitorAccountAction();
}
}
private function createVisitorAccountAction()
{
$setup = Setup::get();
if ($setup['open_signup'] != 'enabled') {
$error = ev_gettext('Sorry, but this feature has been disabled by the administrator.');
$this->error($error);
}
$res = User::createVisitorAccount($setup['accounts_role'], $setup['accounts_projects']);
$this->tpl->assign('signup_result', $res);
// TODO: translate
$map = [
1 => ['Thank you, your account creation request was processed successfully. For security reasons a confirmation email was sent to the provided email address with instructions on how to confirm your request and activate your account.', MessagesHelper::MSG_INFO],
-1 => ['Error: An error occurred while trying to run your query.', MessagesHelper::MSG_ERROR],
-2 => ['Error: The email address specified is already associated with an user in the system.', MessagesHelper::MSG_ERROR],
];
$this->messages->mapMessages($res, $map);
}
/**
* {@inheritdoc}
*/
protected function prepareTemplate()
{
}
}
| mariadb-corporation/eventum | src/Controller/SignupController.php | PHP | gpl-2.0 | 2,410 |
# simpleSound.py
# Plays audio files on Linux and Windows.
# Written Jan-2008 by Timothy Weber.
# Based on (reconstituted) code posted by Bill Dandreta at <http://www.velocityreviews.com/forums/t337346-how-to-play-sound-in-python.html>.
import platform
if platform.system().startswith('Win'):
from winsound import PlaySound, SND_FILENAME, SND_ASYNC
elif platform.system().startswith('Linux'):
from wave import open as waveOpen
from ossaudiodev import open as ossOpen
try:
from ossaudiodev import AFMT_S16_NE
except ImportError:
if byteorder == "little":
AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
else:
AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
def Play(filename):
"""Plays the sound in the given filename, asynchronously."""
if platform.system().startswith('Win'):
PlaySound(filename, SND_FILENAME|SND_ASYNC)
elif platform.system().startswith('Linux'):
try:
s = waveOpen(filename,'rb')
(nc,sw,fr,nf,comptype, compname) = s.getparams( )
dsp = ossOpen('/dev/dsp','w')
dsp.setparameters(AFMT_S16_NE, nc, fr)
data = s.readframes(nf)
s.close()
dsp.write(data)
dsp.close()
except:
pass
| teejaydub/khet | simpleSound.py | Python | gpl-2.0 | 1,290 |
# -*- coding: utf-8 -*-
# Copyright 2011 Christoph Reiter <reiter.christoph@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
import os
import sys
if os.name == "nt" or sys.platform == "darwin":
from quodlibet.plugins import PluginNotSupportedError
raise PluginNotSupportedError
import dbus
from quodlibet import _
from quodlibet import app
from quodlibet.qltk import Icons
from quodlibet.plugins.events import EventPlugin
def get_toplevel_xid():
if app.window.get_window():
try:
return app.window.get_window().get_xid()
except AttributeError: # non x11
pass
return 0
class InhibitFlags(object):
LOGOUT = 1
USERSWITCH = 1 << 1
SUSPEND = 1 << 2
IDLE = 1 << 3
class SessionInhibit(EventPlugin):
PLUGIN_ID = "screensaver_inhibit"
PLUGIN_NAME = _("Inhibit Screensaver")
PLUGIN_DESC = _("Prevents the GNOME screensaver from activating while"
" a song is playing.")
PLUGIN_ICON = Icons.PREFERENCES_DESKTOP_SCREENSAVER
DBUS_NAME = "org.gnome.SessionManager"
DBUS_INTERFACE = "org.gnome.SessionManager"
DBUS_PATH = "/org/gnome/SessionManager"
APPLICATION_ID = "quodlibet"
INHIBIT_REASON = _("Music is playing")
__cookie = None
def enabled(self):
if not app.player.paused:
self.plugin_on_unpaused()
def disabled(self):
if not app.player.paused:
self.plugin_on_paused()
def plugin_on_unpaused(self):
xid = dbus.UInt32(get_toplevel_xid())
flags = dbus.UInt32(InhibitFlags.IDLE)
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
self.__cookie = iface.Inhibit(
self.APPLICATION_ID, xid, self.INHIBIT_REASON, flags)
except dbus.DBusException:
pass
def plugin_on_paused(self):
if self.__cookie is None:
return
try:
bus = dbus.SessionBus()
obj = bus.get_object(self.DBUS_NAME, self.DBUS_PATH)
iface = dbus.Interface(obj, self.DBUS_INTERFACE)
iface.Uninhibit(self.__cookie)
self.__cookie = None
except dbus.DBusException:
pass
| elbeardmorez/quodlibet | quodlibet/quodlibet/ext/events/inhibit.py | Python | gpl-2.0 | 2,526 |
#include "../ProtocolCommand.h"
//#include <sqlite3.h>
using namespace org::esb::net;
using namespace org::esb::hive;
using namespace std;
class CreateHive:public ProtocolCommand {
private:
Socket * socket;
public:
~CreateHive () {
} CreateHive (TcpSocket * socket) {
this->socket = socket;
this->is = socket->getInputStream ();
this->os = socket->getOutputStream ();
}
CreateHive (InputStream * is, OutputStream * os) {
this->is = is;
this->os = os;
}
int isResponsible (cmdId & cmid) {
}
int isResponsible (char *command) {
if (strstr (command, "create hive") > 0) {
return CMD_PROCESS;
}
else if (strcmp (command, "help") == 0) {
return CMD_HELP;
}
return CMD_NA;
}
void process (char *data) {
string msg = "Creating Hive at ";
string path = data + 12;
msg += path;
os->write ((char *) msg.c_str (), msg.length ());
string tableFile = "CREATE TABLE FILE (id, name, size, type)";
string tablePacket =
"CREATE TABLE PACKET (id,pts,dts,stream_index,flags,duration,pos,data_size,data)";
string tableJob = "CREATE TABLE JOB(id,infile,outfile)";
sqlite3 *db;
sqlite3_stmt *pStmt;
char *zErrMsg = 0;
int rc = sqlite3_open (path.c_str (), &db);
if (rc) {
fprintf (stderr, "Can't open database: %s\n",
sqlite3_errmsg (db));
sqlite3_close (db);
return;
}
sqlite3_exec (db, tableFile.c_str (), NULL, NULL, NULL);
sqlite3_exec (db, tablePacket.c_str (), NULL, NULL, NULL);
sqlite3_exec (db, tableJob.c_str (), NULL, NULL, NULL);
}
void printHelp () {
}
};
| psychobob666/MediaEncodingCluster | src/org/esb/hive/protocol/CreateHive.cpp | C++ | gpl-2.0 | 1,553 |
<?php
namespace SimpleCalendar\plugin_deps;
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/*
* Unknown default region, use the first alphabetically.
*/
return require __DIR__ . '/sgs_LT.php';
| projectestac/wordpress-gce | third-party/nesbot/carbon/src/Carbon/Lang/sgs.php | PHP | gpl-2.0 | 375 |
/* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright (C) 2009 - 2012 Jun Liu and Jieping Ye
*/
#include <shogun/lib/slep/overlapping/overlapping.h>
void identifySomeZeroEntries(double * u, int * zeroGroupFlag, int *entrySignFlag,
int *pp, int *gg,
double *v, double lambda1, double lambda2,
int p, int g, double * w, double *G){
int i, j, newZeroNum, iterStep=0;
double twoNorm, temp;
/*
* process the L1 norm
*
* generate the u>=0, and assign values to entrySignFlag
*
*/
for(i=0;i<p;i++){
if (v[i]> lambda1){
u[i]=v[i]-lambda1;
entrySignFlag[i]=1;
}
else{
if (v[i] < -lambda1){
u[i]= -v[i] -lambda1;
entrySignFlag[i]=-1;
}
else{
u[i]=0;
entrySignFlag[i]=0;
}
}
}
/*
* Applying Algorithm 1 for identifying some sparse groups
*
*/
/* zeroGroupFlag denotes whether the corresponding group is zero */
for(i=0;i<g;i++)
zeroGroupFlag[i]=1;
while(1){
iterStep++;
if (iterStep>g+1){
printf("\n Identify Zero Group: iterStep= %d. The code might have a bug! Check it!", iterStep);
return;
}
/*record the number of newly detected sparse groups*/
newZeroNum=0;
for (i=0;i<g;i++){
if(zeroGroupFlag[i]){
/*compute the two norm of the */
twoNorm=0;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
temp=u[ (int) G[j]];
twoNorm+=temp*temp;
}
twoNorm=sqrt(twoNorm);
/*
printf("\n twoNorm=%2.5f, %2.5f",twoNorm,lambda2 * w[3*i+2]);
*/
/*
* Test whether this group should be sparse
*/
if (twoNorm<= lambda2 * w[3*i+2] ){
zeroGroupFlag[i]=0;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++)
u[ (int) G[j]]=0;
newZeroNum++;
/*
printf("\n zero group=%d", i);
*/
}
} /*end of if(!zeroGroupFlag[i]) */
} /*end of for*/
if (newZeroNum==0)
break;
}
*pp=0;
/* zeroGroupFlag denotes whether the corresponding entry is zero */
for(i=0;i<p;i++){
if (u[i]==0){
entrySignFlag[i]=0;
*pp=*pp+1;
}
}
*gg=0;
for(i=0;i<g;i++){
if (zeroGroupFlag[i]==0)
*gg=*gg+1;
}
}
void xFromY(double *x, double *y,
double *u, double *Y,
int p, int g, int *zeroGroupFlag,
double *G, double *w){
int i,j;
for(i=0;i<p;i++)
x[i]=u[i];
for(i=0;i<g;i++){
if(zeroGroupFlag[i]){ /*this group is non-zero*/
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
x[ (int) G[j] ] -= Y[j];
}
}
}/*end of for(i=0;i<g;i++) */
for(i=0;i<p;i++){
if (x[i]>=0){
y[i]=0;
}
else{
y[i]=x[i];
x[i]=0;
}
}
}
void YFromx(double *Y,
double *xnew, double *Ynew,
double lambda2, int g, int *zeroGroupFlag,
double *G, double *w){
int i, j;
double twoNorm, temp;
for(i=0;i<g;i++){
if(zeroGroupFlag[i]){ /*this group is non-zero*/
twoNorm=0;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
temp=xnew[ (int) G[j] ];
Y[j]=temp;
twoNorm+=temp*temp;
}
twoNorm=sqrt(twoNorm); /* two norm for x_{G_i}*/
if (twoNorm > 0 ){ /*if x_{G_i} is non-zero*/
temp=lambda2 * w[3*i+2] / twoNorm;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++)
Y[j] *= temp;
}
else /*if x_{G_j} =0, we let Y^i=Ynew^i*/
{
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++)
Y[j]=Ynew[j];
}
}
}/*end of for(i=0;i<g;i++) */
}
void dualityGap(double *gap, double *penalty2,
double *x, double *Y, int g, int *zeroGroupFlag,
double *G, double *w, double lambda2){
int i,j;
double temp, twoNorm, innerProduct;
*gap=0; *penalty2=0;
for(i=0;i<g;i++){
if(zeroGroupFlag[i]){ /*this group is non-zero*/
twoNorm=0;innerProduct=0;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
temp=x[ (int) G[j] ];
twoNorm+=temp*temp;
innerProduct+=temp * Y[j];
}
twoNorm=sqrt(twoNorm)* w[3*i +2];
*penalty2+=twoNorm;
twoNorm=lambda2 * twoNorm;
if (twoNorm > innerProduct)
*gap+=twoNorm-innerProduct;
}
}/*end of for(i=0;i<g;i++) */
}
void overlapping_gd(double *x, double *gap, double *penalty2,
double *v, int p, int g, double lambda1, double lambda2,
double *w, double *G, double *Y, int maxIter, int flag, double tol){
int YSize=(int) w[3*(g-1) +1]+1;
double *u=(double *)malloc(sizeof(double)*p);
double *y=(double *)malloc(sizeof(double)*p);
double *xnew=(double *)malloc(sizeof(double)*p);
double *Ynew=(double *)malloc(sizeof(double)* YSize );
int *zeroGroupFlag=(int *)malloc(sizeof(int)*g);
int *entrySignFlag=(int *)malloc(sizeof(int)*p);
int pp, gg;
int i, j, iterStep;
double twoNorm,temp, L=1, leftValue, rightValue, gapR, penalty2R;
int nextRestartStep=0;
/*
* call the function to identify some zero entries
*
* entrySignFlag[i]=0 denotes that the corresponding entry is definitely zero
*
* zeroGroupFlag[i]=0 denotes that the corresponding group is definitely zero
*
*/
identifySomeZeroEntries(u, zeroGroupFlag, entrySignFlag,
&pp, &gg,
v, lambda1, lambda2,
p, g, w, G);
penalty2[1]=pp;
penalty2[2]=gg;
/*store pp and gg to penalty2[1] and penalty2[2]*/
/*
*-------------------
* Process Y
*-------------------
* We make sure that Y is feasible
* and if x_i=0, then set Y_{ij}=0
*/
for(i=0;i<g;i++){
if(zeroGroupFlag[i]){ /*this group is non-zero*/
/*compute the two norm of the group*/
twoNorm=0;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
if (! u[ (int) G[j] ] )
Y[j]=0;
twoNorm+=Y[j]*Y[j];
}
twoNorm=sqrt(twoNorm);
if (twoNorm > lambda2 * w[3*i+2] ){
temp=lambda2 * w[3*i+2] / twoNorm;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++)
Y[j]*=temp;
}
}
else{ /*this group is zero*/
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++)
Y[j]=0;
}
}
/*
* set Ynew to zero
*
* in the following processing, we only operator Y and Ynew in the
* possibly non-zero groups by "if(zeroGroupFlag[i])"
*
*/
for(i=0;i<YSize;i++)
Ynew[i]=0;
/*
* ------------------------------------
* Gradient Descent begins here
* ------------------------------------
*/
/*
* compute x=max(u-Y * e, 0);
*
*/
xFromY(x, y, u, Y, p, g, zeroGroupFlag, G, w);
/*the main loop */
for(iterStep=0;iterStep<maxIter;iterStep++){
/*
* the gradient at Y is
*
* omega'(Y)=-x e^T
*
* where x=max(u-Y * e, 0);
*
*/
/*
* line search to find Ynew with appropriate L
*/
while (1){
/*
* compute
* Ynew = proj ( Y + x e^T / L )
*/
for(i=0;i<g;i++){
if(zeroGroupFlag[i]){ /*this group is non-zero*/
twoNorm=0;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
Ynew[j]= Y[j] + x[ (int) G[j] ] / L;
twoNorm+=Ynew[j]*Ynew[j];
}
twoNorm=sqrt(twoNorm);
if (twoNorm > lambda2 * w[3*i+2] ){
temp=lambda2 * w[3*i+2] / twoNorm;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++)
Ynew[j]*=temp;
}
}
}/*end of for(i=0;i<g;i++) */
/*
* compute xnew=max(u-Ynew * e, 0);
*
*void xFromY(double *x, double *y,
* double *u, double *Y,
* int p, int g, int *zeroGroupFlag,
* double *G, double *w)
*/
xFromY(xnew, y, u, Ynew, p, g, zeroGroupFlag, G, w);
/* test whether L is appropriate*/
leftValue=0;
for(i=0;i<p;i++){
if (entrySignFlag[i]){
temp=xnew[i]-x[i];
leftValue+= temp * ( 0.5 * temp + y[i]);
}
}
rightValue=0;
for(i=0;i<g;i++){
if(zeroGroupFlag[i]){ /*this group is non-zero*/
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
temp=Ynew[j]-Y[j];
rightValue+=temp * temp;
}
}
}/*end of for(i=0;i<g;i++) */
rightValue=rightValue/2;
if ( leftValue <= L * rightValue){
temp= L * rightValue / leftValue;
if (temp >5)
L=L*0.8;
break;
}
else{
temp=leftValue / rightValue;
if (L*2 <= temp)
L=temp;
else
L=2*L;
if ( L / g - 2* g ){
if (rightValue < 1e-16){
break;
}
else{
printf("\n GD: leftValue=%e, rightValue=%e, ratio=%e", leftValue, rightValue, temp);
printf("\n L=%e > 2 * %d * %d. There might be a bug here. Otherwise, it is due to numerical issue.", L, g, g);
break;
}
}
}
}
/* compute the duality gap at (xnew, Ynew)
*
* void dualityGap(double *gap, double *penalty2,
* double *x, double *Y, int g, int *zeroGroupFlag,
* double *G, double *w, double lambda2)
*
*/
dualityGap(gap, penalty2, xnew, Ynew, g, zeroGroupFlag, G, w, lambda2);
/*
* flag =1 means restart
*
* flag =0 means with restart
*
* nextRestartStep denotes the next "step number" for
* initializing the restart process.
*
* This is based on the fact that, the result is only beneficial when
* xnew is good. In other words,
* if xnew is not good, then the
* restart might not be helpful.
*/
if ( (flag==0) || (flag==1 && iterStep < nextRestartStep )){
/* copy Ynew to Y, and xnew to x */
memcpy(x, xnew, sizeof(double) * p);
memcpy(Y, Ynew, sizeof(double) * YSize);
/*
printf("\n iterStep=%d, L=%2.5f, gap=%e", iterStep, L, *gap);
*/
}
else{
/*
* flag=1
*
* We allow the restart of the program.
*
* Here, Y is constructed as a subgradient of xnew, based on the
* assumption that Y might be a better choice than Ynew, provided
* that xnew is good enough.
*
*/
/*
* compute the restarting point Y with xnew and Ynew
*
*void YFromx(double *Y,
* double *xnew, double *Ynew,
* double lambda2, int g, int *zeroGroupFlag,
* double *G, double *w)
*/
YFromx(Y, xnew, Ynew, lambda2, g, zeroGroupFlag, G, w);
/*compute the solution with the starting point Y
*
*void xFromY(double *x, double *y,
* double *u, double *Y,
* int p, int g, int *zeroGroupFlag,
* double *G, double *w)
*
*/
xFromY(x, y, u, Y, p, g, zeroGroupFlag, G, w);
/*compute the duality at (x, Y)
*
* void dualityGap(double *gap, double *penalty2,
* double *x, double *Y, int g, int *zeroGroupFlag,
* double *G, double *w, double lambda2)
*
*/
dualityGap(&gapR, &penalty2R, x, Y, g, zeroGroupFlag, G, w, lambda2);
if (*gap< gapR){
/*(xnew, Ynew) is better in terms of duality gap*/
/* copy Ynew to Y, and xnew to x */
memcpy(x, xnew, sizeof(double) * p);
memcpy(Y, Ynew, sizeof(double) * YSize);
/*In this case, we do not apply restart, as (x,Y) is not better
*
* We postpone the "restart" by giving a
* "nextRestartStep"
*/
/*
* we test *gap here, in case *gap=0
*/
if (*gap <=tol)
break;
else{
nextRestartStep=iterStep+ (int) sqrt(gapR / *gap);
}
}
else{ /*we use (x, Y), as it is better in terms of duality gap*/
*gap=gapR;
*penalty2=penalty2R;
}
/*
printf("\n iterStep=%d, L=%2.5f, gap=%e, gapR=%e", iterStep, L, *gap, gapR);
*/
}
/*
* if the duality gap is within pre-specified parameter tol
*
* we terminate the algorithm
*/
if (*gap <=tol)
break;
}
penalty2[3]=iterStep;
penalty2[4]=0;
for(i=0;i<g;i++){
if (zeroGroupFlag[i]==0)
penalty2[4]=penalty2[4]+1;
else{
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
if (x[ (int) G[j] ] !=0)
break;
}
if (j>(int) w[3*i +1])
penalty2[4]=penalty2[4]+1;
}
}
/*
* assign sign to the solution x
*/
for(i=0;i<p;i++){
if (entrySignFlag[i]==-1){
x[i]=-x[i];
}
}
free (u);
free (y);
free (xnew);
free (Ynew);
free (zeroGroupFlag);
free (entrySignFlag);
}
void gradientDescentStep(double *xnew, double *Ynew,
double *LL, double *u, double *y, int *entrySignFlag, double lambda2,
double *x, double *Y, int p, int g, int * zeroGroupFlag,
double *G, double *w){
double twoNorm, temp, L=*LL, leftValue, rightValue;
int i,j;
while (1){
/*
* compute
* Ynew = proj ( Y + x e^T / L )
*/
for(i=0;i<g;i++){
if(zeroGroupFlag[i]){ /*this group is non-zero*/
twoNorm=0;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
Ynew[j]= Y[j] + x[ (int) G[j] ] / L;
twoNorm+=Ynew[j]*Ynew[j];
}
twoNorm=sqrt(twoNorm);
if (twoNorm > lambda2 * w[3*i+2] ){
temp=lambda2 * w[3*i+2] / twoNorm;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++)
Ynew[j]*=temp;
}
}
}/*end of for(i=0;i<g;i++) */
/*
* compute xnew=max(u-Ynew * e, 0);
*
*void xFromY(double *x, double *y,
* double *u, double *Y,
* int p, int g, int *zeroGroupFlag,
* double *G, double *w)
*/
xFromY(xnew, y, u, Ynew, p, g, zeroGroupFlag, G, w);
/* test whether L is appropriate*/
leftValue=0;
for(i=0;i<p;i++){
if (entrySignFlag[i]){
temp=xnew[i]-x[i];
leftValue+= temp * ( 0.5 * temp + y[i]);
}
}
rightValue=0;
for(i=0;i<g;i++){
if(zeroGroupFlag[i]){ /*this group is non-zero*/
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
temp=Ynew[j]-Y[j];
rightValue+=temp * temp;
}
}
}/*end of for(i=0;i<g;i++) */
rightValue=rightValue/2;
/*
printf("\n leftValue =%e, rightValue=%e, L=%e", leftValue, rightValue, L);
*/
if ( leftValue <= L * rightValue){
temp= L * rightValue / leftValue;
if (temp >5)
L=L*0.8;
break;
}
else{
temp=leftValue / rightValue;
if (L*2 <= temp)
L=temp;
else
L=2*L;
if ( L / g - 2* g >0 ){
if (rightValue < 1e-16){
break;
}
else{
printf("\n One Gradient Step: leftValue=%e, rightValue=%e, ratio=%e", leftValue, rightValue, temp);
printf("\n L=%e > 2 * %d * %d. There might be a bug here. Otherwise, it is due to numerical issue.", L, g, g);
break;
}
}
}
}
*LL=L;
}
void overlapping_agd(double *x, double *gap, double *penalty2,
double *v, int p, int g, double lambda1, double lambda2,
double *w, double *G, double *Y, int maxIter, int flag, double tol){
int YSize=(int) w[3*(g-1) +1]+1;
double *u=(double *)malloc(sizeof(double)*p);
double *y=(double *)malloc(sizeof(double)*p);
double *xnew=(double *)malloc(sizeof(double)*p);
double *Ynew=(double *)malloc(sizeof(double)* YSize );
double *xS=(double *)malloc(sizeof(double)*p);
double *YS=(double *)malloc(sizeof(double)* YSize );
/*double *xp=(double *)malloc(sizeof(double)*p);*/
double *Yp=(double *)malloc(sizeof(double)* YSize );
int *zeroGroupFlag=(int *)malloc(sizeof(int)*g);
int *entrySignFlag=(int *)malloc(sizeof(int)*p);
int pp, gg;
int i, j, iterStep;
double twoNorm,temp, L=1, leftValue, rightValue, gapR, penalty2R;
int nextRestartStep=0;
double alpha, alphap=0.5, beta, gamma;
/*
* call the function to identify some zero entries
*
* entrySignFlag[i]=0 denotes that the corresponding entry is definitely zero
*
* zeroGroupFlag[i]=0 denotes that the corresponding group is definitely zero
*
*/
identifySomeZeroEntries(u, zeroGroupFlag, entrySignFlag,
&pp, &gg,
v, lambda1, lambda2,
p, g, w, G);
penalty2[1]=pp;
penalty2[2]=gg;
/*store pp and gg to penalty2[1] and penalty2[2]*/
/*
*-------------------
* Process Y
*-------------------
* We make sure that Y is feasible
* and if x_i=0, then set Y_{ij}=0
*/
for(i=0;i<g;i++){
if(zeroGroupFlag[i]){ /*this group is non-zero*/
/*compute the two norm of the group*/
twoNorm=0;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
if (! u[ (int) G[j] ] )
Y[j]=0;
twoNorm+=Y[j]*Y[j];
}
twoNorm=sqrt(twoNorm);
if (twoNorm > lambda2 * w[3*i+2] ){
temp=lambda2 * w[3*i+2] / twoNorm;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++)
Y[j]*=temp;
}
}
else{ /*this group is zero*/
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++)
Y[j]=0;
}
}
/*
* set Ynew and Yp to zero
*
* in the following processing, we only operate, Yp, Y and Ynew in the
* possibly non-zero groups by "if(zeroGroupFlag[i])"
*
*/
for(i=0;i<YSize;i++)
YS[i]=Yp[i]=Ynew[i]=0;
/*
* ---------------
*
* we first do a gradient descent step for determing the value of an approporate L
*
* Also, we initialize gamma
*
* with Y, we compute a new Ynew
*
*/
/*
* compute x=max(u-Y * e, 0);
*/
xFromY(x, y, u, Y, p, g, zeroGroupFlag, G, w);
/*
* compute (xnew, Ynew) from (x, Y)
*
*
* gradientDescentStep(double *xnew, double *Ynew,
double *LL, double *u, double *y, int *entrySignFlag, double lambda2,
double *x, double *Y, int p, int g, int * zeroGroupFlag,
double *G, double *w)
*/
gradientDescentStep(xnew, Ynew,
&L, u, y,entrySignFlag,lambda2,
x, Y, p, g, zeroGroupFlag,
G, w);
/*
* we have finished one gradient descent to get
*
* (x, Y) and (xnew, Ynew), where (xnew, Ynew) is
*
* a gradient descent step based on (x, Y)
*
* we set (xp, Yp)=(x, Y)
*
* (x, Y)= (xnew, Ynew)
*/
/*memcpy(xp, x, sizeof(double) * p);*/
memcpy(Yp, Y, sizeof(double) * YSize);
/*memcpy(x, xnew, sizeof(double) * p);*/
memcpy(Y, Ynew, sizeof(double) * YSize);
gamma=L;
/*
* ------------------------------------
* Accelerated Gradient Descent begins here
* ------------------------------------
*/
for(iterStep=0;iterStep<maxIter;iterStep++){
while (1){
/*
* compute alpha as the positive root of
*
* L * alpha^2 = (1-alpha) * gamma
*
*/
alpha= ( - gamma + sqrt( gamma * gamma + 4 * L * gamma ) ) / 2 / L;
beta= gamma * (1-alphap)/ alphap / (gamma + L * alpha);
/*
* compute YS= Y + beta * (Y - Yp)
*
*/
for(i=0;i<g;i++){
if(zeroGroupFlag[i]){ /*this group is non-zero*/
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
YS[j]=Y[j] + beta * (Y[j]-Yp[j]);
}
}
}/*end of for(i=0;i<g;i++) */
/*
* compute xS
*/
xFromY(xS, y, u, YS, p, g, zeroGroupFlag, G, w);
/*
*
* Ynew = proj ( YS + xS e^T / L )
*
*/
for(i=0;i<g;i++){
if(zeroGroupFlag[i]){ /*this group is non-zero*/
twoNorm=0;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
Ynew[j]= YS[j] + xS[ (int) G[j] ] / L;
twoNorm+=Ynew[j]*Ynew[j];
}
twoNorm=sqrt(twoNorm);
if (twoNorm > lambda2 * w[3*i+2] ){
temp=lambda2 * w[3*i+2] / twoNorm;
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++)
Ynew[j]*=temp;
}
}
}/*end of for(i=0;i<g;i++) */
/*
* compute xnew=max(u-Ynew * e, 0);
*
*void xFromY(double *x, double *y,
* double *u, double *Y,
* int p, int g, int *zeroGroupFlag,
* double *G, double *w)
*/
xFromY(xnew, y, u, Ynew, p, g, zeroGroupFlag, G, w);
/* test whether L is appropriate*/
leftValue=0;
for(i=0;i<p;i++){
if (entrySignFlag[i]){
temp=xnew[i]-xS[i];
leftValue+= temp * ( 0.5 * temp + y[i]);
}
}
rightValue=0;
for(i=0;i<g;i++){
if(zeroGroupFlag[i]){ /*this group is non-zero*/
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
temp=Ynew[j]-YS[j];
rightValue+=temp * temp;
}
}
}/*end of for(i=0;i<g;i++) */
rightValue=rightValue/2;
if ( leftValue <= L * rightValue){
temp= L * rightValue / leftValue;
if (temp >5)
L=L*0.8;
break;
}
else{
temp=leftValue / rightValue;
if (L*2 <= temp)
L=temp;
else
L=2*L;
if ( L / g - 2* g >0 ){
if (rightValue < 1e-16){
break;
}
else{
printf("\n AGD: leftValue=%e, rightValue=%e, ratio=%e", leftValue, rightValue, temp);
printf("\n L=%e > 2 * %d * %d. There might be a bug here. Otherwise, it is due to numerical issue.", L, g, g);
break;
}
}
}
}
/* compute the duality gap at (xnew, Ynew)
*
* void dualityGap(double *gap, double *penalty2,
* double *x, double *Y, int g, int *zeroGroupFlag,
* double *G, double *w, double lambda2)
*
*/
dualityGap(gap, penalty2,
xnew, Ynew, g, zeroGroupFlag,
G, w, lambda2);
/*
* if the duality gap is within pre-specified parameter tol
*
* we terminate the algorithm
*/
if (*gap <=tol){
memcpy(x, xnew, sizeof(double) * p);
memcpy(Y, Ynew, sizeof(double) * YSize);
break;
}
/*
* flag =1 means restart
*
* flag =0 means with restart
*
* nextRestartStep denotes the next "step number" for
* initializing the restart process.
*
* This is based on the fact that, the result is only beneficial when
* xnew is good. In other words,
* if xnew is not good, then the
* restart might not be helpful.
*/
if ( (flag==0) || (flag==1 && iterStep < nextRestartStep )){
/*memcpy(xp, x, sizeof(double) * p);*/
memcpy(Yp, Y, sizeof(double) * YSize);
/*memcpy(x, xnew, sizeof(double) * p);*/
memcpy(Y, Ynew, sizeof(double) * YSize);
gamma=gamma * (1-alpha);
alphap=alpha;
/*
printf("\n iterStep=%d, L=%2.5f, gap=%e", iterStep, L, *gap);
*/
}
else{
/*
* flag=1
*
* We allow the restart of the program.
*
* Here, Y is constructed as a subgradient of xnew, based on the
* assumption that Y might be a better choice than Ynew, provided
* that xnew is good enough.
*
*/
/*
* compute the restarting point YS with xnew and Ynew
*
*void YFromx(double *Y,
* double *xnew, double *Ynew,
* double lambda2, int g, int *zeroGroupFlag,
* double *G, double *w)
*/
YFromx(YS, xnew, Ynew, lambda2, g, zeroGroupFlag, G, w);
/*compute the solution with the starting point YS
*
*void xFromY(double *x, double *y,
* double *u, double *Y,
* int p, int g, int *zeroGroupFlag,
* double *G, double *w)
*
*/
xFromY(xS, y, u, YS, p, g, zeroGroupFlag, G, w);
/*compute the duality at (xS, YS)
*
* void dualityGap(double *gap, double *penalty2,
* double *x, double *Y, int g, int *zeroGroupFlag,
* double *G, double *w, double lambda2)
*
*/
dualityGap(&gapR, &penalty2R, xS, YS, g, zeroGroupFlag, G, w, lambda2);
if (*gap< gapR){
/*(xnew, Ynew) is better in terms of duality gap*/
/*In this case, we do not apply restart, as (xS,YS) is not better
*
* We postpone the "restart" by giving a
* "nextRestartStep"
*/
/*memcpy(xp, x, sizeof(double) * p);*/
memcpy(Yp, Y, sizeof(double) * YSize);
/*memcpy(x, xnew, sizeof(double) * p);*/
memcpy(Y, Ynew, sizeof(double) * YSize);
gamma=gamma * (1-alpha);
alphap=alpha;
nextRestartStep=iterStep+ (int) sqrt(gapR / *gap);
}
else{
/*we use (xS, YS), as it is better in terms of duality gap*/
*gap=gapR;
*penalty2=penalty2R;
if (*gap <=tol){
memcpy(x, xS, sizeof(double) * p);
memcpy(Y, YS, sizeof(double) * YSize);
break;
}else{
/*
* we do a gradient descent based on (xS, YS)
*
*/
/*
* compute (x, Y) from (xS, YS)
*
*
* gradientDescentStep(double *xnew, double *Ynew,
* double *LL, double *u, double *y, int *entrySignFlag, double lambda2,
* double *x, double *Y, int p, int g, int * zeroGroupFlag,
* double *G, double *w)
*/
gradientDescentStep(x, Y,
&L, u, y, entrySignFlag,lambda2,
xS, YS, p, g, zeroGroupFlag,
G, w);
/*memcpy(xp, xS, sizeof(double) * p);*/
memcpy(Yp, YS, sizeof(double) * YSize);
gamma=L;
alphap=0.5;
}
}
/*
* printf("\n iterStep=%d, L=%2.5f, gap=%e, gapR=%e", iterStep, L, *gap, gapR);
*/
}/* flag =1*/
} /* main loop */
penalty2[3]=iterStep+1;
/*
* get the number of nonzero groups
*/
penalty2[4]=0;
for(i=0;i<g;i++){
if (zeroGroupFlag[i]==0)
penalty2[4]=penalty2[4]+1;
else{
for(j=(int) w[3*i] ; j<= (int) w[3*i +1]; j++){
if (x[ (int) G[j] ] !=0)
break;
}
if (j>(int) w[3*i +1])
penalty2[4]=penalty2[4]+1;
}
}
/*
* assign sign to the solution x
*/
for(i=0;i<p;i++){
if (entrySignFlag[i]==-1){
x[i]=-x[i];
}
}
free (u);
free (y);
free (xnew);
free (Ynew);
free (xS);
free (YS);
/*free (xp);*/
free (Yp);
free (zeroGroupFlag);
free (entrySignFlag);
}
void overlapping(double *x, double *gap, double *penalty2,
double *v, int p, int g, double lambda1, double lambda2,
double *w, double *G, double *Y, int maxIter, int flag, double tol){
switch(flag){
case 0:
case 1:
overlapping_gd(x, gap, penalty2,
v, p, g, lambda1, lambda2,
w, G, Y, maxIter, flag,tol);
break;
case 2:
case 3:
overlapping_agd(x, gap, penalty2,
v, p, g, lambda1, lambda2,
w, G, Y, maxIter, flag-2,tol);
break;
default:
/* printf("\n Wrong flag! The value of flag should be 0,1,2,3. The program uses flag=2.");*/
overlapping_agd(x, gap, penalty2,
v, p, g, lambda1, lambda2,
w, G, Y, maxIter, 0,tol);
break;
}
}
| ratschlab/ASP | src/shogun/lib/slep/overlapping/overlapping.cpp | C++ | gpl-2.0 | 26,209 |
/**
Select
# What? #
Part of my "Responsive Menu Concepts" article on CSS-Tricks
http://css-tricks.com/responsive-menu-concepts
# 2012 by Tim Pietrusky
# timpietrusky.com
**/ | evasmidt/allsafe-drupal | themes/custom/allsafe/js/scripts.js | JavaScript | gpl-2.0 | 191 |
/*****************************************************************************
* slider_manager.cpp : Manage an input slider
*****************************************************************************
* Copyright (C) 2000-2005 the VideoLAN team
* $Id: input_manager.cpp 14556 2006-03-01 19:56:34Z fkuehne $
*
* Authors: Gildas Bazin <gbazin@videolan.org>
* Clément Stenac <zorglub@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "input_manager.hpp"
#include "interface.hpp"
#include "video.hpp"
#include <vlc_meta.h>
/* include the toolbar graphics */
#include "bitmaps/prev.xpm"
#include "bitmaps/next.xpm"
#include "bitmaps/playlist.xpm"
/* IDs for the controls */
enum
{
SliderScroll_Event = wxID_HIGHEST,
DiscMenu_Event,
DiscPrev_Event,
DiscNext_Event
};
BEGIN_EVENT_TABLE(InputManager, wxPanel)
/* Slider events */
EVT_COMMAND_SCROLL(SliderScroll_Event, InputManager::OnSliderUpdate)
/* Disc Buttons events */
EVT_BUTTON(DiscMenu_Event, InputManager::OnDiscMenu)
EVT_BUTTON(DiscPrev_Event, InputManager::OnDiscPrev)
EVT_BUTTON(DiscNext_Event, InputManager::OnDiscNext)
END_EVENT_TABLE()
#define STATUS_STOP 0
#define STATUS_PLAYING 1
#define STATUS_PAUSE 2
/*****************************************************************************
* Constructor.
*****************************************************************************/
InputManager::InputManager( intf_thread_t *_p_intf, Interface *_p_main_intf,
wxWindow *p_parent )
: wxPanel( p_parent )
{
p_intf = _p_intf;
p_main_intf = _p_main_intf;
p_input = NULL;
i_old_playing_status = STATUS_STOP;
i_old_rate = INPUT_RATE_DEFAULT;
b_slider_free = VLC_TRUE;
i_input_hide_delay = 0;
/* Create slider */
slider = new wxSlider( this, SliderScroll_Event, 0, 0, SLIDER_MAX_POS );
/* Create disc buttons */
disc_frame = new wxPanel( this );
disc_menu_button = new wxBitmapButton( disc_frame, DiscMenu_Event,
wxBitmap( playlist_xpm ) );
disc_prev_button = new wxBitmapButton( disc_frame, DiscPrev_Event,
wxBitmap( prev_xpm ) );
disc_next_button = new wxBitmapButton( disc_frame, DiscNext_Event,
wxBitmap( next_xpm ) );
disc_sizer = new wxBoxSizer( wxHORIZONTAL );
disc_sizer->Add( disc_menu_button, 1, wxEXPAND | wxLEFT | wxRIGHT, 1 );
disc_sizer->Add( disc_prev_button, 1, wxEXPAND | wxLEFT | wxRIGHT, 1 );
disc_sizer->Add( disc_next_button, 1, wxEXPAND | wxLEFT | wxRIGHT, 1 );
disc_frame->SetSizer( disc_sizer );
disc_sizer->Layout();
/* Add everything to the panel */
sizer = new wxBoxSizer( wxHORIZONTAL );
SetSizer( sizer );
sizer->Add( slider, 1, wxEXPAND | wxALL, 5 );
sizer->Add( disc_frame, 0, wxALL, 2 );
/* Hide by default */
sizer->Hide( disc_frame );
sizer->Hide( slider );
sizer->Layout();
Fit();
}
InputManager::~InputManager()
{
vlc_mutex_lock( &p_intf->change_lock );
if( p_intf->p_sys->p_input ) vlc_object_release( p_intf->p_sys->p_input );
p_intf->p_sys->p_input = NULL;
vlc_mutex_unlock( &p_intf->change_lock );
}
/*****************************************************************************
* Public methods.
*****************************************************************************/
vlc_bool_t InputManager::IsPlaying()
{
return (p_input && !p_input->b_die);
}
/*****************************************************************************
* Private methods.
*****************************************************************************/
void InputManager::UpdateInput()
{
playlist_t *p_playlist =
(playlist_t *)vlc_object_find( p_intf, VLC_OBJECT_PLAYLIST,
FIND_ANYWHERE );
if( p_playlist != NULL )
{
LockPlaylist( p_intf->p_sys, p_playlist );
p_input = p_intf->p_sys->p_input = p_playlist->p_input;
if( p_intf->p_sys->p_input )
vlc_object_yield( p_intf->p_sys->p_input );
UnlockPlaylist( p_intf->p_sys, p_playlist );
vlc_object_release( p_playlist );
}
}
void InputManager::UpdateNowPlaying()
{
char *psz_now_playing = vlc_input_item_GetInfo( p_input->input.p_item,
_(VLC_META_INFO_CAT), _(VLC_META_NOW_PLAYING) );
if( psz_now_playing && *psz_now_playing )
{
p_main_intf->statusbar->SetStatusText(
wxString(wxU(psz_now_playing)) + wxT( " - " ) +
wxU(p_input->input.p_item->psz_name), 2 );
}
else
{
p_main_intf->statusbar->SetStatusText(
wxU(p_input->input.p_item->psz_name), 2 );
}
free( psz_now_playing );
}
void InputManager::UpdateButtons( vlc_bool_t b_play )
{
if( !b_play )
{
if( i_old_playing_status == STATUS_STOP ) return;
i_old_playing_status = STATUS_STOP;
p_main_intf->TogglePlayButton( PAUSE_S );
p_main_intf->statusbar->SetStatusText( wxT(""), 0 );
p_main_intf->statusbar->SetStatusText( wxT(""), 2 );
/* wxCocoa pretends to support this, but at least 2.6.x doesn't */
#ifndef __APPLE__
#ifdef wxHAS_TASK_BAR_ICON
if( p_main_intf->p_systray )
{
p_main_intf->p_systray->UpdateTooltip(
wxString(wxT("VLC media player - ")) + wxU(_("Stopped")) );
}
#endif
#endif
return;
}
/* Manage Playing status */
vlc_value_t val;
var_Get( p_input, "state", &val );
val.i_int = val.i_int == PAUSE_S ? STATUS_PAUSE : STATUS_PLAYING;
if( i_old_playing_status != val.i_int )
{
i_old_playing_status = val.i_int;
p_main_intf->TogglePlayButton( val.i_int == STATUS_PAUSE ?
PAUSE_S : PLAYING_S );
/* wxCocoa pretends to support this, but at least 2.6.x doesn't */
#ifndef __APPLE__
#ifdef wxHAS_TASK_BAR_ICON
if( p_main_intf->p_systray )
{
p_main_intf->p_systray->UpdateTooltip(
wxU(p_input->input.p_item->psz_name) + wxString(wxT(" - ")) +
(val.i_int == PAUSE_S ? wxU(_("Paused")) : wxU(_("Playing"))));
}
#endif
#endif
}
}
void InputManager::UpdateDiscButtons()
{
vlc_value_t val;
var_Change( p_input, "title", VLC_VAR_CHOICESCOUNT, &val, NULL );
if( val.i_int > 0 && !disc_frame->IsShown() )
{
vlc_value_t val;
#define HELP_MENU N_("Menu")
#define HELP_PCH N_("Previous chapter")
#define HELP_NCH N_("Next chapter")
#define HELP_PTR N_("Previous track")
#define HELP_NTR N_("Next track")
var_Change( p_input, "chapter", VLC_VAR_CHOICESCOUNT, &val, NULL );
if( val.i_int > 0 )
{
disc_menu_button->Show();
disc_sizer->Show( disc_menu_button );
disc_sizer->Layout();
disc_sizer->Fit( disc_frame );
disc_menu_button->SetToolTip( wxU(_( HELP_MENU ) ) );
disc_prev_button->SetToolTip( wxU(_( HELP_PCH ) ) );
disc_next_button->SetToolTip( wxU(_( HELP_NCH ) ) );
}
else
{
disc_menu_button->Hide();
disc_sizer->Hide( disc_menu_button );
disc_prev_button->SetToolTip( wxU(_( HELP_PTR ) ) );
disc_next_button->SetToolTip( wxU(_( HELP_NTR ) ) );
}
ShowDiscFrame();
}
else if( val.i_int == 0 && disc_frame->IsShown() )
{
HideDiscFrame();
}
}
void InputManager::HideSlider()
{
ShowSlider( false );
}
void InputManager::HideDiscFrame()
{
ShowDiscFrame( false );
}
void InputManager::UpdateTime()
{
char psz_time[ MSTRTIME_MAX_SIZE ], psz_total[ MSTRTIME_MAX_SIZE ];
mtime_t i_seconds;
i_seconds = var_GetTime( p_intf->p_sys->p_input, "length" ) / 1000000;
secstotimestr( psz_total, i_seconds );
i_seconds = var_GetTime( p_intf->p_sys->p_input, "time" ) / 1000000;
secstotimestr( psz_time, i_seconds );
p_main_intf->statusbar->SetStatusText(
wxU(psz_time) + wxString(wxT(" / ")) +wxU(psz_total), 0 );
}
void InputManager::Update()
{
/* Update the input */
if( p_input == NULL )
{
UpdateInput();
if( p_input )
{
slider->SetValue( 0 );
}
else if( !i_input_hide_delay )
{
i_input_hide_delay = mdate() + 200000;
}
else if( i_input_hide_delay < mdate() )
{
if( disc_frame->IsShown() ) HideDiscFrame();
if( slider->IsShown() ) HideSlider();
i_input_hide_delay = 0;
}
}
else if( p_input->b_dead )
{
UpdateButtons( VLC_FALSE );
vlc_object_release( p_input );
p_input = NULL;
}
else
{
i_input_hide_delay = 0;
}
if( p_input && !p_input->b_die )
{
vlc_value_t pos, len;
UpdateTime();
UpdateButtons( VLC_TRUE );
UpdateNowPlaying();
UpdateDiscButtons();
/* Really manage the slider */
var_Get( p_input, "position", &pos );
var_Get( p_input, "length", &len );
if( pos.f_float > 0 && !slider->IsShown() ) ShowSlider();
else if( pos.f_float <= 0 && slider->IsShown() ) HideSlider();
/* Update the slider if the user isn't dragging it. */
if( slider->IsShown() && b_slider_free )
{
i_slider_pos = (int)(SLIDER_MAX_POS * pos.f_float);
slider->SetValue( i_slider_pos );
}
/* Manage Speed status */
vlc_value_t val;
var_Get( p_input, "rate", &val );
if( i_old_rate != val.i_int )
{
p_main_intf->statusbar->SetStatusText(
wxString::Format(wxT("x%.2f"),
(float)INPUT_RATE_DEFAULT / val.i_int ), 1 );
i_old_rate = val.i_int;
}
}
}
/*****************************************************************************
* Event Handlers.
*****************************************************************************/
void InputManager::OnDiscMenu( wxCommandEvent& WXUNUSED(event) )
{
input_thread_t *p_input =
(input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT,
FIND_ANYWHERE );
if( p_input )
{
vlc_value_t val; val.i_int = 2;
var_Set( p_input, "title 0", val);
vlc_object_release( p_input );
}
}
void InputManager::OnDiscPrev( wxCommandEvent& WXUNUSED(event) )
{
input_thread_t *p_input =
(input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT,
FIND_ANYWHERE );
if( p_input )
{
int i_type = var_Type( p_input, "prev-chapter" );
vlc_value_t val; val.b_bool = VLC_TRUE;
var_Set( p_input, ( i_type & VLC_VAR_TYPE ) != 0 ?
"prev-chapter" : "prev-title", val );
vlc_object_release( p_input );
}
}
void InputManager::OnDiscNext( wxCommandEvent& WXUNUSED(event) )
{
input_thread_t *p_input =
(input_thread_t *)vlc_object_find( p_intf, VLC_OBJECT_INPUT,
FIND_ANYWHERE );
if( p_input )
{
int i_type = var_Type( p_input, "next-chapter" );
vlc_value_t val; val.b_bool = VLC_TRUE;
var_Set( p_input, ( i_type & VLC_VAR_TYPE ) != 0 ?
"next-chapter" : "next-title", val );
vlc_object_release( p_input );
}
}
void InputManager::OnSliderUpdate( wxScrollEvent& event )
{
vlc_mutex_lock( &p_intf->change_lock );
#ifdef WIN32
if( event.GetEventType() == wxEVT_SCROLL_THUMBRELEASE
|| event.GetEventType() == wxEVT_SCROLL_ENDSCROLL )
{
#endif
if( i_slider_pos != event.GetPosition() && p_intf->p_sys->p_input )
{
vlc_value_t pos;
pos.f_float = (float)event.GetPosition() / (float)SLIDER_MAX_POS;
var_Set( p_intf->p_sys->p_input, "position", pos );
}
#ifdef WIN32
b_slider_free = VLC_TRUE;
}
else
{
b_slider_free = VLC_FALSE;
if( p_intf->p_sys->p_input ) UpdateTime();
}
#endif
#undef WIN32
vlc_mutex_unlock( &p_intf->change_lock );
}
void InputManager::ShowSlider( bool show )
{
if( !!show == !!slider->IsShown() ) return;
UpdateVideoWindow( p_intf, p_main_intf->video_window );
sizer->Show( slider, show );
sizer->Layout();
wxCommandEvent intf_event( wxEVT_INTF, 0 );
p_main_intf->AddPendingEvent( intf_event );
}
void InputManager::ShowDiscFrame( bool show )
{
if( !!show == !!disc_frame->IsShown() ) return;
UpdateVideoWindow( p_intf, p_main_intf->video_window );
sizer->Show( disc_frame, show );
sizer->Layout();
wxCommandEvent intf_event( wxEVT_INTF, 0 );
p_main_intf->AddPendingEvent( intf_event );
}
| scs/uclinux | user/blkfin-apps/vlc/vlc-0.8.6b/modules/gui/wxwidgets/input_manager.cpp | C++ | gpl-2.0 | 13,723 |
<?php defined('IN_IA') or exit('Access Denied');?> <div id="footer">
<span class="pull-left">
<p><?php if(empty($_W['setting']['copyright']['footerleft'])) { ?>Powered by <a href="http://www.weixfu.cn"><b>关于微服务</b></a> v<?php echo IMS_VERSION;?> © 2014 <a href="http://www.weixfu.cn">www.weixfu.cn</a><?php } else { ?><?php echo $_W['setting']['copyright']['footerleft'];?><?php } ?></p>
</span>
<span class="pull-right">
<p><?php if(empty($_W['setting']['copyright']['footerright'])) { ?><a href="http://www.weixfu.cn">关于微服务</a> <?php } else { ?><?php echo $_W['setting']['copyright']['footerright'];?><?php } ?> <?php echo $_W['setting']['copyright']['statcode'];?></p>
</span>
</div>
<div class="emotions" style="display:none;"></div>
</body>
</html> | JoelPub/wordpress-amazon | order/data/tpl/web/default/common/footer.tpl.php | PHP | gpl-2.0 | 825 |
<?php
/**
* Load our components using a static wrapper
*/
namespace MakeitWorkPress\WP_Components;
use WP_Error as WP_Error;
defined( 'ABSPATH' ) or die( 'Go eat veggies!' );
class Build {
/**
* Renders generic template for an atom or molecule.
*
* @param string $type The type, either a molecule or atom
* @param string $template The template to load, either a template in the molecule or atom's folder
* @param array $properties The custom properties for the template
* @param array $render If the element is rendered. If set to false, the contents of the elements are returned
*/
private static function render( $type = 'atom', $template, $properties = [], $render = true ) {
// Empty properties can be neglected
if( empty($properties) ) {
$properties = [];
}
// Properties should be an array
if( ! is_array($properties) ) {
$error = new WP_Error( 'wrong', sprintf(__('The properties for the molecule or atom called %s are not properly formatted as an array.', 'components'), $template) );
echo $error->get_error_message();
return;
}
// If we have atom properties, they should have proper properties
if( isset($properties['atoms']) && is_array($properties['atoms']) ) {
foreach( $properties['atoms'] as $atom ) {
if( ! isset($atom['atom']) ) {
$error = new WP_Error( 'wrong', sprintf(__('The custom atoms within %s are not properly formatted and miss the atom key.', 'components'), $template) );
echo $error->get_error_message();
return;
}
}
}
// Our template path
$path = apply_filters( 'components_' . $type . '_path', COMPONENTS_PATH . $type . 's/' . $template . '.php', $template );
if( file_exists($path) ) {
${$type} = apply_filters( 'components_' . $type . '_properties', self::setDefaultProperties($template, $properties, $type), $template );
// If we have the lazyload script defined, we execute it - but we watch for the WP Optimize Script being active
if( isset(${$type}['lazyload']) && ${$type}['lazyload'] && ! wp_script_is('lazyload') ) {
wp_enqueue_script('lazyload');
}
// If we do not render, we return
if( $render == false ) {
ob_start();
}
require($path);
if( $render == false ) {
return ob_get_clean();
}
} else {
$error = new WP_Error( 'wrong', sprintf( __('The given template for the molecule or atom called %s does not exist.', 'components'), $template ) );
echo $error->get_error_message();
}
}
/**
* Define the default attributes per template. This allows us to dynamically add attributes
*
* @param string $template The template to load
* @param array $properties The custom properties defined by the developer
* @param string $type Whether we load an atom or an molecule
*
* @return array $properties The custom properties merged with the defaults
*/
public static function setDefaultProperties( $template, $properties, $type = 'atom' ) {
// Define our most basic property - the class
$properties['attributes']['class'] = isset($properties['attributes']['class']) ? $type . ' ' . $properties['attributes']['class'] : $type;
$properties['attributes']['class'] .= ' ' . $type . '-' . $template;
/**
* Properties that generate a specific class for a style or are generic
*/
foreach( ['align', 'animation', 'appear', 'background', 'border', 'color', 'display', 'float', 'grid', 'height', 'hover', 'parallax', 'position', 'rounded', 'width'] as $class ) {
if( isset($properties[$class]) && $properties[$class] ) {
// Backgrounds
if( $class == 'background' && preg_match('/hsl|http|https|rgb|linear-gradient|#/', $properties[$class]) ) {
if( preg_match('/http|https/', $properties[$class]) ) {
$properties['attributes']['class'] .= ' components-image-background';
if( isset($properties['lazyload']) && $properties['lazyload'] ) {
$properties['attributes']['data']['bg'] = 'url(' . $properties[$class] . ')';
$properties['attributes']['class'] .= ' lazy';
} else {
$properties['attributes']['style']['background-image'] = 'url(' . $properties[$class] . ')';
}
} else {
$properties['attributes']['style']['background'] = $properties[$class];
}
continue;
}
if( $class == 'border' && preg_match('/hsl|linear-gradient|rgb|#/', $properties[$class]) ) {
if( strpos($properties['border'], 'linear-gradient') === 0 ) {
$properties['attributes']['style']['border'] = '2px solid transparent;';
$properties['attributes']['style']['border-image'] = $properties[$class];
$properties['attributes']['style']['border-image-slice'] = 1;
} else {
$properties['attributes']['style']['border'] = '2px solid ' . $properties[$class];
}
continue;
}
// Color
if( $class == 'color' && preg_match('/hsl|rgb|#/', $properties[$class]) ) {
$properties['attributes']['style']['color'] = $properties[$class];
continue;
}
// Continue if our grid is an array
if( $class == 'grid' && is_array($properties[$class]) ) {
continue;
}
// Height and Width
if( ($class == 'height' || $class == 'width') && preg_match('/ch|em|ex|in|mm|pc|pt|px|rem|vh|vw|%/', $properties[$class]) ) {
$properties['attributes']['style']['min-' . $class] = $properties[$class];
continue;
}
// Set our definite class
$properties['attributes']['class'] .= is_bool($properties[$class]) ? ' components-' . $class : ' components-' . $properties[$class] . '-' . $class;
}
}
return $properties;
}
/**
* Displays any atom
*
* @param string $atom The atom to load
* @param array $variables The custom variables for a molecule
*/
public static function atom( $atom, $variables = array(), $render = true ) {
if( $render == false ) {
return self::render( 'atom', $atom, $variables, $render );
}
self::render( 'atom', $atom, $variables );
}
/**
* Displays any molecule
*
* @param string $molecule The atom to load
* @param array $variables The custom variables for a molecule
*/
public static function molecule( $molecule, $variables = array(), $render = true ) {
if( $render == false ) {
return self::render( 'molecule', $molecule, $variables, $render );
}
self::render( 'molecule', $molecule, $variables );
}
/**
* Turns our attributes into a usuable string for use in our atoms
*
* @param array $attributes The array with custom properties
* @return string $output The attributes as a string
*/
public static function attributes( $attributes = [] ) {
$output = '';
foreach( $attributes as $key => $attribute ) {
// Skip empty attributes
if( ! $attribute ) {
continue;
}
if( $key == 'data' && is_array($attribute) ) {
foreach( $attribute as $data => $value ) {
$output .= 'data-' . $data . '="' . $value . '"';
}
} elseif( $key == 'style' && is_array($attribute) ) {
$output .= $key . '="';
foreach( $attribute as $selector => $value ) {
if( ! $value ) {
continue;
}
$output .= $selector . ':' . $value . ';';
}
$output .= '"';
} else {
$output .= $key .'="' . $attribute . '"';
}
}
return $output;
}
/**
* Allows us to parse arguments in a multidimensional array
*
* @param array $args The arguments to parse
* @param array $default The default arguments
*
* @return array $array The merged array
*/
public static function multiParseArgs( $args, $default ) {
if( ! is_array($default) ) {
return wp_parse_args( $args, $default );
}
$array = [];
// Loop through our multidimensional array
foreach( [$default, $args] as $elements ) {
foreach( $elements as $key => $element ) {
// If we have numbered keys
if( is_integer($key) ) {
$array[] = $element;
// Atoms are always overwritten by the arguments
} elseif( in_array($key, ['atoms', 'contentAtoms', 'footerAtoms', 'headerAtoms', 'image', 'socketAtoms', 'topAtoms']) ) {
$array[$key] = $element;
}
elseif( isset( $array[$key] ) && (is_array( $array[$key] )) && ! empty($array[$key]) && is_array($element) ) {
$array[$key] = self::multiParseArgs( $element, $array[$key] );
} else {
$array[$key] = $element;
}
}
}
return $array;
}
} | leichim/waterfall | vendor/makeitworkpress/wp-components/src/build.php | PHP | gpl-2.0 | 10,695 |
<?php
// notin to do here
| fundar/curul-wp | wp-content/plugins/wordpress-social-login/utilities/index.php | PHP | gpl-2.0 | 28 |
/*
* Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.r.nodes.builtin.base;
import static com.oracle.truffle.r.nodes.builtin.CastBuilder.Predef.stringValue;
import static com.oracle.truffle.r.runtime.RError.Message.MUST_BE_NONNULL_STRING;
import static com.oracle.truffle.r.runtime.builtins.RBehavior.PURE;
import static com.oracle.truffle.r.runtime.builtins.RBuiltinKind.PRIMITIVE;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.dsl.Cached;
import com.oracle.truffle.api.dsl.Fallback;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.r.nodes.attributes.RemoveAttributeNode;
import com.oracle.truffle.r.nodes.attributes.SetAttributeNode;
import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetClassAttributeNode;
import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetDimAttributeNode;
import com.oracle.truffle.r.nodes.attributes.SpecialAttributesFunctions.SetRowNamesAttributeNode;
import com.oracle.truffle.r.nodes.builtin.RBuiltinNode;
import com.oracle.truffle.r.nodes.builtin.base.UpdateAttrNodeGen.InternStringNodeGen;
import com.oracle.truffle.r.nodes.unary.CastIntegerNode;
import com.oracle.truffle.r.nodes.unary.CastIntegerNodeGen;
import com.oracle.truffle.r.nodes.unary.CastListNode;
import com.oracle.truffle.r.nodes.unary.CastToVectorNode;
import com.oracle.truffle.r.nodes.unary.CastToVectorNodeGen;
import com.oracle.truffle.r.nodes.unary.GetNonSharedNode;
import com.oracle.truffle.r.runtime.RError;
import com.oracle.truffle.r.runtime.RError.Message;
import com.oracle.truffle.r.runtime.RRuntime;
import com.oracle.truffle.r.runtime.Utils;
import com.oracle.truffle.r.runtime.builtins.RBuiltin;
import com.oracle.truffle.r.runtime.data.RAttributable;
import com.oracle.truffle.r.runtime.data.RDataFactory;
import com.oracle.truffle.r.runtime.data.RNull;
import com.oracle.truffle.r.runtime.data.RShareable;
import com.oracle.truffle.r.runtime.data.RStringVector;
import com.oracle.truffle.r.runtime.data.model.RAbstractContainer;
import com.oracle.truffle.r.runtime.data.model.RAbstractIntVector;
import com.oracle.truffle.r.runtime.data.model.RAbstractVector;
@RBuiltin(name = "attr<-", kind = PRIMITIVE, parameterNames = {"x", "which", "value"}, behavior = PURE)
public abstract class UpdateAttr extends RBuiltinNode.Arg3 {
@Child private UpdateNames updateNames;
@Child private UpdateDimNames updateDimNames;
@Child private CastIntegerNode castInteger;
@Child private CastToVectorNode castVector;
@Child private CastListNode castList;
@Child private SetClassAttributeNode setClassAttrNode;
@Child private SetRowNamesAttributeNode setRowNamesAttrNode;
@Child private SetAttributeNode setGenAttrNode;
@Child private SetDimAttributeNode setDimNode;
@Child private InternStringNode intern = InternStringNodeGen.create();
public abstract static class InternStringNode extends Node {
public abstract String execute(String value);
@Specialization(limit = "3", guards = "value == cachedValue")
protected static String internCached(@SuppressWarnings("unused") String value,
@SuppressWarnings("unused") @Cached("value") String cachedValue,
@Cached("intern(value)") String interned) {
return interned;
}
@Specialization(replaces = "internCached")
protected static String intern(String value) {
return Utils.intern(value);
}
}
static {
Casts casts = new Casts(UpdateAttr.class);
// Note: cannot check 'attributability' easily because atomic values, e.g int, are not
// RAttributable.
casts.arg("x");
casts.arg("which").defaultError(MUST_BE_NONNULL_STRING, "name").mustBe(stringValue()).asStringVector().findFirst();
}
private RAbstractContainer updateNames(RAbstractContainer container, Object o) {
if (updateNames == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
updateNames = insert(UpdateNamesNodeGen.create());
}
return (RAbstractContainer) updateNames.executeStringVector(container, o);
}
private RAbstractContainer updateDimNames(RAbstractContainer container, Object o) {
if (updateDimNames == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
updateDimNames = insert(UpdateDimNamesNodeGen.create());
}
return updateDimNames.executeRAbstractContainer(container, o);
}
private RAbstractIntVector castInteger(RAbstractVector vector) {
if (castInteger == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
castInteger = insert(CastIntegerNodeGen.create(true, false, false));
}
return (RAbstractIntVector) castInteger.doCast(vector);
}
private RAbstractVector castVector(Object value) {
if (castVector == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
castVector = insert(CastToVectorNodeGen.create(false));
}
return (RAbstractVector) castVector.doCast(value);
}
@Specialization
protected RNull updateAttr(@SuppressWarnings("unused") RNull nullTarget, @SuppressWarnings("unused") String attrName, @SuppressWarnings("unused") RNull nullAttrVal) {
return RNull.instance;
}
@Specialization
protected RAbstractContainer updateAttr(RAbstractContainer container, String name, RNull value,
@Cached("create()") RemoveAttributeNode removeAttrNode,
@Cached("create()") GetNonSharedNode nonShared) {
String internedName = intern.execute(name);
RAbstractContainer result = ((RAbstractContainer) nonShared.execute(container)).materialize();
// the name is interned, so identity comparison is sufficient
if (internedName == RRuntime.DIM_ATTR_KEY) {
if (setDimNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setDimNode = insert(SetDimAttributeNode.create());
}
setDimNode.setDimensions(result, null);
} else if (internedName == RRuntime.NAMES_ATTR_KEY) {
return updateNames(result, value);
} else if (internedName == RRuntime.DIMNAMES_ATTR_KEY) {
return updateDimNames(result, value);
} else if (internedName == RRuntime.CLASS_ATTR_KEY) {
if (setClassAttrNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setClassAttrNode = insert(SetClassAttributeNode.create());
}
setClassAttrNode.reset(result);
return result;
} else if (internedName == RRuntime.ROWNAMES_ATTR_KEY) {
if (setRowNamesAttrNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setRowNamesAttrNode = insert(SetRowNamesAttributeNode.create());
}
setRowNamesAttrNode.setRowNames(result, null);
} else if (result.getAttributes() != null) {
removeAttrNode.execute(result, internedName);
}
return result;
}
@TruffleBoundary
protected static RStringVector convertClassAttrFromObject(Object value) {
if (value instanceof RStringVector) {
return (RStringVector) value;
} else if (value instanceof String) {
return RDataFactory.createStringVector((String) value);
} else {
throw RError.error(RError.SHOW_CALLER, RError.Message.SET_INVALID_CLASS_ATTR);
}
}
@Specialization(guards = "!isRNull(value)")
protected RAbstractContainer updateAttr(RAbstractContainer container, String name, Object value,
@Cached("create()") GetNonSharedNode nonShared) {
String internedName = intern.execute(name);
RAbstractContainer result = ((RAbstractContainer) nonShared.execute(container)).materialize();
// the name is interned, so identity comparison is sufficient
if (internedName == RRuntime.DIM_ATTR_KEY) {
RAbstractIntVector dimsVector = castInteger(castVector(value));
if (dimsVector.getLength() == 0) {
throw error(RError.Message.LENGTH_ZERO_DIM_INVALID);
}
if (setDimNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setDimNode = insert(SetDimAttributeNode.create());
}
setDimNode.setDimensions(result, dimsVector.materialize().getDataCopy());
} else if (internedName == RRuntime.NAMES_ATTR_KEY) {
return updateNames(result, value);
} else if (internedName == RRuntime.DIMNAMES_ATTR_KEY) {
return updateDimNames(result, value);
} else if (internedName == RRuntime.CLASS_ATTR_KEY) {
if (setClassAttrNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setClassAttrNode = insert(SetClassAttributeNode.create());
}
setClassAttrNode.execute(result, convertClassAttrFromObject(value));
return result;
} else if (internedName == RRuntime.ROWNAMES_ATTR_KEY) {
if (setRowNamesAttrNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setRowNamesAttrNode = insert(SetRowNamesAttributeNode.create());
}
setRowNamesAttrNode.setRowNames(result, castVector(value));
} else {
// generic attribute
if (setGenAttrNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
setGenAttrNode = insert(SetAttributeNode.create());
}
setGenAttrNode.execute(result, internedName, value);
}
return result;
}
/**
* All other, non-performance centric, {@link RAttributable} types.
*/
@Fallback
@TruffleBoundary
protected Object updateAttr(Object obj, Object name, Object value) {
assert name instanceof String : "casts should not pass anything but String";
Object object = obj;
if (object instanceof RShareable) {
object = ((RShareable) object).getNonShared();
}
String internedName = intern.execute((String) name);
if (object instanceof RAttributable) {
RAttributable attributable = (RAttributable) object;
if (value == RNull.instance) {
attributable.removeAttr(internedName);
} else {
attributable.setAttr(internedName, value);
}
return object;
} else if (RRuntime.isForeignObject(obj)) {
throw RError.error(this, Message.OBJ_CANNOT_BE_ATTRIBUTED);
} else if (obj == RNull.instance) {
throw RError.error(this, Message.SET_ATTRIBUTES_ON_NULL);
} else {
throw RError.nyi(this, "object cannot be attributed: ");
}
}
}
| akunft/fastr | com.oracle.truffle.r.nodes.builtin/src/com/oracle/truffle/r/nodes/builtin/base/UpdateAttr.java | Java | gpl-2.0 | 12,281 |