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 |
|---|---|---|---|---|---|
'''
TypeString is a core class that extends mimetypes
'''
import re
import os
import mimetypes
import magic
UNKNOWN_MIMETYPE = ('application/x-empty', 'application/octet-stream', 'text/plain')
class TypeString:
def __init__(self, s):
self.str = s
# Extract arguments
if ':' in s:
self.ts_format, _, arguments_str = s.partition(':')
self.arguments = tuple(arguments_str.split(','))
else:
self.ts_format = s
self.arguments = tuple()
# Check if is mimetype, extension or qualifier
self.is_qualifier = False
self.mimetype = None
self.extension = None
if '/' in self.ts_format:
self.mimetype = self.ts_format
ext = mimetypes.guess_extension(self.mimetype)
if ext:
self.extension = ext.strip('.').upper()
elif self.ts_format.isupper():
self.extension = self.ts_format
fn = 'fn.%s' % self.extension
self.mimetype, _ = mimetypes.guess_type(fn) # discard encoding
else:
# Is qualifier, can't determine mimetype
self.is_qualifier = True
def modify_basename(self, basename):
if self.extension:
ext = self.extension.lower()
else:
ext = self.ts_format.replace('/', ':')
if self.arguments:
ext = '.'.join(self.arguments + (ext,))
return '%s.%s' % (basename, ext)
def __str__(self):
return self.str
def __repr__(self):
return "TypeString(%s)" % repr(str(self))
def guess_typestring(path):
'''
Guesses a TypeString from the given path
'''
with open(path, 'rb') as fd:
mimetype = magic.from_buffer(fd.read(128), mime=True)
if mimetype and mimetype not in UNKNOWN_MIMETYPE:
return TypeString(mimetype)
# Otherwise, tries based on extension
_, ext = os.path.splitext(path)
return TypeString(ext.strip('.').upper())
| michaelpb/omnithumb | omnithumb/types/typestring.py | Python | gpl-3.0 | 2,012 |
require 'bibtex/bibliography'
require 'test/unit'
class TestBibliography < Test::Unit::TestCase
include BibTeX
def setup
@b = Bibliography.new
@foo01 = Entry.new(EntryType::Book, 'foo01')
@foo01.add_field :author, 'C. Doof'
@foo01.add_field :year, 2007
@foo01.add_field Field.new(:url, 'www.doof.me.uk')
@bar99 = Entry.new(EntryType::Article, 'bar99')
@bar99.add_field :author, 'N. Cakesniffer'
@bar99.add_field :year, 1999
@bar99.add_field Field.new(:url, 'www.cakesniffer.co.uk')
@b << @foo01
@b << @bar99
end
def test_basic
assert_equal 2, @b.entries.length
assert_equal @foo01, @b['foo01']
end
def test_map
expect = <<END
@article{bar99,
author = {N. Cakesniffer},
year = {1999}
}
@book{foo01,
author = {C. Doof},
year = {2007}
}
END
urlless = @b.map do |e|
e.reject_fields [:url]
end
assert_equal expect, urlless.to_s
end
def test_to_s
expect = <<END
@article{bar99,
author = {N. Cakesniffer},
url = {www.cakesniffer.co.uk},
year = {1999}
}
@book{foo01,
author = {C. Doof},
url = {www.doof.me.uk},
year = {2007}
}
END
assert_equal expect, @b.to_s
end
def test_save
fname = '/tmp/_test.bib'
@b.save fname
f = File.new(fname)
assert_equal @b.to_s, f.read
f.close
File.delete fname
end
end
| nickg/rbib | bibtex/test_bibliography.rb | Ruby | gpl-3.0 | 1,361 |
<?php
namespace Keyword\Model;
use Keyword\Model\Base\KeywordI18n as BaseKeywordI18n;
class KeywordI18n extends BaseKeywordI18n
{
}
| thelia-modules/Keyword | Model/KeywordI18n.php | PHP | gpl-3.0 | 136 |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MetadataGenericContext.cs" company="">
//
// </copyright>
// <summary>
//
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace PEAssemblyReader
{
using System.Collections.Generic;
/// <summary>
/// </summary>
public class MetadataGenericContext : IGenericContext
{
/// <summary>
/// </summary>
private IMethod methodSpecialization;
/// <summary>
/// </summary>
private IType typeSpecialization;
/// <summary>
/// </summary>
public MetadataGenericContext()
: this(new SortedList<IType, IType>())
{
}
/// <summary>
/// </summary>
/// <param name="map">
/// </param>
public MetadataGenericContext(IDictionary<IType, IType> map)
{
this.Map = map;
}
/// <summary>
/// </summary>
/// <param name="type">
/// </param>
/// <param name="allowToUseDefinitionAsSpecialization">
/// </param>
public MetadataGenericContext(IType type, bool allowToUseDefinitionAsSpecialization = false)
: this()
{
this.Init(type, allowToUseDefinitionAsSpecialization);
if (this.TypeSpecialization != null)
{
this.TypeSpecialization.GenericMap(this.Map);
}
}
/// <summary>
/// </summary>
/// <param name="method">
/// </param>
/// <param name="allowToUseDefinitionAsSpecialization">
/// </param>
public MetadataGenericContext(IMethod method, bool allowToUseDefinitionAsSpecialization = false)
: this(method.DeclaringType, allowToUseDefinitionAsSpecialization)
{
this.Init(method, allowToUseDefinitionAsSpecialization);
if (this.MethodSpecialization != null)
{
this.MethodSpecialization.GenericMap(this.Map);
}
}
/// <summary>
/// </summary>
public bool IsEmpty
{
get
{
return this.Map.Count == 0 && this.TypeDefinition == null && this.TypeSpecialization == null && this.MethodDefinition == null
&& this.MethodSpecialization == null;
}
}
/// <summary>
/// </summary>
public IDictionary<IType, IType> Map { get; private set; }
/// <summary>
/// </summary>
public IMethod MethodDefinition { get; set; }
/// <summary>
/// </summary>
public IMethod MethodSpecialization
{
get
{
return this.methodSpecialization;
}
set
{
this.methodSpecialization = value;
if (this.MethodSpecialization != null)
{
this.MethodSpecialization.GenericMap(this.Map);
}
}
}
/// <summary>
/// </summary>
public IType TypeDefinition { get; set; }
/// <summary>
/// </summary>
public IType TypeSpecialization
{
get
{
return this.typeSpecialization;
}
set
{
this.typeSpecialization = value;
if (this.TypeSpecialization != null)
{
this.TypeSpecialization.GenericMap(this.Map);
}
}
}
/// <summary>
/// </summary>
/// <param name="definitionMethod">
/// </param>
/// <param name="specializationMethod">
/// </param>
/// <returns>
/// </returns>
public static IGenericContext CreateMap(IMethod definitionMethod, IMethod specializationMethod)
{
var context = new MetadataGenericContext();
context.Map.GenericMap(definitionMethod.GetGenericParameters(), specializationMethod.GetGenericArguments());
context.Map.GenericMap(definitionMethod.DeclaringType.GenericTypeParameters, specializationMethod.DeclaringType.GenericTypeArguments);
return context;
}
/// <summary>
/// </summary>
/// <param name="method">
/// </param>
/// <param name="allowToUseDefinitionAsSpecialization">
/// </param>
/// <returns>
/// </returns>
public static IGenericContext DiscoverFrom(IMethod method, bool allowToUseDefinitionAsSpecialization = false)
{
if (method.IsGenericMethod || method.IsGenericMethodDefinition)
{
return new MetadataGenericContext(method, allowToUseDefinitionAsSpecialization);
}
var declType = method.DeclaringType;
while (declType != null)
{
if (declType.IsGenericType || declType.IsGenericTypeDefinition)
{
return new MetadataGenericContext(declType, allowToUseDefinitionAsSpecialization);
}
if (declType.IsNested)
{
declType = declType.DeclaringType;
continue;
}
break;
}
return null;
}
/// <summary>
/// </summary>
/// <param name="typeParameter">
/// </param>
/// <returns>
/// </returns>
public IType ResolveTypeParameter(IType typeParameter, bool isByRef = false, bool isPinned = false)
{
IType resolved = null;
if (this.Map.TryGetValue(typeParameter, out resolved))
{
if (isByRef || isPinned)
{
return resolved.Clone(false, false, isByRef, isPinned);
}
return resolved;
}
return typeParameter;
}
/// <summary>
/// </summary>
/// <param name="type">
/// </param>
/// <param name="allowToUseDefinitionAsSpecialization">
/// </param>
private void Init(IType type, bool allowToUseDefinitionAsSpecialization = false)
{
if (type.IsGenericTypeDefinition)
{
this.TypeDefinition = type;
if (allowToUseDefinitionAsSpecialization)
{
this.TypeSpecialization = type;
}
}
if (type.IsGenericType)
{
this.TypeSpecialization = type;
if (this.TypeDefinition == null)
{
this.TypeDefinition = type.GetTypeDefinition();
}
}
}
/// <summary>
/// </summary>
/// <param name="method">
/// </param>
/// <param name="allowToUseDefinitionAsSpecialization">
/// </param>
private void Init(IMethod method, bool allowToUseDefinitionAsSpecialization = false)
{
if (method.IsGenericMethodDefinition)
{
this.MethodDefinition = method;
if (allowToUseDefinitionAsSpecialization)
{
this.MethodSpecialization = method;
}
}
if (method.IsGenericMethod)
{
this.MethodSpecialization = method;
if (this.MethodDefinition == null)
{
this.MethodDefinition = method.GetMethodDefinition();
}
}
}
}
} | FrankLIKE/il2bc | PEAssemblyReader/MetadataGenericContext.cs | C# | gpl-3.0 | 7,903 |
namespace CSV_Analyzer_Pro {
partial class CheckUpdate {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CheckUpdate));
this.label1 = new System.Windows.Forms.Label();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(142, 38);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(108, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Checking for updates";
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(145, 54);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(100, 23);
this.progressBar1.TabIndex = 1;
//
// button1
//
this.button1.Location = new System.Drawing.Point(157, 88);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 2;
this.button1.Text = "Ok";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// CheckUpdate
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(393, 123);
this.Controls.Add(this.button1);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.label1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "CheckUpdate";
this.Text = "CheckUpdate";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Button button1;
}
} | flaminggenius/CSVAnalyzerPro | CSV Analyzer Pro/CSV Analyzer Pro/CheckUpdate.Designer.cs | C# | gpl-3.0 | 3,238 |
<?php
/**
* @In the name of God!
* @author: Iman Moodi (Iman92) & Mohammad Sadgeh Dehghan Niri (MSDN)
* @email: info@apadanacms.ir
* @link: http://www.apadanacms.ir
* @license: http://www.gnu.org/licenses/
* @copyright: Copyright © 2012-2015 ApadanaCms.ir. All rights reserved.
* @Apadana CMS is a Free Software
**/
defined('security') or exit('Direct Access to this location is not allowed.');
class comments
{
public $type;
public $link;
public $action;
public $options;
public $comments;
public $comments_count;
public $message;
public $total;
/**
* This var show comment posing status.if a comment posted and added to database it will be true
* else if comment posting was unsuccessful it will be false else if there is no comment to post
* it is null (by default)
*
* @since 1.1
*/
public $comment_posted = null;
public $start = 1;
public $length = null;
public function __construct($type, $link, $action)
{
$this->type = alphabet($type);
$this->link = intval($link);
$this->action = $action;
$this->options();
}
public function options()
{
if (!$this->options = get_cache('options-comments'))
{
global $d;
$d->query("SELECT `option_value` FROM `#__options` WHERE `option_name`='comments' LIMIT 1");
$result = $d->fetch();
$d->free_result();
$this->options = maybe_unserialize($result['option_value']);
set_cache('options-comments', $this->options);
}
return $this->options;
}
/**
* Get Commets
*
* This function make a query for final parsing and get comments data and real comments count
*
* @return void
* @since 1.0
*
**/
public function query()
{
if ( !isset( $this->comments_count ) || !is_array( $this->comments ) || ! count($this->comments) ) {
global $d;
$limit = null;
if( is_int( $this->start ) ){
$limit = " LIMIT ". $this->start . " ";
if ( is_int( $this->length ) && $this->length > 0) {
$limit .= ", ". $this->length . " ";
}
}
$query = "
SELECT c.*, m.member_avatar, m.member_group, m.member_name
FROM #__comments AS c
LEFT JOIN #__members AS m ON (m.member_id = c.comment_member_id)
WHERE c.comment_type='".$d->escape_string($this->type)."' AND c.comment_link='".intval($this->link)."'".($this->options['approve']==1? " AND (c.comment_approve='1'".(member == 1? " OR c.comment_member_id='".member_id."'" : " OR c.comment_author_ip='".$d->escape_string(get_ip())."'").")" : null).
"GROUP BY c.comment_id
ORDER BY c.comment_id ASC".
$limit ;
$this->comments = $d->get_row($query);
$this->comments_count = is_array($this->comments)? count($this->comments) : 0;
unset($query);
}
}
/**
* Return Total Comments Count
*
* @return int An integer that shows total comments
* @since 1.1
**/
public function get_total_comments()
{
global $d;
if( empty( $this->total ) || !is_int( $this->total ) ){
$query = "
SELECT COUNT(*) AS count FROM #__comments
WHERE comment_type='".$d->escape_string($this->type)."' AND
comment_link='".intval($this->link)."'".
($this->options['approve']==1? " AND (comment_approve='1'".(member == 1? " OR comment_member_id='".member_id."'" : " OR comment_author_ip='".$d->escape_string(get_ip())."'").")" : null);
$data = $d->fetch( $query , 'assoc' , true );
$this->total = $data['count'];
}
return $this->total;
}
public function build()
{
global $member, $options, $tpl, $member_groups;
if (member == 1)
{
$member = member::is('info');
}
// save a new comment
$com = get_param($_POST, 'comment');
if (is_array($com) && count($com))
{
$this->post($com);
}
unset($com);
$this->query();
require_once(engine_dir.'captcha.function.php');
require_once(engine_dir.'editor.function.php');
require_once(engine_dir.'bbcode.class.php');
$bbcode = new bbcode();
$comments = array();
$form = array();
// $file = get_tpl();
$itpl = new template('comments.tpl', template_dir );
($hook = get_hook('comments_build_start'))? eval($hook) : null;
if (is_array($this->comments) && count($this->comments))
{
foreach($this->comments as $com)
{
$array = array(
'{odd-even}' => odd_even(),
'{member-id}' => $com['comment_member_id'],
'{member-avatar}' => member::avatar($com['member_avatar']),
'{member-name}' => $com['member_name'],
'{id}' => $com['comment_id'],
'{author}' => $com['comment_author'],
'{author-email}' => $com['comment_author_email'],
'{author-url}' => $com['comment_author_url'],
'{author-ip}' => $com['comment_author_ip'],
'{date}' => jdate('l j F Y ساعت g:i A', $com['comment_date']),
'{past-time}' => get_past_time($com['comment_date']),
'{text}' => '<a name="comment-'.$com['comment_id'].'"></a>'.nl2br($bbcode->parse($com['comment_text'])),
'{answer-author}' => $com['comment_answer_author'],
'{answer}' => empty($com['comment_answer'])? null : nl2br($bbcode->parse($com['comment_answer'])),
'{language}' => $com['comment_language'],
);
if (isset($member_groups[$com['member_group']]) && $member_groups[$com['member_group']]['group_admin'] == 1)
{
$array['[author-admin]'] = null;
$array['[/author-admin]'] = null;
$array['replace']['#\\[not-author-admin\\](.*?)\\[/not-author-admin\\]#s'] = '';
}
else
{
$array['[not-author-admin]'] = null;
$array['[/not-author-admin]'] = null;
$array['replace']['#\\[author-admin\\](.*?)\\[/author-admin\\]#s'] = '';
}
if (!empty($com['comment_author_url']))
{
$array['[author-url]'] = null;
$array['[/author-url]'] = null;
}
else
{
$array['replace']['#\\[author-url\\](.*?)\\[/author-url\\]#s'] = '';
}
if (!empty($com['comment_answer']))
{
$array['[answer]'] = null;
$array['[/answer]'] = null;
}
else
{
$array['replace']['#\\[answer\\](.*?)\\[/answer\\]#s'] = '';
}
if ($this->options['approve'] == 0 || $com['comment_approve'] == 1)
{
$array['[approve]'] = null;
$array['[/approve]'] = null;
$array['replace']['#\\[not-approve\\](.*?)\\[/not-approve\\]#s'] = '';
}
else
{
$array['[not-approve]'] = null;
$array['[/not-approve]'] = null;
$array['replace']['#\\[approve\\](.*?)\\[/approve\\]#s'] = '';
}
$array['replace']['|{date format=[\'"](.+?)[\'"]}|es'] = 'jdate("\\1", "'.$com['comment_date'].'")';
$itpl->add_for('comments', $array);
}
}
$itpl->assign(array(
'{message}' => empty($this->message)? null : message($this->message, 'error'),
'{action}' => $this->action,
'{name}' => member? (!empty($member['member_alias'])? $member['member_alias'] : member_name) : null,
'{email}' => isset($member['member_email']) && !empty($member['member_email'])? $member['member_email'] : null,
'{url}' => isset($member['member_web']) && !empty($member['member_web'])? $member['member_web'] : 'http://',
'{comments-count}' => $this->comments_count,
'{link}' => $this->link,
'{wysiwyg-textarea}' => $this->options['editor']==1? wysiwyg_textarea('comment[text]', isset($_POST['comment']['text'])? htmlencode($_POST['comment']['text']) : null, 'BBcode') : '<textarea name="comment[text]" id="comment-text" cols="45" rows="5">'.(isset($_POST['comment']['text'])? htmlencode($_POST['comment']['text']) : null).'</textarea>',
'{captcha}' => create_captcha('comment')
));
if ($this->comments_count <= 0)
{
$itpl->assign(array(
'[no-comments]' => null,
'[/no-comments]' => null,
));
$itpl->block('#\\[have-comments\\](.*?)\\[/have-comments\\]#s', '');
}
else
{
$itpl->assign(array(
'[have-comments]' => null,
'[/have-comments]' => null,
));
$itpl->block('#\\[no-comments\\](.*?)\\[/no-comments\\]#s', '');
}
if (!empty($this->message))
{
$itpl->assign(array(
'[message]' => null,
'[/message]' => null,
));
}
else
{
$itpl->block('#\\[message\\](.*?)\\[/message\\]#s', '');
}
if ($this->options['post-guest'] == 1 || member == 1)
{
$itpl->assign(array(
'[post]' => null,
'[/post]' => null,
));
$itpl->block('#\\[not-post\\](.*?)\\[/not-post\\]#s', '');
}
else
{
$itpl->assign(array(
'{message}' => message('فقط کاربران عضو می توانند نظر ارسال کنند!', 'error'),
'[not-post]' => null,
'[/not-post]' => null,
));
$itpl->block('#\\[post\\](.*?)\\[/post\\]#s', '');
}
if ($this->options['editor'] == 1)
{
$itpl->assign(array(
'[editor]' => null,
'[/editor]' => null,
));
$itpl->block('#\\[not-editor\\](.*?)\\[/not-editor\\]#s', '');
}
else
{
$itpl->assign(array(
'[not-editor]' => null,
'[/not-editor]' => null,
));
$itpl->block('#\\[editor\\](.*?)\\[/editor\\]#s', '');
}
($hook = get_hook('comments_build_end'))? eval($hook) : null;
$tpl->assign('{content}', $itpl->get_var(), 'add');
unset($bbcode, $comments, $form, $com, $post_name, $itpl);
}
public function post($post)
{
global $member;
require_once(engine_dir.'captcha.function.php');
$message = array();
$this->comment_posted = false;
($hook = get_hook('comments_post_start'))? eval($hook) : null;
if (member == 1)
{
$member = member::is('info');
$post['name'] = !empty($member['member_alias'])? $member['member_alias'] : member_name;
$post['email'] = $member['member_email'];
$post['url'] = !empty($member['member_web'])? $member['member_web'] : null;
}
else
{
$post['name'] = isset($post['name'])? htmlencode($post['name']) : null;
$post['email'] = isset($post['email'])? nohtml($post['email']) : null;
$post['url'] = isset($post['url'])? nohtml($post['url']) : null;
}
$post['text'] = isset($post['text'])? htmlencode($post['text']) : null;
$post['captcha'] = isset($post['captcha'])? nohtml($post['captcha']) : null;
if (empty($this->type) || !isnum($this->link) || $this->link <= 0)
{
$message[] = 'اطلاعات شناسایی نظر معتبر نمی باشد!';
}
if ($this->options['post-guest'] == 0 && member == 0)
{
$message[] = 'کاربران غیر عضو اجازه ارسال نظر را ندارند';
}
if ($post['name'] == '')
{
$message[] = 'نام خود را وارد نکرده اید!';
}
if ($this->options['email'] == 1)
{
if (empty($post['email']) || !validate_email($post['email']))
{
$message[] = 'ایمیل وارد شده صحیح نیست!';
}
}
if ($post['url'] != '' && $post['url'] != 'http://' && !validate_url($post['url']))
{
$message[] = 'آدرس وبسایت شما معتبر نمی باشد!';
}
if (empty($post['text']))
{
$message[] = 'متن نظر خود را ننوشته اید!';
}
else
{
$text = nohtml($post['text']);
if (apadana_strlen($text) < 5)
{
$message[] = 'نظر شما خیلی کوتاه است حداقل باید 5 حرف باشد!';
}
elseif (apadana_strlen($text) > $this->options['limit'])
{
$message[] = 'نظر شما '.apadana_strlen($text).' حرف است، حداکثر تعداد حروف مجاز '.$this->options['limit'].' حرف می باشد!';
}
}
if (!validate_captcha('comment', $post['captcha']))
{
$message[] = 'کد امنیتی را صحیح وارد نکرده اید!';
}
if (count($message))
{
$this->message = implode('<br/>', $message);
}
else
{
global $d;
if ($post['url'] == 'http://')
{
$post['url'] = null;
}
if (!validate_email($post['email']))
{
$post['email'] = null;
}
#$post['text'] = template_off($post['text']);
$post['text'] = str_replace('{', '{', $post['text']);
$post['text'] = preg_replace('#\s{2,}#', ' ', $post['text']);
$arr = array(
'comment_type' => $this->type,
'comment_link' => intval($this->link),
'comment_author' => $post['name'],
'comment_author_email' => $post['email'],
'comment_author_url' => $post['url'],
'comment_author_ip' => get_ip(),
'comment_date' => time(),
'comment_text' => $post['text'],
'comment_member_id' => member_id,
'comment_approve' => (group_super_admin || member::check_admin_page_access("comments") || $this->options['approve'] == 0) ? 1 : 0
);
$d->insert('comments', $arr);
if ($d->affected_rows())
{
unset($_POST['comment']);
remove_captcha('comment');
remove_cache('comments', true);
$this->comment_posted = true;
($hook = get_hook('comments_post_save'))? eval($hook) : null;
/**
* @since 1.1
*/
($hook = get_hook('comments_post_save_'. $this->type))? eval($hook) : null;
}
else
{
$this->message = 'در ذخیره نظر خطایی رخ داده مجدد تلاش کنید!';
}
}
($hook = get_hook('comments_post_end'))? eval($hook) : null;
unset($text, $message, $post, $arr);
}
public function set_limits($start = 1 , $length = null)
{
if( is_int( $start ) )
$this->start = $start;
if ( ! is_null($length) && is_int( $length ) )
$this->length = $length;
}
}
| Apadana/apadana-cms | engine/comments.class.php | PHP | gpl-3.0 | 13,685 |
#define WeaponNoSlot 0 // dummy weapon
#define WeaponSlotPrimary 1 // primary weapon
#define WeaponSlotHandGun 2 // handGun/sidearm
#define WeaponSlotSecondary 4 // secondary weapon // 4 in ArmA, not 16.
#define WeaponSlotHandGunItem 16 // sidearm/GL magazines // 16 in ArmA, not 32.
#define WeaponSlotItem 256 // main magazines, items, explosives
#define WeaponSlotBinocular 4096 // binocular, NVG, LD, equipment
#define WeaponHardMounted 65536
#define WeaponSlotSmallItems 131072
class CfgWeapons {
class Default;
class ACRE_BaseRadio;
class ItemCore;
class ACRE_PRC77: ACRE_BaseRadio {
displayName = "AN/PRC-77";
useActionTitle = "AN/PRC-77";
model = QPATHTOF(Data\models\prc_77.p3d);
picture = QPATHTOF(Data\prc77_icon.paa);
descriptionShort = "AN/PRC-77 Manpack Radio";
scopeCurator = 2;
scope = 2;
type = 4096;
simulation = "ItemMineDetector";
class ItemInfo {
mass = 120;
allowedSlots[] = {901};
type = 0;
scope = 0;
};
class Library {
libTextDesc = "AN/PRC-77";
};
};
RADIO_ID_LIST(ACRE_PRC77)
};
| Raspu86/acre2 | addons/sys_prc77/CfgWeapons.hpp | C++ | gpl-3.0 | 1,266 |
var structrectangle =
[
[ "height", "structrectangle.html#af460193d9a375b8e2813bf1fe6216cce", null ],
[ "ulx", "structrectangle.html#a4feece2ec58d909444613177ec67e2bc", null ],
[ "uly", "structrectangle.html#ac537f5c6afbda6ef42cc428540058ecb", null ],
[ "width", "structrectangle.html#a57a9b24a714057d8d2ca9a06333560d3", null ]
]; | kipr/harrogate | shared/client/doc/structrectangle.js | JavaScript | gpl-3.0 | 346 |
#!/usr/bin/env python
# encoding: utf-8
from lewei import Cloud as lewei
CLOUDS = {
"lewei": lewei,
} | jt6562/mytvoc | clouds/__init__.py | Python | gpl-3.0 | 110 |
package com.blogger.web.rest.vm;
import com.blogger.service.dto.UserDTO;
import javax.validation.constraints.Size;
import java.time.ZonedDateTime;
import java.util.Set;
/**
* View Model extending the UserDTO, which is meant to be used in the user management UI.
*/
public class ManagedUserVM extends UserDTO {
public static final int PASSWORD_MIN_LENGTH = 4;
public static final int PASSWORD_MAX_LENGTH = 100;
@Size(min = PASSWORD_MIN_LENGTH, max = PASSWORD_MAX_LENGTH)
private String password;
public ManagedUserVM() {
// Empty constructor needed for Jackson.
}
public ManagedUserVM(Long id, String login, String password, String firstName, String lastName,
String email, boolean activated, String imageUrl, String langKey,
String createdBy, ZonedDateTime createdDate, String lastModifiedBy, ZonedDateTime lastModifiedDate,
Set<String> authorities) {
super(id, login, firstName, lastName, email, activated, imageUrl, langKey,
createdBy, createdDate, lastModifiedBy, lastModifiedDate, authorities);
this.password = password;
}
public String getPassword() {
return password;
}
@Override
public String toString() {
return "ManagedUserVM{" +
"} " + super.toString();
}
}
| arslanberk/Blogger | src/main/java/com/blogger/web/rest/vm/ManagedUserVM.java | Java | gpl-3.0 | 1,374 |
/* Copyright (C) 2017 Thomas Terry - All Rights Reserved
* You may use, distribute and modify this code under the
* terms of the GNU GPLv3 license, which unfortunately won't be
* written for another century.
*
* You should have received a copy of the GPLv3 license with
* this file. If not, please visit : gnu.org
*/
#include<screen.h>
Screen::Screen()
{
initscr();
cbreak();
noecho();
curs_set(0);
start_color();
init_pair(1, COLOR_YELLOW, COLOR_BLACK);
init_pair(2, COLOR_RED, COLOR_BLACK);
init_pair(3, COLOR_GREEN, COLOR_BLACK);
this->message = newwin(2, 80, 0, 0);
this->map = newwin(19, 80, 2, 0);
this->stat = newwin(3, 80, 21, 0);
wclear(stdscr);
wrefresh(stdscr);
wclear(this->message);
wclear(this->stat);
wclear(this->map);
wrefresh(this->map);
wrefresh(this->stat);
wrefresh(this->message);
}
Screen::~Screen()
{
delwin( this->message);
delwin( this->map);
delwin( this->stat);
nocbreak();
echo();
curs_set(1);
endwin();
}
int Screen::getInput()
{
return getch();
}
void Screen::draw(int px, int py, struct Tile **map)
{
wclear(this->map);
for (int y = 0; y < 19; y++)
{
for (int x = 0; x<80; x++)
{
if(map[y][x].seen == true){
mvwaddch(this->map, y, x, map[y][x].c);
}
}
}
wattron(this->map, COLOR_PAIR(1));
mvwprintw(this->map, py, px, "@");
wattroff(this->map, COLOR_PAIR(1));
wrefresh(stdscr);
wrefresh(this->map);
}
void Screen::pMessage(char *message)
{
mvwprintw(this->message, 0, 1, message);
}
void Screen::refreshMessage(){ wrefresh(this->message);}
void Screen::clearMessage(){ wclear(this->message);}
void Screen::printStat(Player *p)
{
wclear(this->stat);
mvwprintw(this->stat, 0, 1, "Strength: %d Intelligience: %d Magic: %d", p->Str, p->Int, p->Mp);
wrefresh(this->stat);
}
| thomasscottterry121/roguelike | src/screen.cc | C++ | gpl-3.0 | 1,795 |
/*
* ComponentStrategyRegistryAsComponentStrategyRegistryTest.java
* Copyright 2008-2013 Gamegineer contributors and others.
* All rights reserved.
*
* 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/>.
*
* Created on Aug 3, 2012 at 11:05:34 PM.
*/
package org.gamegineer.table.internal.core.impl;
import org.gamegineer.common.core.util.registry.IRegistry;
import org.gamegineer.table.core.ComponentStrategyId;
import org.gamegineer.table.core.IComponentStrategy;
import org.gamegineer.table.core.IComponentStrategyRegistry;
import org.gamegineer.table.core.test.AbstractComponentStrategyRegistryTestCase;
/**
* A fixture for testing the {@link ComponentStrategyRegistry} class to ensure
* it does not violate the contract of the {@link IComponentStrategyRegistry}
* interface.
*/
public final class ComponentStrategyRegistryAsComponentStrategyRegistryTest
extends AbstractComponentStrategyRegistryTestCase
{
// ======================================================================
// Constructors
// ======================================================================
/**
* Initializes a new instance of the
* {@code ComponentStrategyRegistryAsComponentStrategyRegistryTest} class.
*/
public ComponentStrategyRegistryAsComponentStrategyRegistryTest()
{
}
// ======================================================================
// Methods
// ======================================================================
/*
* @see org.gamegineer.common.core.util.registry.test.AbstractRegistryTestCase#createRegistry()
*/
@Override
protected IRegistry<ComponentStrategyId, IComponentStrategy> createRegistry()
{
return new ComponentStrategyRegistry();
}
}
| gamegineer/dev | main/table/org.gamegineer.table.core.impl.tests/src/org/gamegineer/table/internal/core/impl/ComponentStrategyRegistryAsComponentStrategyRegistryTest.java | Java | gpl-3.0 | 2,425 |
#ifndef UTILS_NETGEN_HPP
#define UTILS_NETGEN_HPP
#include "args.hpp"
#include "graph.hpp"
#include <iomanip>
#include <random>
#include <sstream>
/**
* Names the vertices.
*/
template<typename G>
void
name_vertices(G &g)
{
int count = 1;
int number = boost::num_vertices(g);
int width = int(log10(number)) + 1;
Viter<G> vi, ve;
for (tie(vi, ve) = vertices(g); vi != ve; ++vi)
{
Vertex<G> v = *vi;
std::ostringstream out;
out << "v" << std::setw(width) << std::setfill('0') << count++;
boost::get(boost::vertex_name, g, v) = out.str();
}
}
// We start counting stages from 0. pn is the previous node.
template<typename G, typename T>
void
generate_further(G &g, args &a, T &gen, int stage, Vertex<G> pn)
{
std::bernoulli_distribution qd(a.q);
std::bernoulli_distribution rd(a.r);
std::bernoulli_distribution sd(a.s);
// This is the first node. It can be an ONU or a RN.
Vertex<G> n = add_vertex(g);
// The first fiber.
Edge<G> f = add_edge(pn, n, g).first;
// The type of the first node.
VERTEX_T nt;
// The availability of the first node.
double na;
// The availability of the first fiber.
double fa;
if (stage == a.stages)
{
// We reached the end. It's not a stage, but just an ONU.
// Choose the type of the ONU.
nt = rd(gen) ? ICO : ONU;
na = a.onua;
fa = a.lfa;
}
else
{
// It's a new stage, and so set the type of the RN.
nt = qd(gen) ? ARN : PRN;
na = (nt == PRN ? a.prna : a.arna);
fa = (stage == 0 ? a.ffa : a.dfa);
for (int i = 0; i < a.sratio; ++i)
{
int nstage = sd(gen) ? (stage + 1) : a.stages;
generate_further(g, a, gen, nstage, n);
}
}
boost::get(boost::vertex_type, g, n) = nt;
boost::get(boost::vertex_availa, g, n) = na;
boost::get(boost::edge_availa, g, f) = fa;
}
template<typename G, typename T>
void
generate_pon(G &g, args &a, T &gen)
{
assert(num_vertices(g) == 0);
Vertex<G> olt = add_vertex(g);
boost::get(boost::vertex_type, g, olt) = OLT;
boost::get(boost::vertex_availa, g, olt) = a.olta;
generate_further(g, a, gen, 0, olt);
}
#endif /* UTILS_NETGEN_HPP */
| iszczesniak/availa | utils_netgen.hpp | C++ | gpl-3.0 | 2,206 |
#include <iostream>
#include "tempi/nodefactory.h"
#include "tempi/internals.h"
#include "tempi/midi/midilibrary.h"
using namespace tempi;
bool check_midi_library()
{
NodeFactory factory;
midi::MidiLibrary lib;
lib.load(factory, "midi.");
if (! factory.hasType("midi.receive"))
{
std::cout << __FUNCTION__ << ": Did not register node successfully" << std::endl;
return false;
}
return true;
}
static bool didRegister(NodeFactory &factory, const char *name)
{
if (! factory.hasType(name))
{
std::cout << "Did not register node successfully " << name << std::endl;
return false;
}
return true;
}
bool check_librarytools()
{
NodeFactory factory;
librarytools::loadLibrary<midi::MidiLibrary>(factory, "midi.");
if (! didRegister(factory, "midi.receive")) return false;
return true;
}
bool check_internals()
{
NodeFactory factory;
internals::loadInternals(factory);
if (! didRegister(factory, "base.metro")) return false;
if (! didRegister(factory, "base.nop")) return false;
if (! didRegister(factory, "base.print")) return false;
if (! didRegister(factory, "midi.receive")) return false;
if (! didRegister(factory, "osc.receive")) return false;
if (! didRegister(factory, "osc.send")) return false;
if (! didRegister(factory, "sampler.sampler")) return false;
return true;
}
int main(int argc, char *argv[])
{
if (! check_midi_library()) return 1;
if (! check_librarytools()) return 1;
if (! check_internals()) return 1;
return 0;
}
| aalex/ubuntu-tempi | tests/check_libraries.cpp | C++ | gpl-3.0 | 1,588 |
# -*- coding: utf-8 -*-
# home made test
# Sign convention for fiber sections.
from __future__ import division
import xc_base
import geom
import xc
from solution import predefined_solutions
from model import predefined_spaces
from materials import typical_materials
from postprocess import prop_statistics
import math
__author__= "Luis C. Pérez Tato (LCPT)"
__copyright__= "Copyright 2014, LCPT"
__license__= "GPL"
__version__= "3.0"
__email__= "l.pereztato@gmail.com"
# Problem type
feProblem= xc.FEProblem()
preprocessor= feProblem.getPreprocessor
#Constant positive strain.
epsilon= 3.5e-3
epsilon1= epsilon
epsilon2= epsilon
epsilon3= epsilon
epsilon4= epsilon
#Read section definition from file.
import os
pth= os.path.dirname(__file__)
#print "pth= ", pth
if(not pth):
pth= "."
execfile(pth+"/../../aux/four_fiber_section.py")
sigma= E*epsilon
F= sigma*fiberArea
N0Teor= 4*F
My0Teor= 0.0
Mz0Teor= 0.0
R0Teor=xc.Vector([N0Teor,My0Teor,Mz0Teor])
D0Teor=xc.Vector([epsilon,0.0,0.0])
ratioN0= abs(N0-N0Teor)/N0Teor
ratioN0S= abs(N0S-N0Teor)/N0Teor
ratioMy0= abs(My0-My0Teor)
ratioMy0S= abs(My0S-My0Teor)
ratioMz0= abs(Mz0-Mz0Teor)
ratioMz0S= abs(Mz0S-Mz0Teor)
ratioR0= (R0Teor-R0).Norm()
ratioD0= (D0Teor-D0).Norm()
fourFibersSection.revertToStart()
# Positive My (section)
epsilon1= -epsilon
epsilon2= -epsilon
epsilon3= epsilon
epsilon4= epsilon
f1.getMaterial().setTrialStrain(epsilon1,0.0)
f2.getMaterial().setTrialStrain(epsilon2,0.0)
f3.getMaterial().setTrialStrain(epsilon3,0.0)
f4.getMaterial().setTrialStrain(epsilon4,0.0)
N1= fourFibersSection.getFibers().getResultant()
My1= fourFibersSection.getFibers().getMy(0.0)
Mz1= fourFibersSection.getFibers().getMz(0.0)
fourFibersSection.setupFibers()
RR= fourFibersSection.getStressResultant()
R1= xc.Vector([RR[0],RR[2],RR[1]]) # N= RR[0], My= RR[2], Mz= RR[1]
deformationPlane1= fourFibersSection.getFibers().getDeformationPlane()
fourFibersSection.setTrialDeformationPlane(deformationPlane1)
DD= fourFibersSection.getSectionDeformation()
D1= xc.Vector([DD[0],DD[2],DD[1]]) # epsilon= DD[0], Ky= DD[2], Kz= DD[1]
N1S= fourFibersSection.getN()
My1S= fourFibersSection.getMy()
Mz1S= fourFibersSection.getMz()
N1Teor= 0.0
My1Teor= 2*F*widthOverZ
Mz1Teor= 0.0
R1Teor=xc.Vector([N1Teor,My1Teor,Mz1Teor])
Ky1Teor= 2*epsilon/widthOverZ
D1Teor=xc.Vector([0.0,Ky1Teor,0.0])
ratioN1= abs(N1-N1Teor)
ratioN1S= abs(N1S-N1Teor)
ratioMy1= abs(My1-My1Teor)/My1Teor
ratioMy1S= abs(My1S-My1Teor)/My1Teor
ratioMz1= abs(Mz1-Mz1Teor)
ratioMz1S= abs(Mz1S-Mz1Teor)
ratioR1= (R1Teor-R1).Norm()
ratioD1= (D1Teor-D1).Norm()
# Positive Mz (section)
fourFibersSection.revertToStart()
epsilon1= epsilon
epsilon2= -epsilon
epsilon3= -epsilon
epsilon4= epsilon
f1.getMaterial().setTrialStrain(epsilon1,0.0)
f2.getMaterial().setTrialStrain(epsilon2,0.0)
f3.getMaterial().setTrialStrain(epsilon3,0.0)
f4.getMaterial().setTrialStrain(epsilon4,0.0)
N2= fourFibersSection.getFibers().getResultant()
My2= fourFibersSection.getFibers().getMy(0.0)
Mz2= fourFibersSection.getFibers().getMz(0.0)
deformationPlane2= fourFibersSection.getFibers().getDeformationPlane()
fourFibersSection.setupFibers()
RR= fourFibersSection.getStressResultant()
R2= xc.Vector([RR[0],RR[2],RR[1]]) # N= RR[0], My= RR[2], Mz= RR[1]
fourFibersSection.setTrialDeformationPlane(deformationPlane2)
DD= fourFibersSection.getSectionDeformation()
D2= xc.Vector([DD[0],DD[2],DD[1]]) # epsilon= DD[0], Ky= DD[2], Kz= DD[1]
N2S= fourFibersSection.getN()
My2S= fourFibersSection.getMy()
Mz2S= fourFibersSection.getMz()
N2Teor= 0.0
My2Teor= 0.0
Mz2Teor= -4*F*depthOverY/2.0 #Mz positive is in the opposite direction with respecto to the positive y-axis. ???
R2Teor=xc.Vector([N2Teor,My2Teor,Mz2Teor])
Kz2Teor= 2*epsilon/depthOverY
D2Teor=xc.Vector([0.0,0.0,-Kz2Teor]) #Negative ???
ratioN2= abs(N2-N2Teor)
ratioN2S= abs(N2S-N2Teor)
ratioMy2= abs(My2-My2Teor)
ratioMy2S= abs(My2S-My2Teor)
ratioMz2= abs(Mz2-Mz2Teor)/Mz2Teor
ratioMz2S= abs(Mz2S-Mz2Teor)/Mz2Teor
ratioR2= (R2Teor-R2).Norm()
ratioD2= (D2Teor-D2).Norm()
# Positive Mz, negative My (section)
fourFibersSection.revertToStart()
epsilon= 3.5e-3
epsilon1= epsilon
epsilon2= 0.0
epsilon3= -epsilon
epsilon4= 0.0
f1.getMaterial().setTrialStrain(epsilon1,0.0)
f2.getMaterial().setTrialStrain(epsilon2,0.0)
f3.getMaterial().setTrialStrain(epsilon3,0.0)
f4.getMaterial().setTrialStrain(epsilon4,0.0)
N3= fourFibersSection.getFibers().getResultant()
My3= fourFibersSection.getFibers().getMy(0.0)
Mz3= fourFibersSection.getFibers().getMz(0.0)
deformationPlane3= fourFibersSection.getFibers().getDeformationPlane()
fourFibersSection.setupFibers()
RR= fourFibersSection.getStressResultant()
R3= xc.Vector([RR[0],RR[2],RR[1]]) # N= RR[0], My= RR[2], Mz= RR[1]
fourFibersSection.setTrialDeformationPlane(deformationPlane3)
DD= fourFibersSection.getSectionDeformation()
D3= xc.Vector([DD[0],DD[2],DD[1]]) # epsilon= DD[0], Ky= DD[2], Kz= DD[1]
N3S= fourFibersSection.getN()
My3S= fourFibersSection.getMy()
Mz3S= fourFibersSection.getMz()
N3Teor= 0.0
My3Teor= -2*F*widthOverZ/2.0
Mz3Teor= -2*F*depthOverY/2.0
R3Teor=xc.Vector([N3Teor,My3Teor,Mz3Teor])
Ky3Teor= -epsilon/widthOverZ
Kz3Teor= epsilon/depthOverY
D3Teor=xc.Vector([0.0,Ky3Teor,-Kz3Teor]) #Negative ???
ratioN3= abs(N3-N3Teor)
ratioN3S= abs(N3S-N3Teor)
ratioMy3= abs(My3-My3Teor)
ratioMy3S= abs(My3S-My3Teor)
ratioMz3= abs(Mz3-Mz3Teor)/Mz3Teor
ratioMz3S= abs(Mz3S-Mz3Teor)/Mz3Teor
ratioR3= (R3Teor-R3).Norm()
ratioD3= (D3Teor-D3).Norm()
import math
error= math.sqrt(ratioN0**2+ratioMy0**2+ratioMz0**2+ratioN0S**2+ratioMy0S**2+ratioMz0S**2+ratioR0**2+ratioD0**2+ratioN1**2+ratioMy1**2+ratioMz1**2+ratioN1S**2+ratioMy1S**2+ratioMz1S**2+ratioR1**2+ratioD1**2+ratioN2**2+ratioMy2**2+ratioMz2**2+ratioN2S**2+ratioMy2S**2+ratioMz2S**2+ratioR2**2+ratioD2**2+ratioN3**2+ratioMy3**2+ratioMz3**2+ratioN3S**2+ratioMy3S**2+ratioMz3S**2+ratioR3**2+ratioD3**2)
print 'N0= ', N0, ' N0S= ', N0S, ' N0Teor= ', N0Teor, ' ratioN0= ', ratioN0, ' ratioN0S= ', ratioN0S
print 'My0= ', My0, ' My0S= ', My0S, ' My0Teor= ', My0Teor, ' ratioMy0= ', ratioMy0, ' ratioMy0S= ', ratioMy0S
print 'Mz0= ', Mz0, ' Mz0S= ', Mz0S, ' Mz0Teor= ', Mz0Teor, ' ratioMz0= ', ratioMz0, ' ratioMz0S= ', ratioMz0S
print 'R0= ', R0, ' R0Teor= ', R0Teor, ' ratioR0= ', ratioR0
print 'D0= ', D0, ' D0Teor= ', D0Teor, ' ratioD0= ', ratioD0
print 'N1= ', N1, ' N1S= ', N1S, ' N1Teor= ', N1Teor, ' ratioN1= ', ratioN1, ' ratioN1S= ', ratioN1S
print 'My1= ', My1, ' My1S= ', My1S, ' My1Teor= ', My1Teor, ' ratioMy1= ', ratioMy1, ' ratioMy1S= ', ratioMy1S
print 'Mz1= ', Mz1, ' Mz1S= ', Mz1S, ' Mz1Teor= ', Mz1Teor, ' ratioMz1= ', ratioMz1, ' ratioMz1S= ', ratioMz1S
print 'R1= ', R1, ' R1Teor= ', R1Teor, ' ratioR1= ', ratioR1
print 'D1= ', D1, ' D1Teor= ', D1Teor, ' ratioD1= ', ratioD1
print 'N2= ', N2, ' N2S= ', N2S, ' N2Teor= ', N2Teor, ' ratioN2= ', ratioN2, ' ratioN2S= ', ratioN2S
print 'My2= ', My2, ' My2S= ', My2S, ' My2Teor= ', My2Teor, ' ratioMy2= ', ratioMy2, ' ratioMy2S= ', ratioMy2S
print 'Mz2= ', Mz2, ' Mz2S= ', Mz2S, ' Mz2Teor= ', Mz2Teor, ' ratioMz2= ', ratioMz2, ' ratioMz2S= ', ratioMz2S
print 'R2= ', R2, ' R2Teor= ', R2Teor, ' ratioR2= ', ratioR2
print 'D2= ', D2, ' D2Teor= ', D2Teor, ' ratioD2= ', ratioD2
print 'N3= ', N3, ' N3S= ', N3S, ' N3Teor= ', N3Teor, ' ratioN3= ', ratioN3, ' ratioN3S= ', ratioN3S
print 'My3= ', My3, ' My3S= ', My3S, ' My3Teor= ', My3Teor, ' ratioMy3= ', ratioMy3, ' ratioMy3S= ', ratioMy3S
print 'Mz3= ', Mz3, ' Mz3S= ', Mz3S, ' Mz3Teor= ', Mz3Teor, ' ratioMz3= ', ratioMz3, ' ratioMz3S= ', ratioMz3S
print 'R3= ', R3, ' R3Teor= ', R3Teor, ' ratioR3= ', ratioR3
print 'D3= ', D3, ' D3Teor= ', D3Teor, ' ratioD3= ', ratioD3
print 'error= ', error
from miscUtils import LogMessages as lmsg
fname= os.path.basename(__file__)
if (error < 1e-3):
print "test ",fname,": ok."
else:
lmsg.error(fname+' ERROR.')
| lcpt/xc | verif/tests/materials/fiber_section/test_fiber_section_sign_convention01.py | Python | gpl-3.0 | 7,833 |
Bitrix 16.5 Business Demo = 687b7436ad938b390cdc1d9dea84c199
| gohdan/DFC | known_files/hashes/bitrix/modules/seo/lang/ru/options.php | PHP | gpl-3.0 | 61 |
package org.duniter.elasticsearch.user.dao.group;
/*
* #%L
* Ğchange Pod :: ElasticSearch plugin
* %%
* Copyright (C) 2014 - 2017 EIS
* %%
* 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/gpl-3.0.html>.
* #L%
*/
import org.duniter.elasticsearch.user.dao.CommentDao;
/**
* Created by blavenie on 03/04/17.
*/
public interface GroupCommentDao extends CommentDao {
}
| ucoin-io/ucoinj | cesium-plus-pod-user/src/main/java/org/duniter/elasticsearch/user/dao/group/GroupCommentDao.java | Java | gpl-3.0 | 978 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Defines the version of pairwork
*
* This code fragment is called by moodle_needs_upgrading() and
* /admin/index.php
*
* @package mod_pairwork
* @copyright 2015 Flash Gordon http://www.flashgordon.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$module->version = 2015110700; // If version == 0 then module will not be installed
//$module->version = 2010032200; // The current module version (Date: YYYYMMDDXX)
$module->requires = 2010031900; // Requires this Moodle version
$module->cron = 0; // Period for cron to check this module (secs)
$module->component = 'mod_pairwork'; // To check on upgrade, that module sits in correct place
| andreyamin/moodlebites-dev-course | mod/pairwork/version.php | PHP | gpl-3.0 | 1,463 |
<?php
/**
* @package project
* @version 0.4.0.0
* @author Roman Konertz <konertz@open-lims.org>
* @copyright (c) 2008-2016 by Roman Konertz
* @license GPLv3
*
* This file is part of Open-LIMS
* Available at http://www.open-lims.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;
* version 3 of the License.
*
* 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/>.
*/
/**
* Project Permission Group Create Exception
* @package project
*/
class ProjectPermissionGroupCreateException extends ProjectPermissionGroupException
{
function __construct($message = null)
{
parent::__construct($message);
}
}
?> | open-lims/open-lims | www/core/include/project/exceptions/project_permission_group_create.exception.class.php | PHP | gpl-3.0 | 1,137 |
#
# Copyright (C) 2018, 2020
# Smithsonian Astrophysical Observatory
#
# 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.
#
"""
Support downloading data from URLs in CIAO.
A collection of routines related to data download used in CIAO.
retrieve_url
------------
CIAO 4.11 does not include any SSL support, instead relying on the OS.
This can cause problems on certain platforms. So try with Python and
then fall through to curl or wget. This can hopefully be removed for
CIAO 4.12 or later, but kept in just for now.
find_downloadable_files
-----------------------
Given a URL of a directory, return the files and sub-directories
available. This requires that the web server supports the Apache
mod_autoindex functionality, and is written for accessing the
Chandra Data Archive. Support for other web sites is not guaranteed.
find_all_downloadable_files
---------------------------
Similar to find_downloadble_files but recurses through all sub-directories.
ProgressBar
-----------
Display a "progress" bar, indicating the progress of a download.
This has very-limited functionality.
download_progress
-----------------
Download a URL to a file, supporting
- continuation of a previous partial download
- a rudimentary progress bar to display progress
Stability
---------
This is an internal module, and so the API it provides is not
considered stable (e.g. we may remove this module at any time). Use
at your own risk.
"""
import os
import sys
import ssl
import time
from io import BytesIO
from subprocess import check_output
import urllib.error
import urllib.request
import http.client
from html.parser import HTMLParser
import ciao_contrib.logger_wrapper as lw
logger = lw.initialize_module_logger("downloadutils")
v0 = logger.verbose0
v1 = logger.verbose1
v2 = logger.verbose1
v3 = logger.verbose3
v4 = logger.verbose4
__all__ = ('retrieve_url',
'find_downloadable_files',
'find_all_downloadable_files',
'ProgressBar',
'download_progress')
def manual_download(url):
"""Try curl then wget to query the URL.
Parameters
----------
url : str
The URL for the query; see construct_query
Returns
-------
ans : StringIO instance
The response
"""
v3("Fall back to curl or wget to download: {}".format(url))
# Should package this up nicely, but hardcode for the moment.
#
# It is not clear if this is sufficient to catch "no curl"
# while allowing errors like "no access to the internet"
# to not cause too much pointless work.
#
args = ['curl', '--silent', '-L', url]
v4("About to execute: {}".format(args))
try:
rsp = check_output(args)
except FileNotFoundError as exc1:
v3("Unable to call curl: {}".format(exc1))
args = ['wget', '--quiet', '-O-', url]
v4("About to execute: {}".format(args))
try:
rsp = check_output(args)
except FileNotFoundError as exc2:
v3("Unable to call wget: {}".format(exc2))
emsg = "Unable to access the URL {}.\n".format(url) + \
"Please install curl or wget (and if you " + \
"continue to see this message, contact the " + \
"CXC HelpDesk)."
raise RuntimeError(emsg)
return BytesIO(rsp)
def retrieve_url(url, timeout=None):
"""Handle possible problems retrieving the URL contents.
Using URLs with the https scheme causes problems for certain OS
set ups because CIAO 4.11 does not provide SSL support, but relies
on the system libraries to work. This is "supported" by falling
over from Python to external tools (curl or wget).
Parameters
----------
url : str
The URL to retrieve.
timeout : optional
The timeout parameter for the urlopen call; if not
None then the value is in seconds.
Returns
-------
response : HTTPResponse instance
The response
"""
try:
v3("Retrieving URL: {} timeout={}".format(url, timeout))
if timeout is None:
return urllib.request.urlopen(url)
return urllib.request.urlopen(url, timeout=timeout)
except urllib.error.URLError as ue:
v3("Error opening URL: {}".format(ue))
v3("error.reason = {}".format(ue.reason))
# Assume this is the error message indicating "no SSL support"
# There is a new (in CIAO 4.11) message
# "urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:719)"
#
# It appears that the reason attribute can be an object, so
# for now explicitly convert to a string:
reason = str(ue.reason)
if reason.find('unknown url type: https') != -1 or \
reason.find('CERTIFICATE_VERIFY_FAILED') != -1:
return manual_download(url)
# There used to be a check on the reason for the error,
# converting it into a "user-friendly" message, but this
# was error prone (the check itself was faulty) and
# potentially hid useful error information. So just
# re-raise the error here after logging it.
#
raise
class DirectoryContents(HTMLParser):
"""Extract the output of the mod_autoindex Apache directive.
Limited testing. It assumes that the files are given as links,
there's no other links on the page, and the parent directory is
listed as 'parent directory' (after removing the white space and
converting to lower case). There is special casing to remove links
where the text does not match the name of the link. This is to
handle query fragments, which are used to change the ordering of
the table display rather than be an actual link.
"""
def __init__(self, *args, **kwargs):
self.dirs = []
self.files = []
self.current = None
super().__init__(*args, **kwargs)
def add_link(self):
"""We've found a link, add it to the store"""
if self.current is None:
return
if self.current.endswith('/'):
store = self.dirs
else:
store = self.files
store.append(self.current)
self.current = None
def handle_starttag(self, tag, attrs):
if tag.upper() != 'A':
return
# In case we have a missing close tag
self.add_link()
attrs = dict(attrs)
try:
href = attrs['href']
except KeyError:
raise ValueError("Missing href attribute for a tag")
self.current = href
def handle_endtag(self, tag):
# do not expect end tags within <a> here, so we can
# treat it as the end of the a link if we find it
# (to support missing end tags).
#
if self.current is None:
return
self.add_link()
def handle_data(self, data):
if self.current is None:
return
# Skip the link to the parent directory, and skip any where
# the text is different to the href (e.g. to catch query-only
# links which are used to change the display rather than being
# a link).
#
data = data.strip()
if data.lower() == 'parent directory':
self.current = None
elif self.current != data:
v4(f"Dropping link={self.current} as test={data}")
self.current = None
def unpack_filelist_html(txt, baseurl):
"""Extract the contents of the page (assumed to be a directory listing).
Parameters
----------
txt : str
The HTML contents to parse.
baseurl : str
The URL of the page.
Returns
-------
urls : dict
The keys are directories and files, and the contents are
a list of absolute URLs (as strings).
"""
parser = DirectoryContents()
parser.feed(txt)
if not baseurl.endswith('/'):
baseurl += '/'
dirs = [baseurl + d for d in parser.dirs]
files = [baseurl + f for f in parser.files]
return {'directories': dirs, 'files': files}
def find_downloadable_files(urlname, headers):
"""Find the files and directories present in the given URL.
Report the files present at the given directory, for those
web servers which support an Apache-like mod_autoindex
function (i.e. return a HTML file listing the files and
sub-directories).
Parameters
----------
urlname : str
This must represent a directory.
headers : dict
The headers to add to the HTTP request (e.g. user-agent).
Returns
-------
urls : dict
The keys are directories and files, and the contents are
a list of absolute URLs (as strings).
See Also
--------
find_all_downloadable_files
Notes
-----
This is intended for use with the Chandra Data Archive, and
so there's no guarantee it will work for other web servers:
they may not return the necessary information, or use a
different markup.
Requests are made with *no* SSL validation (since there are
problems with CIAO 4.12 installed via ciao-install on a Ubuntu
machine).
There is no attempt to make a "nice" error message for a user
here, as that is better done in the calling code.
"""
no_context = ssl._create_unverified_context()
req = urllib.request.Request(urlname, headers=headers)
with urllib.request.urlopen(req, context=no_context) as rsp:
html_contents = rsp.read().decode('utf-8')
return unpack_filelist_html(html_contents, urlname)
def find_all_downloadable_files(urlname, headers):
"""Find the files present in the given URL, including sub-directories.
Report the files present at the given directory and
sub-directory, for those web servers which support an Apache-like
mod_autoindex function (i.e. return a HTML file listing the files
and sub-directories).
Parameters
----------
urlname : str
This must represent a directory.
headers : dict
The headers to add to the HTTP request (e.g. user-agent).
Returns
-------
urls : list of str
A list of absolute URLs.
See Also
--------
find_downloadable_files
Notes
-----
This is intended for use with the Chandra Data Archive, and
so there's no guarantee it will work for other web servers:
they may not return the necessary information, or use a
different markup.
Requests are made with *no* SSL validation (since there are
problems with CIAO 4.12 installed via ciao-install on a Ubuntu
machine).
"""
v3("Finding all files available at: {}".format(urlname))
base = find_downloadable_files(urlname, headers)
out = base['files']
todo = base['directories']
v4("Found sub-directories: {}".format(todo))
while True:
v4("Have {} sub-directories to process".format(len(todo)))
if todo == []:
break
durl = todo.pop()
v3("Recursing into {}".format(durl))
subdir = find_downloadable_files(durl, headers)
out += subdir['files']
v4("Adding sub-directories: {}".format(subdir['directories']))
todo += subdir['directories']
return out
class ProgressBar:
"""A very-simple progress "bar".
This just displays the hash marks for each segment of a
download to stdout. It is called from the code doing the
actual download. There is no logic to conditionally display
the output in this class - for instance based on the
current verbose setting - since this should be handled
by the code deciding to call this obejct or not.
Parameters
----------
size : int
The number of bytes to download.
nhash : int
The number of hashes representing the full download
(so each hash represents 100/nhash % of the file)
hashchar : char
The character to display when a chunk has been
downloaded.
Examples
--------
The bar is created with the total number of bytes to download,
then it starts (with an optional number of already-downloaded
bytes), and each chunk that is added is reported with the add
method. Once the download has finished the end method is called.
Note that the methods (start, add, and end) may cause output
to stdout.
>>> progress = ProgressBar(213948)
>>> progress.start()
...
>>> progress.add(8192)
...
>>> progress.add(8192)
...
>>> progress.end()
"""
def __init__(self, size, nhash=20, hashchar='#'):
if size < 0:
raise ValueError("size can not be negative")
if nhash < 1:
raise ValueError("must have at least one hash")
self.size = size
self.nhash = nhash
self.hashchar = hashchar
self.hashsize = size // nhash
self.hdl = sys.stdout
self.added = 0
self.hashes = 0
def start(self, nbytes=0):
"""Initialize the download.
Parameters
----------
nbytes : int, optional
The number of bytes of the file that has already been
downloaded. If not zero this may cause hash marks to be
displayed.
"""
self.added = nbytes
self.hashes = self.added // self.hashsize
if self.hashes == 0:
return
self.hdl.write(self.hashchar * self.hashes)
self.hdl.flush()
def add(self, nbytes):
"""Add the number of bytes for this segment.
This must only be called after start.
Parameters
----------
nbytes : int, optional
The number of bytes added to the file.
"""
if nbytes < 0:
raise ValueError("nbytes must be positive")
if nbytes == 0:
return
self.added += nbytes
hashes = self.added // self.hashsize
if hashes == self.hashes:
return
nadd = hashes - self.hashes
self.hdl.write(self.hashchar * nadd)
self.hdl.flush()
self.hashes = hashes
def end(self):
"""Finished the download.
This is mainly to allow for handling of rounding errors.
"""
nadd = self.nhash - self.hashes
if nadd <= 0:
return
# Don't bother trying to correct for any rounding errors
# if the file wasn't fully downloaded.
#
if self.added < self.size:
return
self.hdl.write(self.hashchar * nadd)
self.hdl.flush()
def myint(x):
"""Convert to an integer, my way."""
return int(x + 0.5)
def stringify_dt(dt):
"""Convert a time interval into a "human readable" string.
Parameters
----------
dt : number
The number of seconds.
Returns
-------
lbl : str
The "human readable" version of the time difference.
Examples
--------
>>> stringify_dt(0.2)
'< 1 s'
>>> stringify_dt(62.3)
'1 m 2 s'
>>> stringify_dt(2402.24)
'40 m 2 s'
"""
if dt < 1:
return "< 1 s"
d = myint(dt // (24 * 3600))
dt2 = dt % (24 * 3600)
h = myint(dt2 // 3600)
dt3 = dt % 3600
m = myint(dt3 // 60)
s = myint(dt3 % 60)
if d > 0:
lbl = "%d day" % d
if d > 1:
lbl += "s"
if h > 0:
lbl += " %d h" % h
elif h > 0:
lbl = "%d h" % h
if m > 0:
lbl += " %d m" % m
elif m > 0:
lbl = "%d m" % m
if s > 0:
lbl += " %d s" % s
else:
lbl = "%d s" % s
return lbl
def stringify_size(s):
"""Convert a file size to a text string.
Parameters
----------
size : int
File size, in bytes
Returns
-------
filesize : str
A "nice" representation of the size
Examples
--------
>>> stringify_size(1023)
'< 1 Kb'
>>> stringify_size(1024)
'1 Kb'
>>> stringify_size(1025)
'1 Kb'
>>> stringify_size(54232)
'53 Kb'
>>> stringify_size(4545833)
'4 Mb'
>>> stringify_size(45458330000)
'4.2 Gb'
"""
if s < 1024:
lbl = "< 1 Kb"
elif s < 1024 * 1024:
lbl = "%d Kb" % (myint(s / 1024.0))
elif s < 1024 * 1024 * 1024:
lbl = "%d Mb" % (myint(s / (1024 * 1024.0)))
else:
lbl = "%.1f Gb" % (s / (1024 * 1024 * 1024.0))
return lbl
def download_progress(url, size, outfile,
headers=None,
progress=None,
chunksize=8192,
verbose=True):
"""Download url and store in outfile, reporting progress.
The download will use chunks, logging the output to the
screen, and will not re-download partial data (e.g.
from a partially-completed earlier attempt). Information
on the state of the download will be displayed to stdout
unless verbose is False. This routine requires that
we already know the size of the file.
Parameters
----------
url : str
The URL to download; this must be http or https based.
size : int
The file size in bytes.
outfile : str
The output file (relative to the current working directory).
Any sub-directories must already exist.
headers : dict, optional
Any additions to the HTTP header in the request (e.g. to
set 'User-Agent'). If None, a user-agent string of
"ciao_contrib.downloadutils.download_progress" is
used).
progress : ProgressBar instance, optional
If not specified a default instance (20 '#' marks) is used.
chunksize : int, optional
The chunk size to use, in bytes.
verbose : bool, optional
Should progress information on the download be written to
stdout?
Notes
-----
This routine assumes that the HTTP server supports ranged
requests [1]_, and ignores SSL validation of the request.
The assumption is that the resource is static (i.e. it hasn't
been updated since content was downloaded). This means that it
is possible the output will be invalid, for instance if it
has increased in length since the last time it was fully
downloaded, or changed and there was a partial download.
References
----------
.. [1] https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests
"""
# I used http.client rather than urllib because I read somewhere
# that urllib did not handle streaming requests (e.g. it would just
# read in everything in one go and then you read from the in-memory
# buffer).
#
# From https://stackoverflow.com/a/24900110 - is it still true?
#
purl = urllib.request.urlparse(url)
if purl.scheme == 'https':
no_context = ssl._create_unverified_context()
conn = http.client.HTTPSConnection(purl.netloc, context=no_context)
elif purl.scheme == 'http':
conn = http.client.HTTPConnection(purl.netloc)
else:
raise ValueError("Unsupported URL scheme: {}".format(url))
startfrom = 0
try:
fsize = os.path.getsize(outfile)
except OSError:
fsize = None
if fsize is not None:
equal_size = fsize == size
v3("Checking on-disk file size " +
"({}) against archive size ".format(fsize) +
"({}): {}".format(size, equal_size))
if equal_size:
if verbose:
# Ugly, since this is set up to match what is needed by
# ciao_contrib.cda.data.ObsIdFile.download rather than
# being generic. Need to look at how messages are
# displayed.
#
sys.stdout.write("{:>20s}\n".format("already downloaded"))
sys.stdout.flush()
return (0, 0)
if fsize > size:
v0("Archive size is less than disk size for " +
"{} - {} vs {} bytes.".format(outfile,
size,
fsize))
return (0, 0)
startfrom = fsize
try:
outfp = open(outfile, 'ab')
except IOError:
raise IOError("Unable to create '{}'".format(outfile))
# Is this seek needed?
if startfrom > 0 and outfp.tell() == 0:
outfp.seek(0, 2)
if progress is None:
progress = ProgressBar(size)
if headers is None:
headers = {'User-Agent':
'ciao_contrib.downloadutils.download_progress'}
else:
# Ensure we copy the header dictionary, since we are going
# to add to it. It is assumed that a shallow copy is
# enough.
#
headers = headers.copy()
# Could hide this if startfrom = 0 and size <= chunksize, but
# it doesn't seem worth it.
#
headers['Range'] = 'bytes={}-{}'.format(startfrom, size - 1)
time0 = time.time()
conn.request('GET', url, headers=headers)
with conn.getresponse() as rsp:
# Assume that rsp.status != 206 would cause some form
# of an error so we don't need to check for this here.
#
if verbose:
progress.start(startfrom)
# Note that the progress bar reflects the expected size, not
# the actual size; this may not be ideal (but don't expect the
# sizes to change so it doesn't really matter).
#
while True:
chunk = rsp.read(chunksize)
if not chunk:
break
outfp.write(chunk)
if verbose:
progress.add(len(chunk))
if verbose:
progress.end()
time1 = time.time()
nbytes = outfp.tell()
outfp.close()
dtime = time1 - time0
if verbose:
rate = (nbytes - startfrom) / (1024 * dtime)
tlabel = stringify_dt(dtime)
sys.stdout.write(" {:>13s} {:.1f} kb/s\n".format(tlabel, rate))
if size != nbytes:
v0("WARNING file sizes do not match: expected {} but downloaded {}".format(size, nbytes))
return (nbytes, dtime)
| cxcsds/ciao-contrib | ciao_contrib/downloadutils.py | Python | gpl-3.0 | 22,858 |
var annotated_dup =
[
[ "AbstractHive", "classAbstractHive.html", "classAbstractHive" ],
[ "Colour", "classColour.html", "classColour" ],
[ "Environment", "classEnvironment.html", "classEnvironment" ],
[ "EventManager", "classEventManager.html", "classEventManager" ],
[ "EvoBeeExperiment", "classEvoBeeExperiment.html", "classEvoBeeExperiment" ],
[ "EvoBeeModel", "classEvoBeeModel.html", "classEvoBeeModel" ],
[ "Flower", "classFlower.html", "classFlower" ],
[ "FloweringPlant", "classFloweringPlant.html", "classFloweringPlant" ],
[ "Hive", "classHive.html", "classHive" ],
[ "HiveConfig", "structHiveConfig.html", "structHiveConfig" ],
[ "HoneyBee", "classHoneyBee.html", "classHoneyBee" ],
[ "Hymenoptera", "classHymenoptera.html", "classHymenoptera" ],
[ "LocalDensityConstraint", "structLocalDensityConstraint.html", "structLocalDensityConstraint" ],
[ "Logger", "classLogger.html", "classLogger" ],
[ "ModelComponent", "classModelComponent.html", "classModelComponent" ],
[ "ModelParams", "classModelParams.html", null ],
[ "Patch", "classPatch.html", "classPatch" ],
[ "PlantTypeConfig", "structPlantTypeConfig.html", "structPlantTypeConfig" ],
[ "PlantTypeDistributionConfig", "structPlantTypeDistributionConfig.html", "structPlantTypeDistributionConfig" ],
[ "Pollen", "structPollen.html", "structPollen" ],
[ "Pollinator", "classPollinator.html", "classPollinator" ],
[ "PollinatorConfig", "structPollinatorConfig.html", "structPollinatorConfig" ],
[ "PollinatorLatestAction", "structPollinatorLatestAction.html", "structPollinatorLatestAction" ],
[ "PollinatorPerformanceInfo", "structPollinatorPerformanceInfo.html", "structPollinatorPerformanceInfo" ],
[ "Position", "classPosition.html", "classPosition" ],
[ "ReflectanceInfo", "classReflectanceInfo.html", "classReflectanceInfo" ],
[ "SDL2_gfxBresenhamIterator", "structSDL2__gfxBresenhamIterator.html", "structSDL2__gfxBresenhamIterator" ],
[ "SDL2_gfxMurphyIterator", "structSDL2__gfxMurphyIterator.html", "structSDL2__gfxMurphyIterator" ],
[ "Visualiser", "classVisualiser.html", "classVisualiser" ],
[ "VisualPreferenceInfo", "structVisualPreferenceInfo.html", "structVisualPreferenceInfo" ],
[ "VisualStimulusInfo", "structVisualStimulusInfo.html", "structVisualStimulusInfo" ]
]; | tim-taylor/evobee | docs/html/annotated_dup.js | JavaScript | gpl-3.0 | 2,376 |
#region Copyright & License Information
/*
* Copyright 2007-2014 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using OpenRA.Server;
using S = OpenRA.Server.Server;
namespace OpenRA.Mods.RA.Server
{
public class MasterServerPinger : ServerTrait, ITick, INotifySyncLobbyInfo, IStartGame, IEndGame
{
const int MasterPingInterval = 60 * 3; // 3 minutes. server has a 5 minute TTL for games, so give ourselves a bit
// of leeway.
public int TickTimeout { get { return MasterPingInterval * 10000; } }
public void Tick(S server)
{
if ((Game.RunTime - lastPing > MasterPingInterval * 1000) || isInitialPing)
PingMasterServer(server);
else
lock (masterServerMessages)
while (masterServerMessages.Count > 0)
server.SendMessage(masterServerMessages.Dequeue());
}
public void LobbyInfoSynced(S server) { PingMasterServer(server); }
public void GameStarted(S server) { PingMasterServer(server); }
public void GameEnded(S server) { PingMasterServer(server); }
int lastPing = 0;
bool isInitialPing = true;
volatile bool isBusy;
Queue<string> masterServerMessages = new Queue<string>();
public void PingMasterServer(S server)
{
if (isBusy || !server.Settings.AdvertiseOnline) return;
lastPing = Game.RunTime;
isBusy = true;
var mod = server.ModData.Manifest.Mod;
// important to grab these on the main server thread, not in the worker we're about to spawn -- they may be modified
// by the main thread as clients join and leave.
var numPlayers = server.LobbyInfo.Clients.Where(c1 => c1.Bot == null && c1.Slot != null).Count();
var numBots = server.LobbyInfo.Clients.Where(c1 => c1.Bot != null).Count();
var numSpectators = server.LobbyInfo.Clients.Where(c1 => c1.Bot == null && c1.Slot == null).Count();
var passwordProtected = string.IsNullOrEmpty(server.Settings.Password) ? 0 : 1;
var clients = server.LobbyInfo.Clients.Where(c1 => c1.Bot == null).Select(c => Convert.ToBase64String(Encoding.UTF8.GetBytes(c.Name))).ToArray();
Action a = () =>
{
try
{
var url = "ping?port={0}&name={1}&state={2}&players={3}&bots={4}&mods={5}&map={6}&maxplayers={7}&spectators={8}&protected={9}&clients={10}";
if (isInitialPing) url += "&new=1";
using (var wc = new WebClient())
{
wc.Proxy = null;
wc.DownloadData(
server.Settings.MasterServer + url.F(
server.Settings.ExternalPort, Uri.EscapeUriString(server.Settings.Name),
(int)server.State,
numPlayers,
numBots,
"{0}@{1}".F(mod.Id, mod.Version),
server.LobbyInfo.GlobalSettings.Map,
server.Map.PlayerCount,
numSpectators,
passwordProtected,
string.Join(",", clients)));
if (isInitialPing)
{
isInitialPing = false;
lock (masterServerMessages)
masterServerMessages.Enqueue("Master server communication established.");
}
}
}
catch (Exception ex)
{
Log.Write("server", ex.ToString());
lock (masterServerMessages)
masterServerMessages.Enqueue("Master server communication failed.");
}
isBusy = false;
};
a.BeginInvoke(null, null);
}
}
}
| UberWaffe/OpenRA | OpenRA.Mods.RA/ServerTraits/MasterServerPinger.cs | C# | gpl-3.0 | 3,554 |
<?php
namespace E4u\Application\Controller;
use E4u\Response\Response;
/**
* <code>
* $exception = new Controller\Redirect();
* throw $exception->setUrl('security/login');
* </code>
*/
class Redirect extends \Exception
{
protected $code = Response::STATUS_REDIRECT;
private $url;
public function setUrl($url) {
$this->url = $url;
return $this;
}
public function getUrl() {
return $this->url;
}
} | nataniel/e4u-framework | src/E4u/Application/Controller/Redirect.php | PHP | gpl-3.0 | 455 |
////////////////////////////////////////////////////////
//
// GEM - Graphics Environment for Multimedia
//
// tigital@mac.com
// ported from pete's_plugins
//
// Implementation file
//
// For information on usage and redistribution, and for a DISCLAIMER OF ALL
// WARRANTIES, see the file, "GEM.LICENSE.TERMS" in this distribution.
//
/////////////////////////////////////////////////////////
#include "Utils/PixPete.h"
#include "pix_backlight.h"
CPPEXTERN_NEW(pix_backlight);
/////////////////////////////////////////////////////////
//
// pix_backlight
//
/////////////////////////////////////////////////////////
// Constructor
//
/////////////////////////////////////////////////////////
pix_backlight :: pix_backlight()
{
m_SpikeScale = 127.0f; // 0 to 255
m_SpikeFloor = 0.0f; // 0 to 255
m_SpikeCeiling = 255.0f; // 0 to 255
init =0;
inlet_new(this->x_obj, &this->x_obj->ob_pd, gensym("float"), gensym("scale"));
inlet_new(this->x_obj, &this->x_obj->ob_pd, gensym("float"), gensym("floor"));
inlet_new(this->x_obj, &this->x_obj->ob_pd, gensym("float"), gensym("ceiling"));
}
/////////////////////////////////////////////////////////
// Destructor
//
/////////////////////////////////////////////////////////
pix_backlight :: ~pix_backlight()
{
//if(init) Pete_BackLight_DeInit();
}
/////////////////////////////////////////////////////////
// processImage
//
/////////////////////////////////////////////////////////
void pix_backlight :: processRGBAImage(imageStruct &image)
{
nWidth = image.xsize;
nHeight = image.ysize;
if (!init) {
//Pete_BackLight_Init();
init = 1;
}
pSource = (U32*)image.data;
myImage.xsize = image.xsize;
myImage.ysize = image.ysize;
myImage.setCsizeByFormat(image.format);
myImage.reallocate();
pOutput = (U32*)myImage.data;
const int nFixedShift=8;
// const int nFixedMult=(1<<nFixedShift);
const int nHalfWidth=(nWidth/2);
const int nHalfHeight=(nHeight/2);
const int nNumPixels = nWidth*nHeight;
U32* pCurrentSource=pSource;
U32* pCurrentOutput=pOutput;
const U32* pSourceEnd=(pSource+nNumPixels);
// const U32* pOutputEnd=(pOutput+nNumPixels);
Pete_ZeroMemory(pOutput,sizeof(U32)*nNumPixels);
const int nSpikeScale=static_cast<int>(m_SpikeScale);
const int nSpikeFloor=static_cast<int>(m_SpikeFloor);
const int nSpikeCeiling=static_cast<int>(m_SpikeCeiling);
int nY=0;
while (pCurrentSource!=pSourceEnd) {
// const U32* pSourceLineStart=pCurrentSource;
const U32* pSourceLineEnd=pCurrentSource+nWidth;
int nX=0;
while (pCurrentSource!=pSourceLineEnd) {
U32 SourceColour=*pCurrentSource;
int nRed=(SourceColour&(0xff<<SHIFT_RED))>>SHIFT_RED;
int nGreen=(SourceColour&(0xff<<SHIFT_GREEN))>>SHIFT_GREEN;
int nBlue=(SourceColour&(0xff<<SHIFT_BLUE))>>SHIFT_BLUE;
int nLuminance =
((90 * nRed)+
(115 * nGreen)+
(51 * nBlue));
nLuminance>>=8;
// SourceColour|=(nLuminance<<24);
nLuminance=clampFunc(nLuminance,nSpikeFloor,nSpikeCeiling);
nLuminance-=nSpikeFloor;
const int nLength=((nLuminance*nSpikeScale)>>nFixedShift);
int nDeltaX=((nX-nHalfWidth)*nLength)>>8;
int nDeltaY=((nY-nHalfHeight)*nLength)>>8;
int nEndX=nX+nDeltaX;
if (nEndX>nWidth) {
nEndX=nWidth;
} else if (nEndX<0) {
nEndX=0;
}
int nEndY=nY+nDeltaY;
if (nEndY>nHeight) {
nEndY=nHeight;
} else if (nEndY<0) {
nEndY=0;
}
int nXInc;
if (nDeltaX<0) {
nXInc=-1;
} else {
nXInc=1;
}
int nYInc;
if (nDeltaY<0) {
nYInc=-1;
} else {
nYInc=1;
}
nDeltaX*=nXInc;
nDeltaY*=nYInc;
int nCurrentX=nX;
int nCurrentY=nY;
if ((nDeltaX==0)&&(nDeltaY==0)) {
nDeltaX=1;
nEndX+=1;
nEndY+=1;
} else if (nDeltaX==0) {
nEndX+=1;
} else if (nDeltaY==0) {
nEndY+=1;
}
U32* pDest=(pOutput+(nCurrentY*nWidth)+nCurrentX);
const int nDestYInc=(nWidth*nYInc);
const int nDestXInc=nXInc;
if (nDeltaX>nDeltaY) {
int nCounter=nDeltaY;
while ((nCurrentX!=nEndX)&&(nCurrentY!=nEndY)) {
#ifdef PETE_DEBUG_BACKLIGHT
if ((nCurrentX<0)||
(nCurrentX>=nWidth)||
(nCurrentY<0)||
(nCurrentY>=nHeight)||
(pDest<pOutput)||
(pDest>=pOutputEnd)) {
while (true); // Pete- Infinite loop, easy way to tell if this triggered!
}
#endif // PETE_DEBUG_BACKLIGHT
const U32 DestColour=*pDest;
if (DestColour<SourceColour) {
*pDest=SourceColour;
} else {
break;
}
if (nCounter>=nDeltaX) {
nCounter-=nDeltaX;
nCurrentY+=nYInc;
pDest+=nDestYInc;
}
nCurrentX+=nXInc;
pDest+=nDestXInc;
nCounter+=nDeltaY;
}
} else {
int nCounter=nDeltaX;
while ((nCurrentX!=nEndX)&&(nCurrentY!=nEndY)) {
#ifdef PETE_DEBUG_BACKLIGHT
if ((nCurrentX<0)||
(nCurrentX>=nWidth)||
(nCurrentY<0)||
(nCurrentY>=nHeight)||
(pDest<pOutput)||
(pDest>=pOutputEnd)) {
while (true); // Pete- Infinite loop, easy way to tell if this triggered!
}
#endif // PETE_DEBUG_BACKLIGHT
const U32 DestColour=*pDest;
if (DestColour<SourceColour) {
*pDest=SourceColour;
} else {
break;
}
if (nCounter>=nDeltaY) {
nCounter-=nDeltaY;
nCurrentX+=nXInc;
pDest+=nDestXInc;
}
nCurrentY+=nYInc;
pDest+=nDestYInc;
nCounter+=nDeltaX;
};
}
pCurrentSource+=1;
pCurrentOutput+=1;
nX+=1;
}
nY+=1;
}
image.data = myImage.data;
}
/////////////////////////////////////////////////////////
// do the YUV processing here
//
/////////////////////////////////////////////////////////
void pix_backlight :: processYUVImage(imageStruct &image)
{
nWidth = image.xsize/2;
nHeight = image.ysize;
if (!init) {
//Pete_BackLight_Init();
init = 1;
}
pSource = (U32*)image.data;
myImage.xsize = image.xsize;
myImage.ysize = image.ysize;
myImage.setCsizeByFormat(image.format);
myImage.reallocate();
pOutput = (U32*)myImage.data;
const int nFixedShift=8;
// const int nFixedMult=(1<<nFixedShift);
const int nHalfWidth=(nWidth/2);
const int nHalfHeight=(nHeight/2);
const int nNumPixels = nWidth*nHeight;
U32* pCurrentSource=pSource;
U32* pCurrentOutput=pOutput;
const U32* pSourceEnd=(pSource+nNumPixels);
// const U32* pOutputEnd=(pOutput+nNumPixels);
//Pete_ZeroMemory(pOutput,sizeof(U32)*nNumPixels);
unsigned char *zero;
zero = (unsigned char*)pOutput;
int temp = nNumPixels;
while(--temp>>1){
*zero++ = 128; *zero++ =0;
*zero++ = 128; *zero++ = 0;
}
union {
unsigned char c[4];
unsigned int i;
}bu;
bu.c[0] = 128;
bu.c[1] = 0;
bu.c[2] = 128;
bu.c[3] = 0;
unsigned int black;
black = bu.i;
const int nSpikeScale=static_cast<int>(m_SpikeScale);
const int nSpikeFloor=static_cast<int>(m_SpikeFloor);
const int nSpikeCeiling=static_cast<int>(m_SpikeCeiling);
int nY=0;
while (pCurrentSource!=pSourceEnd) {
// const U32* pSourceLineStart=pCurrentSource;
const U32* pSourceLineEnd=pCurrentSource+nWidth;
int nX=0;
while (pCurrentSource!=pSourceLineEnd) {
U32 SourceColour=*pCurrentSource;
int nLuminance=(SourceColour&(0xff<<SHIFT_Y1))>>SHIFT_Y1;
nLuminance=clampFunc(nLuminance,nSpikeFloor,nSpikeCeiling);
nLuminance-=nSpikeFloor;
const int nLength=((nLuminance*nSpikeScale)>>nFixedShift);
int nDeltaX=((nX-nHalfWidth)*nLength)>>8;
int nDeltaY=((nY-nHalfHeight)*nLength)>>8;
int nEndX=nX+nDeltaX;
if (nEndX>nWidth) {
nEndX=nWidth;
} else if (nEndX<0) {
nEndX=0;
}
int nEndY=nY+nDeltaY;
if (nEndY>nHeight) {
nEndY=nHeight;
} else if (nEndY<0) {
nEndY=0;
}
int nXInc;
if (nDeltaX<0) {
nXInc=-1;
} else {
nXInc=1;
}
int nYInc;
if (nDeltaY<0) {
nYInc=-1;
} else {
nYInc=1;
}
nDeltaX*=nXInc;
nDeltaY*=nYInc;
int nCurrentX=nX;
int nCurrentY=nY;
if ((nDeltaX==0)&&(nDeltaY==0)) {
nDeltaX=1;
nEndX+=1;
nEndY+=1;
} else if (nDeltaX==0) {
nEndX+=1;
} else if (nDeltaY==0) {
nEndY+=1;
}
U32* pDest=(pOutput+(nCurrentY*nWidth)+nCurrentX);
const int nDestYInc=(nWidth*nYInc);
const int nDestXInc=nXInc;
if (nDeltaX>nDeltaY) {
int nCounter=nDeltaY;
while ((nCurrentX!=nEndX)&&(nCurrentY!=nEndY)) {
#ifdef PETE_DEBUG_BACKLIGHT
if ((nCurrentX<0)||
(nCurrentX>=nWidth)||
(nCurrentY<0)||
(nCurrentY>=nHeight)||
(pDest<pOutput)||
(pDest>=pOutputEnd)) {
while (true); // Pete- Infinite loop, easy way to tell if this triggered!
}
#endif // PETE_DEBUG_BACKLIGHT
const U32 DestColour=*pDest;
if (DestColour<SourceColour || DestColour == black) {
*pDest=SourceColour;
} else {
break;
}
if (nCounter>=nDeltaX) {
nCounter-=nDeltaX;
nCurrentY+=nYInc;
pDest+=nDestYInc;
}
nCurrentX+=nXInc;
pDest+=nDestXInc;
nCounter+=nDeltaY;
}
} else {
int nCounter=nDeltaX;
while ((nCurrentX!=nEndX)&&(nCurrentY!=nEndY)) {
#ifdef PETE_DEBUG_BACKLIGHT
if ((nCurrentX<0)||
(nCurrentX>=nWidth)||
(nCurrentY<0)||
(nCurrentY>=nHeight)||
(pDest<pOutput)||
(pDest>=pOutputEnd)) {
while (true); // Pete- Infinite loop, easy way to tell if this triggered!
}
#endif // PETE_DEBUG_BACKLIGHT
const U32 DestColour=*pDest;
// if (DestColour<SourceColour) {
if (DestColour<SourceColour || DestColour == black) {
*pDest=SourceColour;
} else {
break;
}
if (nCounter>=nDeltaY) {
nCounter-=nDeltaY;
nCurrentX+=nXInc;
pDest+=nDestXInc;
}
nCurrentY+=nYInc;
pDest+=nDestYInc;
nCounter+=nDeltaX;
};
}
pCurrentSource+=1;
pCurrentOutput+=1;
nX+=1;
}
nY+=1;
}
image.data = myImage.data;
}
/////////////////////////////////////////////////////////
// do the Gray processing here
//
/////////////////////////////////////////////////////////
/*
void pix_backlight :: processGrayImage(imageStruct &image)
{
nWidth = image.xsize;
nHeight = image.ysize;
if (!init) {
//Pete_BackLight_Init();
init = 1;
}
unsigned char* pSource = image.data;
if ( myImage.xsize*myImage.ysize*myImage.csize != image.xsize*image.ysize*image.csize ){
int dataSize = image.xsize * image.ysize * image.csize;
myImage.clear();
myImage.allocate(dataSize);
}
myImage.xsize = image.xsize;
myImage.ysize = image.ysize;
myImage.csize = image.csize;
myImage.type = image.type;
unsigned char* pOutput = myImage.data;
const int nFixedShift=8;
// const int nFixedMult=(1<<nFixedShift);
const int nHalfWidth=(nWidth/2);
const int nHalfHeight=(nHeight/2);
const int nNumPixels = nWidth*nHeight;
U32* pCurrentSource=pSource;
U32* pCurrentOutput=pOutput;
const U32* pSourceEnd=(pSource+nNumPixels);
// const U32* pOutputEnd=(pOutput+nNumPixels);
Pete_ZeroMemory(pOutput,sizeof(U32)*nNumPixels);
const int nSpikeScale=static_cast<int>(m_SpikeScale);
const int nSpikeFloor=static_cast<int>(m_SpikeFloor);
const int nSpikeCeiling=static_cast<int>(m_SpikeCeiling);
int nY=0;
while (pCurrentSource!=pSourceEnd) {
// const U32* pSourceLineStart=pCurrentSource;
const U32* pSourceLineEnd=pCurrentSource+nWidth;
int nX=0;
while (pCurrentSource!=pSourceLineEnd) {
U32 SourceColour=*pCurrentSource;
int nRed=(SourceColour&(0xff<<SHIFT_RED))>>SHIFT_RED;
int nGreen=(SourceColour&(0xff<<SHIFT_GREEN))>>SHIFT_GREEN;
int nBlue=(SourceColour&(0xff<<SHIFT_BLUE))>>SHIFT_BLUE;
int nLuminance =
((90 * nRed)+
(115 * nGreen)+
(51 * nBlue));
nLuminance>>=8;
// SourceColour|=(nLuminance<<24);
nLuminance=clampFunc(nLuminance,nSpikeFloor,nSpikeCeiling);
nLuminance-=nSpikeFloor;
const int nLength=((nLuminance*nSpikeScale)>>nFixedShift);
int nDeltaX=((nX-nHalfWidth)*nLength)>>8;
int nDeltaY=((nY-nHalfHeight)*nLength)>>8;
int nEndX=nX+nDeltaX;
if (nEndX>nWidth) {
nEndX=nWidth;
} else if (nEndX<0) {
nEndX=0;
}
int nEndY=nY+nDeltaY;
if (nEndY>nHeight) {
nEndY=nHeight;
} else if (nEndY<0) {
nEndY=0;
}
int nXInc;
if (nDeltaX<0) {
nXInc=-1;
} else {
nXInc=1;
}
int nYInc;
if (nDeltaY<0) {
nYInc=-1;
} else {
nYInc=1;
}
nDeltaX*=nXInc;
nDeltaY*=nYInc;
int nCurrentX=nX;
int nCurrentY=nY;
if ((nDeltaX==0)&&(nDeltaY==0)) {
nDeltaX=1;
nEndX+=1;
nEndY+=1;
} else if (nDeltaX==0) {
nEndX+=1;
} else if (nDeltaY==0) {
nEndY+=1;
}
U32* pDest=(pOutput+(nCurrentY*nWidth)+nCurrentX);
const int nDestYInc=(nWidth*nYInc);
const int nDestXInc=nXInc;
if (nDeltaX>nDeltaY) {
int nCounter=nDeltaY;
while ((nCurrentX!=nEndX)&&(nCurrentY!=nEndY)) {
#ifdef PETE_DEBUG_BACKLIGHT
if ((nCurrentX<0)||
(nCurrentX>=nWidth)||
(nCurrentY<0)||
(nCurrentY>=nHeight)||
(pDest<pOutput)||
(pDest>=pOutputEnd)) {
while (true); // Pete- Infinite loop, easy way to tell if this triggered!
}
#endif // PETE_DEBUG_BACKLIGHT
const U32 DestColour=*pDest;
if (DestColour<SourceColour) {
*pDest=SourceColour;
} else {
break;
}
if (nCounter>=nDeltaX) {
nCounter-=nDeltaX;
nCurrentY+=nYInc;
pDest+=nDestYInc;
}
nCurrentX+=nXInc;
pDest+=nDestXInc;
nCounter+=nDeltaY;
}
} else {
int nCounter=nDeltaX;
while ((nCurrentX!=nEndX)&&(nCurrentY!=nEndY)) {
#ifdef PETE_DEBUG_BACKLIGHT
if ((nCurrentX<0)||
(nCurrentX>=nWidth)||
(nCurrentY<0)||
(nCurrentY>=nHeight)||
(pDest<pOutput)||
(pDest>=pOutputEnd)) {
while (true); // Pete- Infinite loop, easy way to tell if this triggered!
}
#endif // PETE_DEBUG_BACKLIGHT
const U32 DestColour=*pDest;
if (DestColour<SourceColour) {
*pDest=SourceColour;
} else {
break;
}
if (nCounter>=nDeltaY) {
nCounter-=nDeltaY;
nCurrentX+=nXInc;
pDest+=nDestXInc;
}
nCurrentY+=nYInc;
pDest+=nDestYInc;
nCounter+=nDeltaX;
};
}
pCurrentSource+=1;
pCurrentOutput+=1;
nX+=1;
}
nY+=1;
}
image.data = myImage.data;
}
*/
/////////////////////////////////////////////////////////
// static member function
//
/////////////////////////////////////////////////////////
void pix_backlight :: obj_setupCallback(t_class *classPtr)
{
class_addmethod(classPtr, reinterpret_cast<t_method>(&pix_backlight::scaleCallback),
gensym("scale"), A_DEFFLOAT, A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&pix_backlight::floorCallback),
gensym("floor"), A_DEFFLOAT, A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&pix_backlight::ceilingCallback),
gensym("ceiling"), A_DEFFLOAT, A_NULL);
}
void pix_backlight :: scaleCallback(void *data, t_floatarg m_SpikeScale)
{
m_SpikeScale*=255.0;
// if(m_SpikeScale<0.f)m_SpikeScale=0.f;else if(m_SpikeScale>255.f)m_SpikeScale=255.f;
GetMyClass(data)->m_SpikeScale=(m_SpikeScale);
GetMyClass(data)->setPixModified();
}
void pix_backlight :: floorCallback(void *data, t_floatarg m_SpikeFloor)
{
m_SpikeFloor*=255.0;
if(m_SpikeFloor<0.f)m_SpikeFloor=0.f;else if(m_SpikeFloor>255.f)m_SpikeFloor=255.f;
GetMyClass(data)->m_SpikeFloor=(m_SpikeFloor);
GetMyClass(data)->setPixModified();
}
void pix_backlight :: ceilingCallback(void *data, t_floatarg m_SpikeCeiling)
{
m_SpikeCeiling*=255.0;
if(m_SpikeCeiling<0.f)m_SpikeCeiling=0.f;else if(m_SpikeCeiling>255.f)m_SpikeCeiling=255.f;
GetMyClass(data)->m_SpikeCeiling=(m_SpikeCeiling);
GetMyClass(data)->setPixModified();
}
| rvega/morphasynth | vendors/pd-extended-0.43.4/externals/Gem/src/Pixes/pix_backlight.cpp | C++ | gpl-3.0 | 16,287 |
/*
WorldGuard2Secuboid: Convert from WorldGuard regions to Secuboid lands
Copyright (C) 2015 Tabinol
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/>.
*/
package me.tabinol.worldguard2secuboid;
public enum ParType {
PERMISSION,
FLAG
}
| Tabinol/WorldGuard2Secuboid | src/main/java/me/tabinol/worldguard2secuboid/ParType.java | Java | gpl-3.0 | 820 |
#ifndef CITAR_MODEL_PRIVATE_HH
#define CITAR_MODEL_PRIVATE_HH
#include <iostream>
#include <map>
#include <string>
#include <memory>
#include <unordered_map>
#include <citar/util/NonCopyable.hh>
#include <citar/tagger/hmm/BiGram.hh>
#include <citar/tagger/hmm/TriGram.hh>
#include <citar/tagger/hmm/UniGram.hh>
namespace citar {
namespace tagger {
typedef std::unordered_map<std::string, std::map<size_t, size_t> >
WordTagFreqs;
/**
* Instances of this class contain a model for a trigram HMM tagger. It
* consists of the language model (uni/bi/trigram statistics) and a lexicon.
*/
class ModelPrivate
{
public:
BiGramFreqs const &biGrams() const;
WordTagFreqs const &lexicon() const;
std::unordered_map<size_t, std::string> const &numberTags() const;
/**
* Read the model from input streams. An input stream for the lexicon, and
* an input stream for n-gram statistics should be provided. The lexicon
* should list one word per line, followed by pairs of a tag and its
* frequency, for instance:
*
* <pre>
* uncommunicative JJ 1
* dormant JJ 3
* paranormal JJ 1
* plan NN 138 VB 27
* accolades NNS 1
* </pre>
*
* The ngram stream should list one ngram per line with its frequency. For
* instance:
*
* <pre>
* BED ABX 5
* OD , 82
* AP DO 1
* BEN ABN 1
* WPO VBD 5
* </pre>
*/
static ModelPrivate *readModel(std::istream &lexiconStream,
std::istream &nGramStream);
std::unordered_map<std::string, size_t> const &tagNumbers() const;
TriGramFreqs const &triGrams() const;
UniGramFreqs const &uniGrams() const;
private:
ModelPrivate(std::shared_ptr<WordTagFreqs> lexicon,
std::shared_ptr<NGrams> nGrams) :
d_lexicon(lexicon), d_nGrams(nGrams) {}
ModelPrivate(ModelPrivate const &other);
ModelPrivate &operator=(ModelPrivate const &other);
static std::shared_ptr<WordTagFreqs>
readLexicon(std::istream &lexiconStream,
std::unordered_map<std::string, size_t> const &tagNumbers);
static std::shared_ptr<NGrams> readNGrams(std::istream &lexiconStream);
std::shared_ptr<WordTagFreqs> d_lexicon;
std::shared_ptr<NGrams> d_nGrams;
};
inline BiGramFreqs const &ModelPrivate::biGrams() const
{
return d_nGrams->biGrams;
}
inline WordTagFreqs const &ModelPrivate::lexicon() const
{
return *d_lexicon;
}
inline std::unordered_map<size_t, std::string> const &ModelPrivate::numberTags() const
{
return d_nGrams->numberTags;
}
inline std::unordered_map<std::string, size_t> const &ModelPrivate::tagNumbers() const
{
return d_nGrams->tagNumbers;
}
inline TriGramFreqs const &ModelPrivate::triGrams() const
{
return d_nGrams->triGrams;
}
inline UniGramFreqs const &ModelPrivate::uniGrams() const
{
return d_nGrams->uniGrams;
}
}
}
#endif // CITAR_MODEL_HH
| brianray/citar | src/tagger/hmm/ModelPrivate.hh | C++ | gpl-3.0 | 2,739 |
using LinqToVisualTree;
using System;
using System.Collections.Generic;
using System.Linq;
using Telegram.Td.Api;
using Unigram.Controls;
using Unigram.Navigation;
using Unigram.Navigation.Services;
using Unigram.Services;
using Unigram.Services.ViewService;
using Unigram.ViewModels;
using Unigram.ViewModels.Settings;
using Unigram.Views;
using Unigram.Views.Payments;
using Unigram.Views.Settings;
using Unigram.Views.Settings.Popups;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI.WindowManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace Unigram.Common
{
public class TLNavigationService : NavigationService
{
private readonly IProtoService _protoService;
private readonly IPasscodeService _passcodeService;
private readonly IViewService _viewService;
private readonly Dictionary<string, AppWindow> _instantWindows = new Dictionary<string, AppWindow>();
public TLNavigationService(IProtoService protoService, IViewService viewService, Frame frame, int session, string id)
: base(frame, session, id)
{
_protoService = protoService;
_passcodeService = TLContainer.Current.Passcode;
_viewService = viewService;
}
public int SessionId => _protoService.SessionId;
public IProtoService ProtoService => _protoService;
public async void NavigateToInstant(string url)
{
//if (ApiInformation.IsTypePresent("Windows.UI.WindowManagement.AppWindow"))
//{
// _instantWindows.TryGetValue(url, out AppWindow window);
// if (window == null)
// {
// var nav = BootStrapper.Current.NavigationServiceFactory(BootStrapper.BackButton.Ignore, BootStrapper.ExistingContent.Exclude, 0, "0", false);
// var frame = BootStrapper.Current.CreateRootElement(nav);
// nav.Navigate(typeof(InstantPage), url);
// window = await AppWindow.TryCreateAsync();
// window.PersistedStateId = "InstantView";
// window.TitleBar.ExtendsContentIntoTitleBar = true;
// window.Closed += (s, args) =>
// {
// _instantWindows.Remove(url);
// frame = null;
// window = null;
// };
// _instantWindows[url] = window;
// ElementCompositionPreview.SetAppWindowContent(window, frame);
// }
// await window.TryShowAsync();
// window.RequestMoveAdjacentToCurrentView();
//}
//else
{
Navigate(typeof(InstantPage), url);
}
}
public async void NavigateToInvoice(MessageViewModel message)
{
var parameters = new ViewServiceParams
{
Title = message.Content is MessageInvoice invoice && invoice.ReceiptMessageId == 0 ? Strings.Resources.PaymentCheckout : Strings.Resources.PaymentReceipt,
Width = 380,
Height = 580,
PersistentId = "Payments",
Content = control =>
{
var nav = BootStrapper.Current.NavigationServiceFactory(BootStrapper.BackButton.Ignore, BootStrapper.ExistingContent.Exclude, SessionId, "Payments" + Guid.NewGuid(), false);
nav.Navigate(typeof(PaymentFormPage), state: Navigation.Services.NavigationState.GetInvoice(message.ChatId, message.Id));
return BootStrapper.Current.CreateRootElement(nav);
}
};
await _viewService.OpenAsync(parameters);
}
public async void NavigateToSender(MessageSender sender)
{
if (sender is MessageSenderUser user)
{
var response = await ProtoService.SendAsync(new CreatePrivateChat(user.UserId, false));
if (response is Chat chat)
{
Navigate(typeof(ProfilePage), chat.Id);
}
}
else if (sender is MessageSenderChat chat)
{
Navigate(typeof(ProfilePage), chat.ChatId);
}
}
public async void NavigateToChat(Chat chat, long? message = null, long? thread = null, string accessToken = null, NavigationState state = null, bool scheduled = false, bool force = true, bool createNewWindow = false)
{
if (chat == null)
{
return;
}
if (chat.Type is ChatTypePrivate privata)
{
var user = _protoService.GetUser(privata.UserId);
if (user == null)
{
return;
}
if (user.RestrictionReason.Length > 0)
{
await MessagePopup.ShowAsync(user.RestrictionReason, Strings.Resources.AppName, Strings.Resources.OK);
return;
}
}
else if (chat.Type is ChatTypeSupergroup super)
{
var supergroup = _protoService.GetSupergroup(super.SupergroupId);
if (supergroup == null)
{
return;
}
if (supergroup.Status is ChatMemberStatusLeft && string.IsNullOrEmpty(supergroup.Username) && !supergroup.HasLocation && !supergroup.HasLinkedChat && !_protoService.IsChatAccessible(chat))
{
await MessagePopup.ShowAsync(Strings.Resources.ChannelCantOpenPrivate, Strings.Resources.AppName, Strings.Resources.OK);
return;
}
if (supergroup.RestrictionReason.Length > 0)
{
await MessagePopup.ShowAsync(supergroup.RestrictionReason, Strings.Resources.AppName, Strings.Resources.OK);
return;
}
}
if (Frame.Content is ChatPage page && chat.Id.Equals((long)CurrentPageParam) && thread == null && !scheduled && !createNewWindow)
{
if (message != null)
{
await page.ViewModel.LoadMessageSliceAsync(null, message.Value);
}
else
{
await page.ViewModel.LoadMessageSliceAsync(null, chat.LastMessage?.Id ?? long.MaxValue, VerticalAlignment.Bottom);
}
if (accessToken != null && ProtoService.TryGetUser(chat, out User user) && ProtoService.TryGetUserFull(chat, out UserFullInfo userFull))
{
page.ViewModel.AccessToken = accessToken;
page.View.UpdateUserFullInfo(chat, user, userFull, false, true);
}
page.ViewModel.TextField?.Focus(FocusState.Programmatic);
if (App.DataPackages.TryRemove(chat.Id, out DataPackageView package))
{
await page.ViewModel.HandlePackageAsync(package);
}
}
else
{
//NavigatedEventHandler handler = null;
//handler = async (s, args) =>
//{
// Frame.Navigated -= handler;
// if (args.Content is DialogPage page1 /*&& chat.Id.Equals((long)args.Parameter)*/)
// {
// if (message.HasValue)
// {
// await page1.ViewModel.LoadMessageSliceAsync(null, message.Value);
// }
// }
//};
//Frame.Navigated += handler;
state ??= new NavigationState();
if (message != null)
{
state["message_id"] = message.Value;
}
if (accessToken != null)
{
state["access_token"] = accessToken;
}
if (createNewWindow)
{
Type target;
object parameter;
if (thread != null)
{
target = typeof(ChatThreadPage);
parameter = $"{chat.Id};{thread}";
}
else if (scheduled)
{
target = typeof(ChatScheduledPage);
parameter = chat.Id;
}
else
{
target = typeof(ChatPage);
parameter = chat.Id;
}
// This is horrible here but I don't want to bloat this method with dozens of parameters.
var masterDetailPanel = Window.Current.Content.Descendants<MasterDetailPanel>().FirstOrDefault();
if (masterDetailPanel != null)
{
await OpenAsync(target, parameter, size: new Windows.Foundation.Size(masterDetailPanel.ActualDetailWidth, masterDetailPanel.ActualHeight));
}
else
{
await OpenAsync(target, parameter);
}
}
else
{
if (Frame.Content is ChatPage chatPage && thread == null && !scheduled && !force)
{
chatPage.ViewModel.OnNavigatingFrom(null);
chatPage.Dispose();
chatPage.Activate(SessionId);
chatPage.ViewModel.NavigationService = this;
chatPage.ViewModel.Dispatcher = Dispatcher;
await chatPage.ViewModel.OnNavigatedToAsync(chat.Id, Windows.UI.Xaml.Navigation.NavigationMode.New, state);
FrameFacade.RaiseNavigated(chat.Id);
}
else
{
Type target;
object parameter;
if (thread != null)
{
target = typeof(ChatThreadPage);
parameter = $"{chat.Id};{thread}";
}
else if (scheduled)
{
target = typeof(ChatScheduledPage);
parameter = chat.Id;
}
else
{
target = typeof(ChatPage);
parameter = chat.Id;
}
Navigate(target, parameter, state);
}
}
}
}
public async void NavigateToChat(long chatId, long? message = null, long? thread = null, string accessToken = null, NavigationState state = null, bool scheduled = false, bool force = true, bool createNewWindow = false)
{
var chat = _protoService.GetChat(chatId);
if (chat == null)
{
chat = await _protoService.SendAsync(new GetChat(chatId)) as Chat;
}
if (chat == null)
{
return;
}
NavigateToChat(chat, message, thread, accessToken, state, scheduled, force, createNewWindow);
}
public async void NavigateToPasscode()
{
if (_passcodeService.IsEnabled)
{
var dialog = new SettingsPasscodeConfirmPopup();
var confirm = await dialog.ShowQueuedAsync();
if (confirm == ContentDialogResult.Primary)
{
Navigate(typeof(SettingsPasscodePage));
}
}
else
{
var popup = new SettingsPasscodePopup();
var confirm = await popup.ShowQueuedAsync();
if (confirm == ContentDialogResult.Primary)
{
var viewModel = TLContainer.Current.Resolve<SettingsPasscodeViewModel>(SessionId);
if (viewModel != null)
{
viewModel.ToggleCommand.Execute();
}
}
}
}
}
}
| UnigramDev/Unigram | Unigram/Unigram/Common/TLNavigationService.cs | C# | gpl-3.0 | 12,617 |
<?php
namespace AwsSdk2\Aws\CloudTrail;
use AwsSdk2\Aws\S3\S3Client;
use AwsSdk2\Guzzle\Common\Collection;
/**
* The `AwsSdk2\Aws\CloudTrail\LogRecordIterator` provides an easy way to iterate over log records from log files generated by
* AWS CloudTrail. CloudTrail log files contain data about your AWS API calls and are stored in Amazon S3 at a
* predictable path based on a bucket name, a key prefix, an account ID, a region, and date information. The files are
* gzipped and contain structured data in JSON format. This class allows you to specify options via its factory methods,
* including a date range, and emits each log record from any log files that match the provided options.
*
* @yields Collection A log record containing data about an AWS API call is yielded for each iteration on this object
*/
class LogRecordIterator implements \OuterIterator
{
/**
* @var LogFileReader
*/
private $logFileReader;
/**
* @var \Iterator
*/
private $logFileIterator;
/**
* @var array
*/
private $records;
/**
* @var int
*/
private $recordIndex;
/**
* @param S3Client $s3Client
* @param CloudTrailClient $cloudTrailClient
* @param array $options
*
* @return LogRecordIterator
*/
public static function forTrail(S3Client $s3Client, CloudTrailClient $cloudTrailClient, array $options = array())
{
$logFileReader = new LogFileReader($s3Client);
$logFileIterator = LogFileIterator::forTrail($s3Client, $cloudTrailClient, $options);
return new self($logFileReader, $logFileIterator);
}
/**
* @param S3Client $s3Client
* @param string $s3BucketName
* @param array $options
*
* @return LogRecordIterator
*/
public static function forBucket(S3Client $s3Client, $s3BucketName, array $options = array())
{
$logFileReader = new LogFileReader($s3Client);
$logFileIterator = new LogFileIterator($s3Client, $s3BucketName, $options);
return new self($logFileReader, $logFileIterator);
}
/**
* @param S3Client $s3Client
* @param string $s3BucketName
* @param string $s3ObjectKey
*
* @return LogRecordIterator
*/
public static function forFile(S3Client $s3Client, $s3BucketName, $s3ObjectKey)
{
$logFileReader = new LogFileReader($s3Client);
$logFileIterator = new \ArrayIterator(array(array(
'Bucket' => $s3BucketName,
'Key' => $s3ObjectKey,
)));
return new self($logFileReader, $logFileIterator);
}
/**
* @param LogFileReader $logFileReader
* @param \Iterator $logFileIterator
*/
public function __construct(LogFileReader $logFileReader, \Iterator $logFileIterator)
{
$this->logFileReader = $logFileReader;
$this->logFileIterator = $logFileIterator;
$this->records = array();
$this->recordIndex = 0;
}
/**
* Returns the current log record as a Guzzle Collection object. This object behaves like an associative array
* except that it returns `null` on non-existent keys instead of causing an error. See the linked resources for the
* schema of the log record data and how to work with Guzzle Collections.
*
* @return Collection
* @link http://docs.aws.amazon.com/awscloudtrail/latest/userguide/eventreference.html
* @link http://api.guzzlephp.org/class-Guzzle.Common.Collection.html
*/
public function current()
{
if ($this->valid()) {
return new Collection($this->records[$this->recordIndex]);
} else {
return false;
}
}
public function next()
{
$this->recordIndex++;
// If all the records have been exhausted, get more records from the next log file
while (!$this->valid()) {
$this->logFileIterator->next();
$success = $this->loadRecordsFromCurrentLogFile();
if (!$success) {
// The objects iterator is exhausted as well, so stop trying
break;
}
}
}
public function key()
{
if ($logFile = $this->logFileIterator->current()) {
return $logFile['Key'] . '.' . $this->recordIndex;
} else {
return null;
}
}
public function valid()
{
return isset($this->records[$this->recordIndex]);
}
public function rewind()
{
$this->logFileIterator->rewind();
$this->loadRecordsFromCurrentLogFile();
}
public function getInnerIterator()
{
return $this->logFileIterator;
}
/**
* Examines the current file in the `logFileIterator` and attempts to read it and load log records from it using
* the `logFileReader`. This method expects that items pulled from the iterator will take the form:
*
* array(
* 'Bucket' => '...',
* 'Key' => '...',
* )
*
* @return bool Returns `true` if records were loaded and `false` if no records were found
*/
private function loadRecordsFromCurrentLogFile()
{
$this->recordIndex = 0;
$this->records = array();
$logFile = $this->logFileIterator->current();
if ($logFile && isset($logFile['Bucket']) && isset($logFile['Key'])) {
$this->records = $this->logFileReader->read($logFile['Bucket'], $logFile['Key']);
}
return (bool) $logFile;
}
}
| EITIorg/eiti | public_html/sites/all/libraries/awssdk2/Aws/CloudTrail/LogRecordIterator.php | PHP | gpl-3.0 | 5,581 |
package com.example.lars.connector;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by lars on 09.03.17.
*/
public class DBHelper extends SQLiteOpenHelper {
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE IF NOT EXISTS " + DBInfo.EXERCISE_TABLE_NAME + " (" +
DBInfo.EXERCISE_COLUMN_NAME_ID + " INTEGER," +
DBInfo.EXERCISE_COLUMN_NAME_AGE + " STRING,"+
DBInfo.EXERCISE_COLUMN_NAME_AUTORMAIL + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_AUTORNAME + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_DESCRIPTION + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_DURATION + " INTEGER," +
DBInfo.EXERCISE_COLUMN_NAME_GRAPHIC + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_GROUPSIZE + " INTEGER," +
DBInfo.EXERCISE_COLUMN_NAME_IDLOCAL + " INTEGER PRIMARY KEY AUTOINCREMENT," +
DBInfo.EXERCISE_COLUMN_NAME_KEYWORDS + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_LASTCHANGE +" DATE," +
DBInfo.EXERCISE_COLUMN_NAME_MATIRIAL + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_NAME + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_PHYSIS + " INTEGER," +
DBInfo.EXERCISE_COLUMN_NAME_RATING + " DOUBLE," +
DBInfo.EXERCISE_COLUMN_NAME_SPORT + " STRING," +
DBInfo.EXERCISE_COLUMN_NAME_TACTIC + " INTEGER," +
DBInfo.EXERCISE_COLUMN_NAME_TECHNIC + " INTEGER," +
DBInfo.EXERCISE_COLUMN_NAME_VIDEOLINK + " STRING);" +
"CREATE TABLE IF NOT EXISTS "+ DBInfo.TRAININGSUNIT_TABLE_NAME + " (" +
DBInfo.TRAININGSUNIT_COLUMN_NAME_AGE + " STRING," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_AUTORMAIL + " STRING," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_AUTORNAME + " STRING," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_DESCRIPTION + " STRING," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_DURATION + " INTEGER," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_EXERCISE + " STRING," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_ID + " INTEGER," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_IDLOCAL + "INTEGER PRIMARY KEY AUTOINCREMENT," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_KEYWORDS + " STRINGS," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_LASTCHANGE + " DATE," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_NAME + " STRING," +
DBInfo.TRAININGSUNIT_COLUMN_NAME_RATING + " DOUBLE);";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + DBInfo.EXERCISE_TABLE_NAME + "; " +
"DROP TABLE IF EXISTS " + DBInfo.TRAININGSUNIT_TABLE_NAME;
public DBHelper(Context context){
super(context, DBInfo.DATABASE_NAME, null, DBInfo.DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
insertTestdata(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
/**
* Method for getting a database connection.
* @param context Contains context.
* @return A connection to the localdatabase ist returned.
*/
public static DBConnection getConnection (Context context){
DBHelper db = new DBHelper(context);
return new LocalDBConnection(db.getReadableDatabase());
}
public static void insertTestdata(SQLiteDatabase db){
LocalDBConnection con = new LocalDBConnection(db);
ContentValues row = new ContentValues();
row.put(DBInfo.EXERCISE_COLUMN_NAME_ID, 1);
row.put(DBInfo.EXERCISE_COLUMN_NAME_AGE, "A B C");
row.put(DBInfo.EXERCISE_COLUMN_NAME_AUTORMAIL, "mustermax@mail.com");
row.put(DBInfo.EXERCISE_COLUMN_NAME_AUTORNAME, "mustermax");
row.put(DBInfo.EXERCISE_COLUMN_NAME_DESCRIPTION, "Dies ist eine Übung für Flanken von außen.");
row.put(DBInfo.EXERCISE_COLUMN_NAME_DURATION, 30);
row.put(DBInfo.EXERCISE_COLUMN_NAME_GRAPHIC, "HFASFJK");
row.put(DBInfo.EXERCISE_COLUMN_NAME_GROUPSIZE, 5);
row.put(DBInfo.EXERCISE_COLUMN_NAME_KEYWORDS, "Passen");
row.put(DBInfo.EXERCISE_COLUMN_NAME_MATIRIAL, "Ball, Tor");
row.put(DBInfo.EXERCISE_COLUMN_NAME_NAME, "Flanken");
row.put(DBInfo.EXERCISE_COLUMN_NAME_PHYSIS, 1);
row.put(DBInfo.EXERCISE_COLUMN_NAME_RATING, 3.5);
row.put(DBInfo.EXERCISE_COLUMN_NAME_SPORT, "Fußball");
row.put(DBInfo.EXERCISE_COLUMN_NAME_TACTIC,2);
row.put(DBInfo.EXERCISE_COLUMN_NAME_TECHNIC,4);
row.put(DBInfo.EXERCISE_COLUMN_NAME_VIDEOLINK, "https://www.youtube.com/watch?v=C8oi-Q8oWCE");
con.insert(DBInfo.EXERCISE_TABLE_NAME, row);
row.clear();
row.put(DBInfo.EXERCISE_COLUMN_NAME_ID, 2);
row.put(DBInfo.EXERCISE_COLUMN_NAME_AGE, "A B");
row.put(DBInfo.EXERCISE_COLUMN_NAME_AUTORMAIL, "mustermax@mail.com");
row.put(DBInfo.EXERCISE_COLUMN_NAME_AUTORNAME, "mustermax");
row.put(DBInfo.EXERCISE_COLUMN_NAME_DESCRIPTION, "Dies ist eine Übung für Schießen aus der Distanz.");
row.put(DBInfo.EXERCISE_COLUMN_NAME_DURATION, 25);
row.put(DBInfo.EXERCISE_COLUMN_NAME_GRAPHIC, "HFadASFJK");
row.put(DBInfo.EXERCISE_COLUMN_NAME_GROUPSIZE, 4);
row.put(DBInfo.EXERCISE_COLUMN_NAME_KEYWORDS, "Schuss");
row.put(DBInfo.EXERCISE_COLUMN_NAME_MATIRIAL, "Ball, Tor");
row.put(DBInfo.EXERCISE_COLUMN_NAME_NAME, "Topspin");
row.put(DBInfo.EXERCISE_COLUMN_NAME_PHYSIS, 1);
row.put(DBInfo.EXERCISE_COLUMN_NAME_RATING, 4.5);
row.put(DBInfo.EXERCISE_COLUMN_NAME_SPORT, "Fußball");
row.put(DBInfo.EXERCISE_COLUMN_NAME_TACTIC,1);
row.put(DBInfo.EXERCISE_COLUMN_NAME_TECHNIC,5);
row.put(DBInfo.EXERCISE_COLUMN_NAME_VIDEOLINK, "https://www.youtube.com/watch?v=USVxAreHDow");
con.insert(DBInfo.EXERCISE_TABLE_NAME, row);
row.clear();
row.put(DBInfo.EXERCISE_COLUMN_NAME_ID, 3);
row.put(DBInfo.EXERCISE_COLUMN_NAME_AGE, "A B C D");
row.put(DBInfo.EXERCISE_COLUMN_NAME_AUTORMAIL, "mustermax@mail.com");
row.put(DBInfo.EXERCISE_COLUMN_NAME_AUTORNAME, "mustermax");
row.put(DBInfo.EXERCISE_COLUMN_NAME_DESCRIPTION, "Dies ist eine Übung 1 gegen 1.");
row.put(DBInfo.EXERCISE_COLUMN_NAME_DURATION, 15);
row.put(DBInfo.EXERCISE_COLUMN_NAME_GRAPHIC, "HFdadsadASFJK");
row.put(DBInfo.EXERCISE_COLUMN_NAME_GROUPSIZE, 6);
row.put(DBInfo.EXERCISE_COLUMN_NAME_KEYWORDS, "Zweikampf");
row.put(DBInfo.EXERCISE_COLUMN_NAME_MATIRIAL, "3 Ball");
row.put(DBInfo.EXERCISE_COLUMN_NAME_NAME, "Körpertäuschung");
row.put(DBInfo.EXERCISE_COLUMN_NAME_PHYSIS, 3);
row.put(DBInfo.EXERCISE_COLUMN_NAME_RATING, 1.5);
row.put(DBInfo.EXERCISE_COLUMN_NAME_SPORT, "Fußball");
row.put(DBInfo.EXERCISE_COLUMN_NAME_TACTIC,3);
row.put(DBInfo.EXERCISE_COLUMN_NAME_TECHNIC,3);
row.put(DBInfo.EXERCISE_COLUMN_NAME_VIDEOLINK, "https://www.youtube.com/watch?v=HnHatjXLBY8");
System.out.println("TESTDATAINSERT " + con.insert(DBInfo.EXERCISE_TABLE_NAME, row));
row.clear();
}
}
| FBrand/MobileComputing2017 | AppDBConnection/DBHelper.java | Java | gpl-3.0 | 7,405 |
/************************************
* AUTHOR: Divyansh Gaba *
* INSTITUTION: ASET, BIJWASAN *
************************************/
#include<bits/stdc++.h>
#define fast ios_base::sync_with_stdio(0); cin.tie(0);
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define REP(i,a,b) for (int i = a; i <= b; i++)
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pi;
int main()
{
fast;
int test=1;
cin>>test;
while(test--)
{
int n;
cin>>n;
vector<int> v,k;
for(int i = 0;i<n;i++)
{
int a;
cin>>a;
v.PB(a);
k.PB(a);
}
sort(k.begin(),k.end());
int val = k[n-1] + k[n-2];
double ans = 0;
for(int i = 0;i<n-1;i++)
{
for(int j = i+1;j<n;j++)
{
if(val == v[i]+v[j])
ans += 1;
}
}
cout<<fixed<<setprecision(10)<<(ans/double(double(n*(n-1))/2))<<endl;
}
return 0;
}
| divyanshgaba/Competitive-Coding | Random Pair/main.cpp | C++ | gpl-3.0 | 1,044 |
/*
* Kontalk Android client
* Copyright (C) 2018 Kontalk Devteam <devteam@kontalk.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 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/>.
*/
package org.kontalk.service.msgcenter.event;
import org.jxmpp.jid.Jid;
/**
* Version request event.
* @author Daniele Ricci
*/
public class VersionRequest extends RequestEvent {
public final Jid jid;
public VersionRequest(String id, Jid jid) {
super(id);
this.jid = jid;
}
}
| 115ek/androidclient | app/src/main/java/org/kontalk/service/msgcenter/event/VersionRequest.java | Java | gpl-3.0 | 1,049 |
<?php
/**
* @file
* Definition of Drupal\entity_test\Entity\EntityTestRev.
*/
namespace Drupal\entity_test\Entity;
use Drupal\Core\Field\FieldDefinition;
use Drupal\entity_test\Entity\EntityTest;
/**
* Defines the test entity class.
*
* @EntityType(
* id = "entity_test_rev",
* label = @Translation("Test entity - revisions"),
* controllers = {
* "storage" = "Drupal\Core\Entity\FieldableDatabaseStorageController",
* "access" = "Drupal\entity_test\EntityTestAccessController",
* "form" = {
* "default" = "Drupal\entity_test\EntityTestFormController"
* },
* "translation" = "Drupal\content_translation\ContentTranslationController"
* },
* base_table = "entity_test_rev",
* revision_table = "entity_test_rev_revision",
* fieldable = TRUE,
* entity_keys = {
* "id" = "id",
* "uuid" = "uuid",
* "revision" = "revision_id",
* "bundle" = "type"
* },
* links = {
* "canonical" = "entity_test.edit_entity_test_rev",
* "edit-form" = "entity_test.edit_entity_test_rev"
* }
* )
*/
class EntityTestRev extends EntityTest {
/**
* The entity revision id.
*
* @var \Drupal\Core\Field\FieldItemListInterface
*/
public $revision_id;
/**
* {@inheritdoc}
*/
public function init() {
parent::init();
unset($this->revision_id);
}
/**
* Implements Drupal\Core\Entity\EntityInterface::getRevisionId().
*/
public function getRevisionId() {
return $this->get('revision_id')->value;
}
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions($entity_type) {
$fields = parent::baseFieldDefinitions($entity_type);
$fields['revision_id'] = FieldDefinition::create('integer')
->setLabel(t('Revision ID'))
->setDescription(t('The version id of the test entity.'))
->setReadOnly(TRUE);
return $fields;
}
}
| Ignigena/bethel-dashboard | core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/Entity/EntityTestRev.php | PHP | gpl-3.0 | 1,893 |
import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { withTranslation } from "react-i18next";
import FormattedDate from "global/components/FormattedDate";
import classNames from "classnames";
import Authorize from "hoc/Authorize";
import Avatar from "global/components/avatar/index";
import lh from "helpers/linkHandler";
import { Link } from "react-router-dom";
class AnnotationMeta extends PureComponent {
static displayName = "Annotation.Meta";
static propTypes = {
annotation: PropTypes.object.isRequired,
subject: PropTypes.string,
includeMarkers: PropTypes.bool,
t: PropTypes.func
};
static defaultProps = {
includeMarkers: true
};
get subtitle() {
if (!this.props.subject) return this.dateSubtitle;
return this.subjectSubtitle;
}
get name() {
const {
t,
annotation: {
attributes: { currentUserIsCreator, creatorName }
}
} = this.props;
if (currentUserIsCreator) return t("common.me");
return creatorName;
}
get subjectSubtitle() {
const { subject } = this.props;
return (
<div className="annotation-meta__subtitle">
{subject} {this.dateSubtitle}
</div>
);
}
get dateSubtitle() {
const { annotation, t } = this.props;
return (
<span className="annotation-meta__datetime">
<FormattedDate
format="distanceInWords"
date={annotation.attributes.createdAt}
/>{" "}
{t("dates.ago")}
</span>
);
}
get avatarUrl() {
const {
annotation: {
attributes: { creatorAvatarStyles }
}
} = this.props;
return creatorAvatarStyles.smallSquare;
}
get avatarClassNames() {
return classNames({
"annotation-meta__avatar": true,
"annotation-meta__avatar-placeholder-container": !this.avatarUrl,
"annotation-meta__avatar-image-container": this.avatarUrl
});
}
renderMarkers(annotation) {
const t = this.props.t;
return (
<div className="annotation-tag annotation-tag--group">
{annotation.attributes.authorCreated && (
<div className="annotation-tag__inner">
{t("glossary.author_one")}
</div>
)}
{annotation.attributes.private && (
<div className="annotation-tag__inner annotation-tag--secondary">
{t("common.private")}
</div>
)}
{annotation.attributes.flagsCount > 0 && (
<Authorize kind="admin">
<div className="annotation-tag__inner annotation-tag--secondary">
{t("counts.flag", { count: annotation.attributes.flagsCount })}
</div>
</Authorize>
)}
{annotation.attributes.readingGroupId && (
<Link
to={lh.link(
"frontendReadingGroupDetail",
annotation.attributes.readingGroupId,
{
text: annotation.attributes.textId
}
)}
className="annotation-tag__inner"
>
<div className="annotation-tag__text">
{annotation.attributes.readingGroupName}
</div>
</Link>
)}
</div>
);
}
render() {
const { annotation, includeMarkers } = this.props;
if (!annotation) return null;
return (
<section className="annotation-meta">
{/* NB: Empty div required for flex-positioning of private/author marker */}
<div>
<div className={this.avatarClassNames}>
<Avatar url={this.avatarUrl} />
</div>
<h4 className="annotation-meta__author-name">{this.name}</h4>
{this.subtitle}
</div>
{includeMarkers && this.renderMarkers(annotation)}
</section>
);
}
}
export default withTranslation()(AnnotationMeta);
| ManifoldScholar/manifold | client/src/global/components/Annotation/Annotation/UserContent/Meta.js | JavaScript | gpl-3.0 | 3,870 |
/*
* 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.android.server.power;
import android.app.ActivityManagerInternal;
import android.app.AppOpsManager;
import com.android.internal.app.IAppOpsService;
import com.android.internal.app.IBatteryStats;
import com.android.server.EventLogTags;
import com.android.server.LocalServices;
import android.app.ActivityManagerNative;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.input.InputManagerInternal;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.BatteryStats;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManagerInternal;
import android.os.Process;
import android.os.RemoteException;
import android.os.SystemClock;
import android.os.UserHandle;
import android.os.WorkSource;
import android.provider.Settings;
import android.util.EventLog;
import android.util.Slog;
import android.view.WindowManagerPolicy;
import android.view.inputmethod.InputMethodManagerInternal;
/**
* Sends broadcasts about important power state changes.
* <p>
* This methods of this class may be called by the power manager service while
* its lock is being held. Internally it takes care of sending broadcasts to
* notify other components of the system or applications asynchronously.
* </p><p>
* The notifier is designed to collapse unnecessary broadcasts when it is not
* possible for the system to have observed an intermediate state.
* </p><p>
* For example, if the device wakes up, goes to sleep, wakes up again and goes to
* sleep again before the wake up notification is sent, then the system will
* be told about only one wake up and sleep. However, we always notify the
* fact that at least one transition occurred. It is especially important to
* tell the system when we go to sleep so that it can lock the keyguard if needed.
* </p>
*/
final class Notifier {
private static final String TAG = "PowerManagerNotifier";
private static final boolean DEBUG = false;
private static final int INTERACTIVE_STATE_UNKNOWN = 0;
private static final int INTERACTIVE_STATE_AWAKE = 1;
private static final int INTERACTIVE_STATE_ASLEEP = 2;
private static final int MSG_USER_ACTIVITY = 1;
private static final int MSG_BROADCAST = 2;
private static final int MSG_WIRELESS_CHARGING_STARTED = 3;
private static final int MSG_SCREEN_BRIGHTNESS_BOOST_CHANGED = 4;
private static final int MSG_WIRED_CHARGING_STARTED = 5;
private final Object mLock = new Object();
private final Context mContext;
private final IBatteryStats mBatteryStats;
private final IAppOpsService mAppOps;
private final SuspendBlocker mSuspendBlocker;
private final WindowManagerPolicy mPolicy;
private final ActivityManagerInternal mActivityManagerInternal;
private final InputManagerInternal mInputManagerInternal;
private final InputMethodManagerInternal mInputMethodManagerInternal;
private final NotifierHandler mHandler;
private final Intent mScreenOnIntent;
private final Intent mScreenOffIntent;
private final Intent mScreenBrightnessBoostIntent;
// True if the device should suspend when the screen is off due to proximity.
private final boolean mSuspendWhenScreenOffDueToProximityConfig;
// The current interactive state. This is set as soon as an interactive state
// transition begins so as to capture the reason that it happened. At some point
// this state will propagate to the pending state then eventually to the
// broadcasted state over the course of reporting the transition asynchronously.
private boolean mInteractive = true;
private int mInteractiveChangeReason;
private boolean mInteractiveChanging;
// The pending interactive state that we will eventually want to broadcast.
// This is designed so that we can collapse redundant sequences of awake/sleep
// transition pairs while still guaranteeing that at least one transition is observed
// whenever this happens.
private int mPendingInteractiveState;
private boolean mPendingWakeUpBroadcast;
private boolean mPendingGoToSleepBroadcast;
// The currently broadcasted interactive state. This reflects what other parts of the
// system have observed.
private int mBroadcastedInteractiveState;
private boolean mBroadcastInProgress;
private long mBroadcastStartTime;
// True if a user activity message should be sent.
private boolean mUserActivityPending;
public Notifier(Looper looper, Context context, IBatteryStats batteryStats,
IAppOpsService appOps, SuspendBlocker suspendBlocker,
WindowManagerPolicy policy) {
mContext = context;
mBatteryStats = batteryStats;
mAppOps = appOps;
mSuspendBlocker = suspendBlocker;
mPolicy = policy;
mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
mInputMethodManagerInternal = LocalServices.getService(InputMethodManagerInternal.class);
mHandler = new NotifierHandler(looper);
mScreenOnIntent = new Intent(Intent.ACTION_SCREEN_ON);
mScreenOnIntent.addFlags(
Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
mScreenOffIntent = new Intent(Intent.ACTION_SCREEN_OFF);
mScreenOffIntent.addFlags(
Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
mScreenBrightnessBoostIntent =
new Intent(PowerManager.ACTION_SCREEN_BRIGHTNESS_BOOST_CHANGED);
mScreenBrightnessBoostIntent.addFlags(
Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
mSuspendWhenScreenOffDueToProximityConfig = context.getResources().getBoolean(
com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
// Initialize interactive state for battery stats.
try {
mBatteryStats.noteInteractive(true);
} catch (RemoteException ex) { }
}
/**
* Called when a wake lock is acquired.
*/
public void onWakeLockAcquired(int flags, String tag, String packageName,
int ownerUid, int ownerPid, WorkSource workSource, String historyTag) {
if (DEBUG) {
Slog.d(TAG, "onWakeLockAcquired: flags=" + flags + ", tag=\"" + tag
+ "\", packageName=" + packageName
+ ", ownerUid=" + ownerUid + ", ownerPid=" + ownerPid
+ ", workSource=" + workSource);
}
final int monitorType = getBatteryStatsWakeLockMonitorType(flags);
if (monitorType >= 0) {
try {
final boolean unimportantForLogging = ownerUid == Process.SYSTEM_UID
&& (flags & PowerManager.UNIMPORTANT_FOR_LOGGING) != 0;
if (workSource != null) {
mBatteryStats.noteStartWakelockFromSource(workSource, ownerPid, tag,
historyTag, monitorType, unimportantForLogging);
} else {
mBatteryStats.noteStartWakelock(ownerUid, ownerPid, tag, historyTag,
monitorType, unimportantForLogging);
// XXX need to deal with disabled operations.
mAppOps.startOperation(AppOpsManager.getToken(mAppOps),
AppOpsManager.OP_WAKE_LOCK, ownerUid, packageName);
}
} catch (RemoteException ex) {
// Ignore
}
}
}
/**
* Called when a wake lock is changing.
*/
public void onWakeLockChanging(int flags, String tag, String packageName,
int ownerUid, int ownerPid, WorkSource workSource, String historyTag,
int newFlags, String newTag, String newPackageName, int newOwnerUid,
int newOwnerPid, WorkSource newWorkSource, String newHistoryTag) {
final int monitorType = getBatteryStatsWakeLockMonitorType(flags);
final int newMonitorType = getBatteryStatsWakeLockMonitorType(newFlags);
if (workSource != null && newWorkSource != null
&& monitorType >= 0 && newMonitorType >= 0) {
if (DEBUG) {
Slog.d(TAG, "onWakeLockChanging: flags=" + newFlags + ", tag=\"" + newTag
+ "\", packageName=" + newPackageName
+ ", ownerUid=" + newOwnerUid + ", ownerPid=" + newOwnerPid
+ ", workSource=" + newWorkSource);
}
final boolean unimportantForLogging = newOwnerUid == Process.SYSTEM_UID
&& (newFlags & PowerManager.UNIMPORTANT_FOR_LOGGING) != 0;
try {
mBatteryStats.noteChangeWakelockFromSource(workSource, ownerPid, tag, historyTag,
monitorType, newWorkSource, newOwnerPid, newTag, newHistoryTag,
newMonitorType, unimportantForLogging);
} catch (RemoteException ex) {
// Ignore
}
} else {
onWakeLockReleased(flags, tag, packageName, ownerUid, ownerPid, workSource, historyTag);
onWakeLockAcquired(newFlags, newTag, newPackageName, newOwnerUid, newOwnerPid,
newWorkSource, newHistoryTag);
}
}
/**
* Called when a wake lock is released.
*/
public void onWakeLockReleased(int flags, String tag, String packageName,
int ownerUid, int ownerPid, WorkSource workSource, String historyTag) {
if (DEBUG) {
Slog.d(TAG, "onWakeLockReleased: flags=" + flags + ", tag=\"" + tag
+ "\", packageName=" + packageName
+ ", ownerUid=" + ownerUid + ", ownerPid=" + ownerPid
+ ", workSource=" + workSource);
}
final int monitorType = getBatteryStatsWakeLockMonitorType(flags);
if (monitorType >= 0) {
try {
if (workSource != null) {
mBatteryStats.noteStopWakelockFromSource(workSource, ownerPid, tag,
historyTag, monitorType);
} else {
mBatteryStats.noteStopWakelock(ownerUid, ownerPid, tag,
historyTag, monitorType);
mAppOps.finishOperation(AppOpsManager.getToken(mAppOps),
AppOpsManager.OP_WAKE_LOCK, ownerUid, packageName);
}
} catch (RemoteException ex) {
// Ignore
}
}
}
private int getBatteryStatsWakeLockMonitorType(int flags) {
switch (flags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
case PowerManager.PARTIAL_WAKE_LOCK:
return BatteryStats.WAKE_TYPE_PARTIAL;
case PowerManager.SCREEN_DIM_WAKE_LOCK:
case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
return BatteryStats.WAKE_TYPE_FULL;
case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
if (mSuspendWhenScreenOffDueToProximityConfig) {
return -1;
}
return BatteryStats.WAKE_TYPE_PARTIAL;
case PowerManager.DRAW_WAKE_LOCK:
return BatteryStats.WAKE_TYPE_DRAW;
case PowerManager.DOZE_WAKE_LOCK:
// Doze wake locks are an internal implementation detail of the
// communication between dream manager service and power manager
// service. They have no additive battery impact.
return -1;
default:
return -1;
}
}
/**
* Notifies that the device is changing wakefulness.
* This function may be called even if the previous change hasn't finished in
* which case it will assume that the state did not fully converge before the
* next transition began and will recover accordingly.
*/
public void onWakefulnessChangeStarted(final int wakefulness, int reason) {
final boolean interactive = PowerManagerInternal.isInteractive(wakefulness);
if (DEBUG) {
Slog.d(TAG, "onWakefulnessChangeStarted: wakefulness=" + wakefulness
+ ", reason=" + reason + ", interactive=" + interactive);
}
// Tell the activity manager about changes in wakefulness, not just interactivity.
// It needs more granularity than other components.
mHandler.post(new Runnable() {
@Override
public void run() {
mActivityManagerInternal.onWakefulnessChanged(wakefulness);
}
});
// Handle any early interactive state changes.
// Finish pending incomplete ones from a previous cycle.
if (mInteractive != interactive) {
// Finish up late behaviors if needed.
if (mInteractiveChanging) {
handleLateInteractiveChange();
}
// Start input as soon as we start waking up or going to sleep.
mInputManagerInternal.setInteractive(interactive);
mInputMethodManagerInternal.setInteractive(interactive);
// Notify battery stats.
try {
mBatteryStats.noteInteractive(interactive);
} catch (RemoteException ex) { }
// Handle early behaviors.
mInteractive = interactive;
mInteractiveChangeReason = reason;
mInteractiveChanging = true;
handleEarlyInteractiveChange();
}
}
/**
* Notifies that the device has finished changing wakefulness.
*/
public void onWakefulnessChangeFinished() {
if (DEBUG) {
Slog.d(TAG, "onWakefulnessChangeFinished");
}
if (mInteractiveChanging) {
mInteractiveChanging = false;
handleLateInteractiveChange();
}
}
/**
* Handle early interactive state changes such as getting applications or the lock
* screen running and ready for the user to see (such as when turning on the screen).
*/
private void handleEarlyInteractiveChange() {
synchronized (mLock) {
if (mInteractive) {
// Waking up...
mHandler.post(new Runnable() {
@Override
public void run() {
EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 1, 0, 0, 0);
mPolicy.startedWakingUp();
}
});
// Send interactive broadcast.
mPendingInteractiveState = INTERACTIVE_STATE_AWAKE;
mPendingWakeUpBroadcast = true;
updatePendingBroadcastLocked();
} else {
// Going to sleep...
// Tell the policy that we started going to sleep.
final int why = translateOffReason(mInteractiveChangeReason);
mHandler.post(new Runnable() {
@Override
public void run() {
mPolicy.startedGoingToSleep(why);
}
});
}
}
}
/**
* Handle late interactive state changes once they are finished so that the system can
* finish pending transitions (such as turning the screen off) before causing
* applications to change state visibly.
*/
private void handleLateInteractiveChange() {
synchronized (mLock) {
if (mInteractive) {
// Finished waking up...
mHandler.post(new Runnable() {
@Override
public void run() {
mPolicy.finishedWakingUp();
}
});
} else {
// Finished going to sleep...
// This is a good time to make transitions that we don't want the user to see,
// such as bringing the key guard to focus. There's no guarantee for this
// however because the user could turn the device on again at any time.
// Some things may need to be protected by other mechanisms that defer screen on.
// Cancel pending user activity.
if (mUserActivityPending) {
mUserActivityPending = false;
mHandler.removeMessages(MSG_USER_ACTIVITY);
}
// Tell the policy we finished going to sleep.
final int why = translateOffReason(mInteractiveChangeReason);
mHandler.post(new Runnable() {
@Override
public void run() {
EventLog.writeEvent(EventLogTags.POWER_SCREEN_STATE, 0, why, 0, 0);
mPolicy.finishedGoingToSleep(why);
}
});
// Send non-interactive broadcast.
mPendingInteractiveState = INTERACTIVE_STATE_ASLEEP;
mPendingGoToSleepBroadcast = true;
updatePendingBroadcastLocked();
}
}
}
private static int translateOffReason(int reason) {
switch (reason) {
case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN:
return WindowManagerPolicy.OFF_BECAUSE_OF_ADMIN;
case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT:
return WindowManagerPolicy.OFF_BECAUSE_OF_TIMEOUT;
default:
return WindowManagerPolicy.OFF_BECAUSE_OF_USER;
}
}
/**
* Called when screen brightness boost begins or ends.
*/
public void onScreenBrightnessBoostChanged() {
if (DEBUG) {
Slog.d(TAG, "onScreenBrightnessBoostChanged");
}
mSuspendBlocker.acquire();
Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_CHANGED);
msg.setAsynchronous(true);
mHandler.sendMessage(msg);
}
/**
* Called when there has been user activity.
*/
public void onUserActivity(int event, int uid) {
if (DEBUG) {
Slog.d(TAG, "onUserActivity: event=" + event + ", uid=" + uid);
}
try {
mBatteryStats.noteUserActivity(uid, event);
} catch (RemoteException ex) {
// Ignore
}
synchronized (mLock) {
if (!mUserActivityPending) {
mUserActivityPending = true;
Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY);
msg.setAsynchronous(true);
mHandler.sendMessage(msg);
}
}
}
/**
* Called when the screen has turned on.
*/
public void onWakeUp(String reason, int reasonUid, String opPackageName, int opUid) {
if (DEBUG) {
Slog.d(TAG, "onWakeUp: event=" + reason + ", reasonUid=" + reasonUid
+ " opPackageName=" + opPackageName + " opUid=" + opUid);
}
try {
mBatteryStats.noteWakeUp(reason, reasonUid);
if (opPackageName != null) {
mAppOps.noteOperation(AppOpsManager.OP_TURN_SCREEN_ON, opUid, opPackageName);
}
} catch (RemoteException ex) {
// Ignore
}
}
/**
* Called when wireless charging has started so as to provide user feedback.
*/
public void onWirelessChargingStarted() {
if (DEBUG) {
Slog.d(TAG, "onWirelessChargingStarted");
}
mSuspendBlocker.acquire();
Message msg = mHandler.obtainMessage(MSG_WIRELESS_CHARGING_STARTED);
msg.setAsynchronous(true);
mHandler.sendMessage(msg);
}
/**
* Called when wireless charging has started so as to provide user feedback.
*/
public void onWiredChargingStarted() {
if (DEBUG) {
Slog.d(TAG, "onWiredChargingStarted");
}
mSuspendBlocker.acquire();
Message msg = mHandler.obtainMessage(MSG_WIRED_CHARGING_STARTED);
msg.setAsynchronous(true);
mHandler.sendMessage(msg);
}
private void updatePendingBroadcastLocked() {
if (!mBroadcastInProgress
&& mPendingInteractiveState != INTERACTIVE_STATE_UNKNOWN
&& (mPendingWakeUpBroadcast || mPendingGoToSleepBroadcast
|| mPendingInteractiveState != mBroadcastedInteractiveState)) {
mBroadcastInProgress = true;
mSuspendBlocker.acquire();
Message msg = mHandler.obtainMessage(MSG_BROADCAST);
msg.setAsynchronous(true);
mHandler.sendMessage(msg);
}
}
private void finishPendingBroadcastLocked() {
mBroadcastInProgress = false;
mSuspendBlocker.release();
}
private void sendUserActivity() {
synchronized (mLock) {
if (!mUserActivityPending) {
return;
}
mUserActivityPending = false;
}
mPolicy.userActivity();
}
private void sendNextBroadcast() {
final int powerState;
synchronized (mLock) {
if (mBroadcastedInteractiveState == INTERACTIVE_STATE_UNKNOWN) {
// Broadcasted power state is unknown. Send wake up.
mPendingWakeUpBroadcast = false;
mBroadcastedInteractiveState = INTERACTIVE_STATE_AWAKE;
} else if (mBroadcastedInteractiveState == INTERACTIVE_STATE_AWAKE) {
// Broadcasted power state is awake. Send asleep if needed.
if (mPendingWakeUpBroadcast || mPendingGoToSleepBroadcast
|| mPendingInteractiveState == INTERACTIVE_STATE_ASLEEP) {
mPendingGoToSleepBroadcast = false;
mBroadcastedInteractiveState = INTERACTIVE_STATE_ASLEEP;
} else {
finishPendingBroadcastLocked();
return;
}
} else {
// Broadcasted power state is asleep. Send awake if needed.
if (mPendingWakeUpBroadcast || mPendingGoToSleepBroadcast
|| mPendingInteractiveState == INTERACTIVE_STATE_AWAKE) {
mPendingWakeUpBroadcast = false;
mBroadcastedInteractiveState = INTERACTIVE_STATE_AWAKE;
} else {
finishPendingBroadcastLocked();
return;
}
}
mBroadcastStartTime = SystemClock.uptimeMillis();
powerState = mBroadcastedInteractiveState;
}
EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_SEND, 1);
if (powerState == INTERACTIVE_STATE_AWAKE) {
sendWakeUpBroadcast();
} else {
sendGoToSleepBroadcast();
}
}
private void sendBrightnessBoostChangedBroadcast() {
if (DEBUG) {
Slog.d(TAG, "Sending brightness boost changed broadcast.");
}
mContext.sendOrderedBroadcastAsUser(mScreenBrightnessBoostIntent, UserHandle.ALL, null,
mScreeBrightnessBoostChangedDone, mHandler, 0, null, null);
}
private final BroadcastReceiver mScreeBrightnessBoostChangedDone = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mSuspendBlocker.release();
}
};
private void sendWakeUpBroadcast() {
if (DEBUG) {
Slog.d(TAG, "Sending wake up broadcast.");
}
if (ActivityManagerNative.isSystemReady()) {
mContext.sendOrderedBroadcastAsUser(mScreenOnIntent, UserHandle.ALL, null,
mWakeUpBroadcastDone, mHandler, 0, null, null);
} else {
EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2, 1);
sendNextBroadcast();
}
}
private final BroadcastReceiver mWakeUpBroadcastDone = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 1,
SystemClock.uptimeMillis() - mBroadcastStartTime, 1);
sendNextBroadcast();
}
};
private void sendGoToSleepBroadcast() {
if (DEBUG) {
Slog.d(TAG, "Sending go to sleep broadcast.");
}
if (ActivityManagerNative.isSystemReady()) {
mContext.sendOrderedBroadcastAsUser(mScreenOffIntent, UserHandle.ALL, null,
mGoToSleepBroadcastDone, mHandler, 0, null, null);
} else {
EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3, 1);
sendNextBroadcast();
}
}
private final BroadcastReceiver mGoToSleepBroadcastDone = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_DONE, 0,
SystemClock.uptimeMillis() - mBroadcastStartTime, 1);
sendNextBroadcast();
}
};
private void playWirelessChargingStartedSound() {
final boolean enabled = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.CHARGING_SOUNDS_ENABLED, 1) != 0;
final String soundPath = Settings.Global.getString(mContext.getContentResolver(),
Settings.Global.WIRELESS_CHARGING_STARTED_SOUND);
if (enabled && soundPath != null) {
final Uri soundUri = Uri.parse("file://" + soundPath);
if (soundUri != null) {
final Ringtone sfx = RingtoneManager.getRingtone(mContext, soundUri);
if (sfx != null) {
sfx.setStreamType(AudioManager.STREAM_SYSTEM);
sfx.play();
}
}
}
mSuspendBlocker.release();
}
private final class NotifierHandler extends Handler {
public NotifierHandler(Looper looper) {
super(looper, null, true /*async*/);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_USER_ACTIVITY:
sendUserActivity();
break;
case MSG_BROADCAST:
sendNextBroadcast();
break;
case MSG_WIRELESS_CHARGING_STARTED:
case MSG_WIRED_CHARGING_STARTED:
playWirelessChargingStartedSound();
break;
case MSG_SCREEN_BRIGHTNESS_BOOST_CHANGED:
sendBrightnessBoostChangedBroadcast();
break;
}
}
}
}
| OmniEvo/android_frameworks_base | services/core/java/com/android/server/power/Notifier.java | Java | gpl-3.0 | 27,822 |
// ************************************************************************************************
//
// BornAgain: simulate and fit reflection and scattering
//
//! @file gui2/model/applicationmodels.cpp
//! @brief Implements class CLASS?
//!
//! @homepage http://www.bornagainproject.org
//! @license GNU General Public License v3 or higher (see COPYING)
//! @copyright Forschungszentrum Jülich GmbH 2020
//! @authors Scientific Computing Group at MLZ (see CITATION, AUTHORS)
//
// ************************************************************************************************
#include "gui2/model/applicationmodels.h"
#include "gui2/model/experimentaldatacontroller.h"
#include "gui2/model/experimentaldatamodel.h"
#include "gui2/model/instrumentmodel.h"
#include "gui2/model/jobmodel.h"
#include "gui2/model/materialmodel.h"
#include "gui2/model/materialpropertycontroller.h"
#include "gui2/model/sampleitems.h"
#include "gui2/model/samplemodel.h"
#include "gui2/sldeditor/sldelementmodel.h"
#include "mvvm/model/externalproperty.h"
#include "mvvm/model/itempool.h"
#include "mvvm/model/modelutils.h"
#include "mvvm/model/sessionitem.h"
namespace gui2 {
using namespace ModelView;
struct ApplicationModels::ApplicationModelsImpl {
std::unique_ptr<MaterialModel> m_material_model;
std::unique_ptr<SampleModel> m_sample_model;
std::unique_ptr<SLDElementModel> m_sld_view_model;
std::unique_ptr<JobModel> m_job_model;
std::unique_ptr<ExperimentalDataModel> m_experimental_model;
std::unique_ptr<InstrumentModel> m_instrument_model;
std::unique_ptr<MaterialPropertyController> m_material_controller;
std::unique_ptr<ExperimentalDataController> m_data_controller;
std::shared_ptr<ItemPool> item_pool;
ApplicationModelsImpl()
{
item_pool = std::make_shared<ItemPool>();
m_material_model = std::make_unique<MaterialModel>(item_pool);
m_sample_model = std::make_unique<SampleModel>(item_pool);
m_sld_view_model = std::make_unique<SLDElementModel>();
m_job_model = std::make_unique<JobModel>(item_pool);
m_experimental_model = std::make_unique<ExperimentalDataModel>(item_pool);
m_instrument_model = std::make_unique<InstrumentModel>(item_pool);
m_material_controller = std::make_unique<MaterialPropertyController>(m_material_model.get(),
m_sample_model.get());
m_data_controller = std::make_unique<ExperimentalDataController>(m_experimental_model.get(),
m_instrument_model.get());
m_sample_model->create_default_multilayer();
update_material_properties();
}
//! Runs through all layers and assign materials.
//! Expecting 3 materials existing by default (air, default, Si) to assign to our 3 layers.
void update_material_properties()
{
auto multilayer = Utils::TopItem<MultiLayerItem>(m_sample_model.get());
auto layers = multilayer->items<LayerItem>(MultiLayerItem::T_LAYERS);
size_t index(0);
for (const auto& material_property : m_material_model->material_data()) {
if (index < layers.size())
layers[index]->setProperty(LayerItem::P_MATERIAL, material_property);
++index;
}
}
//! Models intended for saving.
std::vector<SessionModel*> persistent_models() const
{
return {m_material_model.get(), m_sample_model.get(), m_instrument_model.get(),
m_experimental_model.get()};
}
//! All application models.
std::vector<SessionModel*> application_models() const
{
return {m_material_model.get(), m_sample_model.get(), m_instrument_model.get(),
m_sld_view_model.get(), m_job_model.get(), m_experimental_model.get()};
}
};
ApplicationModels::ApplicationModels() : p_impl(std::make_unique<ApplicationModelsImpl>()) {}
ApplicationModels::~ApplicationModels() = default;
MaterialModel* ApplicationModels::materialModel()
{
return p_impl->m_material_model.get();
}
SampleModel* ApplicationModels::sampleModel()
{
return p_impl->m_sample_model.get();
}
SLDElementModel* ApplicationModels::sldViewModel()
{
return p_impl->m_sld_view_model.get();
}
JobModel* ApplicationModels::jobModel()
{
return p_impl->m_job_model.get();
}
ExperimentalDataModel* ApplicationModels::experimentalDataModel()
{
return p_impl->m_experimental_model.get();
}
InstrumentModel* ApplicationModels::instrumentModel()
{
return p_impl->m_instrument_model.get();
}
std::vector<SessionModel*> ApplicationModels::persistent_models() const
{
return p_impl->persistent_models();
}
//! Return vector of all models of our application.
std::vector<SessionModel*> ApplicationModels::application_models() const
{
return p_impl->application_models();
}
} // namespace gui2
| gpospelov/BornAgain | gui2/model/applicationmodels.cpp | C++ | gpl-3.0 | 4,964 |
<?php
$vars = Array(
// Simple
// Block
"A" => Array(
Array(
"B" => Array(
Array(
"ALLOWED" => "TRUE"
),
Array(
"ALLOWED" => "FALSE"
),
Array(
"ALLOWED" => "TRUE"
)
)
),
Array(
"B" => Array(
Array(
"ALLOWED" => "FALSE"
),
Array(
"ALLOWED" => "TRUE"
),
Array(
"ALLOWED" => "FALSE"
)
)
)
)
);
?> | neooblaster/Template | tests/data-validation2.php | PHP | gpl-3.0 | 468 |
package know.how.designpatterns.abstractfactory;
public abstract class AbstractAddress {
private String street;
public AbstractAddress(String street){
this.street = street;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public abstract String fullAddress();
}
| skurski/know-how | src/main/java/know/how/designpatterns/abstractfactory/AbstractAddress.java | Java | gpl-3.0 | 354 |
# coding=utf-8
import random
def consumer():
r = None
while 1:
data = yield r
print 'Consuming: {}'.format(data)
r = data + 1
def producer(consumer):
n = 3
consumer.send(None)
while n:
data = random.choice(range(10))
print('Producing: {}'.format(data))
rs = consumer.send(data)
print 'Consumer return: {}'.format(rs)
n -= 1
consumer.close()
c = consumer()
producer(c)
| dongweiming/web_develop | chapter13/section5/use_yield.py | Python | gpl-3.0 | 462 |
package eu.ocomp.brms.web.utils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.primefaces.context.RequestContext;
public abstract class AbstractScr implements Serializable {
private static final long serialVersionUID = 1L;
public AbstractScr() {
// TODO Auto-generated constructor stub
}
public void openDialog(String dialog, String recordId, Boolean recordUpdate) {
Map<String, Object> options = new HashMap<String, Object>();
options.put("modal", true);
options.put("draggable", true);
options.put("resizable", false);
options.put("closable", true);
Map<String, List<String>> params = new HashMap<String, List<String>>();
List<String> id = new ArrayList<String>();
id.add(recordId.toString());
params.put("id", id);
List<String> update = new ArrayList<String>();
update.add(recordUpdate.toString());
params.put("update", update);
RequestContext.getCurrentInstance().openDialog(dialog, options, params);
}
}
| msocha/BRMS | brms/brms-web/src/main/java/eu/ocomp/brms/web/utils/AbstractScr.java | Java | gpl-3.0 | 1,084 |
#include "pdbatom.h"
PdbAtom::PdbAtom(bool win)
{
windows = win;
}
PdbAtom::PdbAtom(string line, bool win){
windows = win;
char c = ' ';
string temp = "";
//Atom Number
for(int i = 6; i <= 10; i++){
c = line[i];
if(c != ' ') temp += c;
}
this->atomNumber = stoi(temp);
//Atom Name
temp = "";
for(int i = 12; i <= 15; i++){
c = line[i];
if(c != ' ') temp += c;
}
this->atomName = temp;
//Alternate Location Indicator
this->alternateLocation = line[16];
//Residue
//temp = line[17] + line[18] + line[19];
temp = line.substr(17,3);
this->residue = temp;
this->residueCode = aa3lto1l(temp);
//Chain
this->chain = line[21];
//Residue Number
temp = "";
for(int i = 22; i <= 25; i++){
c = line[i];
if(c != ' ') temp += c;
}
this->residueNumber = stoi(temp);
//Code for insertion of residues
this->insertionResiduesCode = line[26];
//Position X
temp = "";
for(int i = 30; i <= 37; i++){
c = line[i];
if(c != ' ') temp += c;
}
if(!windows)
replace(temp.begin(),temp.end(),'.',',');
this->x = atof(temp.c_str());
//Position Y
temp = "";
for(int i = 38; i <= 45; i++){
c = line[i];
if(c != ' ') temp += c;
}
if(!windows)
replace(temp.begin(),temp.end(),'.',',');
this->y = atof(temp.c_str());
//Position Z
temp = "";
for(int i = 46; i <= 53; i++){
c = line[i];
if(c != ' ') temp += c;
}
if(!windows)
replace(temp.begin(),temp.end(),'.',',');
this->z = atof(temp.c_str());
//Occupancy
temp = "";
for(int i = 54; i <= 59; i++){
c = line[i];
if(c != ' ') temp += c;
}
if(!windows)
replace(temp.begin(),temp.end(),'.',',');
this->occ = atof(temp.c_str());
//B-factor
temp = "";
for(int i = 60; i <= 65; i++){
c = line[i];
if(c != ' ') temp += c;
}
if(!windows)
replace(temp.begin(),temp.end(),'.',',');
this->bfactor = atof(temp.c_str());
//Segment Identifier
temp = "";
for(int i = 72; i <= 75; i++){
c = line[i];
if(c != ' ') temp += c;
}
this->segmentIdentifier = temp;
//Element
temp = "";
for(int i = 76; i <= 77; i++){
c = line[i];
if(c != ' ') temp += c;
}
this->element = temp;
//Charge
temp = "";
for(int i = 78; i <= 79; i++){
c = line[i];
if(c != ' ') temp += c;
}
this->charge = temp;
//this->seqnumber = 0;
//printf("%d %s %c %s %c %d %c %f %f %f %f %f %s %s %s\n",atomNumber,atomName.c_str(),alternateLocation,residue.c_str(),chain,residueNumber,insertionResiduesCode,x,y,z,occ,bfactor,segmentIdentifier.c_str(),element.c_str(),charge.c_str());
}
PdbAtom::PdbAtom(int atomNb, string atomNm, string residue, char chain, int resNum, float x, float y, float z, float occ, float b, string element, string charge, bool win){
windows = win;
this->atomNumber = atomNb;
this->atomName = atomNm;
this->residue = residue;
this->chain = chain;
this->residueNumber = resNum;
this->x = x;
this->y = y;
this->z = z;
this->occ = occ;
this->bfactor = b;
this->element = element;
this->charge = charge;
}
PdbAtom::~PdbAtom()
{
}
char PdbAtom::aa3lto1l(string res){
if(res == "ARG") return 'R';
else if(res == "HIS") return 'H';
else if(res == "LYS") return 'K';
else if(res == "ASP") return 'D';
else if(res == "GLU") return 'E';
else if(res == "SER") return 'S';
else if(res == "THR") return 'T';
else if(res == "ASN") return 'N';
else if(res == "GLN") return 'Q';
else if(res == "CYS") return 'C';
else if(res == "SEC") return 'U';
else if(res == "GLY") return 'G';
else if(res == "PRO") return 'P';
else if(res == "ALA") return 'A';
else if(res == "VAL") return 'V';
else if(res == "ILE") return 'I';
else if(res == "LEU") return 'L';
else if(res == "MET") return 'M';
else if(res == "PHE") return 'F';
else if(res == "TYR") return 'Y';
else if(res == "TRP") return 'W';
}
int PdbAtom::getAtomNumber(){
return this->atomNumber;
}
void PdbAtom::setAtomNumber(int n){
this->atomNumber = n;
}
string PdbAtom::getAtomName(){
return this->atomName;
}
void PdbAtom::setAtomName(string name){
this->atomName = name;
}
string PdbAtom::getResidue(){
return this->residue;
}
void PdbAtom::setResidue(string aa){
this->residue = aa;
}
char PdbAtom::getChain(){
return this->chain;
}
void PdbAtom::setChain(char c){
this->chain = c;
}
int PdbAtom::getResidueNumber(){
return this->residueNumber;
}
void PdbAtom::setResidueNumber(int n){
this->residueNumber = n;
}
float PdbAtom::getX(){
return this->x;
}
void PdbAtom::setX(float x){
this->x = x;
}
float PdbAtom::getY(){
return this->y;
}
void PdbAtom::setY(float y){
this->y = y;
}
float PdbAtom::getZ(){
return this->z;
}
void PdbAtom::setZ(float z){
this->z = z;
}
float PdbAtom::getOcc(){
return this->occ;
}
void PdbAtom::setOcc(float occ){
this->occ = occ;
}
float PdbAtom::getBfactor(){
return this->bfactor;
}
void PdbAtom::setBfactor(float bf){
this->bfactor = bf;
}
string PdbAtom::getElement(){
return this->element;
}
void PdbAtom::setElement(string ele){
this->element = ele;
}
string PdbAtom::getCharge(){
return this->charge;
}
void PdbAtom::setCharge(string c){
this->charge = c;
}
char PdbAtom::getResidueCode(){
return this->residueCode;
}
void PdbAtom::setResidueCode(char r){
this->residueCode = r;
}
string PdbAtom::to_string(float bf){
string line = "ATOM ";
string temp;
//ATOM NUMBER
temp = std::to_string(this->atomNumber);
switch(temp.size()){
case 0:
{
line += " ";
break;
}
case 1:
{
line += " " + temp;
break;
}
case 2:
{
line += " " + temp;
break;
}
case 3:
{
line += " " + temp;
break;
}
case 4:
{
line += " " + temp;
break;
}
case 5:
{
line += temp;
break;
}
}
line += " ";
//ATOM NAME
switch(this->atomName.size()){
case 0:
{
line += " ";
break;
}
case 1:
{
line += this->atomName + " ";
break;
}
case 2:
{
line += this->atomName + " ";
break;
}
case 3:
{
line += this->atomName + " ";
break;
}
case 4:
{
line += this->atomName;
break;
}
}
//ALTERNATE LOCATION INDICATOR
line += this->alternateLocation;
//RESIDUE NAME
line += this->residue;
line += " ";
//CHAIN
line += this->chain;
//RESIDUE SEQUENCE NUMBER
temp = std::to_string(this->residueNumber);
switch(temp.size()){
case 0:
{
line += " ";
break;
}
case 1:
{
line += " " + temp;
break;
}
case 2:
{
line += " " + temp;
break;
}
case 3:
{
line += " " + temp;
break;
}
case 4:
{
line += temp;
break;
}
}
//CODE FOR INSERTION OF RESIDUES
line += this->insertionResiduesCode;
line += " ";
//X
stringstream stream;
stream << fixed << setprecision(3) << this->x;
temp = stream.str();
switch(temp.size()){
case 5:
{
line += " " + temp;
break;
}
case 6:
{
line += " " + temp;
break;
}
case 7:
{
line += " " + temp;
break;
}
case 8:
{
line += temp;
break;
}
}
//Y
stringstream stream2;
stream2 << fixed << setprecision(3) << this->y;
temp = stream2.str();
switch(temp.size()){
case 5:
{
line += " " + temp;
break;
}
case 6:
{
line += " " + temp;
break;
}
case 7:
{
line += " " + temp;
break;
}
case 8:
{
line += temp;
break;
}
}
//Z
stringstream stream3;
stream3 << fixed << setprecision(3) << this->z;
temp = stream3.str();
switch(temp.size()){
case 5:
{
line += " " + temp;
break;
}
case 6:
{
line += " " + temp;
break;
}
case 7:
{
line += " " + temp;
break;
}
case 8:
{
line += temp;
break;
}
}
//OCCUPANCY
stringstream stream4;
stream4 << fixed << setprecision(2) << this->occ;
temp = stream4.str();
switch(temp.size()){
case 4:
{
line += " " + temp;
break;
}
case 5:
{
line += " " + temp;
break;
}
case 6:
{
line += temp;
break;
}
}
//B-FACTOR (SUBSTITUTE)
stringstream stream5;
stream5 << fixed << setprecision(1) << bf;
temp = stream5.str();
switch(temp.size()){
case 3:
{
line += " " + temp;
break;
}
case 4:
{
line += " " + temp;
break;
}
case 5:
{
line += " " + temp;
break;
}
case 6:
{
line += temp;
break;
}
}
line += " ";
//SEGMENT IDENTIFIER
switch(this->segmentIdentifier.size()){
case 0:
{
line += " ";
break;
}
case 1:
{
line += this->segmentIdentifier + " ";
break;
}
case 2:
{
line += this->segmentIdentifier + " ";
break;
}
case 3:
{
line += this->segmentIdentifier + " ";
break;
}
case 4:
{
line += this->segmentIdentifier;
break;
}
}
//ELEMENT SYMBOL
switch(this->element.size()){
case 0:
{
line += " ";
break;
}
case 1:
{
line += " " + this->element;
break;
}
case 2:
{
line += this->element;
break;
}
}
//CHARGE OF ELEMENT
switch(this->charge.size()){
case 0:
{
line += " ";
break;
}
case 1:
{
line += " " + this->charge;
break;
}
case 2:
{
line += this->charge;
break;
}
}
return line;
}
| duenti/PFstats | Pfstats/pdbatom.cpp | C++ | gpl-3.0 | 10,564 |
<?php
// This file is part of Stack - http://stack.maths.ed.ac.uk/
//
// Stack 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.
//
// Stack 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 Stack. If not, see <http://www.gnu.org/licenses/>.
/**
* This script lets the user send commands to the Maxima, and see the response.
* This can be useful for learning about the CAS syntax, and also for testing
* that maxima is working correctly.
*
* @copyright 2012 University of Birmingham
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(__DIR__.'/../../../../config.php');
require_once($CFG->libdir . '/questionlib.php');
require_once(__DIR__ . '/../locallib.php');
require_once(__DIR__ . '/../stack/utils.class.php');
require_once(__DIR__ . '/../stack/options.class.php');
require_once(__DIR__ . '/../stack/cas/castext.class.php');
require_once(__DIR__ . '/../stack/cas/keyval.class.php');
require_login();
// Get the parameters from the URL.
$questionid = optional_param('questionid', null, PARAM_INT);
if (!$questionid) {
$context = context_system::instance();
require_capability('qtype/stack:usediagnostictools', $context);
$urlparams = array();
} else {
// Load the necessary data.
$questiondata = $DB->get_record('question', array('id' => $questionid), '*', MUST_EXIST);
$question = question_bank::load_question($questionid);
// Process any other URL parameters, and do require_login.
list($context, $seed, $urlparams) = qtype_stack_setup_question_test_page($question);
// Check permissions.
question_require_capability_on($questiondata, 'view');
}
$context = context_system::instance();
$PAGE->set_context($context);
$PAGE->set_url('/question/type/stack/adminui/caschat.php', $urlparams);
$title = stack_string('chattitle');
$PAGE->set_title($title);
$debuginfo = '';
$errs = '';
$varerrs = array();
$vars = optional_param('vars', '', PARAM_RAW);
$string = optional_param('cas', '', PARAM_RAW);
$simp = optional_param('simp', '', PARAM_RAW);
// Always fix dollars in this script.
// Very useful for converting existing text for use elswhere in Moodle, such as in pages of text.
$string = stack_maths::replace_dollars($string);
// Sort out simplification.
if ('on' == $simp) {
$simp = true;
} else {
$simp = false;
}
// Initially simplification should be on.
if (!$vars and !$string) {
$simp = true;
}
if ($string) {
$options = new stack_options();
$options->set_site_defaults();
$options->set_option('simplify', $simp);
$session = new stack_cas_session2(array(), $options);
if ($vars) {
$keyvals = new stack_cas_keyval($vars, $options, 0);
$session = $keyvals->get_session();
$varerrs = $keyvals->get_errors();
}
if (!$varerrs) {
$ct = new stack_cas_text($string, $session, 0);
$displaytext = $ct->get_display_castext();
$errs = $ct->get_errors();
$debuginfo = $ct->get_debuginfo();
}
}
echo $OUTPUT->header();
echo $OUTPUT->heading($title);
echo html_writer::tag('p', stack_string('chatintro'));
// If we are editing the General Feedback from a question it is very helpful to see the question text.
if ($questionid) {
echo $OUTPUT->heading(stack_string('questiontext'), 3);
echo html_writer::tag('pre', $question->questiontext, array('class' => 'questiontext'));
}
if (!$varerrs) {
if ($string) {
echo $OUTPUT->box(stack_ouput_castext($displaytext));
}
}
if ($simp) {
$simp = stack_string('autosimplify').' '.
html_writer::empty_tag('input', array('type' => 'checkbox', 'checked' => $simp, 'name' => 'simp'));
} else {
$simp = stack_string('autosimplify').' '.html_writer::empty_tag('input', array('type' => 'checkbox', 'name' => 'simp'));
}
$varlen = substr_count($vars, "\n") + 3;
$stringlen = max(substr_count($string, "\n") + 3, 8);
echo html_writer::tag('form',
html_writer::tag('h2', stack_string('questionvariables')) .
html_writer::tag('p', implode($varerrs)) .
html_writer::tag('p', html_writer::tag('textarea', $vars,
array('cols' => 100, 'rows' => $varlen, 'name' => 'vars'))) .
html_writer::tag('p', $simp) .
html_writer::tag('h2', stack_string('castext')) .
html_writer::tag('p', $errs) .
html_writer::tag('p', html_writer::tag('textarea', $string,
array('cols' => 100, 'rows' => $stringlen, 'name' => 'cas'))) .
html_writer::tag('p', html_writer::empty_tag('input',
array('type' => 'submit', 'value' => stack_string('chat')))),
array('action' => $PAGE->url, 'method' => 'post'));
if ($string) {
echo $OUTPUT->heading(stack_string('questionvariablevalues'), 3);
echo html_writer::start_tag('div', array('class' => 'questionvariables'));
echo html_writer::tag('pre', $session->get_keyval_representation(true));
echo html_writer::end_tag('div');
}
if ('' != trim($debuginfo)) {
echo $OUTPUT->box($debuginfo);
}
echo $OUTPUT->footer();
| maths/moodle-qtype_stack | adminui/caschat.php | PHP | gpl-3.0 | 5,572 |
<?php
$url = $_SERVER['REQUEST_URI'];
// Prior to 5.4.7 this would show the path as "//www.example.com/path"
var_dump(parse_url($url));
?>
| doczine/Feeds | pdf_ad.php | PHP | gpl-3.0 | 141 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cu.uci.coj.restapi.controller;
import com.mangofactory.swagger.annotations.ApiIgnore;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
import cu.uci.coj.dao.ContestDAO;
import cu.uci.coj.dao.CountryDAO;
import cu.uci.coj.dao.InstitutionDAO;
import cu.uci.coj.dao.UserDAO;
import cu.uci.coj.model.Country;
import cu.uci.coj.model.Institution;
import cu.uci.coj.model.User;
import cu.uci.coj.restapi.templates.CountryDescriptionRest;
import cu.uci.coj.restapi.templates.CountryRest;
import cu.uci.coj.restapi.templates.InstitutionDescriptionRest;
import cu.uci.coj.restapi.templates.InstitutionRest;
import cu.uci.coj.restapi.templates.UserRest;
import cu.uci.coj.restapi.utils.ErrorUtils;
import cu.uci.coj.utils.paging.IPaginatedList;
import cu.uci.coj.utils.paging.PagingOptions;
import java.security.Principal;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @author lucy
*/
@Controller
@RequestMapping("/ranking")
public class RestScoreboardsController{
@Resource
private UserDAO userDAO;
@Resource
private InstitutionDAO institutionDAO;
@Resource
private CountryDAO countryDAO;
@Resource
private ContestDAO contestDAO;
@ApiOperation(value = "Obtener tabla de posiciones por usuarios",
notes = "Devuelve las posiciones de todos los usuarios del COJ.",
response = UserRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Ejemplo de respuesta del método") })
@RequestMapping(value = "/byuser", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public List<UserRest> getRankingByUser(
@ApiParam(value = "Filtrar por nombre de usuario") @RequestParam(required = false, value = "pattern") String pattern,
@ApiParam(value = "Filtrar por seguidos") @RequestParam(required = false, defaultValue = "false", value = "following") Boolean following,
@ApiParam(value = "Filtrar por conectados") @RequestParam(required = false, defaultValue = "false", value = "online") Boolean online) {
Integer uid = null;
int found = userDAO.countEnabledUsersForScoreboard(pattern, online, uid);
if(found>400)
found = 400;
List<User> listUsers = new LinkedList();
for(int i=1;i<=end(found);i++){
PagingOptions options = new PagingOptions(i);
IPaginatedList<User> pages = userDAO.getUserRanking(pattern, found, online, uid, options);
listUsers.addAll(pages.getList());
}
List<UserRest> listUsersRest = new LinkedList();
for(User u:listUsers){
UserRest ur = new UserRest(u.getRank(), u.getCountry(), u.getCountry_desc(), u.getUsername(), u.getStatus(),u.getTotal(), u.getAccu(),u.getPercent(),u.getPoints());
listUsersRest.add(ur);
}
return listUsersRest;
}
@ApiOperation(value = "Obtener tabla de posiciones por instituciones",
notes = "Devuelve las posiciones de todos las instituciones registradas en el COJ.",
response = InstitutionRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Ejemplo de respuesta del método") })
@RequestMapping(value = "/byinstitution", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public List<InstitutionRest> getRankingByInstitucions(
@RequestParam(required = false, value = "pattern") String pattern) {
int found = institutionDAO.countEnabledInstitutions(pattern);
if(found>400)
found = 400;
List<Institution> listInstitution = new LinkedList();
for(int i=1;i<=end(found);i++){
PagingOptions options = new PagingOptions(i);
IPaginatedList<Institution> pages = institutionDAO.getEnabledInstitutions(pattern, found, options);
listInstitution.addAll(pages.getList());
}
List<InstitutionRest> listInstitucionRest = new LinkedList();
for(Institution i:listInstitution){
InstitutionRest ir = new InstitutionRest(i.getId(),i.getRank(), i.getCzip() ,i.getCname(),i.getName(), i.getUsers(), i.getAcc(),i.getPoints());
listInstitucionRest.add(ir);
}
return listInstitucionRest;
}
@ApiOperation(value = "Obtener tabla de posiciones por países",
notes = "Devuelve las posiciones de todos los países registrados en el COJ.",
response = CountryRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Ejemplo de respuesta del método") })
@RequestMapping(value = "/bycountry", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public List<CountryRest> getRankingByCountry(@RequestParam(required = false, value = "pattern") String pattern) {
int found = countryDAO.countEnabledCountries(pattern);
if(found>400)
found = 400;
List<Country> listCountry = new LinkedList();
for(int i=1;i<=end(found);i++){
PagingOptions options = new PagingOptions(i);
IPaginatedList<Country> pages = countryDAO.getEnabledCountries(pattern, found, options);
listCountry.addAll(pages.getList());
}
List<CountryRest> listCountryRest = new LinkedList();
for(Country c:listCountry){
CountryRest cr = new CountryRest(c.getId(),c.getRank(), c.getZip(), c.getName(),c.getInstitutions(),c.getUsers(), c.getAcc(), c.getPoints());
listCountryRest.add(cr);
}
return listCountryRest;
}
@ApiOperation(value = "Obtener tabla de posiciones de las instituciones por país",
notes = "Dado el identificador de un país, devuelve las posiciones de todas sus instituciones registradas en el COJ.",
response = InstitutionRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 404, message = "bad country id") })
@RequestMapping(value = "/institutionbycountry/{country_id}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getRankingInstitutionByCountry(
@ApiParam(value = "Identificador del pais") @PathVariable int country_id) {
Country c = countryDAO.object("country.by.id", Country.class, country_id);
if(c == null)
return new ResponseEntity<>(ErrorUtils.BAD_COUNTRY_ID, HttpStatus.NOT_FOUND);
int found = institutionDAO.countEnabledInstitutionsByCountry("", country_id);
if(found>400)
found = 400;
List<Institution> listInstitution = new LinkedList();
for(int i=1;i<=end(found);i++){
PagingOptions options = new PagingOptions(i);
IPaginatedList<Institution> pages = institutionDAO.getEnabledInstitutionsByCountry("", found, options, country_id);
listInstitution.addAll(pages.getList());
}
List<InstitutionRest> listInstitucionRest = new LinkedList();
for(Institution i:listInstitution){
InstitutionRest ir = new InstitutionRest(i.getId(),i.getRank(), i.getCzip(), i.getCname(),i.getName(), i.getUsers(), i.getAcc(),i.getPoints());
listInstitucionRest.add(ir);
}
return new ResponseEntity<>(listInstitucionRest, HttpStatus.OK);
}
@ApiOperation(value = "Obtener tabla de posiciones de los usuarios por país",
notes = "Dado el identificador de un país, devuelve las posiciones de todos sus usuarios registrados en el COJ.",
response = InstitutionRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 404, message = "bad country id") })
@RequestMapping(value = "/usersbycountry/{country_id}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getRankingUsersByCountry(
@ApiParam(value = "Identificador del pais") @PathVariable int country_id) {
Country c = countryDAO.object("country.by.id", Country.class, country_id);
if(c == null)
return new ResponseEntity<>(ErrorUtils.BAD_COUNTRY_ID, HttpStatus.NOT_FOUND);
int found = userDAO.countEnabledUsersByCountry("",false, country_id);
if(found>400)
found = 400;
List<User> listUsers = new LinkedList();
for(int i=1;i<=end(found);i++){
PagingOptions options = new PagingOptions(i);
IPaginatedList<User> pages = userDAO.getCountryUsersRanking("", found, false, options, country_id);
listUsers.addAll(pages.getList());
}
List<UserRest> listUsersRest = new LinkedList();
for(User u:listUsers){
UserRest ur = new UserRest(u.getRank(), u.getCountry(), u.getCountry_desc(), u.getUsername(), u.getStatus(),u.getTotal(), u.getAccu(),u.getPercent(),u.getPoints());
listUsersRest.add(ur);
}
return new ResponseEntity<>(listUsersRest, HttpStatus.OK);
}
@ApiOperation(value = "Obtener tabla de posiciones de los usuarios por institución",
notes = "Dado el identificador de una institución, devuelve las posiciones de todos sus usuarios registrados en el COJ.",
response = UserRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 404, message = "bad institution id") })
@RequestMapping(value = "/usersbyinstitution/{inst_id}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getRankingUsersByInstitution(
@PathVariable int inst_id) {
Institution ins = institutionDAO.object("institution.id", Institution.class, inst_id);
if(ins == null)
return new ResponseEntity<>(ErrorUtils.BAD_INSTITUTION_ID, HttpStatus.NOT_FOUND);
int found = userDAO.countEnabledUsersByInstitutions("", false, inst_id);
if(found>400)
found = 400;
List<User> listUsers = new LinkedList();
for(int i=1;i<=end(found);i++){
PagingOptions options = new PagingOptions(i);
IPaginatedList<User> pages = userDAO.getInstitutionUsersRanking("", found, false, options, inst_id);
listUsers.addAll(pages.getList());
}
List<UserRest> listUsersRest = new LinkedList();
for(User u:listUsers){
UserRest ur = new UserRest(u.getRank(), u.getCountry(), u.getCountry_desc(), u.getUsername(), u.getStatus(),u.getTotal(), u.getAccu(),u.getPercent(),u.getPoints());
listUsersRest.add(ur);
}
return new ResponseEntity<>(listUsersRest, HttpStatus.OK);
}
@ApiOperation(value = "Obtener tabla de posiciones de los usuarios en las competencias",
notes = "Devuelve las posiciones de todos los usuarios en las competencias.",
response = UserRest.class,
responseContainer = "List")
@RequestMapping(value = "/bycontest", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public List<UserRest> getRankingByContest(
@ApiIgnore Principal principal,
@ApiParam(value = "Filtrar por nombre de usuario") @RequestParam(required = false, value = "pattern") String pattern) {
int found = contestDAO.countContestGeneralScoreboard(pattern);
if(found>400)
found = 400;
List<User> listUsers = new LinkedList();
for(int i=1;i<=end(found);i++){
PagingOptions options = new PagingOptions(i);
IPaginatedList<User> pages = contestDAO.getContestGeneralScoreboard(found, pattern, options);
listUsers.addAll(pages.getList());
}
List<UserRest> listUsersRest = new LinkedList();
for(User u:listUsers){
UserRest ur = new UserRest(u.getRank(), u.getCountry(), u.getCountry_desc(), u.getUsername(), u.getStatus(),u.getTotal(), u.getAccu(),u.getPercent(),u.getPoints());
listUsersRest.add(ur);
}
return listUsersRest;
}
@ApiOperation(value = "Obtener la descripción de una institución",
notes = "Dado el identificador de una institución, devuelve las descripción asociada a la misma.",
response = InstitutionDescriptionRest.class)
@ApiResponses(value = { @ApiResponse(code = 404, message = "bad institution id") })
@RequestMapping(value = "/description/institution/{inst_id}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getDescriptionInstitutionByInstID(@PathVariable int inst_id) {
Institution i = institutionDAO.object("institution.id", Institution.class, inst_id);
if(i == null)
return new ResponseEntity<>(ErrorUtils.BAD_INSTITUTION_ID, HttpStatus.NOT_FOUND);
i.setCount(institutionDAO.integer("institution.profile.count.users", inst_id));
i.setPoints(institutionDAO.real(0.0,"user.score.enabled.inst", inst_id));
i.setRank(institutionDAO.integer(-1,"insitutions.rank", inst_id));
i.setRankincountry(institutionDAO.integer(-1,"institution.rank.incountry" , i.getCountry_id(),inst_id));
Country c = countryDAO.object("country.by.id", Country.class, i.getCountry_id());
String logo = "http://coj.uci.cu/images/school/"+i.getZip()+".png";
InstitutionDescriptionRest idescrip = new InstitutionDescriptionRest(i.getName(),i.getZip(), logo, i.getWebsite(), c.getZip(), c.getName(), i.getCount(), i.getPoints(),i.getRank(), i.getRankincountry());
return new ResponseEntity<>(idescrip, HttpStatus.OK);
}
@ApiOperation(value = "Obtener la descripción de un país",
notes = "Dado el identificador de un país, devuelve las descripción asociada a este.",
response = CountryDescriptionRest.class)
@ApiResponses(value = { @ApiResponse(code = 404, message = "bad country id") })
@RequestMapping(value = "/description/country/{country_id}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getDescriptionCountryByCountryID(
@ApiParam(value = "Identificador de País") @PathVariable int country_id) {
Country c = countryDAO.object("country.by.id", Country.class, country_id);
if(c == null)
return new ResponseEntity<>(ErrorUtils.BAD_COUNTRY_ID, HttpStatus.NOT_FOUND);
c.setInstitutions(countryDAO.integer("count.institutions", country_id));
c.setPoints(countryDAO.real("user.score", country_id));
c.setRank(countryDAO.integer("country.rank", country_id));
c.setUsers(countryDAO.integer("count.users", country_id));
String flag = "http://coj.uci.cu/images/countries/"+c.getZip()+".png";
CountryDescriptionRest cdescrip = new CountryDescriptionRest(c.getName(),c.getZip_two(), c.getZip(), flag, c.getWebsite(), c.getInstitutions(), c.getUsers(), c.getPoints(), c.getRank());
return new ResponseEntity<>(cdescrip, HttpStatus.OK);
}
@ApiOperation(value = "Obtener tabla de posiciones por usuarios (Paginados)",
notes = "Devuelve las posiciones de todos los usuarios del COJ por páginas.",
response = UserRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 400, message = "page out of index") })
@RequestMapping(value = "/byuser/page/{page}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getRankingByUserFromTo(
@ApiParam(value = "Número de la página") @PathVariable int page) {
Integer uid = null;
int found = userDAO.countEnabledUsersForScoreboard("", false, uid);
if (page > 0 && page <= end(found)) {
PagingOptions options = new PagingOptions(page);
IPaginatedList<User> pages = userDAO.getUserRanking("", found, false, uid, options);
List<UserRest> listUsersRest = new LinkedList();
for(User u:pages.getList()){
UserRest ur = new UserRest(u.getRank(), u.getCountry(), u.getCountry_desc(), u.getUsername(), u.getStatus(),u.getTotal(), u.getAccu(),u.getPercent(),u.getPoints());
listUsersRest.add(ur);
}
return new ResponseEntity<>(listUsersRest, HttpStatus.OK);
}
else
return new ResponseEntity<>(ErrorUtils.PAGE_OUT_OF_INDEX, HttpStatus.BAD_REQUEST);
}
@ApiOperation(value = "Obtener tabla de posiciones por instituciones (Paginados)",
notes = "Devuelve las posiciones de todos las instituciones del COJ por páginas.",
response = InstitutionRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 400, message = "page out of index") })
@RequestMapping(value = "/byinstitution/page/{page}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getRankingByInstitutionFromTo(
@ApiParam(value = "Número de la página") @PathVariable int page) {
int found = institutionDAO.countEnabledInstitutions("");
if (page > 0 && page <= end(found)) {
PagingOptions options = new PagingOptions(page);
IPaginatedList<Institution> pages = institutionDAO.getEnabledInstitutions("", found, options);
List<InstitutionRest> listInstitucionRest = new LinkedList();
for(Institution i:pages.getList()){
InstitutionRest ir = new InstitutionRest(i.getId(),i.getRank(), i.getCzip(), i.getCname(),i.getName(), i.getUsers(), i.getAcc(),i.getPoints());
listInstitucionRest.add(ir);
}
return new ResponseEntity<>(listInstitucionRest, HttpStatus.OK);
}
else
return new ResponseEntity<>(ErrorUtils.PAGE_OUT_OF_INDEX, HttpStatus.BAD_REQUEST);
}
@ApiOperation(value = "Obtener tabla de posiciones por países (Paginados)",
notes = "Devuelve las posiciones de todos los países del COJ por páginas.",
response = CountryRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 400, message = "page out of index") })
@RequestMapping(value = "/bycountry/page/{page}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getRankingByCountryFromTo(
@ApiParam(value = "Número de la página") @PathVariable int page) {
int found = countryDAO.countEnabledCountries("");
if (page > 0 && page <= end(found)) {
PagingOptions options = new PagingOptions(page);
IPaginatedList<Country> pages = countryDAO.getEnabledCountries("", found, options);
List<CountryRest> listCountryRest = new LinkedList();
for(Country c:pages.getList()){
CountryRest cr = new CountryRest(c.getId(),c.getRank(), c.getZip(), c.getName(),c.getInstitutions(),c.getUsers(), c.getAcc(), c.getPoints());
listCountryRest.add(cr);
}
return new ResponseEntity<>(listCountryRest, HttpStatus.OK);
}
else
return new ResponseEntity<>(ErrorUtils.PAGE_OUT_OF_INDEX, HttpStatus.BAD_REQUEST);
}
@ApiOperation(value = "Obtener tabla de posiciones de los usuarios por competencias (Paginados)",
notes = "Devuelve las posiciones de todos los usuarios del COJ en las competencias por páginas.",
response = UserRest.class,
responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = 400, message = "page out of index") })
@RequestMapping(value = "/bycontest/page/{page}", method = RequestMethod.GET, headers = "Accept=application/json")
@ResponseBody
public ResponseEntity<?> getRankingBybycontestFromTo(
@ApiParam(value = "Número de la página") @PathVariable int page) {
int found = contestDAO.countContestGeneralScoreboard("");
if (page > 0 && page <= end(found)) {
PagingOptions options = new PagingOptions(page);
IPaginatedList<User> pages = contestDAO.getContestGeneralScoreboard(found, "", options);
List<UserRest> listUsersRest = new LinkedList();
for(User u:pages.getList()){
UserRest ur = new UserRest(u.getRank(), u.getCountry(), u.getCountry_desc(), u.getUsername(), u.getStatus(),u.getTotal(), u.getAccu(),u.getPercent(),u.getPoints());
listUsersRest.add(ur);
}
return new ResponseEntity<>(listUsersRest, HttpStatus.OK);
}
else
return new ResponseEntity<>(ErrorUtils.PAGE_OUT_OF_INDEX, HttpStatus.BAD_REQUEST);
}
private int end(int found){
if(found%30==0)
return found/30;
else
return (found/30)+1;
}
}
| dovier/coj-web | src/main/java/cu/uci/coj/restapi/controller/RestScoreboardsController.java | Java | gpl-3.0 | 22,868 |
import unittest
from decimal import Decimal
from itertools import product
from .riemann import riemann_sum as riemann, RiemannMethod
# Test functions
# lowercase are functions, uppercase are their antiderivatives assuming C = 0.
def f1(x):
return 0
def F1(x):
return 0
def f2(x):
return 3
def F2(x):
return 3 * x
def f3(x):
return x
def F3(x):
return x ** 2 / 2
def f4(x):
return 8 * x
def F4(x):
return 4 * x ** 2
def f5(x):
return 6 * x ** 2
def F5(x):
return 2 * x ** 3
class RiemannTests(unittest.TestCase):
tolerance = Decimal('0.005')
dx = Decimal('0.00001')
functions = [(f1, F1), (f2, F2), (f3, F3), (f4, F4), (f5, F5)]
test_points = [
(0, 1), # Simplest case for most functions
(0, 3), # From zero
(-2, 0), # To zero
(4, 10), # Detatched from zero, positive
(-10, -4), # Detatched from zero, negative
(-5, 7) # Across zero
]
test_points.extend([tuple(reversed(bounds)) for bounds in test_points]) # List, not generator, to evaluate everything before appending
def test_riemann_sum(self):
"""
Test the riemann_sum function by ensuring its results are within a certain small tolerance of the actual value.
The tolerance is set above, and used as `self._tolerance`.
Every function above is tested for every method and every pair of test points, as well as for each pair reversed.
"""
for (func, antiderivative), method, (x1, x2) in product(self.functions, RiemannMethod, self.test_points):
with self.subTest(function=func.__name__, x1=x1, x2=x2, method=method):
estimate = riemann(func, x1, x2, self.dx, method)
actual = Decimal(antiderivative(x2) - antiderivative(x1))
self.assertAlmostEqual(estimate, actual, delta=self.tolerance)
def test_methods(self):
"""
Test the different methods of Riemann summing to ensure they exhibit the known errors/biases.
For example, a left-hand Riemann sum underestimates increasing functions and overestimates decreasing ones.
"""
def func(x):
return x ** 3
def antiderivative(x):
return x ** 4 / 4
x1, x2, dx = map(Decimal, (-10, 10, '0.5')) # Intentionally large dx to exacerbate over/under-estimation
actual = Decimal(antiderivative(x2) - antiderivative(x1))
# Because x^3 is always increasing, left-hand should underestimate it.
estimate_left = riemann(func, x1, x2, dx, RiemannMethod.left)
self.assertLess(estimate_left, actual)
# Because x^3 is always increasing, right-hand should overestimate it.
estimate_right = riemann(func, x1, x2, dx, RiemannMethod.right)
self.assertGreater(estimate_right, actual)
# Because x^3 is rotationally symmetrical about the origin and the input range is symmetrical about the origin, middle and trapezoid should be dead-on.
estimate_middle = riemann(func, x1, x2, dx, RiemannMethod.middle)
estimate_trapezoid = riemann(func, x1, x2, dx, RiemannMethod.trapezoid)
self.assertEqual(estimate_middle, actual)
self.assertEqual(estimate_trapezoid, actual)
| BayMinimum/Hacktoberfest-Mathematics | calculus/riemann_sum/python/riemann_sum_test.py | Python | gpl-3.0 | 2,960 |
var mongoose = require('mongoose');
/** The review document schema */
var reviewSchema = new mongoose.Schema({
author: String,
rating: {
type: Number,
required: true,
min: 0,
max: 5
},
reviewText: String,
createdOn: {
type: Date,
"default": Date.now
}
});
/** The opening time document schema */
var openingTimeSchema = new mongoose.Schema({
days: {
type: String,
required: true
},
opening: String,
closing: String,
closed: {
type: Boolean,
required: true
}
});
/** The location document schema */
var locationSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
address: String,
rating: {
type: Number,
"default": 0,
min: 0,
max: 5
},
facilities: [String],
coords: {
type: [Number],
index: '2dsphere'
},
openingTimes: [openingTimeSchema],
reviews: [reviewSchema]
});
/** Defining 'Location' model */
mongoose.model('Location', locationSchema);
| Pringlez/Reviewer-App | app_api/models/locations.js | JavaScript | gpl-3.0 | 1,099 |
<TS language="fa_IR" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Create a new address</source>
<translation>گشایش حسابی جدید</translation>
</message>
<message>
<source>&New</source>
<translation>جدید</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>کپی کردن حساب انتخاب شده به حافظه سیستم - کلیپ بورد</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>و کپی آدرس</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>صدور داده نوار جاری به یک فایل</translation>
</message>
<message>
<source>&Delete</source>
<translation>و حذف</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>کپی و برچسب</translation>
</message>
<message>
<source>&Edit</source>
<translation>و ویرایش</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv) فایل جداگانه دستوری</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>برچسب</translation>
</message>
<message>
<source>Address</source>
<translation>حساب</translation>
</message>
<message>
<source>(no label)</source>
<translation>(برچسب ندارد)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Enter passphrase</source>
<translation>رمز/پَس فرِیز را وارد کنید</translation>
</message>
<message>
<source>New passphrase</source>
<translation>رمز/پَس فرِیز جدید را وارد کنید</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>رمز/پَس فرِیز را دوباره وارد کنید</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>wallet را رمزگذاری کنید</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>برای انجام این عملکرد به رمز/پَس فرِیزِwallet نیاز است تا آن را از حالت قفل درآورد.</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>باز کردن قفل wallet </translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>برای کشف رمز wallet، به رمز/پَس فرِیزِwallet نیاز است.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>کشف رمز wallet</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>تغییر رمز/پَس فرِیز</translation>
</message>
<message>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>رمز/پَس فرِیزِ قدیم و جدید را در wallet وارد کنید</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>رمزگذاری wallet را تایید کنید</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>تایید رمزگذاری</translation>
</message>
<message>
<source>Emercoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your emercoins from being stolen by malware infecting your computer.</source>
<translation>Emercoin برای اتمام فرایند رمزگذاری بسته خواهد شد. به خاطر داشته باشید که رمزگذاری WALLET شما، کامپیوتر شما را از آلودگی به بدافزارها مصون نمی دارد.</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>رمزگذاری تایید نشد</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>رمزگذاری به علت خطای داخلی تایید نشد. wallet شما رمزگذاری نشد</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>رمزهای/پَس فرِیزهایِ وارد شده با هم تطابق ندارند</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>قفل wallet باز نشد</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>رمزهای/پَس فرِیزهایِ وارد شده wallet برای کشف رمز اشتباه است.</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>کشف رمز wallet انجام نشد</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Sign &message...</source>
<translation>امضا و پیام</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>به روز رسانی با شبکه...</translation>
</message>
<message>
<source>&Overview</source>
<translation>و بازبینی</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>نمای کلی از wallet را نشان بده</translation>
</message>
<message>
<source>&Transactions</source>
<translation>و تراکنش</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>تاریخچه تراکنش را باز کن</translation>
</message>
<message>
<source>E&xit</source>
<translation>خروج</translation>
</message>
<message>
<source>Quit application</source>
<translation>از "درخواست نامه"/ application خارج شو</translation>
</message>
<message>
<source>About &Qt</source>
<translation>درباره و QT</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>نمایش اطلاعات درباره QT</translation>
</message>
<message>
<source>&Options...</source>
<translation>و انتخابها</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>و رمزگذاری wallet</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>و گرفتن نسخه پیشتیبان از wallet</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>تغییر رمز/پَس فرِیز</translation>
</message>
<message>
<source>Modify configuration options for Emercoin</source>
<translation>اصلاح انتخابها برای پیکربندی Emercoin</translation>
</message>
<message>
<source>Backup wallet to another location</source>
<translation>گرفتن نسخه پیشتیبان در آدرسی دیگر</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>رمز مربوط به رمزگذاریِ wallet را تغییر دهید</translation>
</message>
<message>
<source>Emercoin</source>
<translation>Emercoin</translation>
</message>
<message>
<source>Wallet</source>
<translation>کیف پول</translation>
</message>
<message>
<source>&Send</source>
<translation>و ارسال</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>&نمایش/ عدم نمایش و</translation>
</message>
<message>
<source>&File</source>
<translation>و فایل</translation>
</message>
<message>
<source>&Settings</source>
<translation>و تنظیمات</translation>
</message>
<message>
<source>&Help</source>
<translation>و راهنما</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>نوار ابزار</translation>
</message>
<message>
<source>Error</source>
<translation>خطا</translation>
</message>
<message>
<source>Up to date</source>
<translation>روزآمد</translation>
</message>
<message>
<source>Catching up...</source>
<translation>در حال روزآمد سازی..</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>ارسال تراکنش</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>تراکنش دریافتی</translation>
</message>
<message>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>تاریخ: %1⏎ میزان وجه : %2⏎ نوع: %3⏎ آدرس: %4⏎
</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>wallet رمزگذاری شد و در حال حاضر از حالت قفل در آمده است</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>wallet رمزگذاری شد و در حال حاضر قفل است</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<source>Network Alert</source>
<translation>هشدار شبکه</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Amount:</source>
<translation>میزان وجه:</translation>
</message>
<message>
<source>Amount</source>
<translation>میزان</translation>
</message>
<message>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<source>Confirmed</source>
<translation>تایید شده</translation>
</message>
<message>
<source>Copy address</source>
<translation>آدرس را کپی کنید</translation>
</message>
<message>
<source>Copy label</source>
<translation>برچسب را کپی کنید</translation>
</message>
<message>
<source>Copy amount</source>
<translation>میزان وجه کپی شود</translation>
</message>
<message>
<source>(no label)</source>
<translation>(برچسب ندارد)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>ویرایش حساب</translation>
</message>
<message>
<source>&Label</source>
<translation>و برچسب</translation>
</message>
<message>
<source>&Address</source>
<translation>حساب&</translation>
</message>
<message>
<source>New receiving address</source>
<translation>حساب دریافت کننده جدید
</translation>
</message>
<message>
<source>New sending address</source>
<translation>حساب ارسال کننده جدید</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>ویرایش حساب دریافت کننده</translation>
</message>
<message>
<source>Edit sending address</source>
<translation>ویرایش حساب ارسال کننده</translation>
</message>
<message>
<source>The entered address "%1" is not a valid Emercoin address.</source>
<translation>آدرس وارد شده "%1" یک آدرس صحیح برای emercoin نسشت</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>عدم توانیی برای قفل گشایی wallet</translation>
</message>
<message>
<source>New key generation failed.</source>
<translation>عدم توانیی در ایجاد کلید جدید</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>نسخه</translation>
</message>
<message>
<source>Usage:</source>
<translation>میزان استفاده:</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Error</source>
<translation>خطا</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>انتخاب/آپشن</translation>
</message>
<message>
<source>&OK</source>
<translation>و تایید</translation>
</message>
<message>
<source>&Cancel</source>
<translation>و رد</translation>
</message>
<message>
<source>default</source>
<translation>پیش فرض</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>فرم</translation>
</message>
<message>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Emercoin network after a connection is established, but this process has not completed yet.</source>
<translation>اطلاعات نمایش داده شده ممکن است روزآمد نباشد. wallet شما به صورت خودکار بعد از برقراری اتصال با شبکه emercoin به روز می شود اما این فرایند هنوز تکمیل نشده است.</translation>
</message>
<message>
<source>out of sync</source>
<translation>خارج از روزآمد سازی</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
</context>
<context>
<name>PeerTableModel</name>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>میزان</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>Client name</source>
<translation>نام کنسول RPC</translation>
</message>
<message>
<source>Client version</source>
<translation>ویرایش کنسول RPC</translation>
</message>
<message>
<source>Network</source>
<translation>شبکه</translation>
</message>
<message>
<source>Number of connections</source>
<translation>تعداد اتصال</translation>
</message>
<message>
<source>Block chain</source>
<translation>زنجیره مجموعه تراکنش ها</translation>
</message>
<message>
<source>Current number of blocks</source>
<translation>تعداد زنجیره های حاضر</translation>
</message>
<message>
<source>Welcome to the Emercoin RPC console.</source>
<translation>به کنسول آر.پی.سی. EMERCOIN خوش آمدید</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Label:</source>
<translation>و برچسب</translation>
</message>
<message>
<source>Copy label</source>
<translation>برچسب را کپی کنید</translation>
</message>
<message>
<source>Copy amount</source>
<translation>میزان وجه کپی شود</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>Address</source>
<translation>حساب</translation>
</message>
<message>
<source>Amount</source>
<translation>میزان</translation>
</message>
<message>
<source>Label</source>
<translation>برچسب</translation>
</message>
<message>
<source>Message</source>
<translation>پیام</translation>
</message>
<message>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>متن وارد شده طولانی است، متنِ برچسب/پیام را کوتاه کنید</translation>
</message>
<message>
<source>Error encoding URI into QR Code.</source>
<translation>خطای تبدیل URI به کد QR</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<source>Label</source>
<translation>برچسب</translation>
</message>
<message>
<source>Message</source>
<translation>پیام</translation>
</message>
<message>
<source>Amount</source>
<translation>میزان</translation>
</message>
<message>
<source>(no label)</source>
<translation>(برچسب ندارد)</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>سکه های ارسالی</translation>
</message>
<message>
<source>Amount:</source>
<translation>میزان وجه:</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>ارسال همزمان به گیرنده های متعدد</translation>
</message>
<message>
<source>Balance:</source>
<translation>مانده حساب:</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>تایید عملیات ارسال </translation>
</message>
<message>
<source>S&end</source>
<translation>و ارسال</translation>
</message>
<message>
<source>Confirm send coins</source>
<translation>تایید ارسال بیت کوین ها</translation>
</message>
<message>
<source>Copy amount</source>
<translation>میزان وجه کپی شود</translation>
</message>
<message>
<source>The amount to pay must be larger than 0.</source>
<translation>میزان پرداخت باید بیشتر از 0 باشد</translation>
</message>
<message>
<source>The amount exceeds your balance.</source>
<translation>مقدار مورد نظر از مانده حساب بیشتر است.</translation>
</message>
<message>
<source>(no label)</source>
<translation>(برچسب ندارد)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>و میزان وجه</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>پرداخت و به چه کسی</translation>
</message>
<message>
<source>Enter a label for this address to add it to your address book</source>
<translation>یک برچسب برای این آدرس بنویسید تا به دفترچه آدرسهای شما اضافه شود</translation>
</message>
<message>
<source>&Label:</source>
<translation>و برچسب</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt و A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>آدرس را بر کلیپ بورد کپی کنید</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt و P</translation>
</message>
<message>
<source>Message:</source>
<translation>پیام:</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>&Sign Message</source>
<translation>و امضای پیام </translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt و A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>آدرس را بر کلیپ بورد کپی کنید</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt و P</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Open until %1</source>
<translation>باز کن تا %1</translation>
</message>
<message>
<source>%1/unconfirmed</source>
<translation>%1 / تایید نشده</translation>
</message>
<message>
<source>%1 confirmations</source>
<translation>%1 تایید</translation>
</message>
<message>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<source>label</source>
<translation>برچسب</translation>
</message>
<message>
<source>Message</source>
<translation>پیام</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>شناسه کاربری</translation>
</message>
<message>
<source>Amount</source>
<translation>میزان</translation>
</message>
<message>
<source>, has not been successfully broadcast yet</source>
<translation>، هنوز با موفقیت ارسال نگردیده است</translation>
</message>
<message>
<source>unknown</source>
<translation>ناشناس</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>Transaction details</source>
<translation>جزئیات تراکنش</translation>
</message>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation>این بخش جزئیات تراکنش را نشان می دهد</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<source>Type</source>
<translation>گونه</translation>
</message>
<message>
<source>Address</source>
<translation>حساب</translation>
</message>
<message>
<source>Open until %1</source>
<translation>باز کن تا %1</translation>
</message>
<message>
<source>Confirmed (%1 confirmations)</source>
<translation>تایید شده (%1 تاییدها)</translation>
</message>
<message>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>این block توسط گره های دیگری دریافت نشده است و ممکن است قبول نشود</translation>
</message>
<message>
<source>Generated but not accepted</source>
<translation>تولید شده اما قبول نشده است</translation>
</message>
<message>
<source>Received with</source>
<translation>دریافت با</translation>
</message>
<message>
<source>Received from</source>
<translation>دریافت شده از</translation>
</message>
<message>
<source>Sent to</source>
<translation>ارسال به</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>وجه برای شما </translation>
</message>
<message>
<source>Mined</source>
<translation>استخراج شده</translation>
</message>
<message>
<source>(n/a)</source>
<translation>خالی</translation>
</message>
<message>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>وضعیت تراکنش. با اشاره به این بخش تعداد تاییدها نمایش داده می شود</translation>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation>زمان و تاریخی که تراکنش دریافت شده است</translation>
</message>
<message>
<source>Type of transaction.</source>
<translation>نوع تراکنش</translation>
</message>
<message>
<source>Destination address of transaction.</source>
<translation>آدرس مقصد در تراکنش</translation>
</message>
<message>
<source>Amount removed from or added to balance.</source>
<translation>میزان وجه کم شده یا اضافه شده به حساب</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation>همه</translation>
</message>
<message>
<source>Today</source>
<translation>امروز</translation>
</message>
<message>
<source>This week</source>
<translation>این هفته</translation>
</message>
<message>
<source>This month</source>
<translation>این ماه</translation>
</message>
<message>
<source>Last month</source>
<translation>ماه گذشته</translation>
</message>
<message>
<source>This year</source>
<translation>این سال</translation>
</message>
<message>
<source>Range...</source>
<translation>حدود..</translation>
</message>
<message>
<source>Received with</source>
<translation>دریافت با</translation>
</message>
<message>
<source>Sent to</source>
<translation>ارسال به</translation>
</message>
<message>
<source>To yourself</source>
<translation>به شما</translation>
</message>
<message>
<source>Mined</source>
<translation>استخراج شده</translation>
</message>
<message>
<source>Other</source>
<translation>دیگر</translation>
</message>
<message>
<source>Enter address or label to search</source>
<translation>آدرس یا برچسب را برای جستجو وارد کنید</translation>
</message>
<message>
<source>Min amount</source>
<translation>حداقل میزان وجه</translation>
</message>
<message>
<source>Copy address</source>
<translation>آدرس را کپی کنید</translation>
</message>
<message>
<source>Copy label</source>
<translation>برچسب را کپی کنید</translation>
</message>
<message>
<source>Copy amount</source>
<translation>میزان وجه کپی شود</translation>
</message>
<message>
<source>Edit label</source>
<translation>برچسب را ویرایش کنید</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv) فایل جداگانه دستوری</translation>
</message>
<message>
<source>Confirmed</source>
<translation>تایید شده</translation>
</message>
<message>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<source>Type</source>
<translation>گونه</translation>
</message>
<message>
<source>Label</source>
<translation>برچسب</translation>
</message>
<message>
<source>Address</source>
<translation>حساب</translation>
</message>
<message>
<source>ID</source>
<translation>شناسه کاربری</translation>
</message>
<message>
<source>Range:</source>
<translation>دامنه:</translation>
</message>
<message>
<source>to</source>
<translation>به</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>سکه های ارسالی</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<source>Export the data in the current tab to a file</source>
<translation>صدور داده نوار جاری به یک فایل</translation>
</message>
<message>
<source>Backup Wallet</source>
<translation>گرفتن نسخه پیشتیبان از Wallet</translation>
</message>
<message>
<source>Wallet Data (*.dat)</source>
<translation>داده های Wallet
(*.dat)</translation>
</message>
<message>
<source>Backup Failed</source>
<translation>عملیات گرفتن نسخه پیشتیبان انجام نشد</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Options:</source>
<translation>انتخابها:</translation>
</message>
<message>
<source>Specify data directory</source>
<translation>دایرکتوری داده را مشخص کن</translation>
</message>
<message>
<source>Accept command line and JSON-RPC commands</source>
<translation>command line و JSON-RPC commands را قبول کنید</translation>
</message>
<message>
<source>Run in the background as a daemon and accept commands</source>
<translation>به عنوان daemon بک گراند را اجرا کنید و دستورات را قبول نمایید</translation>
</message>
<message>
<source>Use the test network</source>
<translation>از تستِ شبکه استفاده نمایید</translation>
</message>
<message>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>ارسال اطلاعات پیگیری/خطایابی به کنسول به جای ارسال به فایل debug.log</translation>
</message>
<message>
<source>Username for JSON-RPC connections</source>
<translation>شناسه کاربری برای ارتباطاتِ JSON-RPC</translation>
</message>
<message>
<source>Password for JSON-RPC connections</source>
<translation>رمز برای ارتباطاتِ JSON-RPC</translation>
</message>
<message>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>دستور را وقتی بهترین بلاک تغییر کرد اجرا کن (%s در دستور توسط block hash جایگزین شده است)</translation>
</message>
<message>
<source>Upgrade wallet to latest format</source>
<translation>wallet را به جدیدترین نسخه روزآمد کنید</translation>
</message>
<message>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>زنجیره بلاک را برای تراکنش جا افتاده در WALLET دوباره اسکن کنید</translation>
</message>
<message>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>برای ارتباطاتِ JSON-RPC از OpenSSL (https) استفاده کنید</translation>
</message>
<message>
<source>This help message</source>
<translation>این پیام راهنما</translation>
</message>
<message>
<source>Loading addresses...</source>
<translation>لود شدن آدرسها..</translation>
</message>
<message>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>خطا در هنگام لود شدن wallet.dat: Wallet corrupted</translation>
</message>
<message>
<source>Error loading wallet.dat</source>
<translation>خطا در هنگام لود شدن wallet.dat</translation>
</message>
<message>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>میزان اشتباه است for -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>وجوه ناکافی</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>لود شدن نمایه بلاکها..</translation>
</message>
<message>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>یک گره برای اتصال اضافه کنید و تلاش کنید تا اتصال را باز نگاه دارید</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>wallet در حال لود شدن است...</translation>
</message>
<message>
<source>Cannot downgrade wallet</source>
<translation>قابلیت برگشت به نسخه قبلی برای wallet امکان پذیر نیست</translation>
</message>
<message>
<source>Cannot write default address</source>
<translation>آدرس پیش فرض قابل ذخیره نیست</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>اسکنِ دوباره...</translation>
</message>
<message>
<source>Done loading</source>
<translation>اتمام لود شدن</translation>
</message>
<message>
<source>Error</source>
<translation>خطا</translation>
</message>
</context>
</TS> | EvgenijM86/emercoin | src/qt/locale/bitcoin_fa_IR.ts | TypeScript | gpl-3.0 | 35,898 |
using System;
#pragma warning disable 1591
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedParameter.Local
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IntroduceOptionalParameters.Global
// ReSharper disable MemberCanBeProtected.Global
// ReSharper disable InconsistentNaming
namespace RTWin.Annotations
{
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes,
/// so the check for <c>null</c> is necessary before its usage
/// </summary>
/// <example><code>
/// [CanBeNull] public object Test() { return null; }
/// public void UseTest() {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter |
AttributeTargets.Property | AttributeTargets.Delegate |
AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class CanBeNullAttribute : Attribute { }
/// <summary>
/// Indicates that the value of the marked element could never be <c>null</c>
/// </summary>
/// <example><code>
/// [NotNull] public object Foo() {
/// return null; // Warning: Possible 'null' assignment
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter |
AttributeTargets.Property | AttributeTargets.Delegate |
AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class NotNullAttribute : Attribute { }
/// <summary>
/// Indicates that the marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor. The format string
/// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form
/// </summary>
/// <example><code>
/// [StringFormatMethod("message")]
/// public void ShowError(string message, params object[] args) { /* do something */ }
/// public void Foo() {
/// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Constructor | AttributeTargets.Method,
AllowMultiple = false, Inherited = true)]
public sealed class StringFormatMethodAttribute : Attribute
{
/// <param name="formatParameterName">
/// Specifies which parameter of an annotated method should be treated as format-string
/// </param>
public StringFormatMethodAttribute(string formatParameterName)
{
FormatParameterName = formatParameterName;
}
public string FormatParameterName { get; private set; }
}
/// <summary>
/// Indicates that the function argument should be string literal and match one
/// of the parameters of the caller function. For example, ReSharper annotates
/// the parameter of <see cref="System.ArgumentNullException"/>
/// </summary>
/// <example><code>
/// public void Foo(string param) {
/// if (param == null)
/// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)]
public sealed class InvokerParameterNameAttribute : Attribute { }
/// <summary>
/// Indicates that the method is contained in a type that implements
/// <see cref="System.ComponentModel.INotifyPropertyChanged"/> interface
/// and this method is used to notify that some property value changed
/// </summary>
/// <remarks>
/// The method should be non-static and conform to one of the supported signatures:
/// <list>
/// <item><c>NotifyChanged(string)</c></item>
/// <item><c>NotifyChanged(params string[])</c></item>
/// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item>
/// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item>
/// <item><c>SetProperty{T}(ref T, T, string)</c></item>
/// </list>
/// </remarks>
/// <example><code>
/// public class Foo : INotifyPropertyChanged {
/// public event PropertyChangedEventHandler PropertyChanged;
/// [NotifyPropertyChangedInvocator]
/// protected virtual void NotifyChanged(string propertyName) { ... }
///
/// private string _name;
/// public string Name {
/// get { return _name; }
/// set { _name = value; NotifyChanged("LastName"); /* Warning */ }
/// }
/// }
/// </code>
/// Examples of generated notifications:
/// <list>
/// <item><c>NotifyChanged("Property")</c></item>
/// <item><c>NotifyChanged(() => Property)</c></item>
/// <item><c>NotifyChanged((VM x) => x.Property)</c></item>
/// <item><c>SetProperty(ref myField, value, "Property")</c></item>
/// </list>
/// </example>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute
{
public NotifyPropertyChangedInvocatorAttribute() { }
public NotifyPropertyChangedInvocatorAttribute(string parameterName)
{
ParameterName = parameterName;
}
public string ParameterName { get; private set; }
}
/// <summary>
/// Describes dependency between method input and output
/// </summary>
/// <syntax>
/// <p>Function Definition Table syntax:</p>
/// <list>
/// <item>FDT ::= FDTRow [;FDTRow]*</item>
/// <item>FDTRow ::= Input => Output | Output <= Input</item>
/// <item>Input ::= ParameterName: Value [, Input]*</item>
/// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item>
/// <item>Value ::= true | false | null | notnull | canbenull</item>
/// </list>
/// If method has single input parameter, it's name could be omitted.<br/>
/// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same)
/// for method output means that the methos doesn't return normally.<br/>
/// <c>canbenull</c> annotation is only applicable for output parameters.<br/>
/// You can use multiple <c>[ContractAnnotation]</c> for each FDT row,
/// or use single attribute with rows separated by semicolon.<br/>
/// </syntax>
/// <examples><list>
/// <item><code>
/// [ContractAnnotation("=> halt")]
/// public void TerminationMethod()
/// </code></item>
/// <item><code>
/// [ContractAnnotation("halt <= condition: false")]
/// public void Assert(bool condition, string text) // regular assertion method
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null => true")]
/// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty()
/// </code></item>
/// <item><code>
/// // A method that returns null if the parameter is null, and not null if the parameter is not null
/// [ContractAnnotation("null => null; notnull => notnull")]
/// public object Transform(object data)
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null=>false; =>true,result:notnull; =>false, result:null")]
/// public bool TryParse(string s, out Person result)
/// </code></item>
/// </list></examples>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public sealed class ContractAnnotationAttribute : Attribute
{
public ContractAnnotationAttribute([NotNull] string contract)
: this(contract, false) { }
public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates)
{
Contract = contract;
ForceFullStates = forceFullStates;
}
public string Contract { get; private set; }
public bool ForceFullStates { get; private set; }
}
/// <summary>
/// Indicates that marked element should be localized or not
/// </summary>
/// <example><code>
/// [LocalizationRequiredAttribute(true)]
/// public class Foo {
/// private string str = "my string"; // Warning: Localizable string
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class LocalizationRequiredAttribute : Attribute
{
public LocalizationRequiredAttribute() : this(true) { }
public LocalizationRequiredAttribute(bool required)
{
Required = required;
}
public bool Required { get; private set; }
}
/// <summary>
/// Indicates that the value of the marked type (or its derivatives)
/// cannot be compared using '==' or '!=' operators and <c>Equals()</c>
/// should be used instead. However, using '==' or '!=' for comparison
/// with <c>null</c> is always permitted.
/// </summary>
/// <example><code>
/// [CannotApplyEqualityOperator]
/// class NoEquality { }
/// class UsesNoEquality {
/// public void Test() {
/// var ca1 = new NoEquality();
/// var ca2 = new NoEquality();
/// if (ca1 != null) { // OK
/// bool condition = ca1 == ca2; // Warning
/// }
/// }
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Interface | AttributeTargets.Class |
AttributeTargets.Struct, AllowMultiple = false, Inherited = true)]
public sealed class CannotApplyEqualityOperatorAttribute : Attribute { }
/// <summary>
/// When applied to a target attribute, specifies a requirement for any type marked
/// with the target attribute to implement or inherit specific type or types.
/// </summary>
/// <example><code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// public class ComponentAttribute : Attribute { }
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// public class MyComponent : IComponent { }
/// </code></example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
[BaseTypeRequired(typeof(Attribute))]
public sealed class BaseTypeRequiredAttribute : Attribute
{
public BaseTypeRequiredAttribute([NotNull] Type baseType)
{
BaseType = baseType;
}
[NotNull] public Type BaseType { get; private set; }
}
/// <summary>
/// Indicates that the marked symbol is used implicitly
/// (e.g. via reflection, in external library), so this symbol
/// will not be marked as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public sealed class UsedImplicitlyAttribute : Attribute
{
public UsedImplicitlyAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public UsedImplicitlyAttribute(
ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
public ImplicitUseKindFlags UseKindFlags { get; private set; }
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
/// <summary>
/// Should be used on attributes and causes ReSharper
/// to not mark symbols marked with such attributes as unused
/// (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public sealed class MeansImplicitUseAttribute : Attribute
{
public MeansImplicitUseAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public MeansImplicitUseAttribute(
ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; }
[UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
[Flags]
public enum ImplicitUseKindFlags
{
Default = Access | Assign | InstantiatedWithFixedConstructorSignature,
/// <summary>Only entity marked with attribute considered used</summary>
Access = 1,
/// <summary>Indicates implicit assignment to a member</summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type with fixed constructor signature.
/// That means any unused constructor parameters won't be reported as such.
/// </summary>
InstantiatedWithFixedConstructorSignature = 4,
/// <summary>Indicates implicit instantiation of a type</summary>
InstantiatedNoFixedConstructorSignature = 8,
}
/// <summary>
/// Specify what is considered used implicitly
/// when marked with <see cref="MeansImplicitUseAttribute"/>
/// or <see cref="UsedImplicitlyAttribute"/>
/// </summary>
[Flags]
public enum ImplicitUseTargetFlags
{
Default = Itself,
Itself = 1,
/// <summary>Members of entity marked with attribute are considered used</summary>
Members = 2,
/// <summary>Entity marked with attribute and all its members considered used</summary>
WithMembers = Itself | Members
}
/// <summary>
/// This attribute is intended to mark publicly available API
/// which should not be removed and so is treated as used
/// </summary>
[MeansImplicitUse]
public sealed class PublicAPIAttribute : Attribute
{
public PublicAPIAttribute() { }
public PublicAPIAttribute([NotNull] string comment)
{
Comment = comment;
}
[NotNull] public string Comment { get; private set; }
}
/// <summary>
/// Tells code analysis engine if the parameter is completely handled
/// when the invoked method is on stack. If the parameter is a delegate,
/// indicates that delegate is executed while the method is executed.
/// If the parameter is an enumerable, indicates that it is enumerated
/// while the method is executed
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, Inherited = true)]
public sealed class InstantHandleAttribute : Attribute { }
/// <summary>
/// Indicates that a method does not make any observable state changes.
/// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>
/// </summary>
/// <example><code>
/// [Pure] private int Multiply(int x, int y) { return x * y; }
/// public void Foo() {
/// const int a = 2, b = 2;
/// Multiply(a, b); // Waring: Return value of pure method is not used
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Method, Inherited = true)]
public sealed class PureAttribute : Attribute { }
/// <summary>
/// Indicates that a parameter is a path to a file or a folder
/// within a web project. Path can be relative or absolute,
/// starting from web root (~)
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public class PathReferenceAttribute : Attribute
{
public PathReferenceAttribute() { }
public PathReferenceAttribute([PathReference] string basePath)
{
BasePath = basePath;
}
[NotNull] public string BasePath { get; private set; }
}
// ASP.NET MVC attributes
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute
{
public AspMvcAreaMasterLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute
{
public AspMvcAreaPartialViewLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute
{
public AspMvcAreaViewLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcMasterLocationFormatAttribute : Attribute
{
public AspMvcMasterLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute
{
public AspMvcPartialViewLocationFormatAttribute(string format) { }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcViewLocationFormatAttribute : Attribute
{
public AspMvcViewLocationFormatAttribute(string format) { }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC action. If applied to a method, the MVC action name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcActionAttribute : Attribute
{
public AspMvcActionAttribute() { }
public AspMvcActionAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[NotNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC area.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcAreaAttribute : PathReferenceAttribute
{
public AspMvcAreaAttribute() { }
public AspMvcAreaAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[NotNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that
/// the parameter is an MVC controller. If applied to a method,
/// the MVC controller name is calculated implicitly from the context.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcControllerAttribute : Attribute
{
public AspMvcControllerAttribute() { }
public AspMvcControllerAttribute([NotNull] string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
[NotNull] public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(String, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcMasterAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(String, Object)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcModelTypeAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that
/// the parameter is an MVC partial view. If applied to a method,
/// the MVC partial view name is calculated implicitly from the context.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcPartialViewAttribute : PathReferenceAttribute { }
/// <summary>
/// ASP.NET MVC attribute. Allows disabling all inspections
/// for MVC views within a class or a method.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class AspMvcSupressViewErrorAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcDisplayTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcEditorTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC template.
/// Use this attribute for custom wrappers similar to
/// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view. If applied to a method, the MVC view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(Object)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcViewAttribute : PathReferenceAttribute { }
/// <summary>
/// ASP.NET MVC attribute. When applied to a parameter of an attribute,
/// indicates that this parameter is an MVC action name
/// </summary>
/// <example><code>
/// [ActionName("Foo")]
/// public ActionResult Login(string returnUrl) {
/// ViewBag.ReturnUrl = Url.Action("Foo"); // OK
/// return RedirectToAction("Bar"); // Error: Cannot resolve action
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
public sealed class AspMvcActionSelectorAttribute : Attribute { }
[AttributeUsage(
AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Field, Inherited = true)]
public sealed class HtmlElementAttributesAttribute : Attribute
{
public HtmlElementAttributesAttribute() { }
public HtmlElementAttributesAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
[AttributeUsage(
AttributeTargets.Parameter | AttributeTargets.Field |
AttributeTargets.Property, Inherited = true)]
public sealed class HtmlAttributeValueAttribute : Attribute
{
public HtmlAttributeValueAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
// Razor attributes
/// <summary>
/// Razor attribute. Indicates that a parameter or a method is a Razor section.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, Inherited = true)]
public sealed class RazorSectionAttribute : Attribute { }
} | t123/ReadingTool.Win | RTWin/Properties/Annotations.cs | C# | gpl-3.0 | 23,764 |
<?php
/*
* Copyright (C) 2015-2018 P. Mergey
* 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/>.
*/
// Heading
$_['heading_title'] = 'Total des ventes';
// Text
$_['text_extension'] = 'Extensions';
$_['text_success'] = 'Vous venez de modifier le tableau de bord des ventes !';
$_['text_edit'] = 'Modifier le tableau de bord des ventes';
$_['text_view'] = 'Voir plus...';
// Entry
$_['entry_status'] = 'Statut';
$_['entry_sort_order'] = 'Classement';
$_['entry_width'] = 'Largeur';
// Error
$_['error_permission'] = 'Attention : vous n’avez pas l’autorisation de modifier le tableau de bord des ventes !';
| GizMecano/opencart-2-fr | admin/language/fr-FR/extension/dashboard/sale.php | PHP | gpl-3.0 | 1,202 |
# This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import unittest
import trytond.tests.test_tryton
from trytond.tests.test_tryton import ModuleTestCase
class WebdavTestCase(ModuleTestCase):
'Test Webdav module'
module = 'webdav'
def suite():
suite = trytond.tests.test_tryton.suite()
suite.addTests(unittest.TestLoader().loadTestsFromTestCase(
WebdavTestCase))
return suite
| tryton/webdav | tests/test_webdav.py | Python | gpl-3.0 | 504 |
package NJU.HouseWang.nju_eas_client.net;
import java.io.IOException;
import java.util.Stack;
/**
* 网络连接池
*
* @author Xin
* @version 2013-12-12
*/
public class ClientPool {
/**
* 连接池单件
*/
private static ClientPool cPool = null;
/**
* 存放连接的栈
*/
private Stack<Client> clientStack = new Stack<Client>();
/**
* 默认最大连接数
*/
private static final int DEFAULT_MAX_SIZE = 32;
/**
* 默认最小连接数
*/
private static final int DEFAULT_MIN_SIZE = 16;
/**
* 默认IP
*/
private static final String DEFAULT_IP = "localhost";
/**
* 默认端口
*/
private static final int DEFAULT_PORT = 9100;
/**
* 最大连接数
*/
private int maxSize;
/**
* 最小连接数
*/
private int minSize;
/**
* 当前连接数
*/
private int linkNum = 0;
/**
* 当前IP
*/
private String ip;
/**
* 当前端口
*/
private int port;
/**
* 以默认配置构造
*/
private ClientPool() {
maxSize = DEFAULT_MAX_SIZE;
minSize = DEFAULT_MIN_SIZE;
ip = DEFAULT_IP;
port = DEFAULT_PORT;
}
/**
* 以默认配置取得单件
*
* @return ClientPool单件
*/
public static ClientPool getInstance() {
if (cPool != null) {
return cPool;
} else {
cPool = new ClientPool();
try {
cPool.initialize();
} catch (Exception e) {
e.printStackTrace();
}
return cPool;
}
}
/**
* 自定义构造
*
* @param ip
* @param port
* @param maxSize
* @param minSize
*/
private ClientPool(String ip, int port, int maxSize, int minSize) {
this.maxSize = maxSize;
this.minSize = minSize;
this.ip = ip;
this.port = port;
}
/**
* 得到自定义构造的单件
*
* @param ip
* @param port
* @param max
* @param min
* @return
*/
public static ClientPool getInstance(String ip, int port, int max, int min) {
if (cPool != null) {
return cPool;
} else {
cPool = new ClientPool(ip, port, max, min);
return cPool;
}
}
/**
* 初始化连接数
*/
private void initialize() {
for (int i = 0; i < maxSize; i++) {
Client c = new Client(ip, port);
try {
c.createConnection();
} catch (IOException e) {
break;
}
clientStack.push(c);
linkNum++;
}
}
/**
* 关闭连接池
*/
public void shutdown() {
while (clientStack.isEmpty()) {
clientStack.pop().shutDownConnection();
}
}
/**
* 得到连接
*
* @return 连接
*/
public Client getClient() {
if (linkNum < minSize) {
new Thread(new Runnable() {
public void run() {
initialize();
}
}).start();
}
linkNum--;
return clientStack.pop();
}
}
| NJU-HouseWang/nju-eas-client | src/main/java/NJU/HouseWang/nju_eas_client/net/ClientPool.java | Java | gpl-3.0 | 2,651 |
# -*- coding: utf-8 -*-
# EDIS - a simple cross-platform IDE for C
#
# This file is part of Edis
# Copyright 2014-2015 - Gabriel Acosta <acostadariogabriel at gmail>
# License: GPLv3 (see http://www.gnu.org/licenses/gpl.html)
from PyQt4.QtGui import (
QGraphicsOpacityEffect,
QFrame
)
from PyQt4.QtCore import (
QPropertyAnimation,
Qt
)
from PyQt4.Qsci import QsciScintilla
class Minimap(QsciScintilla):
def __init__(self, weditor):
QsciScintilla.__init__(self, weditor)
self._weditor = weditor
self._indentation = self._weditor._indentation
self.setLexer(self._weditor.lexer())
# Configuración Scintilla
self.setMouseTracking(True)
self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, False)
self.SendScintilla(QsciScintilla.SCI_HIDESELECTION, True)
self.setFolding(QsciScintilla.NoFoldStyle, 1)
self.setReadOnly(True)
self.setCaretWidth(0)
self.setStyleSheet("background: transparent; border: 0px;")
# Opacity
self.effect = QGraphicsOpacityEffect()
self.setGraphicsEffect(self.effect)
self.effect.setOpacity(0.5)
# Deslizador
self.slider = Slider(self)
self.slider.hide()
def resizeEvent(self, event):
super(Minimap, self).resizeEvent(event)
self.slider.setFixedWidth(self.width())
lines_on_screen = self._weditor.SendScintilla(
QsciScintilla.SCI_LINESONSCREEN)
self.slider.setFixedHeight(lines_on_screen * 4)
def update_geometry(self):
self.setFixedHeight(self._weditor.height())
self.setFixedWidth(self._weditor.width() * 0.13)
x = self._weditor.width() - self.width()
self.move(x, 0)
self.zoomIn(-3)
def update_code(self):
text = self._weditor.text().replace('\t', ' ' * self._indentation)
self.setText(text)
def leaveEvent(self, event):
super(Minimap, self).leaveEvent(event)
self.slider.animation.setStartValue(0.2)
self.slider.animation.setEndValue(0)
self.slider.animation.start()
def enterEvent(self, event):
super(Minimap, self).enterEvent(event)
if not self.slider.isVisible():
self.slider.show()
else:
self.slider.animation.setStartValue(0)
self.slider.animation.setEndValue(0.2)
self.slider.animation.start()
class Slider(QFrame):
def __init__(self, minimap):
QFrame.__init__(self, minimap)
self._minimap = minimap
self.setStyleSheet("background: gray; border-radius: 3px;")
# Opacity
self.effect = QGraphicsOpacityEffect()
self.setGraphicsEffect(self.effect)
self.effect.setOpacity(0.2)
# Animación
self.animation = QPropertyAnimation(self.effect, "opacity")
self.animation.setDuration(150)
# Cursor
self.setCursor(Qt.OpenHandCursor)
def mouseMoveEvent(self, event):
super(Slider, self).mouseMoveEvent(event)
#FIXME: funciona algo loco
pos = self.mapToParent(event.pos())
dy = pos.y() - (self.height() / 2)
if dy < 0:
dy = 0
self.move(0, dy)
pos.setY(pos.y() - event.pos().y())
self._minimap._weditor.verticalScrollBar().setValue(pos.y())
self._minimap.verticalScrollBar().setSliderPosition(
self._minimap.verticalScrollBar().sliderPosition() + 2)
self._minimap.verticalScrollBar().setValue(pos.y() - event.pos().y())
def mousePressEvent(self, event):
super(Slider, self).mousePressEvent(event)
self.setCursor(Qt.ClosedHandCursor)
def mouseReleaseEvent(self, event):
super(Slider, self).mouseReleaseEvent(event)
self.setCursor(Qt.OpenHandCursor) | centaurialpha/edis | src/ui/editor/minimap.py | Python | gpl-3.0 | 3,836 |
<?php
// $Header: /cvsroot/html2ps/output._interface.class.php,v 1.8 2007/01/09 20:13:48 Konstantin Exp $
class OutputDriver {
function add_link($x, $y, $w, $h, $target) { }
function add_local_link($left, $top, $width, $height, $anchor) { }
function circle($x, $y, $r) { }
function clip() {}
function close() { die("Unoverridden 'close' method called in ".get_class($this)); }
function closepath() {}
function content_type() { die("Unoverridden 'content_type' method called in ".get_class($this)); }
function dash($x, $y) { }
function decoration($underline, $overline, $strikeout) { }
function error_message() { die("Unoverridden 'error_message' method called in ".get_class($this)); }
function new_form($name) {}
function field_multiline_text($x, $y, $w, $h, $value, $field_name) { }
function field_text($x, $y, $w, $h, $value, $field_name) { }
function field_password($x, $y, $w, $h, $value, $field_name) { }
function field_pushbutton($x, $y, $w, $h) { }
function field_pushbuttonimage($x, $y, $w, $h, $field_name, $value, $actionURL) { }
function field_pushbuttonreset($x, $y, $w, $h) { }
function field_pushbuttonsubmit($x, $y, $w, $h, $field_name, $value, $actionURL) { }
function field_checkbox($x, $y, $w, $h, $name, $value, $checked) { }
function field_radio($x, $y, $w, $h, $groupname, $value, $checked) { }
function field_select($x, $y, $w, $h, $name, $value, $options) { }
function fill() { }
function font_ascender($name, $encoding) {}
/**
* Note that positive value returned by this function
* means offset to the BOTTOM!
*/
function font_descender($name, $encoding) {}
function get_bottom() {}
function image($image, $x, $y, $scale) {}
function image_scaled($image, $x, $y, $scale_x, $scale_y) { }
function image_ry($image, $x, $y, $height, $bottom, $ox, $oy, $scale) { }
function image_rx($image, $x, $y, $width, $right, $ox, $oy, $scale) { }
function image_rx_ry($image, $x, $y, $width, $height, $right, $bottom, $ox, $oy, $scale) { }
function lineto($x, $y) { }
function moveto($x, $y) { }
function next_page($height) { }
function release() { }
function restore() { }
function save() { }
// Note that there's no functions for setting bold/italic style of the fonts;
// you must keep in mind that roman/bold/italic font variations are, in fact, different
// fonts stored in different files and it is the business of the font resolver object to
// find the appropriate font name. Here we just re-use it.
//
function setfont($name, $encoding, $size) {}
// function setfontcore($name, $size) {}
function setlinewidth($x) { }
function setrgbcolor($r, $g, $b) { }
function set_watermark($text) { }
function show_xy($text, $x, $y) {}
function stringwidth($string, $name, $encoding, $size) { }
function stroke() { }
}
?> | fearless359/simpleinvoices | library/pdf/output._interface.class.php | PHP | gpl-3.0 | 2,855 |
/*****************************************************************
* This file is part of Managing Agricultural Research for Learning &
* Outcomes Platform (MARLO).
* MARLO 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.
* MARLO 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 MARLO. If not, see <http://www.gnu.org/licenses/>.
*****************************************************************/
/**************
* @author Diego Perez - CIAT/CCAFS
**************/
package org.cgiar.ccafs.marlo.data.manager.impl;
import org.cgiar.ccafs.marlo.data.dao.InstitutionDictionaryDAO;
import org.cgiar.ccafs.marlo.data.manager.InstitutionDictionaryManager;
import org.cgiar.ccafs.marlo.data.model.InstitutionDictionary;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
@Named
public class InstitutionDictionaryManagerImpl implements InstitutionDictionaryManager {
private InstitutionDictionaryDAO institutionDictionaryDAO;
@Inject
public InstitutionDictionaryManagerImpl(InstitutionDictionaryDAO institutionDictionaryDAO) {
super();
this.institutionDictionaryDAO = institutionDictionaryDAO;
}
@Override
public List<InstitutionDictionary> getAll() {
return institutionDictionaryDAO.getAll();
}
@Override
public InstitutionDictionary getInstitutionDictionaryById(long id) {
return institutionDictionaryDAO.getInstitutionDictionaryById(id);
}
}
| CCAFS/MARLO | marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/manager/impl/InstitutionDictionaryManagerImpl.java | Java | gpl-3.0 | 1,922 |
using System;
namespace Artemis.Core
{
/// <summary>
/// Represents errors that occur within the Artemis Core
/// </summary>
public class ArtemisCoreException : Exception
{
internal ArtemisCoreException(string message) : base(message)
{
}
internal ArtemisCoreException(string message, Exception inner) : base(message, inner)
{
}
}
} | SpoinkyNL/Artemis | src/Artemis.Core/Exceptions/ArtemisCoreException.cs | C# | gpl-3.0 | 413 |
package sidben.villagertweaks.network;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import sidben.villagertweaks.ModVillagerTweaks;
import sidben.villagertweaks.common.ExtendedGolem;
import sidben.villagertweaks.common.ExtendedVillagerZombie;
import sidben.villagertweaks.helper.GolemEnchantment;
import sidben.villagertweaks.helper.LogHelper;
import sidben.villagertweaks.tracker.ClientInfoTracker;
/*
* NOTE:
*
* One problem I have with this class is that sending messages to client when the player reaches the "PlayerEvent.StartTracking"
* event causes the client to receive the pack BEFORE the client loads any entities, so I have to store the message locally and
* check again on the "EntityJoinWorld" event for the client-side.
*
* One way I could prevent this is, instead of sending the messages instantly, I can store them in a list on the server and send
* all at once at a later event, when I expect the client to have all entities loaded.
*
* Would that cause too much network traffic at once? How risky is the desync? Isn't y current method better, since
* it uses the client memory instead of server's memory? Need future tests.
*
*/
/**
* Responsible for sending and receiving packets / messages between client and server.
*
*/
public class NetworkHelper
{
//---------------------------------------------------------------------
// Message Dispatch
//---------------------------------------------------------------------
/**
* Send custom info from zombies villagers when the player starts to track them.
* Mainly used to notify the client of the zombie villager profession, so it
* can render the correct skin.
*
* Server -> Client
*/
public static void sendVillagerProfessionMessage(int zombieId, ExtendedVillagerZombie properties, EntityPlayer target) {
if (zombieId > 0 && properties != null && properties.getProfession() >= 0)
{
MessageZombieVillagerProfession message = new MessageZombieVillagerProfession(zombieId, properties.getProfession());
// Debug
LogHelper.info("~~Sending Message - Zombie Profession~~");
LogHelper.info(" target: " + target);
LogHelper.info(" " + message.toString());
// Sends a message to the player, with the zombie extra info
ModVillagerTweaks.NetworkWrapper.sendTo(message, (EntityPlayerMP)target);
}
}
/**
* Send custom info about golems (iron and snow) when the player starts to track them.
* Mainly used to notify the client of the golem special enchantments, so it
* can render the correct particles / overlay.
*
* Server -> Client
*
*/
public static void sendEnchantedGolemInfoMessage(int golemId, ExtendedGolem properties, EntityPlayer target) {
if (golemId > 0 && properties != null) {
int[] ids = GolemEnchantment.convert(properties.getEnchantments());
if (ids.length > 0) {
MessageGolemEnchantments message = new MessageGolemEnchantments(golemId, ids);
// Debug
LogHelper.info("~~Sending Message - Enchanted Iron Golem info~~");
LogHelper.info(" target: " + target);
LogHelper.info(" " + message.toString());
// Sends a message to the player, with the golem extra info
ModVillagerTweaks.NetworkWrapper.sendTo(message, (EntityPlayerMP)target);
}
}
}
/**
* Send info about the golems (iron and snow) to all players around a certain radius of them.
*
* Server -> Client
*
*/
public static void sendEnchantedGolemInfoMessage(EntityLiving golem, ExtendedGolem properties) {
if (golem != null && properties != null) {
int[] ids = GolemEnchantment.convert(properties.getEnchantments());
if (ids.length > 0) {
MessageGolemEnchantments message = new MessageGolemEnchantments(golem.getEntityId(), ids);
TargetPoint target = new TargetPoint(golem.dimension, golem.posX, golem.posY, golem.posZ, 64.0D);
// Debug
LogHelper.info("~~Sending Message - Enchanted Iron Golem info~~");
LogHelper.info(" target: " + target);
LogHelper.info(" " + message.toString());
// Sends a message to the player, with the golem extra info
ModVillagerTweaks.NetworkWrapper.sendToAllAround(message, target);
}
}
}
//---------------------------------------------------------------------
// Message Receival
//---------------------------------------------------------------------
public static class VillagerProfessionHandler implements IMessageHandler<MessageZombieVillagerProfession, IMessage> {
@Override
public IMessage onMessage(MessageZombieVillagerProfession message, MessageContext ctx) {
// Debug
LogHelper.info("~~Receiving Message - Zombie Profession~~");
LogHelper.info(" " + message.toString());
if (message.getEntityID() > 0 && message.getProfession() >= 0) {
// Saves the info to be used later, when the entity actually loads
ClientInfoTracker.addZombieMessage(message);
// Attempts to sync the entity. Most of the times the entity won't be found
// when this code execute, but on some cases the entity can join the world
// before the packet is received (e.g. villager gets zombified).
ClientInfoTracker.SyncZombieMessage(message.getEntityID());
}
return null;
}
}
public static class GolemEnchantmentHandler implements IMessageHandler<MessageGolemEnchantments, IMessage> {
@Override
public IMessage onMessage(MessageGolemEnchantments message, MessageContext ctx)
{
// Debug
LogHelper.info("~~Receiving Message - Enchanted Iron Golem info~~");
LogHelper.info(" " + message.toString());
if (message.getEntityID() > 0) {
// Saves the info to be used later, when the entity actually loads
ClientInfoTracker.addGolemMessage(message);
// Attempts to sync the entity. Most of the times the entity won't be found
// when this code execute, but on some cases the entity can join the world
// before the packet is received (e.g. villager gets zombified).
ClientInfoTracker.SyncGolemMessage(message.getEntityID());
}
return null;
}
}
}
| sidben/VillagerTweaks | src/main/java/sidben/villagertweaks/network/NetworkHelper.java | Java | gpl-3.0 | 7,380 |
<?php
class TableNames
{
const RESERVATION_SERIES_ALIAS = 'rs';
const ACCESSORIES = 'accessories';
const GROUPS_ALIAS = 'g';
const RESERVATION_ACCESSORIES_ALIAS = 'ra';
const RESOURCES = 'resources';
const SCHEDULES = 'schedules';
const USERS = 'users';
}
?> | glamprou/bookings | lib/Database/Commands/TableNames.php | PHP | gpl-3.0 | 285 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package local_iomad_signup
* @copyright 2021 Derick Turner
* @author Derick Turner
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/** Include required files */
require_once($CFG->libdir.'/filelib.php');
/**
* Form for editing HTML block instances.
*
* @copyright 2010 Petr Skoda (http://skodak.org)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package block_html
* @category files
* @param stdClass $course course object
* @param stdClass $birecord_or_cm block instance record
* @param stdClass $context context object
* @param string $filearea file area
* @param array $args extra arguments
* @param bool $forcedownload whether or not force download
* @param array $options additional options affecting the file serving
* @return bool
* @todo MDL-36050 improve capability check on stick blocks, so we can check user capability before sending images.
*/
function local_iomad_track_pluginfile($course, $birecord_or_cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
global $DB, $CFG, $USER;
if ($context->contextlevel != CONTEXT_COURSE) {
send_file_not_found();
}
require_login();
if ($filearea !== 'issue') {
send_file_not_found();
}
$fs = get_file_storage();
$itemid = array_shift($args);
$filename = array_pop($args);
$filepath = $args ? '/'.implode('/', $args).'/' : '/';
if (!$file = $fs->get_file($context->id, 'local_iomad_track', 'issue', $itemid, $filepath, $filename) or $file->is_directory()) {
send_file_not_found();
}
// NOTE: it woudl be nice to have file revisions here, for now rely on standard file lifetime,
// do not lower it because the files are dispalyed very often.
\core\session\manager::write_close();
send_stored_file($file, null, 0, $forcedownload, $options);
}
/*
* Function to remove entries from the local_iomad_track table.
*
* @param boolean $full remove just the saved certificate or everything.
*/
function local_iomad_track_delete_entry($trackid, $full=false) {
global $DB,$CFG;
// Do we have a recorded certificate?
if ($cert = $DB->get_record('local_iomad_track_certs', array('trackid' => $trackid))) {
$DB->delete_records('local_iomad_track_certs', array('id' => $cert->id));
}
// Remove the actual underlying file.
if ($file = $DB->get_record_sql("SELECT * FROM {files}
WHERE component= :component
AND itemid = :itemid
AND filename != '.'",
array('component' => 'local_iomad_track', 'itemid' => $trackid))) {
$filedir1 = substr($file->contenthash,0,2);
$filedir2 = substr($file->contenthash,2,2);
$filepath = $CFG->dataroot . '/filedir/' . $filedir1 . '/' . $filedir2 . '/' . $file->contenthash;
unlink($filepath);
}
$DB->delete_records('files', array('itemid' => $trackid, 'component' => 'local_iomad_track'));
// Are we getting rid of the full record?
if ($full) {
$DB->delete_records('local_iomad_track', array('id' => $trackid));
}
}
| iomad/iomad | local/iomad_track/lib.php | PHP | gpl-3.0 | 3,966 |
using System.Collections.Generic;
using Newtonsoft.Json;
using ShareX.HelpersLib;
using ShareX.ImageEffectsLib;
namespace ShareX.TaskManagement
{
public class TaskSettingsImage
{
//#region Image / General
public EImageFormat ImageFormat = EImageFormat.PNG;
public int ImageJPEGQuality = 90;
public GIFQuality ImageGIFQuality = GIFQuality.Default;
public int ImageSizeLimit = 1024;
public EImageFormat ImageFormat2 = EImageFormat.JPEG;
public FileExistAction FileExistAction = FileExistAction.Ask;
//#endregion Image / General
//#region Image / Effects
[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Auto)]
public List<ImageEffect> ImageEffects = ImageEffectManager.GetDefaultImageEffects();
public bool ShowImageEffectsWindowAfterCapture = false;
public bool ImageEffectOnlyRegionCapture = false;
//#endregion Image / Effects
//#region Image / Thumbnail
public int ThumbnailWidth = 200;
public int ThumbnailHeight = 0;
public string ThumbnailName = "-thumbnail";
public bool ThumbnailCheckSize = false;
//#endregion Image / Thumbnail
}
}
| justkarli/ShareX | ShareX/TaskManagement/TaskSettingsImage.cs | C# | gpl-3.0 | 1,230 |
using System;
using System.Reflection;
using BankTransferSample.Commands;
using BankTransferSample.Domain;
using BankTransferSample.DomainEvents;
using ECommon.Autofac;
using ECommon.Configurations;
using ECommon.Components;
using ECommon.JsonNet;
using ECommon.Log4Net;
using ECommon.Utilities;
using ENode.Commanding;
using ENode.Configurations;
using ENode.Eventing;
namespace BankTransferSample
{
class Program
{
static void Main(string[] args)
{
InitializeENodeFramework();
var commandService = ObjectContainer.Resolve<ICommandService>();
Console.WriteLine(string.Empty);
//创建两个银行账户
commandService.Execute(new CreateAccountCommand("00001", "雪华")).Wait();
commandService.Execute(new CreateAccountCommand("00002", "凯锋")).Wait();
Console.WriteLine(string.Empty);
//每个账户都存入1000元
commandService.StartProcess(new StartDepositTransactionCommand(ObjectId.GenerateNewStringId(), "00001", 1000)).Wait();
commandService.StartProcess(new StartDepositTransactionCommand(ObjectId.GenerateNewStringId(), "00002", 1000)).Wait();
Console.WriteLine(string.Empty);
//账户1向账户2转账300元
commandService.StartProcess(new StartTransferTransactionCommand(new TransferTransactionInfo(ObjectId.GenerateNewStringId(), "00001", "00002", 300D))).Wait();
Console.WriteLine(string.Empty);
//账户2向账户1转账500元
commandService.StartProcess(new StartTransferTransactionCommand(new TransferTransactionInfo(ObjectId.GenerateNewStringId(), "00002", "00001", 500D))).Wait();
Console.WriteLine(string.Empty);
Console.WriteLine("Press Enter to exit...");
Console.ReadLine();
}
static void InitializeENodeFramework()
{
var assemblies = new[] { Assembly.GetExecutingAssembly() };
Configuration
.Create()
.UseAutofac()
.RegisterCommonComponents()
.UseLog4Net()
.UseJsonNet()
.CreateENode()
.RegisterENodeComponents()
.SetProviders()
.RegisterBusinessComponents(assemblies)
.UseEQueue()
.InitializeBusinessAssemblies(assemblies)
.StartRetryCommandService()
.StartWaitingCommandService()
.StartEQueue();
Console.WriteLine("ENode framework started...");
}
}
}
| key-value/BankTransferSample | src/Program.cs | C# | gpl-3.0 | 2,645 |
Joomla 3.6.4 = be7f77906288a07f69084e46680ff6e5
Joomla 3.4.8 = 96990e227c35c2adc8f1f42e2493f9c0
| gohdan/DFC | known_files/hashes/libraries/vendor/joomla/event/src/EventInterface.php | PHP | gpl-3.0 | 96 |
// Copyright (C) 2015, 2017 Simon Mika <simon@mika.se>
//
// This file is part of SysPL.
//
// SysPL 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.
//
// SysPL 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 SysPL. If not, see <http://www.gnu.org/licenses/>.
//
import { Utilities } from "@cogneco/mend"
import * as Tokens from "../Tokens"
import { Declaration } from "./Declaration"
import { Node } from "./Node"
export abstract class SymbolDeclaration extends Declaration {
constructor(symbol: string, tokens?: Utilities.Enumerable<Tokens.Substance> | Node) {
super(symbol, tokens)
}
}
| syspl/syspl | source/SyntaxTree/SymbolDeclaration.ts | TypeScript | gpl-3.0 | 1,053 |
using UnityEngine;
using System.Collections;
public class DoorHandleScript : MonoBehaviour {
private Transform Target = null;
private Vector3 LookAtPos = Vector3.zero;
public Transform Joint;
void Start () {
}
void Update () {
if (Target != null)
{
//test with the vive if this works
LookAtPos = new Vector3(Target.position.x, Joint.position.y, Target.position.z);
Joint.LookAt(LookAtPos);
Joint.localEulerAngles = new Vector3(0, ClampAngle(Joint.localEulerAngles.y, 270, 90), 0);
}
}
public void SetTarget(Transform newTarget)
{
Target = newTarget;
}
public Transform GetTarget()
{
return Target;
}
float ClampAngle(float angle, float min, float max)
{
float returnAngle = 0;
while (angle > 180)
{
angle -= 360;
}
while (max > 180)
{
max -= 360;
}
while (min > 180)
{
min -= 360;
}
returnAngle = Mathf.Clamp(angle, min, max);
while (returnAngle < 0)
{
returnAngle += 360;
}
return returnAngle;
}
}
| Snailpower/IdontAmbulancecare | Newest/Assets/Scripts/New/DoorHandleScript.cs | C# | gpl-3.0 | 1,224 |
#!/usr/bin/env python
# coding: utf-8
"""setuptools based setup module"""
from setuptools import setup
# from setuptools import find_packages
# To use a consistent encoding
import codecs
from os import path
import osvcad
here = path.abspath(path.dirname(__file__))
# Get the long description from the README_SHORT file
with codecs.open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name=osvcad.__name__,
version=osvcad.__version__,
description=osvcad.__description__,
long_description=long_description,
url=osvcad.__url__,
download_url=osvcad.__download_url__,
author=osvcad.__author__,
author_email=osvcad.__author_email__,
license=osvcad.__license__,
classifiers=[
'Development Status :: 3 - Alpha',
'Topic :: Software Development',
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6'
],
keywords=['OpenCascade', 'PythonOCC', 'ccad', 'CAD', 'parts', 'json'],
packages=['osvcad',
'osvcad.jupyter',
'osvcad.utils',
'osvcad.ui'],
install_requires=[],
# OCC, scipy and wx cannot be installed via pip
extras_require={'dev': [],
'test': ['pytest', 'coverage'], },
package_data={},
data_files=[('osvcad/ui/icons',
['osvcad/ui/icons/blue_folder.png',
'osvcad/ui/icons/file_icon.png',
'osvcad/ui/icons/folder.png',
'osvcad/ui/icons/green_folder.png',
'osvcad/ui/icons/open.png',
'osvcad/ui/icons/python_icon.png',
'osvcad/ui/icons/quit.png',
'osvcad/ui/icons/refresh.png',
'osvcad/ui/icons/save.png']),
('osvcad/ui',
['osvcad/ui/osvcad.ico',
'osvcad/ui/osvcadui.ini'])],
entry_points={},
scripts=['bin/osvcad-ui']
)
| osv-team/osvcad | setup.py | Python | gpl-3.0 | 2,202 |
// Decompiled with JetBrains decompiler
// Type: System.Web.UI.IHierarchyData
// Assembly: System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// MVID: 7E68A73E-4066-4F24-AB0A-F147209F50EC
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Web.dll
namespace System.Web.UI
{
/// <summary>
/// Exposes a node of a hierarchical data structure, including the node object and some properties that describe characteristics of the node. Objects that implement the <see cref="T:System.Web.UI.IHierarchyData"/> interface can be contained in <see cref="T:System.Web.UI.IHierarchicalEnumerable"/> collections, and are used by ASP.NET site navigation and data source controls.
/// </summary>
public interface IHierarchyData
{
/// <summary>
/// Indicates whether the hierarchical data node that the <see cref="T:System.Web.UI.IHierarchyData"/> object represents has any child nodes.
/// </summary>
///
/// <returns>
/// true if the current node has child nodes; otherwise, false.
/// </returns>
bool HasChildren { get; }
/// <summary>
/// Gets the hierarchical path of the node.
/// </summary>
///
/// <returns>
/// A <see cref="T:System.String"/> that identifies the hierarchical path relative to the current node.
/// </returns>
string Path { get; }
/// <summary>
/// Gets the hierarchical data node that the <see cref="T:System.Web.UI.IHierarchyData"/> object represents.
/// </summary>
///
/// <returns>
/// An <see cref="T:System.Object"/> hierarchical data node object.
/// </returns>
object Item { get; }
/// <summary>
/// Gets the name of the type of <see cref="T:System.Object"/> contained in the <see cref="P:System.Web.UI.IHierarchyData.Item"/> property.
/// </summary>
///
/// <returns>
/// The name of the type of object that the <see cref="T:System.Web.UI.IHierarchyData"/> object represents.
/// </returns>
string Type { get; }
/// <summary>
/// Gets an enumeration object that represents all the child nodes of the current hierarchical node.
/// </summary>
///
/// <returns>
/// An <see cref="T:System.Web.UI.IHierarchicalEnumerable"/> collection of child nodes of the current hierarchical node.
/// </returns>
IHierarchicalEnumerable GetChildren();
/// <summary>
/// Gets an <see cref="T:System.Web.UI.IHierarchyData"/> object that represents the parent node of the current hierarchical node.
/// </summary>
///
/// <returns>
/// An <see cref="T:System.Web.UI.IHierarchyData"/> object that represents the parent node of the current hierarchical node.
/// </returns>
IHierarchyData GetParent();
}
}
| mater06/LEGOChimaOnlineReloaded | LoCO Client Files/Decompressed Client/Extracted DLL/System.Web/System/Web/UI/IHierarchyData.cs | C# | gpl-3.0 | 2,771 |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Colosoft.Excel{
public partial class FORMULA : Record {
public FORMULA (Record a) : base (a) {
}
public UInt16 RowIndex;
public UInt16 ColIndex;
public UInt16 XFIndex;
public UInt64 Result;
public UInt16 OptionFlags;
public UInt32 Unused;
public Byte[] FormulaData;
public override void Decode () {
MemoryStream a = new MemoryStream (Data);
BinaryReader b = new BinaryReader (a);
this.RowIndex = b.ReadUInt16 ();
this.ColIndex = b.ReadUInt16 ();
this.XFIndex = b.ReadUInt16 ();
this.Result = b.ReadUInt64 ();
this.OptionFlags = b.ReadUInt16 ();
this.Unused = b.ReadUInt32 ();
this.FormulaData = b.ReadBytes ((int)(a.Length - a.Position));
}
}
}
| fabrimaciel/colosoft | Excel/Colosoft.Excel/FORMULA2.cs | C# | gpl-3.0 | 795 |
package org.jcloarca.twitterclient.images;
/**
* Created by JCLoarca on 6/19/2016 1:38 AM.
*/
public interface ImagesInteractor {
void execute();
}
| JoseLoarca/twitterclient | TwitterClient/app/src/main/java/org/jcloarca/twitterclient/images/ImagesInteractor.java | Java | gpl-3.0 | 155 |
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="shortcut icon" href="images/icon/profile.png"/>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>LAPORAN PELAKSANAAN PENUGASAN</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="bg">
<div id= "main">
<div id="header">
<div id="logo">
<h1><a href="http://www.pln.co.id">PT. PLN (Persero) </a> </h1>
<h2><a href="https://simdiklat.pln-pusdiklat.co.id/portal/"> Pusat Pendidikan dan Pelatihan </a></h2>
</div>
</div>
<div id="buttons">
<ul>
<?
include "inc/config.inc.php";
include "inc/function.inc.php";
include "inc/tools.inc.php";
$act = "Informasi Pegawai";
if(!ceksession($session, $act)) header("Location: errorsession.htm");
/* cari nipeg pengunjung */
$sql = "select user from $tbl_session where session='$session'";
$q = mysql_query($sql);
list($user) = mysql_fetch_row($q);
$sql1 = "select kd_posisi from $tbl_bio01 where nipeg='$user'";
$q1 = mysql_query($sql1);
list($kd_posisi) = mysql_fetch_row($q1);
print "
<li class=first><a href=info-pegawai.php?session=$session>Awal</a></li>
<li><a href=daftar-pegawai.php?session=$session>Daftar Pegawai</a></li>
<li><a href=cek-pegawai.php?session=$session&nipeg=$user&pos=$kd_posisi>Biodata</a></li>
<li><a href=ubah-data.php?session=$session>Koreksi Data</a></li>
<li><a href=Dozir.php?session=$session>Lihat Dosir</a></li>
<li><a href=Input_Restitusi.php?session=$session>Input Restitusi</a></li>
<li class='dropdown'>
<a class='dropdown-toggle' data-toggle='dropdown' href='#'>Menu 1 <span class='caret'></span></a>
<ul class='dropdown-menu'>
<li><a href='#' style='color:black'>Form 4.1</a></li>
<li><a href='#' style='color:black'>Form 4.2</a></li>
</ul>
</li>
";
/* cari nipeg pengunjung */
$sql = "select user from $tbl_session where session='$session'";
$q = mysql_query($sql);
list($nipeg) = mysql_fetch_row($q);
/* cek apakah pengunjung adalah admin atau bukan */
$sql = "select nipeg from $tbl_admin where nipeg='$nipeg'";
$q = mysql_query($sql);
list($adadata) = mysql_fetch_row($q);
/* apabila admin, tambahan menu baru */
$sql = "select nipeg from admin_dosir where nipeg like '$adadata'";
$q = mysql_query($sql);
list($cek_nipeg) = mysql_fetch_row($q);
$sql = "select nipeg from super_admin where nipeg like '$adadata'";
$q = mysql_query($sql);
list($super) = mysql_fetch_row($q);
if($super != '') {
print "
<li><a href=daftar-pesan.php?session=$session>Daftar Pesan</a></li>
<li><a href=importSAP.php?session=$session>Import Data dari SAP</a></li>
";
}
if($cek_nipeg != ''){
print "
<li><a href=inputdozir1.php?session=$session>Input Dosir</a></li>
";
}
print "
<li><a href=logout.php?session=$session>Keluar</a></li>
";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbsipeg";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT nipeg FROM wig WHERE nipeg = '$user'";
$result = mysqli_query($conn, $sql2);
if ($result->num_rows > 0) {
//header("Location: Form_PLT3.php?session=$session&user2=$user");
// output data of each row
// while($row = $result->fetch_assoc()) {
// echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
//}
} else {
//echo "0 results";
}
$sql2 = "SELECT kd_posisi FROM bio01 WHERE nipeg = '$user'";
$result = mysqli_query($conn, $sql2);
if ($result->num_rows > 0) {
//header("Location: Form_PLT2.php?session=$session");
while($row = $result->fetch_assoc()) {
$posisi = $row["kd_posisi"];
$posisi = str_replace(" ","",$posisi);
}
} else {
//echo "0 results";
}
$sql2 = "SELECT wig.nipeg, bio01.kd_posisi
FROM bio01
INNER JOIN wig
ON bio01.nipeg=wig.nipeg;
";
$result = mysqli_query($conn, $sql2);
if ($result->num_rows > 0) {
//header("Location: Form_PLT2.php?session=$session");
while($row = $result->fetch_assoc()) {
$nama = $row["kd_posisi"];
$array = str_split($nama);
$num_digits = strlen($array);
$jumlah ="";
for($i=0;$i<$num_digits;$i++)
{
$jumlah .= $array[$i];
}
$pengisi = $row["nipeg"];
if($jumlah == $posisi)
{
//header("Location: Form_PLT2.php?session=$session&user2=$pengisi");
}
else{}
}
} else {
}
?>
</ul></div>
<div class="container">
<br>
<div class="row">
<div class="col-md-5 col-md-offset-2"><b style="font-size:20px">LAPORAN PELAKSANAAN PENUGASAN</b></div>
</div>
<br>
<?php
echo '<form class="form-horizontal" method="post" action="insert_laporan_pelaksanaan.php?session='.$session.'">';
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbsipeg";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql2 = "SELECT plt FROM wig where nipeg = '$user2'";
$result2 = $conn->query($sql2);
echo '<div class="form-group">';
echo '<div class="col-sm-3">';
echo '<label for="sel1">PLT:</label>';
echo '<p class="form-control-static">';
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
$jabatan = $row["plt"];
}
echo $jabatan;
echo '</p>';
echo '</div>';
echo '</div>';
}
$sql2 = "SELECT * FROM laporan_pelaksanaan where nipeg = '$user'";
$result2 = $conn->query($sql2);
if ($result2->num_rows > 0) {
// output data of each row
while($row = $result2->fetch_assoc()) {
print'
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 text-left">JUDUL :</label>
</div>
<div class="form-group">
<div class="col-sm-5" >';
echo '<p class="form-control-static">'.$row["judul"].' </p></div></div>';
echo '<br>';
print'
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 text-left">ABSTRAK :</label>
</div>
<div class="form-group">
<div class="col-sm-5">';
echo '<p class="form-control-static">'.$row["abstrak"].' </p></div></div><br>';
print'
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 text-left">LATAR BELAKANG :</label>
</div>
<div class="form-group">
<div class="col-sm-5">';
echo '<p class="form-control-static">'.$row["latar_belakang"].' </p></div></div><br>';
print'
<div class="form-group">
<label for="inputEmail3" class="col-md-4 text-left">LAPORAN PENCAPAIAN WIG DAN LAG MEASURE :</label>
</div>
<div class="form-group">
<div class="col-sm-5">';
echo '<p class="form-control-static">'.$row["laporan_pencapaian"].' </p></div></div><br>';
print'
<div class="form-group">
<label for="inputEmail3" class="col-sm-4 text-left">USULAN DAN REKOMENDASI :</label>
</div>
<div class="form-group">
<div class="col-sm-5">';
echo '<p class="form-control-static">'.$row["usulan_rekomendasi"].' </p></div></div>';
}
}
$sql = "SELECT feedback FROM laporan_pelaksanaan where nipeg = '$user2'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div class="form-group">';
echo '<div class="col-sm-5">';
echo '<label for="exampleInputName2">Feedback : </label><br>';
echo $row['feedback'];
echo '</div>';
echo '</div>';
}
} else {
echo "0 results";
}
$status = null;
$sql = "SELECT status FROM laporan_pelaksanaan where nipeg = '$user2'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if($row["status"] == 0)
{
echo '<div id="tombol">';
echo '<button type="submit" class="btn btn-warning" name="tombol1" value="1" disabled="disabled">Belum Disetujui</button>';
echo '</div>';
}
else{
echo '<div id="tombol">';
echo '<button type="submit" class="btn btn-success" name="tombol1" value="0" disabled="disabled">Disetujui</button>';
echo '</div>';
}
}
} else {
echo '<div id="tombol">';
echo '<button type="submit" class="btn btn-warning" name="tombol1" value="1" disabled="disabled">Belum Disetujui</button>';
echo '</div>';
}
$conn->close();
?>
<br>
<!--div class="form-group">
<div class="col-sm-5">
<label for="exampleInputName2">Nomor Induk Pegawai</label>
<input type="text" class="form-control" id="exampleInputName2" placeholder="Nipeg Anda" name="nipeg">
</div>
</div-->
<input type="submit" name="Submit" value="Next" />
</form>
</div>
</div>
</div>
</body>
<script>
var nomor = 4;
function add()
{
$("#tambah").append(' <div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label"> '+nomor+' :</label><div class="col-sm-5" ><textarea type="text" class="form-control" placeholder="Text input" name="lmw1'+nomor+'"></textarea></div></div>');
nomor++;
}
var nomor2 = 4;
function add2()
{
$("#tambah2").append(' <div class="form-group"><label for="inputEmail3" class="col-sm-2 control-label"> '+nomor2+' :</label><div class="col-sm-5" ><textarea type="text" class="form-control" placeholder="Text input" name="lmw2'+nomor2+'"></textarea></div></div>');
nomor2++;
}
</script>
</html> | amadibra/sipeg | Form_PLT453.php | PHP | gpl-3.0 | 9,824 |
# Copyright (C) 2011 Pawel Stiasny
# 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/>.
import curses
import locale
import pickle
import os
import os.path
from fractions import Fraction
from .tablature import Fret, Chord, Bar, Tablature, ChordRange
from . import symbols
from . import music
from .player import Player
locale.setlocale(locale.LC_ALL, '')
encoding = locale.getpreferredencoding()
class Editor:
screen_initiated = False
cursor_prev_bar_x = 2
insert_duration = Fraction('1/4')
st = ''
file_name = None
terminate = False
visible_meta = 'meter'
continuous_playback = False
yanked_bar = None
string = 0
def __init__(self, stdscr, tab = Tablature()):
self.root = stdscr
self.tab = tab
self.nmap = {}
self.motion_commands = {}
self.commands = {}
self.player = Player()
def init_screen(self):
screen_height, screen_width = self.root.getmaxyx()
self.stdscr = curses.newwin(screen_height - 1, 0, 0, 0)
self.stdscr.keypad(1)
if self.file_name:
self.set_term_title(self.file_name + ' - VITABS')
else:
self.set_term_title('[unnamed] - VITABS')
self.status_line = curses.newwin(0, 0, screen_height - 1, 0)
self.status_line.scrollok(False)
self.first_visible_bar = self.tab.cursor_bar
self.redraw_view()
self.cy = 2
self.move_cursor()
curses.doupdate()
self.screen_initiated = True
def make_motion_cmd(self, f):
'''Turn a motion command into a normal mode command'''
def motion_wrap(ed, num):
m = f(ed, num)
if m is not None:
ed.make_motion(f(ed, num))
motion_wrap.__name__ = f.__name__
motion_wrap.__doc__ = f.__doc__
motion_wrap.nosidefx = True
return motion_wrap
def mark_changed(self):
if not getattr(self.tab, 'changed', False):
if self.file_name:
self.set_term_title(self.file_name + ' + - VITABS')
else:
self.set_term_title('[unnamed] + - VITABS')
self.tab.changed = True
def register_handlers(self, module):
'''Add commands defined in the module'''
for f in module.__dict__.values():
if hasattr(f, 'normal_keys'):
if getattr(f, 'motion_command', False):
for k in f.normal_keys:
self.nmap[k] = self.make_motion_cmd(f)
self.motion_commands[k] = f
else:
for k in f.normal_keys:
self.nmap[k] = f
if hasattr(f, 'handles_command'):
self.commands[f.handles_command] = f
def load_tablature(self, filename):
'''Unpickle tab from a file'''
try:
if os.path.isfile(filename):
infile = open(filename, 'rb')
self.tab = pickle.load(infile)
infile.close()
else:
self.tab = Tablature()
self.file_name = filename
self.set_term_title(filename + ' - VITABS')
self.st = '{0} ({1} bars, tuning: {2})'.format(
filename, len(self.tab.bars),
music.tuning_str(getattr(self.tab, 'tuning', music.standard_E)))
except:
self.st = 'Error: Can\'t open the specified file'
def save_tablature(self, filename):
'''Pickle tab to a file'''
if hasattr(self.tab, 'changed'):
self.tab.changed = False
delattr(self.tab, 'changed')
try:
outfile = open(filename, 'wb')
pickle.dump(self.tab, outfile)
outfile.close()
self.file_name = filename
except:
self.st = 'Error: Can\'t save'
self.set_term_title(filename + ' - VITABS')
def set_term_title(self, text):
'''Atempt to change virtual terminal window title'''
import sys
try:
term = os.environ['TERM']
if 'xterm' in term or 'rxvt' in term:
sys.stdout.write('\033]0;' + text + '\007')
sys.stdout.flush()
except:
pass
def draw_bar(self, y, x, bar):
'''Render a single bar at specified position'''
stdscr = self.stdscr
screen_width = self.stdscr.getmaxyx()[1]
stdscr.vline(y, x - 1, curses.ACS_VLINE, 6)
gcd = bar.gcd()
total_width = bar.total_width(gcd)
for i in range(6):
stdscr.hline(y + i, x, curses.ACS_HLINE, total_width)
x += 1
for chord in bar.chords:
for i in list(chord.strings.keys()):
if x < screen_width:
stdscr.addstr(y+i, x, str(chord.strings[i]), curses.A_BOLD)
# should it really be here?
if self.visible_meta == 'length':
dstr = music.len_str(chord.duration)
if x + len(dstr) < screen_width:
stdscr.addstr(y - 1, x, dstr)
width = int(chord.duration / gcd)
x = x + width*2 + 1
if x + 1 < screen_width:
stdscr.vline(y, x + 1, curses.ACS_VLINE, 6)
return x + 2
def draw_bar_meta(self, y, x, bar, prev_bar, index):
'''Print additional bar info at specified position'''
if self.visible_meta == 'meter':
if (prev_bar == None
or bar.sig_num != prev_bar.sig_num
or bar.sig_den != prev_bar.sig_den):
self.stdscr.addstr(
y, x,
str(bar.sig_num) + '/' + str(bar.sig_den))
elif self.visible_meta == 'number':
self.stdscr.addstr(y, x, str(index))
elif self.visible_meta == 'label':
if hasattr(bar, 'label'):
self.stdscr.addstr(y, x, bar.label)
def draw_tab(self, t):
'''Render the whole tablature'''
x = 2
y = 1
prev_bar = None
screen_height, screen_width = self.stdscr.getmaxyx()
for i, tbar in enumerate(t.bars[self.first_visible_bar - 1 : ]):
bar_width = tbar.total_width(tbar.gcd())
if x + bar_width >= screen_width and x != 2:
x = 2
y += 8
if y + 8 > screen_height:
break
self.draw_bar_meta(y, x, tbar, prev_bar, self.first_visible_bar + i)
x = self.draw_bar(y + 1, x, tbar)
self.last_visible_bar = i + self.first_visible_bar
prev_bar = tbar
def redraw_view(self):
'''Redraw tab window'''
self.stdscr.erase()
self.draw_tab(self.tab) # merge theese functions?
self.stdscr.noutrefresh()
def term_resized(self):
'''Called when the terminal window is resized, updates window sizes'''
height, width = self.root.getmaxyx()
self.status_line.mvwin(height - 1, 0)
self.stdscr.resize(height - 1, width)
self.redraw_view()
self.move_cursor()
def redraw_status(self):
'''Update status bar'''
width = self.status_line.getmaxyx()[1]
self.status_line.erase()
# general purpose status line
self.status_line.addstr(0, 0, self.st)
# position indicator
self.status_line.addstr(
0, width - 8,
'{0},{1}'.format(self.tab.cursor_bar, self.tab.cursor_chord))
# note length indicator
self.status_line.addstr(
0, width - 16,
str(self.tab.get_cursor_chord().duration))
# meter incomplete indicator
cb = self.tab.get_cursor_bar()
if cb.real_duration() != cb.required_duration():
self.status_line.addstr(0, width - 18, 'M')
self.status_line.noutrefresh()
def pager(self, lines):
'''Display a list of lines in a paged fashion'''
self.root.scrollok(True)
self.root.clear()
i = 0
h = self.root.getmaxyx()[0]
for line in lines:
self.root.addstr(i, 1, line)
i += 1
if i == h - 1:
self.root.addstr(i, 0, '<Space> NEXT PAGE')
self.root.refresh()
while self.get_char() != ord(' '): pass
self.root.clear()
i = 0
self.root.addstr(h - 1, 0, '<Space> CONTINUE')
while self.get_char(self.root) != ord(' '): pass
self.root.scrollok(False)
self.root.clear()
self.redraw_view()
def move_cursor(self, new_bar=None, new_chord=None, cache_lengths=False):
'''Set new cursor position'''
if not new_bar: new_bar = self.tab.cursor_bar
if not new_chord: new_chord = self.tab.cursor_chord
if not cache_lengths: self.cursor_prev_bar_x = None
# make sure the cursor stays inside the visible bar range
if new_bar < self.first_visible_bar or new_bar > self.last_visible_bar:
self.first_visible_bar = new_bar
self.redraw_view()
newbar_i = self.tab.bars[new_bar - 1]
# calculate the width of preceeding bars
screen_height, screen_width = self.stdscr.getmaxyx()
if new_bar != self.tab.cursor_bar or self.cursor_prev_bar_x == None:
self.cursor_prev_bar_x = 2
self.cy = 2
if new_bar > self.first_visible_bar:
for b in self.tab.bars[self.first_visible_bar - 1 : new_bar - 1]:
barw = b.total_width(b.gcd()) + 1
self.cursor_prev_bar_x += barw
if (self.cursor_prev_bar_x > screen_width and
self.cursor_prev_bar_x != 2 + barw):
self.cursor_prev_bar_x = 2 + barw
self.cy += 8
# should the cursor bar be wrapped?
newbar_w = newbar_i.total_width(newbar_i.gcd()) + 1
if newbar_w + self.cursor_prev_bar_x > screen_width:
self.cursor_prev_bar_x = 2
self.cy += 8
# width of preceeding chords
offset = 1
gcd = newbar_i.gcd()
for c in newbar_i.chords[:new_chord - 1]:
offset += int(c.duration / gcd)*2 + 1
self.tab.cursor_bar = new_bar
self.tab.cursor_chord = new_chord
self.cx = self.cursor_prev_bar_x + offset
def make_motion(self, pos):
self.move_cursor(pos[0], 1 if pos[1] is None else pos[1],
cache_lengths=True)
def go_left(self, num=1):
'''Returns position pair [num] chords left from the cursor'''
if self.tab.cursor_chord <= num:
if self.tab.cursor_bar > 1:
return (self.tab.cursor_bar - 1,
len(self.tab.bars[self.tab.cursor_bar - 2].chords))
else:
return (1, 1)
else:
return (self.tab.cursor_bar, self.tab.cursor_chord - num)
def move_cursor_left(self):
self.make_motion(self.go_left())
def go_right(self, num=1):
'''Returns position pair [num] chords right from the cursor'''
if self.tab.cursor_chord + num > len(self.tab.get_cursor_bar().chords):
if self.tab.cursor_bar < len(self.tab.bars):
return (self.tab.cursor_bar + 1, 1)
else:
return self.tab.last_position()
else:
return (self.tab.cursor_bar, self.tab.cursor_chord + num)
def move_cursor_right(self):
self.make_motion(self.go_right())
def play_range(self, fro, to):
def redraw_playback_status():
self.st = 'Playing... <CTRL-C> to abort'
self.redraw_status()
curses.setsyx(self.cy - 1, self.cx)
curses.doupdate()
def move_to_beginning():
self.move_cursor(fro[0], fro[1])
redraw_playback_status()
return True
def update_playback_status():
self.move_cursor_right()
redraw_playback_status()
return True
p = self.player
p.before_repeat = move_to_beginning
p.post_play_chord = update_playback_status
p.set_instrument(getattr(self.tab, 'instrument', 24))
p.play(ChordRange(self.tab, fro, to), self.continuous_playback)
self.st = ''
def get_char(self, parent=None):
'''Get a character from terminal, handling things like terminal
resize'''
if parent is None:
parent = self.stdscr
c = parent.getch()
if c == curses.KEY_RESIZE:
self.term_resized()
return c
def insert_mode(self, free_motion=False):
'''Switch to insert mode and listen for keys'''
if free_motion:
self.st = '-- REPLACE --'
else:
self.st = '-- INSERT --'
self.redraw_view()
insert_beg = self.tab.cursor_position()
insert_end = insert_beg
while True:
self.redraw_status()
curses.setsyx(self.cy + self.string, self.cx)
curses.doupdate()
c = self.get_char()
if c == 27: # ESCAPE
self.st = ''
break
elif ord('0') <= c <= ord('9'):
curch = self.tab.get_cursor_chord()
string = self.string
if string in curch.strings and curch.strings[string].fret < 10:
st_dec = curch.strings[string].fret * 10
curch.strings[string].fret = st_dec + c - ord('0')
else:
curch.strings[string] = Fret(c - ord('0'))
self.redraw_view()
elif c == curses.KEY_DC or c == ord('x'):
if self.string in self.tab.get_cursor_chord().strings:
del self.tab.get_cursor_chord().strings[self.string]
self.redraw_view()
elif c == curses.KEY_UP or c == ord('k'):
self.string = max(self.string - 1, 0)
elif c == curses.KEY_DOWN or c == ord('j'):
self.string = min(self.string + 1, 5)
elif c == ord('E'): self.string = 5
elif c == ord('A'): self.string = 4
elif c == ord('D'): self.string = 3
elif c == ord('G'): self.string = 2
elif c == ord('B'): self.string = 1
elif c == ord('e'): self.string = 0
elif c == ord(' '):
# TODO: don't repeat yourself...
self.tab.get_cursor_bar().chords.insert(
self.tab.cursor_chord,
Chord(self.insert_duration))
self.redraw_view()
self.move_cursor_right()
self.move_cursor()
insert_end = (insert_end[0], insert_end[1] + 1)
elif (c == curses.KEY_RIGHT or c == ord('l')) and not free_motion:
right = (self.tab.cursor_bar, self.tab.cursor_chord + 1)
if right > insert_end:
self.tab.get_cursor_bar().chords.insert(
self.tab.cursor_chord,
Chord(self.insert_duration))
self.redraw_view()
insert_end = right
self.make_motion(right)
self.move_cursor()
elif (c == curses.KEY_LEFT or c == ord('h')) and not free_motion:
left = self.go_left()
if left >= insert_beg:
self.make_motion(left)
elif c == curses.KEY_RIGHT or c == ord('l') and free_motion:
self.move_cursor_right()
elif (c == curses.KEY_LEFT or c == ord('h')) and free_motion:
self.move_cursor_left()
try:
# try to find a symbol in key -> symbol dict
sym = symbols.keys[c]
fr = self.tab.get_cursor_chord().strings[self.string]
if sym in fr.symbols:
fr.symbols.remove(sym)
else:
fr.symbols.append(sym)
self.redraw_view()
except KeyError:
pass
def exec_command(self, args, apply_to=None):
cmd = args[0]
try:
if apply_to is not None:
try:
self.commands[cmd](self, args, apply_to=apply_to)
except TypeError:
self.st = 'Command does not accept range'
else:
self.commands[cmd](self, args)
except KeyError:
self.st = 'Invalid command'
def command_mode(self):
'''Read a command'''
import sys
curses.echo()
self.status_line.erase()
self.status_line.addstr(0, 0, ":")
try:
line = self.status_line.getstr(0, 1).decode(encoding)
except KeyboardInterrupt:
line = ''
words = line.split(' ')
cmd = words[0]
curses.noecho()
if cmd:
try:
self.exec_command(words)
except:
exc = sys.exc_info()
self.st = "Exception: " + str(exc[0].__name__) + ": " + \
str(exc[1])
self.redraw_view()
def _is_number(self, char):
return (ord('0') <= char <= ord('9'))
def _parse_numeric_arg(self, c, num_arg):
if num_arg:
num_arg = num_arg * 10 + c - ord('0')
elif c != ord('0'):
num_arg = c - ord('0')
return num_arg
def expect_range(self, num=None, whole_bar_cmd=None):
'''Get a motion command and return a range from cursor position to
motion'''
num_motion = None
c = self.get_char()
while self._is_number(c) and (c != ord('0') or num_motion):
num_motion = self._parse_numeric_arg(c, num_motion)
c = self.get_char()
if num_motion and num: total_num = num * num_motion
elif num_motion: total_num = num_motion
else: total_num = num
cur = self.tab.cursor_position()
if whole_bar_cmd and c == whole_bar_cmd:
return ChordRange(self.tab,
(cur[0], 1),
(cur[0], None))
try:
dest = self.motion_commands[c](self, total_num)
if dest:
if dest > cur:
return ChordRange(self.tab, cur, dest)
else:
return ChordRange(self.tab, dest, cur)
except KeyError:
return None
def normal_mode(self):
'''Enter normal mode, returns on quit'''
num_arg = None
t = self.tab
while True:
if self.terminate:
break
self.redraw_status()
self.st = ''
curses.setsyx(self.cy - 1, self.cx)
curses.doupdate()
# TODO: accept multi-char commands
try:
c = self.get_char()
if c in self.nmap:
cmd = self.nmap[c]
cmd(self, num_arg)
if not (getattr(cmd, 'nosidefx', False)):
self.mark_changed()
self.redraw_view()
if self._is_number(c):
num_arg = self._parse_numeric_arg(c, num_arg)
if num_arg: self.st = str(num_arg)
else:
# reset after a command
num_arg = None
if c == 27: # ESCAPE
self.st = ''
except KeyboardInterrupt:
self.st = 'Use :q<Enter> to quit'
| pstiasny/VITABS | vitabs/editor.py | Python | gpl-3.0 | 20,458 |
/*
* myTask.hpp
*
* Created on: 10-11-2012
* Author: lukee
*/
#ifndef ATASK_HPP_
#define ATASK_HPP_
#include "stm32f4xx.h"
/* FreeRTOS includes */
#include "FreeRTOS.h"
#include "task.h"
#include "semphr.h"
//my include
#include "hw_config.h"
#include "math.h"
static const uint8_t queueSIZE = 6;
extern "C" void vBALANCETask(void *pvParameters);
extern "C++"
{
class CBalance
{
private:
static const uint16_t N = 32; //table size
static const float a, b, c, d; //exponential coefficients
float accelXFloat, accelYFloat;
int8_t meanX[N], meanY[N];
int16_t meanXSigma, meanYSigma, accelX, accelY;
int16_t accelXCal, accelYCal;
static const uint8_t maxValue; //maksymalna wartosc wskazania przy wychyleniu 90st
static const uint8_t cmpValue; //wartosc do porownywania przyspieszenia
uint16_t k, j;
//void GetData(void);
static int temp;
public:
int8_t xBuffer_receive[queueSIZE]; //bufor wejsciowy
CBalance(void);
//~CBalance(void);
void Calibrate(void);
void Calculate(void);
void SetData(void);
};
}
#endif /* ATASK_HPP_ */
| darklukee/poziomica | inc/aTask.hpp | C++ | gpl-3.0 | 1,061 |
/* =Spatial directions
* ------------------------------------------------------------ */
Direction = new (function() { /* jshint ignore:line */
this.n = new Vector( 0, 1); this.up = this.n;
this.ne = new Vector( 1, 1);
this.e = new Vector( 1, 0); this.right = this.e;
this.se = new Vector( 1, -1);
this.s = new Vector( 0, -1); this.bottom = this.s;
this.sw = new Vector(-1, -1);
this.w = new Vector(-1, 0); this.left = this.w;
this.nw = new Vector(-1, 1);
})();
Directions = [ "n", "ne", "e", "se", "s", "sw", "w", "nw" ];
Directions.vectors = [ new Vector(0, 1), new Vector(1, 1),
new Vector(1, 0), new Vector(1, -1), new Vector(0, -1),
new Vector(-1, -1), new Vector(-1, 0), new Vector(-1, 1) ];
Directions._indexOf = function(direction) {
for (var i = 0; i < Directions.vectors.length; ++i)
if (Directions.vectors[i].equal(direction))
return i;
assert(false,
"Directions._indexOf: Invalid direction: "+direction);
};
Direction.vectorToDirectionName = function(directionVector) {
return Directions[Directions._indexOf(directionVector)];
};
Direction.vectorToDirection = function(vector) {
return new Vector(vector.x ? 1 : 0, vector.y ? 1 : 0);
};
Direction.vectorToDistance = function(vector) {
return Math.max(vector.x, vector.y);
};
Direction.rotate = function(direction, degree) {
var resolution = 45;
var shift = degree / resolution;
assert(shift - (shift>>0) === 0,
"Direction.rotate: "+"'degree' ("+degree+
") must be a multiple of "+resolution);
return Directions.vectors[(Directions._indexOf(direction) + shift +
Directions.length) % Directions.length];
};
Direction.random = function() {
var x, y, vec;
while (!x && !y) {
x = randomInt(-1, 1);
y = randomInt(-1, 1);
}
return new Vector(x, y);
};
Direction.forEach = function(callback, thisArg) {
var self = this;
Directions.forEach(
function(str) { callback(self[str], str, self); }, thisArg);
};
/* Iterate through directions by gradually going farther
* from 'initialDirection' */
Direction.forEachFrom =
function(initialDirection, callback, thisArg) {
var initI = Directions.indexOf(
Direction.vectorToDirectionName(initialDireciton));
var curI = initI;
var upI, loI;
function incrementUp() {
return upI += upI < Directions.length ? 1 : 0; }
function incrementLo() {
return loI -= loI > 0 ? 1 : Directions.length; }
while (upI !== initI && loI !== initI) {
callback.call(thisArg,
directions.vectors[curI], directions[curI], this);
if (curI === upI) { curI = incrementUp(); }
else { curI = incrementLo(); }
}
};
Direction.some = function(callback, thisArg) {
var self = this;
return Directions.some(
function(str) {
return callback.call(thisArg, self[str], str, self); },
thisArg);
};
| lleaff/ASCII-life | src/js/lib/world_directions.js | JavaScript | gpl-3.0 | 2,772 |
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2022 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM 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.
*
* EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Modules\Crm\Tools\MassEmail;
use Laminas\Mail\Message;
use Espo\Entities\EmailTemplate;
use Espo\Repositories\EmailAddress as EmailAddressRepository;
use Espo\Core\{
Exceptions\Error,
ORM\EntityManager,
ServiceFactory,
Utils\Config,
Utils\Language,
Mail\EmailSender,
Mail\Sender,
Mail\Mail\Header\XQueueItemId,
Utils\Log,
};
use Espo\{
Modules\Crm\Entities\EmailQueueItem,
Modules\Crm\Entities\Campaign,
Modules\Crm\Entities\MassEmail,
Modules\Crm\Services\Campaign as CampaignService,
Services\EmailTemplate as EmailTemplateService,
ORM\Entity,
Entities\Email,
};
use Exception;
use DateTime;
class Processor
{
private $config;
private $serviceFactory;
private $entityManager;
private $defaultLanguage;
private $emailSender;
protected const MAX_ATTEMPT_COUNT = 3;
protected const MAX_PER_HOUR_COUNT = 10000;
private $campaignService = null;
private $emailTemplateService = null;
protected $log;
public function __construct(
Config $config,
ServiceFactory $serviceFactory,
EntityManager $entityManager,
Language $defaultLanguage,
EmailSender $emailSender,
Log $log
) {
$this->config = $config;
$this->serviceFactory = $serviceFactory;
$this->entityManager = $entityManager;
$this->defaultLanguage = $defaultLanguage;
$this->emailSender = $emailSender;
$this->log = $log;
}
public function process(MassEmail $massEmail, bool $isTest = false): void
{
$maxBatchSize = $this->config->get('massEmailMaxPerHourCount', self::MAX_PER_HOUR_COUNT);
if (!$isTest) {
$threshold = new DateTime();
$threshold->modify('-1 hour');
$sentLastHourCount = $this->entityManager
->getRDBRepository(EmailQueueItem::ENTITY_TYPE)
->where([
'status' => EmailQueueItem::STATUS_SENT,
'sentAt>' => $threshold->format('Y-m-d H:i:s'),
])
->count();
if ($sentLastHourCount >= $maxBatchSize) {
return;
}
$maxBatchSize = $maxBatchSize - $sentLastHourCount;
}
$queueItemList = $this->entityManager
->getRDBRepository(EmailQueueItem::ENTITY_TYPE)
->where([
'status' => EmailQueueItem::STATUS_PENDING,
'massEmailId' => $massEmail->getId(),
'isTest' => $isTest,
])
->limit(0, $maxBatchSize)
->find();
$templateId = $massEmail->get('emailTemplateId');
if (!$templateId) {
$this->setFailed($massEmail);
return;
}
$campaign = null;
$campaignId = $massEmail->get('campaignId');
if ($campaignId) {
$campaign = $this->entityManager->getEntity('Campaign', $campaignId);
}
$emailTemplate = $this->entityManager->getEntity('EmailTemplate', $templateId);
if (!$emailTemplate) {
$this->setFailed($massEmail);
return;
}
/** @var iterable<\Espo\Entities\Attachment> */
$attachmentList = $this->entityManager
->getRDBRepository('EmailTemplate')
->getRelation($emailTemplate, 'attachments')
->find();
$smtpParams = null;
if ($massEmail->get('inboundEmailId')) {
$inboundEmail = $this->entityManager->getEntity('InboundEmail', $massEmail->get('inboundEmailId'));
if (!$inboundEmail) {
throw new Error(
"Group Email Account '" . $massEmail->get('inboundEmailId') . "' is not available."
);
}
if (
$inboundEmail->get('status') !== 'Active' ||
!$inboundEmail->get('useSmtp') ||
!$inboundEmail->get('smtpIsForMassEmail')
) {
throw new Error(
"Group Email Account '" . $massEmail->get('inboundEmailId') . "' can't be used for Mass Email."
);
}
$inboundEmailService = $this->serviceFactory->create('InboundEmail');
$smtpParams = $inboundEmailService->getSmtpParamsFromAccount($inboundEmail);
if (!$smtpParams) {
throw new Error(
"Group Email Account '" . $massEmail->get('inboundEmailId') . "' has no SMTP params."
);
}
if ($inboundEmail->get('replyToAddress')) {
$smtpParams['replyToAddress'] = $inboundEmail->get('replyToAddress');
}
}
foreach ($queueItemList as $queueItem) {
$this->sendQueueItem(
$queueItem,
$massEmail,
$emailTemplate,
$attachmentList,
$campaign,
$isTest,
$smtpParams
);
}
if (!$isTest) {
$countLeft = $this->entityManager
->getRDBRepository(EmailQueueItem::ENTITY_TYPE)
->where([
'status' => EmailQueueItem::STATUS_PENDING,
'massEmailId' => $massEmail->getId(),
'isTest' => false,
])
->count();
if ($countLeft == 0) {
$massEmail->set('status', MassEmail::STATUS_COMPLETE);
$this->entityManager->saveEntity($massEmail);
}
}
}
protected function getPreparedEmail(
EmailQueueItem $queueItem,
MassEmail $massEmail,
EmailTemplate $emailTemplate,
Entity $target,
iterable $trackingUrlList = []
): ?Email {
$templateParams = [
'parent' => $target,
];
$emailData = $this->getEmailTemplateService()->parseTemplate($emailTemplate, $templateParams);
$body = $emailData['body'];
$optOutUrl = $this->getSiteUrl() . '?entryPoint=unsubscribe&id=' . $queueItem->getId();
$optOutLink =
'<a href="' . $optOutUrl . '">' .
$this->defaultLanguage->translate('Unsubscribe', 'labels', 'Campaign') .
'</a>';
$body = str_replace('{optOutUrl}', $optOutUrl, $body);
$body = str_replace('{optOutLink}', $optOutLink, $body);
foreach ($trackingUrlList as $trackingUrl) {
$url = $this->getSiteUrl() .
'?entryPoint=campaignUrl&id=' . $trackingUrl->getId() . '&queueItemId=' . $queueItem->getId();
$body = str_replace($trackingUrl->get('urlToUse'), $url, $body);
}
if (
!$this->config->get('massEmailDisableMandatoryOptOutLink') &&
stripos($body, '?entryPoint=unsubscribe&id') === false
) {
if ($emailData['isHtml']) {
$body .= "<br><br>" . $optOutLink;
}
else {
$body .= "\n\n" . $optOutUrl;
}
}
$trackImageAlt = $this->defaultLanguage->translate('Campaign', 'scopeNames');
$trackOpenedUrl = $this->getSiteUrl() . '?entryPoint=campaignTrackOpened&id=' . $queueItem->getId();
$trackOpenedHtml =
'<img alt="' . $trackImageAlt . '" width="1" height="1" border="0" src="' . $trackOpenedUrl . '">';
if ($massEmail->get('campaignId') && $this->config->get('massEmailOpenTracking')) {
if ($emailData['isHtml']) {
$body .= '<br>' . $trackOpenedHtml;
}
}
$emailData['body'] = $body;
$email = $this->entityManager->getEntity('Email');
$email->set($emailData);
$emailAddress = $target->get('emailAddress');
if (empty($emailAddress)) {
return null;
}
$email->set('to', $emailAddress);
if ($massEmail->get('fromAddress')) {
$email->set('from', $massEmail->get('fromAddress'));
}
if ($massEmail->get('replyToAddress')) {
$email->set('replyTo', $massEmail->get('replyToAddress'));
}
return $email;
}
protected function prepareQueueItemMessage(
EmailQueueItem $queueItem,
Sender $sender,
Message $message,
array &$params
): void {
$header = new XQueueItemId();
$header->setId($queueItem->getId());
$message->getHeaders()->addHeader($header);
$message->getHeaders()->addHeaderLine('Precedence', 'bulk');
if (!$this->config->get('massEmailDisableMandatoryOptOutLink')) {
$optOutUrl = $this->getSiteUrl() . '?entryPoint=unsubscribe&id=' . $queueItem->getId();
$message->getHeaders()->addHeaderLine('List-Unsubscribe', '<' . $optOutUrl . '>');
}
$fromAddress = $params['fromAddress'] ?? $this->config->get('outboundEmailFromAddress');
if ($this->config->get('massEmailVerp')) {
if ($fromAddress && strpos($fromAddress, '@')) {
$bounceAddress = explode('@', $fromAddress)[0] . '+bounce-qid-' . $queueItem->getId() .
'@' . explode('@', $fromAddress)[1];
$sender->withEnvelopeOptions([
'from' => $bounceAddress,
]);
}
}
}
protected function setFailed(MassEmail $massEmail): void
{
$massEmail->set('status', MassEmail::STATUS_FAILED);
$this->entityManager->saveEntity($massEmail);
$queueItemList = $this->entityManager
->getRDBRepository(EmailQueueItem::ENTITY_TYPE)
->where([
'status' => EmailQueueItem::STATUS_PENDING,
'massEmailId' => $massEmail->getId(),
])
->find();
foreach ($queueItemList as $queueItem) {
$queueItem->set('status', EmailQueueItem::STATUS_FAILED);
$this->entityManager->saveEntity($queueItem);
}
}
/**
* @param iterable<\Espo\Entities\Attachment> $attachmentList
*/
protected function sendQueueItem(
EmailQueueItem $queueItem,
MassEmail $massEmail,
EmailTemplate $emailTemplate,
$attachmentList = [],
?Campaign $campaign = null,
bool $isTest = false,
$smtpParams = null
): bool {
$queueItemFetched = $this->entityManager->getEntity($queueItem->getEntityType(), $queueItem->getId());
if ($queueItemFetched->get('status') !== EmailQueueItem::STATUS_PENDING) {
return false;
}
$queueItem->set('status', EmailQueueItem::STATUS_SENDING);
$this->entityManager->saveEntity($queueItem);
$target = $this->entityManager->getEntity($queueItem->get('targetType'), $queueItem->get('targetId'));
$emailAddress = null;
if ($target) {
$emailAddress = $target->get('emailAddress');
}
if (
!$target ||
!$target->getId() ||
!$emailAddress
) {
$queueItem->set('status', EmailQueueItem::STATUS_FAILED);
$this->entityManager->saveEntity($queueItem);
return false;
}
/** @var EmailAddressRepository $emailAddressRepository */
$emailAddressRepository = $this->entityManager->getRepository('EmailAddress');
$emailAddressRecord = $emailAddressRepository->getByAddress($emailAddress);
if ($emailAddressRecord) {
if ($emailAddressRecord->get('invalid') || $emailAddressRecord->get('optOut')) {
$queueItem->set('status', EmailQueueItem::STATUS_FAILED);
$this->entityManager->saveEntity($queueItem);
return false;
}
}
$trackingUrlList = [];
if ($campaign) {
$trackingUrlList = $this->entityManager
->getRDBRepository('Campaign')
->getRelation($campaign, 'trackingUrls')
->find();
}
$email = $this->getPreparedEmail($queueItem, $massEmail, $emailTemplate, $target, $trackingUrlList);
if (!$email) {
return false;
}
if ($email->get('replyToAddress')) {
unset($smtpParams['replyToAddress']);
}
if ($campaign) {
$email->setLinkMultipleIdList(
'teams',
$campaign->getLinkMultipleIdList('teams')
);
}
$params = [];
if ($massEmail->get('fromName')) {
$params['fromName'] = $massEmail->get('fromName');
}
if ($massEmail->get('replyToName')) {
$params['replyToName'] = $massEmail->get('replyToName');
}
try {
$attemptCount = $queueItem->get('attemptCount');
$attemptCount++;
$queueItem->set('attemptCount', $attemptCount);
$sender = $this->emailSender->create();
if ($smtpParams) {
$sender->withSmtpParams($smtpParams);
}
$message = new Message();
$this->prepareQueueItemMessage($queueItem, $sender, $message, $params);
$sender
->withParams($params)
->withMessage($message)
->withAttachments($attachmentList)
->send($email);
}
catch (Exception $e) {
$maxAttemptCount = $this->config->get('massEmailMaxAttemptCount', self::MAX_ATTEMPT_COUNT);
if ($queueItem->get('attemptCount') >= $maxAttemptCount) {
$queueItem->set('status', EmailQueueItem::STATUS_FAILED);
}
else {
$queueItem->set('status', EmailQueueItem::STATUS_PENDING);
}
$this->entityManager->saveEntity($queueItem);
$this->log->error('MassEmail#sendQueueItem: [' . $e->getCode() . '] ' .$e->getMessage());
return false;
}
$emailObject = $emailTemplate;
if ($massEmail->get('storeSentEmails') && !$isTest) {
$this->entityManager->saveEntity($email);
$emailObject = $email;
}
$queueItem->set('emailAddress', $target->get('emailAddress'));
$queueItem->set('status', EmailQueueItem::STATUS_SENT);
$queueItem->set('sentAt', date('Y-m-d H:i:s'));
$this->entityManager->saveEntity($queueItem);
if ($campaign) {
$this->getCampaignService()->logSent(
$campaign->getId(),
$queueItem->getId(),
$target,
$emailObject,
$target->get('emailAddress'),
null,
$queueItem->get('isTest')
);
}
return true;
}
protected function getEmailTemplateService(): EmailTemplateService
{
if (!$this->emailTemplateService) {
$this->emailTemplateService = $this->serviceFactory->create('EmailTemplate');
}
return $this->emailTemplateService;
}
protected function getCampaignService(): CampaignService
{
if (!$this->campaignService) {
$this->campaignService = $this->serviceFactory->create('Campaign');
}
return $this->campaignService;
}
protected function getSiteUrl(): string
{
return $this->config->get('massEmailSiteUrl') ?? $this->config->get('siteUrl');
}
}
| espocrm/espocrm | application/Espo/Modules/Crm/Tools/MassEmail/Processor.php | PHP | gpl-3.0 | 16,942 |
/*
* Copyright (C) 2005-2010 Erik Nilsson, software on versionstudio 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 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/>.
*/
#include "common.h"
#include "aboutdialog.h"
#include "hyperlinks.h"
INT CALLBACK AboutDialog::dialogProc(HWND hWnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
switch ( msg )
{
case WM_COMMAND:
{
switch ( wParam )
{
case IDC_BUTTON_CLOSE:
{
EndDialog(hWnd, NULL);
}
break;
case IDC_STATIC_URL:
{
char sz[255] = {0};
GetWindowText(GetDlgItem(hWnd,IDC_STATIC_URL),sz,255);
ShellExecute(hWnd,"open",sz,NULL,NULL,SW_SHOWNORMAL);
}
break;
}
}
break;
}
return 0;
}
void AboutDialog::dialogInit(HWND hWnd,LPARAM lParam)
{
SetWindowText(GetDlgItem(hWnd,IDC_STATIC_APPLICATION), TEXT(APP_NAME) TEXT(" ") TEXT(APP_VERSION) TEXT(APP_MILESTONE));
ConvertStaticToHyperlink(GetDlgItem(hWnd,IDC_STATIC_URL));
WinUtil::WindowUtil::centerParent(hWnd);
SetFocus(GetDlgItem(hWnd, IDC_BUTTON_CLOSE));
}
| versionstudio/vibestreamer | src/win32/AboutDialog.cpp | C++ | gpl-3.0 | 1,655 |
namespace Ribbonizer.Wrappers.Microsoft
{
using System.Diagnostics.CodeAnalysis;
using System.Windows.Controls;
using System.Windows.Controls.Ribbon;
using Ribbonizer.Ribbon.Groups;
[ExcludeFromCodeCoverage]
internal class RibbonGroupWrapper : IRibbonGroupView, IWrapper<RibbonGroup>
{
private readonly RibbonGroup ribbonGroup;
public RibbonGroupWrapper(RibbonGroup ribbonGroup)
{
this.ribbonGroup = ribbonGroup;
}
public RibbonGroup Wrapped
{
get { return this.ribbonGroup; }
}
public string Caption
{
get { return (string)this.ribbonGroup.Header; }
set { this.ribbonGroup.Header = value; }
}
public void AddItem(object item)
{
var wrapper = item as IWrapper<Control>;
if (wrapper != null)
{
this.ribbonGroup.Items.Add(wrapper.Wrapped);
}
else
{
this.ribbonGroup.Items.Add(item);
}
}
}
} | BrunoJuchli/RibbonizerSample | Ribbonizer.Wrappers.Microsoft/RibbonGroupWrapper.cs | C# | gpl-3.0 | 1,094 |
require 'rails_helper'
RSpec.describe MultipleChoiceQuestion, type: :model do
describe "#correct" do
context "answered questions (right)" do
let(:answered_question) { build(:multiple_choice_question) }
it { expect(answered_question).to be_valid }
it { expect(answered_question.correct?).to eq(true) }
end
context "answered questions (wrong)" do
let(:answered_question) { build(:multiple_choice_question, :wrong) }
it { expect(answered_question).to be_valid }
it { expect(answered_question.correct?).to eq(false) }
end
context "unanswered questions" do
let(:unanswered_question) do
build(:multiple_choice_question, :answers => [
FactoryGirl.build(:true_false_answer, :unset_wrong, :answer_text => "unset_wrong"),
FactoryGirl.build(:true_false_answer, :unset_right, :answer_text => "unset_right") ] )
end
it { expect(unanswered_question).to be_valid }
it { expect(unanswered_question.correct?).to be false }
end
end
end
| dtu-compute/dtu-quiz | spec/models/multiple_choice_question_spec.rb | Ruby | gpl-3.0 | 1,050 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="es" sourcelanguage="en">
<context>
<name>XmppStream</name>
<message>
<source>Password request</source>
<translation>Solicitar contraseña</translation>
</message>
<message>
<source>Enter password for <b>%1</b></source>
<translation>Entrar la contraseña para <b>%1</b></translation>
</message>
<message>
<source>Connection not specified</source>
<translation>Conexión sin definir</translation>
</message>
</context>
<context>
<name>XmppStreams</name>
<message>
<source>XMPP Streams Manager</source>
<translation>Administrador de flujos XMPP</translation>
</message>
<message>
<source>Allows other modules to create XMPP streams and get access to them</source>
<translation>Permite a otros módulos crear flujos XMPP y tener acceso a ellos</translation>
</message>
<message>
<source>XMPP stream destroyed</source>
<translation>Flujo XMP destruido</translation>
</message>
<message>
<source>Secure connection is not established</source>
<translation>No se ha podido establecer una conexión segura</translation>
</message>
<message>
<source>Connection closed unexpectedly</source>
<translation>La conexión ha cerrado inesperadamente</translation>
</message>
<message>
<source>Failed to start connection</source>
<translation>Error al iniciar la conexión</translation>
</message>
</context>
</TS>
| sanchay160887/vacuum-im | src/translations/es/xmppstreams.ts | TypeScript | gpl-3.0 | 1,626 |
/*
* Copyright (c) 2017-2020 Amir Czwink (amir130@hotmail.de)
*
* This file is part of Std++.
*
* Std++ 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.
*
* Std++ 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 Std++. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
//Local
#include "../../Multimedia/Packet.hpp"
#include "../../Multitasking/Mutex.hpp"
#include "../../Rendering/Texture2D.hpp"
#include "PathRenderTargetWidget.hpp"
namespace StdXX
{
namespace UI
{
class STDPLUSPLUS_API VideoWidget : public PathRenderTargetWidget
{
public:
//Constructor
inline VideoWidget(const WidgetFrameBufferSetup& frameBufferSetup)
: PathRenderTargetWidget(frameBufferSetup),
texture(nullptr), nextFrame(nullptr)
{
}
//Destructor
~VideoWidget();
//Methods
void UpdatePicture(Multimedia::Packet *videoPacket, Math::Size<uint16> frameSize);
protected:
//Event handlers
void OnRealized() override;
private:
//Members
Rendering::Texture2D *texture;
Multimedia::Packet *nextFrame;
Math::Size<uint16> frameSize;
Mutex frameLock;
//Eventhandlers
void OnPaint(PaintEvent& event) override;
};
}
} | aczwink/ACStdLib | include/Std++/UI/Displays/VideoWidget.hpp | C++ | gpl-3.0 | 1,633 |
package net.spencer.test.init;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.spencer.test.Reference;
import net.spencer.test.entity.EntityBomb;
import net.spencer.test.entity.EntityFireball;
import net.spencer.test.items.ItemBomb;
import net.spencer.test.items.ItemCheese;
import net.spencer.test.items.ItemCheeseStick;
import net.spencer.test.items.ItemFillStick;
import net.spencer.test.items.ItemFireball;
import net.spencer.test.items.ItemMCBowl;
import net.spencer.test.items.ItemMagicStick;
public class ModItems {
public static Item cheese, magic_stick, bomb, mcbowl, cheese_stick, fill_stick, fireball;
public static void init () {
cheese = new ItemCheese(5, 1, false).setAlwaysEdible();
mcbowl = new ItemMCBowl(8, 1.5f, false).setAlwaysEdible();
magic_stick = new ItemMagicStick();
cheese_stick = new ItemCheeseStick();
bomb = new ItemBomb();
fill_stick = new ItemFillStick();
fireball = new ItemFireball();
}
public static void register () {
GameRegistry.register(cheese);
GameRegistry.register(magic_stick);
GameRegistry.register(bomb);
GameRegistry.register(mcbowl);
GameRegistry.register(cheese_stick);
GameRegistry.register(fill_stick);
GameRegistry.register(fireball);
}
public static void registerRenders () {
registerRender (cheese);
registerRender (magic_stick);
registerRender (bomb);
registerRender (mcbowl);
registerRender (cheese_stick);
registerRender (fill_stick);
registerRender (fireball);
//RenderingRegistry.registerEntityRenderingHandler(entityClass, RenderSnowball());
}
private static void registerRender (Item item) {
System.out.println(item.getRegistryName());
Minecraft.getMinecraft().getRenderItem().getItemModelMesher()
.register(item, 0, new ModelResourceLocation(item.getRegistryName(), "inventory"));
}
}
| SpencerFranklin/MinecraftMod | src/main/java/net/spencer/test/init/ModItems.java | Java | gpl-3.0 | 2,194 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InsuranceSystem.Library.Models.Catalogs;
namespace InsuranceSystem.Library.Models.Documents
{
public class PostBlankItem
{
public int Id { get; set; }
public int PostBlankId { get; set; }
public virtual PostBlank PostBlank { get; set; }
public int BlankId { get; set; }
public virtual Blank Blank { get; set; }
public decimal Price { get; set; }
}
}
| mishakos/InsuranceSystem.Library | InsuranceSystem.Library/Models/Documents/PostBlankItem.cs | C# | gpl-3.0 | 537 |
package in.nikitapek.dueler.util;
import com.google.gson.reflect.TypeToken;
import in.nikitapek.dueler.Arena;
import org.bukkit.Location;
import java.lang.reflect.Type;
import java.util.TreeSet;
@SuppressWarnings("rawtypes")
public final class SupplementaryTypes {
public static final Type LOCATION = new TypeToken<Location>() {
}.getType();
public static final Type ARENA = new TypeToken<Arena>() {
}.getType();
public static final Type TREESET = new TypeToken<TreeSet>() {
}.getType();
private SupplementaryTypes() {
}
}
| MinerAp/dueler | src/main/java/in/nikitapek/dueler/util/SupplementaryTypes.java | Java | gpl-3.0 | 559 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Produces a graph of log accesses for a user
*
* Generates an image representing the log data in a graphical manner for a user.
*
* @package report_log
* @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require("../../config.php");
require_once("$CFG->libdir/graphlib.php");
require_once($CFG->dirroot.'/report/log/locallib.php');
$id = required_param('id', PARAM_INT); // Course ID
$type = required_param('type', PARAM_FILE); // Graph Type
$user = required_param('user', PARAM_INT); // Student ID
$date = optional_param('date', 0, PARAM_INT); // A time of a day (in GMT)
$url = new moodle_url('/report/log/graph.php', array('id'=>$id,'type'=>$type,'user'=>$user,'date'=>$date));
$PAGE->set_url($url);
if ($type !== "usercourse.png" and $type !== "userday.png") {
$type = 'userday.png';
}
$course = $DB->get_record("course", array("id"=>$id), '*', MUST_EXIST);
$user = $DB->get_record("user", array("id"=>$user, 'deleted'=>0), '*', MUST_EXIST);
$coursecontext = context_course::instance($course->id);
$personalcontext = context_user::instance($user->id);
if ($USER->id != $user->id and has_capability('moodle/user:viewuseractivitiesreport', $personalcontext)
and !is_enrolled($coursecontext, $USER) and is_enrolled($coursecontext, $user)) {
//TODO: do not require parents to be enrolled in courses - this is a hack!
require_login();
$PAGE->set_course($course);
} else {
require_login($course);
}
list($all, $today) = report_log_can_access_user_report($user, $course);
if ($type === "userday.png") {
if (!$today) {
require_capability('report/log:viewtoday', $coursecontext);
}
} else {
if (!$all) {
require_capability('report/log:view', $coursecontext);
}
}
add_to_log($course->id, 'course', 'report log', "report/log/graph.php?user=$user->id&id=$course->id&type=$type&date=$date", $course->id);
$logs = array();
$timenow = time();
if ($type === "usercourse.png") {
$site = get_site();
if ($course->id == $site->id) {
$courseselect = 0;
} else {
$courseselect = $course->id;
}
$maxseconds = REPORT_LOG_MAX_DISPLAY * 3600 * 24; // seconds
//$maxseconds = 60 * 3600 * 24; // seconds
if ($timenow - $course->startdate > $maxseconds) {
$course->startdate = $timenow - $maxseconds;
}
if (!empty($CFG->loglifetime)) {
$maxseconds = $CFG->loglifetime * 3600 * 24; // seconds
if ($timenow - $course->startdate > $maxseconds) {
$course->startdate = $timenow - $maxseconds;
}
}
$timestart = $coursestart = usergetmidnight($course->startdate);
if ((($timenow - $timestart)/86400.0) > 40) {
$reducedays = 7;
} else {
$reducedays = 0;
}
$days = array();
$i = 0;
while ($timestart < $timenow) {
$timefinish = $timestart + 86400;
if ($reducedays) {
if ($i % $reducedays) {
$days[$i] = "";
} else {
$days[$i] = userdate($timestart, "%a %d %b");
}
} else {
$days[$i] = userdate($timestart, "%a %d %b");
}
$logs[$i] = 0;
$i++;
$timestart = $timefinish;
}
if ($rawlogs = get_logs_usercourse($user->id, $courseselect, $coursestart)) {
foreach ($rawlogs as $rawlog) {
$logs[$rawlog->day] = $rawlog->num;
}
}
$graph = new graph(750, 400);
<<<<<<< HEAD
=======
$a = new stdClass();
>>>>>>> 230e37bfd87f00e0d010ed2ffd68ca84a53308d0
$a->coursename = format_string($course->shortname, true, array('context' => $coursecontext));
$a->username = fullname($user, true);
$graph->parameter['title'] = get_string("hitsoncourse", "", $a);
$graph->x_data = $days;
$graph->y_data['logs'] = $logs;
$graph->y_order = array('logs');
if (!empty($CFG->preferlinegraphs)) {
$graph->y_format['logs'] = array('colour' => 'blue','line' => 'line');
} else {
$graph->y_format['logs'] = array('colour' => 'blue','bar' => 'fill','bar_size' => 0.6);
$graph->parameter['bar_spacing'] = 0;
}
$graph->parameter['y_label_left'] = get_string("hits");
$graph->parameter['label_size'] = "12";
$graph->parameter['x_axis_angle'] = 90;
$graph->parameter['x_label_angle'] = 0;
$graph->parameter['tick_length'] = 0;
$graph->parameter['shadow'] = 'none';
error_reporting(5); // ignore most warnings such as font problems etc
$graph->draw_stack();
} else {
$site = get_site();
if ($course->id == $site->id) {
$courseselect = 0;
} else {
$courseselect = $course->id;
}
if ($date) {
$daystart = usergetmidnight($date);
} else {
$daystart = usergetmidnight(time());
}
$dayfinish = $daystart + 86400;
$hours = array();
for ($i=0; $i<=23; $i++) {
$logs[$i] = 0;
$hour = $daystart + $i * 3600;
$hours[$i] = $i;
}
if ($rawlogs = get_logs_userday($user->id, $courseselect, $daystart)) {
foreach ($rawlogs as $rawlog) {
$logs[$rawlog->hour] = $rawlog->num;
}
}
$graph = new graph(750, 400);
<<<<<<< HEAD
=======
$a = new stdClass();
>>>>>>> 230e37bfd87f00e0d010ed2ffd68ca84a53308d0
$a->coursename = format_string($course->shortname, true, array('context' => $coursecontext));
$a->username = fullname($user, true);
$graph->parameter['title'] = get_string("hitsoncoursetoday", "", $a);
$graph->x_data = $hours;
$graph->y_data['logs'] = $logs;
$graph->y_order = array('logs');
if (!empty($CFG->preferlinegraphs)) {
$graph->y_format['logs'] = array('colour' => 'blue','line' => 'line');
} else {
$graph->y_format['logs'] = array('colour' => 'blue','bar' => 'fill','bar_size' => 0.9);
}
$graph->parameter['y_label_left'] = get_string("hits");
$graph->parameter['label_size'] = "12";
$graph->parameter['x_axis_angle'] = 0;
$graph->parameter['x_label_angle'] = 0;
$graph->parameter['shadow'] = 'none';
error_reporting(5); // ignore most warnings such as font problems etc
$graph->draw_stack();
}
| khan0407/FinalArcade | report/log/graph.php | PHP | gpl-3.0 | 6,948 |
"""
Updates the version in the binary executable of the Forged Alliance game. Will write a new ForgedAlliance.version.exe
file.
Usage:
update_version <version> [--file=<file>] [--dest=<dest>]
Options:
--file=<file> The binary file to update [default: ForgedAlliance.exe]
--dest=<dest> The folder path where to create the patched filed [default: .]
"""
import os
import struct
import shutil
import logging
from docopt import docopt
logger = logging.getLogger(__name__)
def update_exe_version(source, destination, version):
"""
:param source: Path to the static base copy of ForgedAlliance.exe - Hardcoded in API
:param destination: Path this update is being copied to
:param version: New mod version
:return:
"""
# os.path.join due to Python 2.7 compatibility
destination = os.path.join(str(destination), "ForgedAlliance.%s.exe" % version)
shutil.copyfile(str(source), str(destination))
addr = [0xd3d3f, 0x47612c, 0x476665]
f = open(str(destination), 'rb+')
for a in addr:
v = struct.pack("<L", int(version))
f.seek(a+1, 0)
f.write(v)
f.close()
logger.info("Saved ForgedAlliance.%s.exe" % version)
return f
if __name__ == '__main__':
arguments = docopt(__doc__)
source, destination, version = arguments.get('--file'), arguments.get('--dest'), arguments.get('<version>')
update_exe_version(source, destination, version)
| FAForever/faftools | faf/tools/fa/update_version.py | Python | gpl-3.0 | 1,436 |
package net.berrueta.smwdump;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.Collections;
import java.util.LinkedList;
import net.sourceforge.jwbf.mediawiki.actions.MediaWiki;
import net.sourceforge.jwbf.mediawiki.actions.queries.AllPageTitles;
import net.sourceforge.jwbf.mediawiki.bots.MediaWikiBot;
import org.apache.log4j.Logger;
import org.xml.sax.SAXParseException;
import com.hp.hpl.jena.iri.IRIFactory;
import com.hp.hpl.jena.iri.impl.IRIImplException;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.NodeIterator;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.shared.JenaException;
/**
* Script to extract a RDF dump from a SemanticMediaWiki instance by
* means of web requests, i.e., without having local access to the server
* or the database.
*
* Command line syntax: wikiURL [outputfile.rdf]
*
* The wikiURL parameter should be the URL of the wiki, i.e.,
* http://www.crisiswiki.org/
*
* The second parameter is optional. If specified, the collected
* RDF triples will be stored in that file. Otherwise, the
* file "out.rdf" is assumed.
*
* @author Diego Berrueta
*
*/
public class Main {
private static final Logger logger = Logger.getLogger(Main.class);
/**
* Milliseconds between requests
*/
private static final long DELAY_MILIS = 0;
/**
* @param args
*/
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please provide the URL to the wiki as the first argument, e.g., http://www.crisiswiki.org/");
} else {
String wikiUrl = args[0];
File outputFile = new File(args.length == 2 ? args[1] : "out.rdf");
MediaWikiBot b = new MediaWikiBot (wikiUrl);
int count = 0;
Model m = ModelFactory.createDefaultModel();
LinkedList<String> articleNames = new LinkedList<String>();
for (int namespace : MediaWiki.NS_ALL) {
logger.info("Geting a list of all pages in namespace " + namespace); // see http://en.wikipedia.org/wiki/Wikipedia:Namespace
AllPageTitles apt = new AllPageTitles(b, namespace);
articleNames.addAll(asList(apt));
}
logger.info("There are " + articleNames.size() + " pages");
long startTime = System.currentTimeMillis();
for (String articleName : articleNames) {
logger.info("Getting RDF data for article (" + count + " of " + articleNames.size() + "): " + articleName);
readArticleIntoModel(m, wikiUrl, articleName);
logger.info("After reading [[" + articleName + "]], the model contains " + m.size() + " triples");
count++;
long currentTime = System.currentTimeMillis();
double progress = (double) count / (double) articleNames.size();
long elapsedTime = currentTime-startTime;
long remainingTime = Math.round(elapsedTime * (1-progress) / progress);
logger.info("Elapsed time (sec): " + (currentTime-startTime)/1000 + " -- Progress: " + Math.floor(progress * 100.0) + "% -- Est. remaining time (sec): " + remainingTime/1000);
Thread.sleep(DELAY_MILIS);
}
removeMalformedURIs(m);
// save data
logger.info("Saving " + m.size() + " triples to file " + outputFile + ", " + count + " pages have been retrieved");
m.write(new FileOutputStream(outputFile)); // avoid FileWriter, see http://jena.sourceforge.net/IO/iohowto.html#encoding
}
}
private static LinkedList<String> asList(AllPageTitles apt) {
LinkedList<String> articleNames = new LinkedList<String>();
for (String articleName : apt) {
articleNames.add(articleName);
}
return articleNames;
}
/**
* Fetches the RDF triples about a wiki article and adds them to the model
*
* @param m
* @param articleName
*/
private static void readArticleIntoModel(Model m, String wikiUrl, String articleName) {
String rdfUrl = wikiUrl + "index.php?title=Special:ExportRDF/" + MediaWiki.encode(articleName);
logger.debug("RDF URL: " + rdfUrl);
try {
m.read(rdfUrl);
} catch (JenaException e) {
logger.error("Skipped " + rdfUrl + " because of parsing errors", e);
}
}
/**
* Remove buggy resource URIs, i.e., URIs that are not valid
*
* @param m
*/
private static void removeMalformedURIs(Model m) {
IRIFactory iriFactory = IRIFactory.semanticWebImplementation();
NodeIterator nodeIterator = m.listObjects();
while (nodeIterator.hasNext()) {
RDFNode node = nodeIterator.next();
if (node.isResource() == true && node.isAnon() == false) {
Resource resource = node.asResource();
logger.info("Checking " + resource.getURI());
try {
iriFactory.construct(resource.getURI()); // just try to construct the IRI, check for exceptions
} catch (IRIImplException e) {
logger.error("Malformed URI fetched from wiki: " + resource.getURI());
logger.info("Removing all triples with object: " + resource.getURI());
m.removeAll(null, null, resource);
}
}
}
}
}
| berrueta/smw-dump | src/main/java/net/berrueta/smwdump/Main.java | Java | gpl-3.0 | 5,672 |
// Decompiled with JetBrains decompiler
// Type: System.Web.UI.WebControls.GridViewCommandEventArgs
// Assembly: System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// MVID: 7E68A73E-4066-4F24-AB0A-F147209F50EC
// Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Web.dll
using System.Runtime;
namespace System.Web.UI.WebControls
{
/// <summary>
/// Provides data for the <see cref="E:System.Web.UI.WebControls.GridView.RowCommand"/> event.
/// </summary>
public class GridViewCommandEventArgs : CommandEventArgs
{
private GridViewRow _row;
private object _commandSource;
/// <summary>
/// Gets the source of the command.
/// </summary>
///
/// <returns>
/// A instance of the <see cref="T:System.Object"/> class that represents the source of the command.
/// </returns>
public object CommandSource
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get
{
return this._commandSource;
}
}
/// <summary>
/// Gets or sets a value that indicates whether the control has handled the event.
/// </summary>
///
/// <returns>
/// true if data-bound event code was skipped or has finished; otherwise, false.
/// </returns>
public bool Handled { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get; [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] set; }
internal GridViewRow Row
{
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get
{
return this._row;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Web.UI.WebControls.GridViewCommandEventArgs"/> class using the specified row, source of the command, and event arguments.
/// </summary>
/// <param name="row">A <see cref="T:System.Web.UI.WebControls.GridViewRow"/> object that represents the row containing the button.</param><param name="commandSource">The source of the command.</param><param name="originalArgs">A <see cref="T:System.Web.UI.WebControls.CommandEventArgs"/> object that contains event data.</param>
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public GridViewCommandEventArgs(GridViewRow row, object commandSource, CommandEventArgs originalArgs)
: base(originalArgs)
{
this._row = row;
this._commandSource = commandSource;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Web.UI.WebControls.GridViewCommandEventArgs"/> class using the specified source of the command and event arguments.
/// </summary>
/// <param name="commandSource">The source of the command.</param><param name="originalArgs">A <see cref="T:System.Web.UI.WebControls.CommandEventArgs"/> object that contains event data.</param>
[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
public GridViewCommandEventArgs(object commandSource, CommandEventArgs originalArgs)
: base(originalArgs)
{
this._commandSource = commandSource;
}
}
}
| mater06/LEGOChimaOnlineReloaded | LoCO Client Files/Decompressed Client/Extracted DLL/System.Web/System/Web/UI/WebControls/GridViewCommandEventArgs.cs | C# | gpl-3.0 | 3,381 |
import React from 'react';
import { InputComponent, TSlobsInputProps, useInput, ValuesOf } from './inputs';
import { Slider, InputNumber, Row, Col } from 'antd';
import { SliderSingleProps } from 'antd/lib/slider';
import InputWrapper from './InputWrapper';
import omit from 'lodash/omit';
// select which features from the antd lib we are going to use
const ANT_SLIDER_FEATURES = ['min', 'max', 'step', 'tooltipPlacement', 'tipFormatter'] as const;
export type TSliderInputProps = TSlobsInputProps<
{ hasNumberInput?: boolean; slimNumberInput?: boolean },
number,
SliderSingleProps,
ValuesOf<typeof ANT_SLIDER_FEATURES>
>;
export const SliderInput = InputComponent((partialProps: TSliderInputProps) => {
// apply default props
const p = {
hasNumberInput: false,
...partialProps,
};
const { inputAttrs, wrapperAttrs, dataAttrs } = useInput('slider', p, ANT_SLIDER_FEATURES);
const numberInputHeight = p.slimNumberInput ? '50px' : '70px';
function onChangeHandler(val: number) {
// don't emit onChange if the value is out of range
if (typeof val !== 'number') return;
if (typeof p.max === 'number' && val > p.max) return;
if (typeof p.min === 'number' && val < p.min) return;
inputAttrs.onChange(val);
}
return (
<InputWrapper {...wrapperAttrs}>
<Row>
<Col flex="auto" {...dataAttrs} data-role="input" data-value={inputAttrs.value}>
<Slider {...inputAttrs} />
</Col>
{p.hasNumberInput && (
<Col flex={numberInputHeight}>
<InputNumber
// Antd passes tooltipPlacement onto a DOM element when passed as
// a prop to InputNumber, which makes React complain. It's not a
// valid prop for InputNumber anyway, so we just omit it.
{...omit(inputAttrs, 'tooltipPlacement')}
onChange={onChangeHandler}
style={{ width: numberInputHeight, marginLeft: '8px' }}
/>
</Col>
)}
</Row>
</InputWrapper>
);
});
| stream-labs/streamlabs-obs | app/components-react/shared/inputs/SliderInput.tsx | TypeScript | gpl-3.0 | 2,040 |
/*
* μlogger
*
* Copyright(C) 2019 Bartek Fabiszewski (www.fabiszewski.net)
*
* This 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/>.
*/
import { lang as $, config } from '../initializer.js';
import MapViewModel from '../mapviewmodel.js';
import uAlert from '../alert.js';
import uTrack from '../track.js';
import uUtils from '../utils.js';
// google maps
/**
* Google Maps API
* @class GoogleMapsApi
* @implements {MapViewModel.api}
*/
export default class GoogleMapsApi {
/**
* @param {MapViewModel} vm
*/
constructor(vm) {
/** @type {google.maps.Map} */
this.map = null;
/** @type {MapViewModel} */
this.viewModel = vm;
/** @type {google.maps.Polyline[]} */
this.polies = [];
/** @type {google.maps.Marker[]} */
this.markers = [];
/** @type {google.maps.InfoWindow} */
this.popup = null;
/** @type {number} */
this.timeoutHandle = 0;
}
/**
* Load and initialize api scripts
* @return {Promise<void, Error>}
*/
init() {
const params = `?${(config.googleKey) ? `key=${config.googleKey}&` : ''}callback=gm_loaded`;
const gmReady = Promise.all([
GoogleMapsApi.onScriptLoaded(),
uUtils.loadScript(`https://maps.googleapis.com/maps/api/js${params}`, 'mapapi_gmaps', GoogleMapsApi.loadTimeoutMs)
]);
return gmReady.then(() => this.initMap());
}
/**
* Listen to Google Maps callbacks
* @return {Promise<void, Error>}
*/
static onScriptLoaded() {
const timeout = uUtils.timeoutPromise(GoogleMapsApi.loadTimeoutMs);
const gmInitialize = new Promise((resolve, reject) => {
window.gm_loaded = () => {
GoogleMapsApi.gmInitialized = true;
resolve();
};
window.gm_authFailure = () => {
GoogleMapsApi.authError = true;
let message = $._('apifailure', 'Google Maps');
message += '<br><br>' + $._('gmauthfailure');
message += '<br><br>' + $._('gmapilink');
if (GoogleMapsApi.gmInitialized) {
uAlert.error(message);
}
reject(new Error(message));
};
if (GoogleMapsApi.authError) {
window.gm_authFailure();
}
if (GoogleMapsApi.gmInitialized) {
window.gm_loaded();
}
});
return Promise.race([ gmInitialize, timeout ]);
}
/**
* Start map engine when loaded
*/
initMap() {
const mapOptions = {
center: new google.maps.LatLng(config.initLatitude, config.initLongitude),
zoom: 8,
mapTypeId: google.maps.MapTypeId.TERRAIN,
scaleControl: true,
controlSize: 30
};
// noinspection JSCheckFunctionSignatures
this.map = new google.maps.Map(this.viewModel.mapElement, mapOptions);
this.popup = new google.maps.InfoWindow();
this.popup.addListener('closeclick', () => {
this.popupClose();
});
this.saveState = () => {
this.viewModel.state.mapParams = this.getState();
};
}
/**
* Clean up API
*/
cleanup() {
this.polies.length = 0;
this.markers.length = 0;
this.popup = null;
if (this.map && this.map.getDiv()) {
this.map.getDiv().innerHTML = '';
}
this.map = null;
}
/**
* Display track
* @param {uPositionSet} track
* @param {boolean} update Should fit bounds if true
* @return {Promise.<void>}
*/
displayTrack(track, update) {
if (!track || !track.hasPositions) {
return Promise.resolve();
}
google.maps.event.clearListeners(this.map, 'idle');
const promise = new Promise((resolve) => {
google.maps.event.addListenerOnce(this.map, 'tilesloaded', () => {
console.log('tilesloaded');
if (this.map) {
this.saveState();
this.map.addListener('idle', this.saveState);
}
resolve();
})
});
// init polyline
const polyOptions = {
strokeColor: config.strokeColor,
strokeOpacity: config.strokeOpacity,
strokeWeight: config.strokeWeight
};
// noinspection JSCheckFunctionSignatures
let poly;
const latlngbounds = new google.maps.LatLngBounds();
if (this.polies.length) {
poly = this.polies[0];
for (let i = 0; i < this.markers.length; i++) {
latlngbounds.extend(this.markers[i].getPosition());
}
} else {
poly = new google.maps.Polyline(polyOptions);
poly.setMap(this.map);
this.polies.push(poly);
}
const path = poly.getPath();
let start = this.markers.length;
if (start > 0) {
this.removePoint(--start);
}
for (let i = start; i < track.length; i++) {
// set marker
this.setMarker(i, track);
// update polyline
const position = track.positions[i];
const coordinates = new google.maps.LatLng(position.latitude, position.longitude);
if (track instanceof uTrack) {
path.push(coordinates);
}
latlngbounds.extend(coordinates);
}
if (update) {
this.map.fitBounds(latlngbounds);
if (track.length === 1) {
// only one point, zoom out
const zListener =
google.maps.event.addListenerOnce(this.map, 'bounds_changed', function () {
if (this.getZoom()) {
this.setZoom(15);
}
});
setTimeout(() => {
google.maps.event.removeListener(zListener);
}, 2000);
}
}
return promise;
}
/**
* Clear map
*/
clearMap() {
if (this.polies) {
for (let i = 0; i < this.polies.length; i++) {
this.polies[i].setMap(null);
}
}
if (this.markers) {
for (let i = 0; i < this.markers.length; i++) {
this.markers[i].setMap(null);
}
}
if (this.popup.getMap()) {
this.popupClose();
}
this.popup.setContent('');
this.markers.length = 0;
this.polies.length = 0;
}
/**
* @param {string} fill Fill color
* @param {boolean} isLarge Is large icon
* @param {boolean} isExtra Is styled with extra mark
* @return {google.maps.Icon}
*/
static getMarkerIcon(fill, isLarge, isExtra) {
// noinspection JSValidateTypes
return {
anchor: new google.maps.Point(15, 35),
url: MapViewModel.getSvgSrc(fill, isLarge, isExtra)
};
}
/**
* Set marker
* @param {uPositionSet} track
* @param {number} id
*/
setMarker(id, track) {
// marker
const position = track.positions[id];
// noinspection JSCheckFunctionSignatures
const marker = new google.maps.Marker({
position: new google.maps.LatLng(position.latitude, position.longitude),
title: (new Date(position.timestamp * 1000)).toLocaleString(),
map: this.map
});
const isExtra = position.hasComment() || position.hasImage();
let icon;
if (track.isLastPosition(id)) {
icon = GoogleMapsApi.getMarkerIcon(config.colorStop, true, isExtra);
} else if (track.isFirstPosition(id)) {
icon = GoogleMapsApi.getMarkerIcon(config.colorStart, true, isExtra);
} else {
icon = GoogleMapsApi.getMarkerIcon(isExtra ? config.colorExtra : config.colorNormal, false, isExtra);
}
marker.setIcon(icon);
marker.addListener('click', () => {
this.popupOpen(id, marker);
});
marker.addListener('mouseover', () => {
this.viewModel.model.markerOver = id;
});
marker.addListener('mouseout', () => {
this.viewModel.model.markerOver = null;
});
this.markers.push(marker);
}
/**
* @param {number} id
*/
removePoint(id) {
if (this.markers.length > id) {
this.markers[id].setMap(null);
this.markers.splice(id, 1);
if (this.polies.length) {
this.polies[0].getPath().removeAt(id);
}
if (this.viewModel.model.markerSelect === id) {
this.popupClose();
}
}
}
/**
* Open popup on marker with given id
* @param {number} id
* @param {google.maps.Marker} marker
*/
popupOpen(id, marker) {
this.popup.setContent(this.viewModel.getPopupElement(id));
this.popup.open(this.map, marker);
this.viewModel.model.markerSelect = id;
}
/**
* Close popup
*/
popupClose() {
this.viewModel.model.markerSelect = null;
this.popup.close();
}
/**
* Animate marker
* @param id Marker sequential id
*/
animateMarker(id) {
if (this.popup.getMap()) {
this.popupClose();
clearTimeout(this.timeoutHandle);
}
const icon = this.markers[id].getIcon();
this.markers[id].setIcon(GoogleMapsApi.getMarkerIcon(config.colorHilite, false, false));
this.markers[id].setAnimation(google.maps.Animation.BOUNCE);
this.timeoutHandle = setTimeout(() => {
this.markers[id].setIcon(icon);
this.markers[id].setAnimation(null);
}, 2000);
}
/**
* Get map bounds
* @returns {number[]} Bounds [ lon_sw, lat_sw, lon_ne, lat_ne ]
*/
getBounds() {
const bounds = this.map.getBounds();
const lat_sw = bounds.getSouthWest().lat();
const lon_sw = bounds.getSouthWest().lng();
const lat_ne = bounds.getNorthEast().lat();
const lon_ne = bounds.getNorthEast().lng();
return [ lon_sw, lat_sw, lon_ne, lat_ne ];
}
/**
* Zoom to track extent
*/
zoomToExtent() {
const bounds = new google.maps.LatLngBounds();
for (let i = 0; i < this.markers.length; i++) {
bounds.extend(this.markers[i].getPosition());
}
this.map.fitBounds(bounds);
}
/**
* Zoom to bounds
* @param {number[]} bounds [ lon_sw, lat_sw, lon_ne, lat_ne ]
*/
zoomToBounds(bounds) {
const sw = new google.maps.LatLng(bounds[1], bounds[0]);
const ne = new google.maps.LatLng(bounds[3], bounds[2]);
const latLngBounds = new google.maps.LatLngBounds(sw, ne);
this.map.fitBounds(latLngBounds);
}
/**
* Is given position within viewport
* @param {number} id
* @return {boolean}
*/
isPositionVisible(id) {
if (id >= this.markers.length) {
return false;
}
return this.map.getBounds().contains(this.markers[id].getPosition());
}
/**
* Center to given position
* @param {number} id
*/
centerToPosition(id) {
if (id < this.markers.length) {
this.map.setCenter(this.markers[id].getPosition());
}
}
/**
* Update size
*/
// eslint-disable-next-line class-methods-use-this
updateSize() {
// ignore for google API
}
/**
* Set default track style
*/
// eslint-disable-next-line class-methods-use-this
setTrackDefaultStyle() {
// ignore for google API
}
/**
* Set gradient style for given track property and scale
* @param {uTrack} track
* @param {string} property
* @param {{ minValue: number, maxValue: number, minColor: number[], maxColor: number[] }} scale
*/
// eslint-disable-next-line class-methods-use-this,no-unused-vars
setTrackGradientStyle(track, property, scale) {
// ignore for google API
}
static get loadTimeoutMs() {
return 10000;
}
/**
* Set map state
* Note: ignores rotation
* @param {MapParams} state
*/
updateState(state) {
this.map.setCenter({ lat: state.center[0], lng: state.center[1] });
this.map.setZoom(state.zoom);
}
/**
* Get map state
* Note: ignores rotation
* @return {MapParams|null}
*/
getState() {
if (this.map) {
const center = this.map.getCenter();
return {
center: [ center.lat(), center.lng() ],
zoom: this.map.getZoom(),
rotation: 0
};
}
return null;
}
// eslint-disable-next-line class-methods-use-this
saveState() {/* empty */}
}
/** @type {boolean} */
GoogleMapsApi.authError = false;
/** @type {boolean} */
GoogleMapsApi.gmInitialized = false;
| bfabiszewski/ulogger-server | js/src/mapapi/api_gmaps.js | JavaScript | gpl-3.0 | 12,253 |
from django.views.generic import CreateView, DetailView, UpdateView, ListView
from django.views.generic import DeleteView
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext_lazy as _
from django import http
from django.contrib import messages
from .. import forms
from .. import models
class CarNew(CreateView):
model = models.Car
form_class = forms.CarForm
template_name = 'web/car_new.html'
success_url = reverse_lazy('car_list')
def form_valid(self, form):
form.instance.owner = self.request.user
return super(CarNew, self).form_valid(form)
class CarUpdate(UpdateView):
model = models.Car
form_class = forms.CarForm
template_name = 'web/car_new.html'
success_url = reverse_lazy('cars')
def dispatch(self, request, *args, **kwargs):
obj = models.Car.objects.filter(pk=kwargs['pk']).filter(
owner=self.request.user)
if not obj:
messages.error(request, _('This car is not yours.'))
return http.HttpResponseRedirect(reverse_lazy('car_list'))
return super(CarUpdate, self).dispatch(request, *args, **kwargs)
class CarList(ListView):
model = models.Car
def get_queryset(self):
return models.Car.objects.filter(owner=self.request.user).all()
class CarDetail(DetailView):
model = models.Car
class CarDelete(DeleteView):
model = models.Car
| jizdoteka/jizdoteka-web | apps/web/views/car.py | Python | gpl-3.0 | 1,433 |
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2015 Petroules Corporation.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qbs.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "architectures.h"
#include <QMap>
#include <QMapIterator>
#include <QStringList>
namespace qbs {
QString canonicalTargetArchitecture(const QString &architecture,
const QString &vendor,
const QString &system,
const QString &abi)
{
const QString arch = canonicalArchitecture(architecture);
const bool isApple = (vendor == QStringLiteral("apple")
|| system == QStringLiteral("darwin")
|| system == QStringLiteral("macosx")
|| system == QStringLiteral("ios")
|| system == QStringLiteral("tvos")
|| system == QStringLiteral("watchos")
|| abi == QStringLiteral("macho"));
if (arch == QStringLiteral("armv7a") && isApple)
return QStringLiteral("armv7");
if (arch == QStringLiteral("x86"))
return QStringLiteral("i386");
return arch;
}
QString canonicalArchitecture(const QString &architecture)
{
QMap<QString, QStringList> archMap;
archMap.insert(QLatin1String("x86"), QStringList()
<< QLatin1String("i386")
<< QLatin1String("i486")
<< QLatin1String("i586")
<< QLatin1String("i686")
<< QLatin1String("ia32")
<< QLatin1String("ia-32")
<< QLatin1String("x86_32")
<< QLatin1String("x86-32")
<< QLatin1String("intel32")
<< QLatin1String("mingw32"));
archMap.insert(QLatin1String("x86_64"), QStringList()
<< QLatin1String("x86-64")
<< QLatin1String("x64")
<< QLatin1String("amd64")
<< QLatin1String("ia32e")
<< QLatin1String("em64t")
<< QLatin1String("intel64")
<< QLatin1String("mingw64"));
archMap.insert(QLatin1String("arm64"), QStringList()
<< QLatin1String("aarch64"));
archMap.insert(QLatin1String("ia64"), QStringList()
<< QLatin1String("ia-64")
<< QLatin1String("itanium"));
archMap.insert(QLatin1String("ppc"), QStringList()
<< QLatin1String("powerpc"));
archMap.insert(QLatin1String("ppc64"), QStringList()
<< QLatin1String("powerpc64"));
archMap.insert(QLatin1String("ppc64le"), QStringList()
<< QLatin1String("powerpc64le"));
QMapIterator<QString, QStringList> i(archMap);
while (i.hasNext()) {
i.next();
if (i.value().contains(architecture.toLower()))
return i.key();
}
return architecture;
}
} // namespace qbs
| Philips14171/qt-creator-opensource-src-4.2.1 | src/shared/qbs/src/lib/corelib/tools/architectures.cpp | C++ | gpl-3.0 | 4,533 |
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("xLogger")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("xLogger")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("bf86f714-1268-4859-988e-b53fc3664328")]
// 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")]
| xwcg/SpawnBot | xLogger/Properties/AssemblyInfo.cs | C# | gpl-3.0 | 1,390 |
/*
* Copyright (C) 2014 GG-Net GmbH - Oliver Günther
*
* 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/>.
*/
package eu.ggnet.dwoss.mandator.ui;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Map;
/**
* Creates an intermediate proxy object for a given interface. All calls are
* cached.
*
* @author Martin Ankerl (martin.ankerl@gmail.at)
* @version $Rev$
*/
public class CachedProxy {
/**
* Query object to find out if the exact same query was already made.
*
* @author Martin Ankerl (martin.ankerl@profactor.at)
* @version $Rev$
*/
private static final class Args {
private final Method mMethod;
private final Object[] mArgs;
private final int mHash;
public Args(final Method m, final Object[] args) {
mMethod = m;
mArgs = args;
// precalculate hash
mHash = calcHash();
}
/**
* Method and all the arguments have to be equal. Assumes that obj is of
* the same type.
*/
@Override
public boolean equals(final Object obj) {
final Args other = (Args)obj;
if ( !mMethod.equals(other.mMethod) ) {
return false;
}
if ( mArgs != null ) {
for (int i = 0; i < mArgs.length; ++i) {
Object o1 = mArgs[i];
Object o2 = other.mArgs[i];
if ( !(o1 == null ? o2 == null : o1.equals(o2)) ) {
return false;
}
}
}
return true;
}
/**
* Use the precalculated hash.
*/
@Override
public int hashCode() {
return mHash;
}
/**
* Try to use a good & fast hash function here.
*/
public int calcHash() {
int h = mMethod.hashCode();
if ( mArgs != null ) {
for (final Object o : mArgs) {
h = h * 65599 + (o == null ? 0 : o.hashCode());
}
}
return h;
}
}
/**
* Creates an intermediate proxy object that uses cached results if
* available, otherwise calls the given code.
*
* @param <T>
* Type of the class.
* @param clazz
* @param code
* The actual calculation code that should be cached.
* @return The proxy.
*/
@SuppressWarnings("unchecked")
public static <T> T create(Class<T> clazz, final T code) {
// create the cache
final Map<Args, Object> argsToOutput = new HashMap<>();
// proxy for the interface T
return (T)Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz}, new InvocationHandler() {
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
final Args input = new Args(method, args);
Object result = argsToOutput.get(input);
// check containsKey to support null values
if ( result == null && !argsToOutput.containsKey(input) ) {
// make sure exceptions are handled transparently
try {
result = method.invoke(code, args);
argsToOutput.put(input, result);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
return result;
}
});
}
}
| gg-net/dwoss | ui/mandator/src/main/java/eu/ggnet/dwoss/mandator/ui/CachedProxy.java | Java | gpl-3.0 | 4,405 |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Exception Class for Selenium
*
* PHP versions 5
*
* 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.
*
*/
/**
* uses PEAR_Exception
*/
//require_once 'PEAR/Exception.php';
/**
* Testing_Selenium_Exception
*
* @category Testing
* @package Testing_Selenium
* @author Shin Ohno <ganchiku at gmail dot com>
* @author Bjoern Schotte <schotte at mayflower dot de>
* @version @package_version@
*/
class Testing_Selenium_Exception extends Exception
{
}
?> | manusis/dblite | test/lib/Testing/Selenium/Exception.php | PHP | gpl-3.0 | 1,100 |
/*
* Copyright 2015
* Hélène Perrier <helene.perrier@liris.cnrs.fr>
* Jérémy Levallois <jeremy.levallois@liris.cnrs.fr>
* David Coeurjolly <david.coeurjolly@liris.cnrs.fr>
* Jacques-Olivier Lachaud <jacques-olivier.lachaud@univ-savoie.fr>
* Jean-Philippe Farrugia <jean-philippe.farrugia@liris.cnrs.fr>
* Jean-Claude Iehl <jean-claude.iehl@liris.cnrs.fr>
*
* This file is part of ICTV.
*
* ICTV 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.
*
* ICTV 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 ICTV. If not, see <http://www.gnu.org/licenses/>
*/
#include "BlitFramebuffer.h"
#include "GL/GLQuery.h"
#include "GL/GLTexture.h"
#include "GL/GLVertexArray.h"
#include "GL/GLBuffer.h"
#include "ProgramManager.h"
#include "Format.h"
void updateFramebufferRegion()
{
float regionw = 0.5f * Parameters::getInstance()->g_window.width / Parameters::getInstance()->g_framebuffer_region.mag;
float regionh = 0.5f * Parameters::getInstance()->g_window.height / Parameters::getInstance()->g_framebuffer_region.mag;
gk::TVec2<float> min(regionw, regionh);
gk::TVec2<float> max(Parameters::getInstance()->g_window.width - regionw, Parameters::getInstance()->g_window.height - regionh);
Parameters::getInstance()->g_framebuffer_region.p[0] = std::max(Parameters::getInstance()->g_framebuffer_region.p[0], min[0]);
Parameters::getInstance()->g_framebuffer_region.p[1] = std::max(Parameters::getInstance()->g_framebuffer_region.p[1], min[1]);
Parameters::getInstance()->g_framebuffer_region.p[0] = std::min(Parameters::getInstance()->g_framebuffer_region.p[0], max[0]);
Parameters::getInstance()->g_framebuffer_region.p[1] = std::min(Parameters::getInstance()->g_framebuffer_region.p[1], max[1]);
glProgramUniform3f (Parameters::getInstance()->g_programs[PROGRAM_FRAMEBUFFER_BLIT],
Parameters::getInstance()->g_uniform_locations[LOCATION_FRAMEBUFFER_BLIT_VIEWPORT],
Parameters::getInstance()->g_framebuffer_region.p[0] - regionw,
Parameters::getInstance()->g_framebuffer_region.p[1] - regionh,
Parameters::getInstance()->g_framebuffer_region.mag);
}
void BlitFramebuffer::loadFramebuffersTextures()
{
fprintf (stderr, "Loading framebuffer textures... "); fflush (stderr);
if (glIsTexture (Parameters::getInstance()->g_textures[TEXTURE_Z]))
glDeleteTextures (1, &Parameters::getInstance()->g_textures[TEXTURE_Z]);
if (glIsTexture (Parameters::getInstance()->g_textures[TEXTURE_RGBA]))
glDeleteTextures (1, &Parameters::getInstance()->g_textures[TEXTURE_RGBA]);
glGenTextures (1, &Parameters::getInstance()->g_textures[TEXTURE_Z]);
glGenTextures (1, &Parameters::getInstance()->g_textures[TEXTURE_RGBA]);
// TODO use ARB_texture_storage_multisample asap
if (Parameters::getInstance()->g_window.msaa_factor > 0) {
glBindTexture (GL_TEXTURE_2D_MULTISAMPLE, Parameters::getInstance()->g_textures[TEXTURE_Z]);
glTexImage2DMultisample (GL_TEXTURE_2D_MULTISAMPLE,
Parameters::getInstance()->g_window.msaa_factor,
GL_DEPTH24_STENCIL8,
Parameters::getInstance()->g_window.width, Parameters::getInstance()->g_window.height,
Parameters::getInstance()->g_window.msaa_fixedsamplelocations);
glBindTexture (GL_TEXTURE_2D_MULTISAMPLE, Parameters::getInstance()->g_textures[TEXTURE_RGBA]);
glTexImage2DMultisample (GL_TEXTURE_2D_MULTISAMPLE,
Parameters::getInstance()->g_window.msaa_factor,
GL_RGBA8,
Parameters::getInstance()->g_window.width, Parameters::getInstance()->g_window.height,
Parameters::getInstance()->g_window.msaa_fixedsamplelocations);
} else {
glBindTexture (GL_TEXTURE_2D, Parameters::getInstance()->g_textures[TEXTURE_Z]);
glTexStorage2D (GL_TEXTURE_2D, 1, GL_DEPTH24_STENCIL8,
Parameters::getInstance()->g_window.width, Parameters::getInstance()->g_window.height);
glBindTexture (GL_TEXTURE_2D, Parameters::getInstance()->g_textures[TEXTURE_RGBA]);
glTexStorage2D (GL_TEXTURE_2D, 1, GL_RGBA8,
Parameters::getInstance()->g_window.width, Parameters::getInstance()->g_window.height);
}
fprintf (stderr, "Success\n");
}
void BlitFramebuffer::loadFramebuffers()
{
fprintf (stderr, "Loading framebuffers... "); fflush (stderr);
if (glIsFramebuffer (Parameters::getInstance()->g_framebuffers[FRAMEBUFFER_DEFAULT]))
glDeleteFramebuffers(1, &Parameters::getInstance()->g_framebuffers[FRAMEBUFFER_DEFAULT]);
glGenFramebuffers (1, &Parameters::getInstance()->g_framebuffers[FRAMEBUFFER_DEFAULT]);
glBindFramebuffer (GL_FRAMEBUFFER, Parameters::getInstance()->g_framebuffers[FRAMEBUFFER_DEFAULT]);
glFramebufferTexture2D (GL_FRAMEBUFFER,
GL_COLOR_ATTACHMENT0,
Parameters::getInstance()->g_window.msaa_factor > 0 ? GL_TEXTURE_2D_MULTISAMPLE
: GL_TEXTURE_2D,
Parameters::getInstance()->g_textures[TEXTURE_RGBA],
0);
glFramebufferTexture2D (GL_FRAMEBUFFER,
GL_DEPTH_STENCIL_ATTACHMENT,
Parameters::getInstance()->g_window.msaa_factor > 0 ? GL_TEXTURE_2D_MULTISAMPLE
: GL_TEXTURE_2D,
Parameters::getInstance()->g_textures[TEXTURE_Z],
0);
glDrawBuffer (GL_COLOR_ATTACHMENT0);
if (GL_FRAMEBUFFER_COMPLETE != glCheckFramebufferStatus (GL_FRAMEBUFFER)) {
fprintf (stderr, "Failure\n");
exit(0);
}
glBindFramebuffer (GL_FRAMEBUFFER, 0);
fprintf (stderr, "Success\n");
}
void BlitFramebuffer::loadProgram()
{
fprintf (stderr, "Loading framebuffer blit program... "); fflush (stderr);
gk::GLCompiler& c = gk::loadProgram(SHADER_PATH("framebuffer_blit.glsl"));
c.defineVertex("MSAA_FACTOR", Format("%i", Parameters::getInstance()->g_window.msaa_factor).text);
c.defineFragment("MSAA_FACTOR", Format("%i", Parameters::getInstance()->g_window.msaa_factor).text);
GLProgram* tmp = c.make();
if (tmp->errors)
exit(-1);
Parameters::getInstance()->g_programs[PROGRAM_FRAMEBUFFER_BLIT] = tmp->name;
Parameters::getInstance()->g_uniform_locations[LOCATION_FRAMEBUFFER_BLIT_VIEWPORT] =
glGetUniformLocation (Parameters::getInstance()->g_programs[PROGRAM_FRAMEBUFFER_BLIT], "u_viewport");
Parameters::getInstance()->g_uniform_locations[LOCATION_FRAMEBUFFER_BLIT_SAMPLER] =
glGetUniformLocation (Parameters::getInstance()->g_programs[PROGRAM_FRAMEBUFFER_BLIT], "u_framebuffer_sampler");
glProgramUniform1i (Parameters::getInstance()->g_programs[PROGRAM_FRAMEBUFFER_BLIT],
Parameters::getInstance()->g_uniform_locations[LOCATION_FRAMEBUFFER_BLIT_SAMPLER],
TEXTURE_RGBA);
updateFramebufferRegion();
fprintf (stderr, "Success\n");
}
void BlitFramebuffer::blit()
{
/** Blit the framebuffer on screen (done manually to allow MSAA) **/
glPolygonMode (GL_FRONT_AND_BACK, GL_FILL);
glDisable(GL_DEPTH_TEST);
glBindFramebuffer (GL_READ_FRAMEBUFFER, Parameters::getInstance()->g_framebuffers[FRAMEBUFFER_DEFAULT]);
glBindFramebuffer (GL_DRAW_FRAMEBUFFER, 0);
glViewport (0, 0, Parameters::getInstance()->g_window.width, Parameters::getInstance()->g_window.height);
glUseProgram (Parameters::getInstance()->g_programs[PROGRAM_FRAMEBUFFER_BLIT]);
glBindVertexArray (Parameters::getInstance()->g_vertex_arrays[VERTEX_ARRAY_EMPTY]);
glDrawArrays (GL_TRIANGLE_STRIP, 0, 4);
glBindFramebuffer (GL_READ_FRAMEBUFFER, 0);
glBindVertexArray (0);
}
| dcoeurjo/ICTV | src/cpp/BlitFramebuffer.cpp | C++ | gpl-3.0 | 8,912 |
<?php
/**
* @section LICENSE
* This file is part of Wikimedia IEG Grant Review application.
*
* Wikimedia IEG Grant Review application 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.
*
* Wikimedia IEG Grant Review application 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 Wikimedia IEG Grant Review application. If not, see
* <http://www.gnu.org/licenses/>.
*
* @file
* @copyright © 2014 Bryan Davis, Wikimedia Foundation and contributors.
*/
namespace Wikimedia\IEGReview\Dao;
use \PDO;
use \PDOException;
use Psr\Log\LoggerInterface;
/**
* Base class for data access objects.
*
* @author Bryan Davis <bd808@wikimedia.org>
* @copyright © 2014 Bryan Davis, Wikimedia Foundation and contributors.
*/
abstract class AbstractDao {
/**
* @var PDO $db
*/
protected $dbh;
/**
* @var LoggerInterface $logger
*/
protected $logger;
/**
* @param string $dsn PDO data source name
* @param string $user Database user
* @param string $pass Database password
* @param LoggerInterface $logger Log channel
*/
public function __construct( $dsn, $user, $pass, $logger = null ) {
$this->logger = $logger ?: new \Psr\Log\NullLogger();
$this->dbh = new PDO( $dsn, $user, $pass,
array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => true, //FIXME: good idea?
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
)
);
}
/**
* Bind values to a prepared statement.
*
* If an associative array of values is provided, the data type to use when
* binding will be inferred by looking for a "<type>_" prefix at the
* beginning of the array key. This can come in very handy if you are using
* parameters in places like LIMIT clauses where binding as a string (the
* default type for PDO binds) will cause a syntax error.
*
* @param \PDOStatement $stmt Previously prepared statement
* @param array $values Values to bind
*/
protected function bind( $stmt, $values ) {
$values = $values ?: array();
if ( (bool)count( array_filter( array_keys( $values ), 'is_string' ) ) ) {
// associative array provided
foreach ( $values as $key => $value ) {
// infer bind type from key prefix
list( $prefix, $ignored ) = explode( '_', "{$key}_", 2 );
$type = \PDO::PARAM_STR;
switch ( $prefix ) {
case 'int':
$type = \PDO::PARAM_INT;
break;
case 'bool':
$type = \PDO::PARAM_BOOL;
break;
case 'null':
$type = \PDO::PARAM_NULL;
break;
default:
$type = \PDO::PARAM_STR;
}
$stmt->bindValue( $key, $value, $type );
}
} else {
// vector provided
$idx = 1;
foreach ( $values as $value ) {
$stmt->bindValue( $idx, $value );
$idx++;
}
}
}
/**
* Prepare and execute an SQL statement and return the first row of results.
*
* @param string $sql SQL
* @param array $params Prepared statement parameters
* @return array First response row
*/
protected function fetch( $sql, $params = null ) {
$stmt = $this->dbh->prepare( $sql );
$this->bind( $stmt, $params );
$stmt->execute();
return $stmt->fetch();
}
/**
* Prepare and execute an SQL statement and return all results.
*
* @param string $sql SQL
* @param array $params Prepared statement parameters
* @return array Result rows
*/
protected function fetchAll( $sql, $params = null ) {
$this->logger->debug( $sql, $params ?: array() );
$stmt = $this->dbh->prepare( $sql );
$this->bind( $stmt, $params );
$stmt->execute();
return $stmt->fetchAll();
}
/**
* Prepare and execute an SQL statement and return all results plus the
* number of rows found on the server side.
*
* The SQL is expected to contain the "SQL_CALC_FOUND_ROWS" option in the
* select statement. If it does not, the number of found rows returned is
* dependent on MySQL's interpretation of the query.
*
* @param string $sql SQL
* @param array $params Prepared statement parameters
* @return object StdClass with rows and found memebers
*/
protected function fetchAllWithFound( $sql, $params = null ) {
$ret = new \StdClass;
$ret->rows = $this->fetchAll( $sql, $params );
$ret->found = $this->fetch( 'SELECT FOUND_ROWS() AS found' );
$ret->found = $ret->found['found'];
return $ret;
}
/**
* Prepare and execute an SQL statement in a transaction.
*
* @param string $sql SQL
* @param array $params Prepared statement parameters
* @return bool False if an exception was generated, true otherwise
*/
protected function update( $sql, $params = null ) {
$stmt = $this->dbh->prepare( $sql );
try {
$this->dbh->begintransaction();
$stmt->execute( $params );
$this->dbh->commit();
return true;
} catch ( PDOException $e) {
$this->dbh->rollback();
$this->logger->error( 'Update failed.', array(
'method' => __METHOD__,
'exception' => $e,
'sql' => $sql,
'params' => $params,
) );
return false;
}
}
/**
* Prepare and execute an SQL statement in a transaction.
*
* @param string $sql SQL
* @param array $params Prepared statement parameters
* @return int|bool Last insert id or false if an exception was generated
*/
protected function insert( $sql, $params = null ) {
$stmt = $this->dbh->prepare( $sql );
try {
$this->dbh->beginTransaction();
$stmt->execute( $params );
$rowid = $this->dbh->lastInsertId();
$this->dbh->commit();
return $rowid;
} catch ( PDOException $e) {
$this->dbh->rollback();
$this->logger->error( 'Insert failed.', array(
'method' => __METHOD__,
'exception' => $e,
'sql' => $sql,
'params' => $params,
) );
return false;
}
}
/**
* Construct a where clause.
* @param array $where List of conditions
* @param string $conjunction Joining operation ('and' or 'or')
* @return string Where clause or empty string
*/
protected static function buildWhere( array $where, $conjunction = 'AND' ) {
if ( $where ) {
return 'WHERE (' . implode( ") {$conjunction} (", $where ) . ') ';
}
return '';
}
/**
* Create a string by joining all arguments with spaces.
*
* If one or more of the arguments are arrays each element of the array will
* be included independently.
*
* @return string New string
*/
protected static function concat( /*varags*/ ) {
$args = array();
foreach ( func_get_args() as $arg ) {
if ( is_array( $arg ) ) {
$args = array_merge( $args, $arg );
} else {
$args[] = $arg;
}
}
return implode( ' ', $args );
}
} //end AbstractDao
| bd808/wikimedia-iegreview | src/Dao/AbstractDao.php | PHP | gpl-3.0 | 6,999 |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 13 23:48:22 2015
@author: thorsten
"""
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
import os, sys
ROOT_DIR = os.path.dirname(__file__)
sys.path.append(os.path.join(ROOT_DIR,'..','..','CSXCAD','python'))
extensions = [
Extension("*", [os.path.join(os.path.dirname(__file__), "openEMS","*.pyx")],
language="c++", # generate C++ code
libraries = ['CSXCAD','openEMS', 'nf2ff']),
]
setup(
name="openEMS",
version = '0.0.33',
description = "Python interface for the openEMS FDTD library",
classifiers = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Topic :: Software Development :: Libraries :: Python Modules',
'Operating System :: POSIX :: Linux',
'Operating System :: Microsoft :: Windows',
],
author = 'Thorsten Liebig',
author_email = 'Thorsten.Liebig@gmx.de',
maintainer = 'Thorsten Liebig',
maintainer_email = 'Thorsten.Liebig@gmx.de',
url = 'http://openEMS.de',
packages=["openEMS", ],
package_data={'openEMS': ['*.pxd']},
ext_modules = cythonize(extensions)
)
| georgmichel/openEMS | python/setup.py | Python | gpl-3.0 | 1,466 |
/*
Copyright 2015 Philipp Adam, Manuel Caspari, Nicolas Lukaschek
contact@ravenapp.org
This file is part of Raven.
Raven 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.
Raven 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 Raven. If not, see <http://www.gnu.org/licenses/>.
*/
package at.flack.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class SMSDefaultDelivery extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("at.flack");
if (intent.hasExtra("smsto"))
launchIntent.putExtra("CONTACT_NUMBER", intent.getStringExtra("smsto"));
startActivity(launchIntent);
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
| manuelsc/Raven-Messenger | Raven App/src/main/java/at/flack/activity/SMSDefaultDelivery.java | Java | gpl-3.0 | 1,519 |
/*
* RescoreModule.cpp
*
* Created on: Feb 21, 2017
* Author: louis
*/
#include "RescoreModule.h"
#include "Logging.h"
namespace SLM {
RescoreModule::RescoreModule(SLM::BackoffStrategy* bo, const std::string& outputDirectory)
: backoffStrategy(bo), outputDirectory(outputDirectory)
{
// TODO Auto-generated constructor stub
}
RescoreModule::~RescoreModule() {
// TODO Auto-generated destructor stub
}
void RescoreModule::nextFile(const std::string& originalFileName)
{
this->originalFileName = originalFileName;
nbestList = SLM::NBestList();
}
void RescoreModule::addLine(const std::string& originalSentenceString, int originalRank, double acousticModelScore, double languageModelScore, int numberOfWords)
{
currentLine = new SLM::NBestItem(originalSentenceString, originalRank, acousticModelScore, languageModelScore, numberOfWords);
lprob = 0.0;
oovs = 0;
usedPatternsForLine = 0;
}
void RescoreModule::rescoreLine()
{
L_V << "RescoreModule: rescore ppl =" << pow(2, (-lprob)/usedPatternsForLine) << " P:" << lprob << " U:" << usedPatternsForLine << "\n";
// currentLine->setRescore(pow(2, lprob/usedPatternsForLine));
currentLine->setRescore(lprob);
nbestList.add(currentLine);
}
void RescoreModule::rescoreFile()
{
nbestList.determineNewRanks();
nbestList.printToFile(originalFileName, outputDirectory);
}
void RescoreModule::evaluatePattern(const Pattern& focus, const Pattern& context, bool isOOV)
{
double prob = backoffStrategy->prob(context, focus, isOOV);
if(isOOV)
{
L_P << "RescoreModule: ***";
++oovs;
} else
{
L_P << "RescoreModule: ";
++usedPatterns;
++usedPatternsForLine;
lprob += prob;
}
L_P << "prob =" << prob << "\n";
}
} /* namespace SLM */
| naiaden/SLM | RescoreModule.cpp | C++ | gpl-3.0 | 1,725 |
#!/usr/bin/env python3
import gi
import os
import webbrowser
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class ButtonWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Hall Launcher")
self.set_border_width(10)
hbox = Gtk.Box(spacing=100)
hbox.set_homogeneous(False)
vbox_top = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing = 10)
vbox_top.set_homogeneous(False)
vbox_bottom = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing = 10)
vbox_bottom.set_homogeneous(False)
vbox_next = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing = 10)
vbox_next.set_homogeneous(False)
hbox.pack_start(vbox_top, True, True, 0)
hbox.pack_start(vbox_bottom, True, True, 0)
hbox.pack_start(vbox_next, True, True, 0)
button1 = Gtk.Button.new_with_label("HallLinux")
button1.connect("clicked", self.on_halllinux_clicked)
button2 = Gtk.Button.new_with_mnemonic("Mousepad Text Editor")
button2.connect("clicked", self.open_mousepad_clicked)
button_google_chrome = Gtk.Button.new_with_mnemonic("Google Chromium")
button_google_chrome.connect("clicked", self.google_chromium)
button_google_firefox = Gtk.Button.new_with_mnemonic("Google Firefox")
button_google_firefox.connect("clicked", self.google_firefox)
button_youtube_chrome = Gtk.Button.new_with_mnemonic("Youtube Chromium")
button_youtube_chrome.connect("clicked", self.youtube_chromium)
button_youtube_firefox = Gtk.Button.new_with_mnemonic("Youtube Firefox")
button_youtube_firefox.connect("clicked", self.youtube_firefox)
button_drive = Gtk.Button.new_with_mnemonic("Google Drive")
button_drive.connect("clicked", self.google_drive)
button_keep = Gtk.Button.new_with_mnemonic("Google Keep")
button_keep.connect("clicked", self.google_keep)
button_quit = Gtk.Button.new_with_mnemonic("QUIT")
button_quit.connect("clicked", self.quit_clicked)
vbox_top.pack_start(button1, True, True, 0)
vbox_top.pack_start(button2, True, True, 0)
vbox_top.pack_start(button_google_chrome, True, True, 0)
vbox_top.pack_start(button_google_firefox, True, True, 0)
vbox_bottom.pack_start(button_youtube_chrome, True, True, 0)
vbox_bottom.pack_start(button_youtube_firefox, True, True, 0)
vbox_bottom.pack_start(button_drive, True, True, 0)
vbox_bottom.pack_start(button_keep, True, True, 0)
vbox_next.pack_start(button_quit, True, True, 0)
self.add(hbox)
def on_halllinux_clicked(self, button):
webbrowser.get('chromium').open('www.halllinux.com')
def google_chromium(self, button):
webbrowser.get('chromium').open('www.google.com')
def google_firefox(self, button):
webbrowser.get('firefox').open('www.google.com')
def youtube_chromium(self, button):
webbrowser.get('chromium').open('www.youtube.com')
def youtube_firefox(self, button):
webbrowser.get('firefox').open('www.youtube.com')
def google_drive(self, button):
webbrowser.get('chromium').open('drive.google.com')
def google_keep(self, button):
webbrowser.get('chromium').open('keep.google.com')
def open_mousepad_clicked(self, button):
os.system("mousepad&!")
def quit_clicked(self, button):
print("Closing application")
Gtk.main_quit()
win = ButtonWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
| HallLinux/Hall_Launcher | hall_launcher.py | Python | gpl-3.0 | 3,662 |
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Basic tests for Page Templates used in content-space.
$Id: test_dtmlpage.py 67630 2006-04-27 00:54:03Z jim $
"""
import unittest
from zope.security.checker import NamesChecker, defineChecker
from zope.traversing.adapters import Traverser, DefaultTraversable
from zope.traversing.interfaces import ITraverser, ITraversable
from zope.app.testing.placelesssetup import PlacelessSetup
from zope.app.testing import ztapi
from zope.app.container.contained import contained
from zope.app.dtmlpage.dtmlpage import DTMLPage
class Data(object):
def __init__(self, **kw):
self.__dict__.update(kw)
def __getitem__(self, name):
return getattr(self, name)
class DTMLPageTests(PlacelessSetup, unittest.TestCase):
def setUp(self):
super(DTMLPageTests, self).setUp()
ztapi.provideAdapter(None, ITraverser, Traverser)
ztapi.provideAdapter(None, ITraversable, DefaultTraversable)
defineChecker(Data, NamesChecker(['URL', 'name', '__getitem__']))
def test(self):
page = DTMLPage()
page.setSource(
u'<html>'
u'<head><title><dtml-var title></title></head>'
u'<body>'
u'<a href="<dtml-var "REQUEST.URL[\'1\']">">'
u'<dtml-var name>'
u'</a></body></html>'
)
page = contained(page, Data(name=u'zope'))
out = page.render(Data(URL={u'1': u'http://foo.com/'}),
title=u"Zope rules")
out = ' '.join(out.split())
self.assertEqual(
out,
u'<html><head><title>Zope rules</title></head><body>'
u'<a href="http://foo.com/">'
u'zope'
u'</a></body></html>'
)
def test_suite():
return unittest.makeSuite(DTMLPageTests)
if __name__=='__main__':
unittest.TextTestRunner().run(test_suite())
| Donkyhotay/MoonPy | zope/app/dtmlpage/tests/test_dtmlpage.py | Python | gpl-3.0 | 2,514 |
<?php
/**
* Dolumar engine, php/html MMORTS engine
* Copyright (C) 2009 Thijs Van der Schaeghe
* CatLab Interactive bvba, Gent, Belgium
* http://www.catlab.eu/
* http://www.dolumar.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 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
$width = isset ($_GET['width']) ? $_GET['width'] : 200;
$tilesToLoad = isset ($_GET['tiles']) ? $_GET['tiles'] : ceil ($width / 4);
$nocache = isset ($_GET['nocache']) ? true : false;
/*
Return the background image.
*/
function getBackgroundImage ($x, $y, $tilesToLoad, $usecache = true)
{
global $color_cache;
$cachename = 'i'.intval($_GET['x']).'p'.intval($_GET['y']).$tilesToLoad.'.png';
$cache = Neuron_Core_Cache::__getInstance ('minimapbg/');
if ($usecache && $cache->hasCache ($cachename, 0))
{
$img = $cache->getFileName ($cachename);
return imagecreatefrompng ($img);
}
else
{
$color_cache = array ();
// Build the new background image.
$tileSizeX = 8;
$tileSizeY = $tileSizeX / 2;
$halfTileX = floor ($tileSizeX / 2);
$halfTileY = floor ($tileSizeY / 2);
$im = imagecreate ($tileSizeX * $tilesToLoad, $tileSizeY * $tilesToLoad);
$background = imagecolorallocate ($im, 0, 0, 0);
$switchpoint = $tilesToLoad;
$loadExtra = 1;
$startX = ( $x + $y ) * $switchpoint;
$startY = ( $x - $y ) * $switchpoint;
for ($i = (0 - $loadExtra - 1); $i < ($switchpoint * 2) + $loadExtra + 1; $i ++)
{
if ($i > $switchpoint)
{
$offset = ($i - $switchpoint) * 2;
}
else {
$offset = 0;
}
$colStart = 0 - $i + $offset - $loadExtra;
$colEnd = $i - $offset + $loadExtra + 1;
//$output['sq'][$sQ]['tl'][$i] = array ();
$tx = $startX + $i;
$white = imagecolorallocate ($im, 255, 255, 255);
for ($j = $colStart - 1; $j < $colEnd + 1; $j ++)
{
$ty = $startY - $j;
$px = round (($i - $j) * floor ($tileSizeX / 2));
$py = round (($i + $j) * floor ($tileSizeY / 2));
// Check for building
/*
if (isset ($buildings[$tx]) && isset ($buildings[$tx][$ty]))
{
$color = color_cache ($im, $buildings[$tx][$ty][0]->getMapColor ());
}
else
{
*/
$location = Dolumar_Map_Location::getLocation ($tx, $ty);
$c = $location->getHeightIntencity ();
$col = $location->getMapColor ();
$col[0] = floor ($col[0] * $c);
$col[1] = floor ($col[1] * $c);
$col[2] = floor ($col[2] * $c);
$color = color_cache ($im, $col);
//}
$punten = array
(
// Startpunt
$px + $halfTileX, $py,
$px + $tileSizeX, $py + $halfTileY,
$px + $halfTileX, $py + $tileSizeY,
$px, $py + $halfTileY
);
imagefilledpolygon($im, $punten, 4, $color);
}
}
ob_start ();
imagepng ($im, null);
$cache->setCache ($cachename, ob_get_clean ());
return $im;
}
}
function color_cache ($im, $color)
{
global $color_cache;
if (!isset ($color_cache[$color[0].'_'.$color[1].'_'.$color[2]]))
{
$color_cache[$color[0].'_'.$color[1].'_'.$color[2]] = imagecolorallocate ($im, $color[0], $color[1], $color[2]);
}
return $color_cache[$color[0].'_'.$color[1].'_'.$color[2]];
}
if (isset ($_GET['x']) && isset ($_GET['y']))
{
$extension = 'png';
$cache = Neuron_Core_Cache::__getInstance ('minimap/');
// Fetch cache
$cachename = 'i'.intval($_GET['x']).'p'.intval($_GET['y']).$tilesToLoad.$extension;
$image = $cache->getCache ($cachename, 60 * 60 * 6);
//$image = false;
if ($image && !$nocache)
{
header("Content-type: image/".$extension);
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 60*60*12) . " GMT");
echo $image;
}
else
{
//$cache->setCache ($cachename, 'locked');
$x = $_GET['x'];
$y = $_GET['y'];
$im = getBackgroundImage ($x, $y, $tilesToLoad);
$color_cache = array ();
// Build the new background image.
$tileSizeX = 8;
$tileSizeY = $tileSizeX / 2;
$halfTileX = floor ($tileSizeX / 2);
$halfTileY = floor ($tileSizeY / 2);
$switchpoint = $tilesToLoad;
$loadExtra = 1;
$startX = ( $x + $y ) * $switchpoint;
$startY = ( $x - $y ) * $switchpoint;
$db = Neuron_Core_Database::__getInstance ();
$locations = array
(
array
(
$startX + ($switchpoint/2),
$startY - ($switchpoint/2)
)
);
// Load buildings from SQL
$buildingSQL = Dolumar_Map_Map::getBuildingsFromLocations ($locations, $switchpoint + 25);
foreach ($buildingSQL as $buildingV)
{
$race = Dolumar_Races_Race::getRace ($buildingV['race']);
$b = Dolumar_Buildings_Building::getBuilding
(
$buildingV['buildingType'],
$race,
$buildingV['xas'], $buildingV['yas']
);
$b->setData ($buildingV['bid'], $buildingV);
//$buildings[floor ($buildingV['xas'])][floor ($buildingV['yas'])][] = $b;
$x = floor ($buildingV['xas']);
$y = floor ($buildingV['yas']);
$color = color_cache ($im, $b->getMapColor ());
$i = $x - $startX;
$j = $startY - $y;
$px = round (($i - $j) * floor ($tileSizeX / 2));
$py = round (($i + $j) * floor ($tileSizeY / 2));
$tileSizeX = 8;
$tileSizeY = $tileSizeX / 2;
$halfTileX = floor ($tileSizeX / 2);
$halfTileY = floor ($tileSizeY / 2);
$punten = array
(
// Startpunt
$px + $halfTileX, $py, // Boven
$px + $tileSizeX, $py + $halfTileY, // Rechts
$px + $halfTileX, $py + $tileSizeY, // Onder
$px, $py + $halfTileY // Links
);
imagefilledpolygon ($im, $punten, 4, $color);
}
// Start output buffering
ob_start ();
if ($extension == 'gif')
{
imagegif ($im);
}
else
{
imagepng ($im, null);
}
imagedestroy ($im);
// Fetch thze output & flush it down the toilet
header("Content-type: image/".$extension);
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 60*60*12) . " GMT");
$output = ob_get_flush();
$cache->setCache ($cachename, $output);
}
}
| CatLabInteractive/dolumar-engine | src/Neuron/GameServer/scripts/image/minimap.php | PHP | gpl-3.0 | 6,605 |
/*
Copyright (c) 2011 Tsz-Chiu Au, Peter Stone
University of Texas at Austin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the University of Texas at Austin nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package aim4.map.destination;
import java.util.List;
import aim4.config.Debug;
import aim4.map.Road;
import aim4.map.lane.Lane;
/**
* The IdentityDestinationSelector always chooses the Vehicle's current Road
* as the destination Road, unless it is not a legal destination Road, in
* which case it throws a RuntimeException.
*/
public class IdentityDestinationSelector implements DestinationSelector {
/////////////////////////////////
// CONSTRUCTORS
/////////////////////////////////
/**
* Create a new IdentityDestinationSelector from the given Layout.
*/
public IdentityDestinationSelector() {
}
/////////////////////////////////
// PUBLIC METHODS
/////////////////////////////////
/**
* {@inheritDoc}
*/
@Override
public Road selectDestination(Lane currentLane) {
return Debug.currentMap.getRoad(currentLane);
}
@Override
public List<Road> getPossibleDestination(Lane currentLane) {
// TODO Auto-generated method stub
return null;
}
}
| shunzh/aim5 | src/main/java/aim4/map/destination/IdentityDestinationSelector.java | Java | gpl-3.0 | 2,542 |
/*
* Copyright (C) 2020 Timo Vesalainen <timo.vesalainen@iki.fi>
*
* 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/>.
*/
package org.vesalainen.fx;
import java.util.prefs.Preferences;
import javafx.util.StringConverter;
/**
*
* @author Timo Vesalainen <timo.vesalainen@iki.fi>
*/
public class ObjectPreference<T> extends PreferenceBase<T>
{
private final StringConverter<T> converter;
public ObjectPreference(Preferences preferences, String key, T def, StringConverter<T> converter)
{
super(preferences, key, def);
this.converter = converter;
}
@Override
public T getValue()
{
return converter.fromString(preferences.get(key, converter.toString(def)));
}
@Override
public void setValue(T def)
{
if (def != null)
{
preferences.put(key, converter.toString(def));
}
else
{
preferences.remove(key);
}
fireValueChangedEvent();
}
}
| tvesalainen/util | util/src/main/java/org/vesalainen/fx/ObjectPreference.java | Java | gpl-3.0 | 1,649 |