code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using Gwupe.Cloud.Messaging.Elements;
namespace Gwupe.Cloud.Messaging.Response
{
[DataContract]
public class VCardRs : API.Response
{
public override String type
{
get { return "VCard-RS"; }
set { }
}
[DataMember] public UserElement userElement;
[DataMember] public TeamElement teamElement;
[DataMember] public RelationshipElement relationshipElement;
public PartyElement PartyElement
{
get
{
return IsTeam() ? (PartyElement)teamElement : userElement;
}
}
public Boolean IsTeam()
{
return teamElement != null;
}
}
}
|
gwupe/Gwupe
|
BlitsMeCloudClient/Messaging/Response/VCardRs.cs
|
C#
|
gpl-2.0
| 881
|
#ifndef IQSETTINGMANAGER_H
#define IQSETTINGMANAGER_H
#include <QObject>
#include <QSettings>
#include <QDateTime>
#include "iqsmpp/iqsmpp.h"
class IQSettingManager
{
public:
static void setCinemaName(const QString &name) {setSettingParam("cinemaName", name);}
static void setUpdateInterval(const int interval) {setSettingParam("updateInterval", interval);}
static void setODBCDataSource(const QString &dataSource) {setSettingParam("odbcDataSource", dataSource);}
static void setODBCUserName(const QString &userName) {setSettingParam("odbcUserName", userName);}
static void setODBCPassword(const QString &password) {setSettingParam("odbcPassword", password);}
static void setSenderText(const QString &senderText) {setSettingParam("senderText", senderText);}
static void setLastReservationId(const quint32 id) {setSettingParam("lastReservationId", id);}
static void setSMPPHostName(const QString &hostName) {setSettingParam("smppHostName", hostName);}
static void setSMPPHostPort(const quint16 port) {setSettingParam("smppHostPort", port);}
static void setSMPPSystemId(const QString &systemId) {setSettingParam("smppSystemId", systemId);}
static void setSMPPPassword(const QString &password) {setSettingParam("smppPassword", password);}
static void setSMPPSourceNPI(const IQSMPP::NPI npi) {setSettingParam("smppSourceNPI", static_cast<quint8>(npi));}
static void setSMPPSourceTON(const IQSMPP::TON ton) {setSettingParam("smppSourceTON", static_cast<quint8>(ton));}
static void setSMPPSourceAddres(const QString &addres) {setSettingParam("smppSourceAddres", addres);}
static void setSMPPDestinationNPI(const IQSMPP::NPI npi) {setSettingParam("smppDestinationNPI", static_cast<quint8>(npi));}
static void setSMPPDestinationTON(const IQSMPP::TON ton) {setSettingParam("smppDestinationTON", static_cast<quint8>(ton));}
static void setSMPPEqueireLinkSendInterval(const int interval) {setSettingParam("smmpEnqueireLinkSendInterval", interval);}
static void setSMPPSMSPerSecond(const int count) {setSettingParam("smppSMSPerSecond", count);}
static void setODBCDatabaseName(const QString &name) {setSettingParam("databaseName", name);}
static void setEnableNotificationOfReservation(const bool enable) {setSettingParam("enableNotificatonOfReservation", enable);}
static void setEnableSubscribeMovePoster(const bool enable) {setSettingParam("enableSubscribeMoviePoster", enable);}
static void setSubscribeMovePosterSource(const int sourceId) {setSettingParam("subscribeMovePosterSource", sourceId);}
static void setSubscribeMovePosterFile(const QString &file) {setSettingParam("subscribeMovePosterFile", file);}
static void setEnableWebAcces(const bool enable) {setSettingParam("enableWebAcces", enable);}
static void setWebAccesPort(const quint16 port) {setSettingParam("webAccesPort", port);}
static void setWebAccesSecretKey(const QString secretKey) {setSettingParam("webAccesSecretKey", secretKey);}
static QString cinemaName() {return settingParam("cinemaName", "").toString();}
static bool enableNotificationOfReservation() {return settingParam("enableNotificatonOfReservation", true).toBool();}
static bool enableSubscribeMovePoster() {return settingParam("enableSubscribeMoviePoster", true).toBool();}
static int subscribeMovePosterSource() {return settingParam("subscribeMovePosterSource", 0).toInt();}
static QString subscribeMovePosterFile() {return settingParam("subscribeMovePosterFile", "").toString();}
static int updateInterval() {return settingParam("updateInterval", 10).toInt();}
static QString odbcDataSource() {return settingParam("odbcDataSource", "").toString();}
static QString odbcUserName() {return settingParam("odbcUserName", "sa").toString();}
static QString odbcPassword() {return settingParam("odbcPassword", "").toString();}
static QString odbcDatabaseName() {return settingParam("databaseName", "KINO").toString();}
static QString senderText() {return settingParam("senderText", "").toString();}
static quint32 lastReservationId();
static QString smppHostName() {return settingParam("smppHostName", "127.0.0.1").toString();}
static quint16 smppHostPort() {return settingParam("smppHostPort", "2775").toUInt();}
static QString smppSystemId() {return settingParam("smppSystemId", "").toString();}
static QString smppPassword() {return settingParam("smppPassword", "").toString();}
static IQSMPP::NPI smppSourceNPI() {return static_cast<IQSMPP::NPI>(settingParam("smppSourceNPI", 0).toUInt());}
static IQSMPP::TON smppSourceTON() {return static_cast<IQSMPP::TON>(settingParam("smppSourceTON", 0).toUInt());}
static QString smppSourceAddres() {return settingParam("smppSourceAddres", "").toString();}
static IQSMPP::NPI smppDestinationNPI() {return static_cast<IQSMPP::NPI>(settingParam("smppDestinationNPI", 0).toUInt());}
static IQSMPP::TON smppDestinationTON() {return static_cast<IQSMPP::TON>(settingParam("smppDestinationTON", 0).toUInt());}
static int smppEnqueireLinkSendInterval() {return settingParam("smmpEnqueireLinkSendInterval", 5).toInt();}
static int smppSMSPerSecond() {return settingParam("smppSMSPerSecond", 2).toInt();}
static bool enableWebAcces() {return settingParam("enableWebAcces", true).toBool();}
static quint16 webAccesPort() {return settingParam("webAccesPort", 7532).toInt();}
static QString webAccesSecretKey() {return settingParam("webAccesSecretKey", "123456").toString();}
private:
IQSettingManager();
static void setSettingParam(const QString &key, const QVariant &value);
static QVariant settingParam(const QString &key, const QVariant &defaultValue = QVariant());
};
#endif // IQSETTINGMANAGER_H
|
0x6368656174/iqSmsSender
|
iqsettingmanager.h
|
C
|
gpl-2.0
| 5,951
|
<!doctype html>
<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
<link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />
<link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />
<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />
<meta name="keywords" content="Activity," />
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />
<meta name="description" content="方式1this.powerManager = (PowerManager) this .getSystemService(Context.POWER_SERVICE);this.wakeLock = this.powerManager.newWakeLock( PowerManager.FULL_WAKE_LOCK, “My Lock”);//保持常亮 this.wakeLock.acquire(">
<meta property="og:type" content="article">
<meta property="og:title" content="Activity保持长亮">
<meta property="og:url" content="https://pillowzhou.github.io/2017/03/18/Activity保持长亮/index.html">
<meta property="og:site_name" content="Develop Note">
<meta property="og:description" content="方式1this.powerManager = (PowerManager) this .getSystemService(Context.POWER_SERVICE);this.wakeLock = this.powerManager.newWakeLock( PowerManager.FULL_WAKE_LOCK, “My Lock”);//保持常亮 this.wakeLock.acquire(">
<meta property="og:updated_time" content="2017-03-18T15:06:17.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Activity保持长亮">
<meta name="twitter:description" content="方式1this.powerManager = (PowerManager) this .getSystemService(Context.POWER_SERVICE);this.wakeLock = this.powerManager.newWakeLock( PowerManager.FULL_WAKE_LOCK, “My Lock”);//保持常亮 this.wakeLock.acquire(">
<script type="text/javascript" id="hexo.configurations">
var NexT = window.NexT || {};
var CONFIG = {
root: '/',
scheme: 'Muse',
sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
fancybox: true,
motion: true,
duoshuo: {
userId: '0',
author: '博主'
},
algolia: {
applicationID: '',
apiKey: '',
indexName: '',
hits: {"per_page":10},
labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
}
};
</script>
<link rel="canonical" href="https://pillowzhou.github.io/2017/03/18/Activity保持长亮/"/>
<title> Activity保持长亮 | Develop Note </title>
</head>
<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
<div class="container one-collumn sidebar-position-left page-post-detail ">
<div class="headband"></div>
<header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
<div class="header-inner"><div class="site-brand-wrapper">
<div class="site-meta ">
<div class="custom-logo-site-title">
<a href="/" class="brand" rel="start">
<span class="logo-line-before"><i></i></span>
<span class="site-title">Develop Note</span>
<span class="logo-line-after"><i></i></span>
</a>
</div>
<p class="site-subtitle">总结经验,汲取教训</p>
</div>
<div class="site-nav-toggle">
<button>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
<span class="btn-bar"></span>
</button>
</div>
</div>
<nav class="site-nav">
<ul id="menu" class="menu">
<li class="menu-item menu-item-home">
<a href="/" rel="section">
<i class="menu-item-icon fa fa-fw fa-home"></i> <br />
首页
</a>
</li>
<li class="menu-item menu-item-archives">
<a href="/archives" rel="section">
<i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
归档
</a>
</li>
<li class="menu-item menu-item-tags">
<a href="/tags" rel="section">
<i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
标签
</a>
</li>
</ul>
</nav>
</div>
</header>
<main id="main" class="main">
<div class="main-inner">
<div class="content-wrap">
<div id="content" class="content">
<div id="posts" class="posts-expand">
<article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
<link itemprop="mainEntityOfPage" href="https://pillowzhou.github.io/2017/03/18/Activity保持长亮/">
<span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
<meta itemprop="name" content="wooden fish">
<meta itemprop="description" content="">
<meta itemprop="image" content="/images/avatar.gif">
</span>
<span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
<meta itemprop="name" content="Develop Note">
</span>
<header class="post-header">
<h1 class="post-title" itemprop="name headline">
Activity保持长亮
</h1>
<div class="post-meta">
<span class="post-time">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-o"></i>
</span>
<span class="post-meta-item-text">发表于</span>
<time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-18T22:30:24+08:00">
2017-03-18
</time>
</span>
<span class="post-category" >
<span class="post-meta-divider">|</span>
<span class="post-meta-item-icon">
<i class="fa fa-folder-o"></i>
</span>
<span class="post-meta-item-text">分类于</span>
<span itemprop="about" itemscope itemtype="http://schema.org/Thing">
<a href="/categories/Android-Note/" itemprop="url" rel="index">
<span itemprop="name">Android-Note</span>
</a>
</span>
</span>
</div>
</header>
<div class="post-body" itemprop="articleBody">
<p>方式1<br>this.powerManager = (PowerManager) this .getSystemService(Context.POWER_SERVICE);<br>this.wakeLock = this.powerManager.newWakeLock( PowerManager.FULL_WAKE_LOCK, “My Lock”);<br>//保持常亮 this.wakeLock.acquire();<br>//释放 this.wakeLock.release();</p>
<p>方式2<br>getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);<br>清除时使用clearFlags</p>
<p>方式3 androidmanifest中配置<br>这个设置android:keepScreenOn=”true”等同于FLAG_KEEP_SCREEN_ON。</p>
</div>
<div>
</div>
<div>
</div>
<footer class="post-footer">
<div class="post-tags">
<a href="/tags/Activity/" rel="tag"># Activity</a>
</div>
<div class="post-nav">
<div class="post-nav-next post-nav-item">
<a href="/2017/03/18/更改Activity亮度/" rel="next" title="更改Activity亮度">
<i class="fa fa-chevron-left"></i> 更改Activity亮度
</a>
</div>
<span class="post-nav-divider"></span>
<div class="post-nav-prev post-nav-item">
<a href="/2017/03/18/修改jar中的class文件/" rel="prev" title="修改jar中的class文件">
修改jar中的class文件 <i class="fa fa-chevron-right"></i>
</a>
</div>
</div>
</footer>
</article>
<div class="post-spread">
</div>
</div>
</div>
<div class="comments" id="comments">
</div>
</div>
<div class="sidebar-toggle">
<div class="sidebar-toggle-line-wrap">
<span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
<span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
</div>
</div>
<aside id="sidebar" class="sidebar">
<div class="sidebar-inner">
<section class="site-overview sidebar-panel sidebar-panel-active">
<div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
<img class="site-author-image" itemprop="image"
src="/images/avatar.gif"
alt="wooden fish" />
<p class="site-author-name" itemprop="name">wooden fish</p>
<p class="site-description motion-element" itemprop="description"></p>
</div>
<nav class="site-state motion-element">
<div class="site-state-item site-state-posts">
<a href="/archives">
<span class="site-state-item-count">20</span>
<span class="site-state-item-name">日志</span>
</a>
</div>
<div class="site-state-item site-state-categories">
<span class="site-state-item-count">5</span>
<span class="site-state-item-name">分类</span>
</div>
<div class="site-state-item site-state-tags">
<a href="/tags">
<span class="site-state-item-count">11</span>
<span class="site-state-item-name">标签</span>
</a>
</div>
</nav>
<div class="links-of-author motion-element">
</div>
</section>
</div>
</aside>
</div>
</main>
<footer id="footer" class="footer">
<div class="footer-inner">
<div class="copyright" >
©
<span itemprop="copyrightYear">2017</span>
<span class="with-love">
<i class="fa fa-heart"></i>
</span>
<span class="author" itemprop="copyrightHolder">wooden fish</span>
</div>
<div class="powered-by">
由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>
<div class="theme-info">
主题 -
<a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
NexT.Muse
</a>
</div>
</div>
</footer>
<div class="back-to-top">
<i class="fa fa-arrow-up"></i>
</div>
</div>
<script type="text/javascript">
if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
window.Promise = null;
}
</script>
<script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
<script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
<script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
<script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
<script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>
</body>
</html>
|
pillowzhou/pillowzhou.github.io
|
2017/03/18/Activity保持长亮/index.html
|
HTML
|
gpl-2.0
| 13,210
|
<?php
/**
* Register all actions and filters for the plugin
*
* @link http://boozang.com
* @since 1.0.0
*
* @package Boozang
* @subpackage Boozang/includes
*/
/**
* Register all actions and filters for the plugin.
*
* Maintain a list of all hooks that are registered throughout
* the plugin, and register them with the WordPress API. Call the
* run function to execute the list of actions and filters.
*
* @package Boozang
* @subpackage Boozang/includes
* @author Mats <mats.ljunggren@boozang.com>
*/
class Boozang_Loader {
/**
* The array of actions registered with WordPress.
*
* @since 1.0.0
* @access protected
* @var array $actions The actions registered with WordPress to fire when the plugin loads.
*/
protected $actions;
/**
* The array of filters registered with WordPress.
*
* @since 1.0.0
* @access protected
* @var array $filters The filters registered with WordPress to fire when the plugin loads.
*/
protected $filters;
/**
* Initialize the collections used to maintain the actions and filters.
*
* @since 1.0.0
*/
public function __construct() {
$this->actions = array();
$this->filters = array();
}
/**
* Add a new action to the collection to be registered with WordPress.
*
* @since 1.0.0
* @param string $hook The name of the WordPress action that is being registered.
* @param object $component A reference to the instance of the object on which the action is defined.
* @param string $callback The name of the function definition on the $component.
* @param int $priority Optional. he priority at which the function should be fired. Default is 10.
* @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1.
*/
public function add_action( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) {
$this->actions = $this->add( $this->actions, $hook, $component, $callback, $priority, $accepted_args );
}
/**
* Add a new filter to the collection to be registered with WordPress.
*
* @since 1.0.0
* @param string $hook The name of the WordPress filter that is being registered.
* @param object $component A reference to the instance of the object on which the filter is defined.
* @param string $callback The name of the function definition on the $component.
* @param int $priority Optional. he priority at which the function should be fired. Default is 10.
* @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1
*/
public function add_filter( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) {
$this->filters = $this->add( $this->filters, $hook, $component, $callback, $priority, $accepted_args );
}
/**
* A utility function that is used to register the actions and hooks into a single
* collection.
*
* @since 1.0.0
* @access private
* @param array $hooks The collection of hooks that is being registered (that is, actions or filters).
* @param string $hook The name of the WordPress filter that is being registered.
* @param object $component A reference to the instance of the object on which the filter is defined.
* @param string $callback The name of the function definition on the $component.
* @param int $priority The priority at which the function should be fired.
* @param int $accepted_args The number of arguments that should be passed to the $callback.
* @return array The collection of actions and filters registered with WordPress.
*/
private function add( $hooks, $hook, $component, $callback, $priority, $accepted_args ) {
$hooks[] = array(
'hook' => $hook,
'component' => $component,
'callback' => $callback,
'priority' => $priority,
'accepted_args' => $accepted_args
);
return $hooks;
}
/**
* Register the filters and actions with WordPress.
*
* @since 1.0.0
*/
public function run() {
foreach ( $this->filters as $hook ) {
add_filter( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] );
}
foreach ( $this->actions as $hook ) {
add_action( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] );
}
}
}
|
ljunggren/boozang-wp
|
includes/class-boozang-loader.php
|
PHP
|
gpl-2.0
| 4,838
|
using System;
namespace DLib.Model.Interfaces
{
public interface ICreated
{
DateTime created_on { get; set; }
string created_by { get; set; }
}
}
|
daredev/DLib
|
DLib/DLib/Model/Interfaces/ICreated.cs
|
C#
|
gpl-3.0
| 178
|
using CP77.CR2W.Reflection;
namespace CP77.CR2W.Types
{
[REDMeta]
public class DropPointController : ScriptableDC
{
public DropPointController(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
|
Traderain/Wolven-kit
|
CP77.CR2W/Types/cp77/DropPointController.cs
|
C#
|
gpl-3.0
| 231
|
package com.example.sample.unit.test.SampleUnitTestsSB_154.dao.mockito;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.mock.mockito.SpyBean;
import org.springframework.test.context.junit4.SpringRunner;
import com.example.sample.unit.test.SampleUnitTestsSB_154.dao.ExampleDAOImpl;
@RunWith(SpringRunner.class) // since 1.4.X version we can use this annotation to run the test using SB features
public class ExampleDAOImplTest {
// include the query because if you change the query accidentally the test case will fail (it's a good checkpoint)
final static String QUERY_FIND_ALL = " SELECT * FROM TEST ";
// SpyBean instantiates the subject of test, injects the mocked dependencies and invokes the real object methods
@SpyBean
ExampleDAOImpl exampleDAOImpl;
// mock the autowired dependency of the test subject
@MockBean
DataSource dataSourceMock;
// mocks the connection used by the DataSource mock
@MockBean
Connection connectionMock;
// mocks the prepared statment used by the DataSource mock
@MockBean
PreparedStatement preparedStatementMock = null;
// mocks the result set used by the DataSource mock
@MockBean
ResultSet resultSetMock = null;
// used to assert and catch the expected exceptions thrown by the test subject
@Rule
public ExpectedException thrown = ExpectedException.none();
// expect values to be returned by the dao
private Map<String,String> expectedNames;
// executed before each test case method -> initializes the expected values
@Before
public void setUp() {
expectedNames = new HashMap<>();
for (int i = 1; i < 6; i++) {
expectedNames.put(String.valueOf(i), "Name "+ i);
}
// we don't need initializes the mocked objects and their dependencies -> Spring Boot doing that :)
// MockitoAnnotations.initMocks(this);
}
@Test
public void findAllWithValidArgumentsShouldReturnAMapWithAllNames() throws Exception {
// you can use in static way or do a static import
// mocks the expected behavior for the DAO in this test case
// important: you will test only the logic and the coverage of the test subject so mock the dependencies for that
Mockito.doReturn(connectionMock).when(dataSourceMock).getConnection();
Mockito.doReturn(preparedStatementMock).when(connectionMock).prepareStatement(QUERY_FIND_ALL);
Mockito.doReturn(resultSetMock).when(preparedStatementMock).executeQuery();
// mocks the ResultSet iteration and sets the expect results
// you can chain the expected behavior of the iteration
Mockito.doReturn(true).doReturn(true).doReturn(true).doReturn(true).doReturn(true).doReturn(false).when(resultSetMock).next();
Mockito.doReturn("1").doReturn("2").doReturn("3").doReturn("4").doReturn("5").when(resultSetMock).getString(1);
Mockito.doReturn(expectedNames.get("1"))
.doReturn(expectedNames.get("2"))
.doReturn(expectedNames.get("3"))
.doReturn(expectedNames.get("4"))
.doReturn(expectedNames.get("5"))
.when(resultSetMock).getString(2);
// mocks the finally block
Mockito.doNothing().when(resultSetMock).close(); // the close method is a void method so you don't expect any result
Mockito.doNothing().when(preparedStatementMock).close();
Mockito.doNothing().when(connectionMock).close();
// invokes the test subject that uses the mocked behaviors
Map<String,String> result = exampleDAOImpl.findAll();
// assert the expected results of the test case
assertThat(result, notNullValue());
assertThat(result.size(), equalTo(expectedNames.size()));
assertThat(result.get("1"), equalTo(expectedNames.get("1"))); // should be "Name 1"
assertThat(result.get("1"), equalTo("Name 1")); // another way for the previous assertion
assertThat(result.get("2"), equalTo(expectedNames.get("2")));
assertThat(result.get("3"), equalTo(expectedNames.get("3")));
assertThat(result.get("4"), equalTo(expectedNames.get("4")));
assertThat(result.get("5"), equalTo(expectedNames.get("5")));
// indicates to Mockito that verifies if the mocked objects were called
Mockito.verify(dataSourceMock).getConnection();
// you should include Mockito.verify for each mocked method and object
}
@Test
public void findAllWithValidArgumentsShouldThrowASQLExceptionWhenGetConnectionThrowsAnException() throws Exception {
SQLException expectedException = new SQLException("Get Connection Exception");
// should be before the test subject method invocation
// indicates that the test case expects an exception of SQLException class with this message
thrown.expect(SQLException.class);
thrown.expectMessage(expectedException.getMessage());
// forces to throw an exception from the service to test the controller's catch code
Mockito.doThrow(expectedException).when(dataSourceMock).getConnection();
// mocks the finally block
Mockito.doNothing().when(resultSetMock).close(); // the close method is a void method so you don't expect any result
Mockito.doNothing().when(preparedStatementMock).close();
Mockito.doNothing().when(connectionMock).close();
// invokes the test subject that uses the mocked behaviors
// don't expect any assert because the DAO method should thrown an Exception
exampleDAOImpl.findAll();
Mockito.verify(dataSourceMock).getConnection();
// you should include Mockito.verify for each mocked method and object
}
}
|
Gabotto/SampleUnitTests
|
SampleUnitTests-SB_1.5.4/src/test/java/com/example/sample/unit/test/SampleUnitTestsSB_154/dao/mockito/ExampleDAOImplTest.java
|
Java
|
gpl-3.0
| 5,914
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="es">
<head>
<!-- Generated by javadoc (version 1.7.0_17) on Tue Nov 19 15:40:32 CET 2013 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class bookstore.presentation.view.BookStoreGUI</title>
<meta name="date" content="2013-11-19">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class bookstore.presentation.view.BookStoreGUI";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../bookstore/presentation/view/BookStoreGUI.html" title="class in bookstore.presentation.view">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?bookstore/presentation/view/class-use/BookStoreGUI.html" target="_top">Frames</a></li>
<li><a href="BookStoreGUI.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class bookstore.presentation.view.BookStoreGUI" class="title">Uses of Class<br>bookstore.presentation.view.BookStoreGUI</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../bookstore/presentation/view/BookStoreGUI.html" title="class in bookstore.presentation.view">BookStoreGUI</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#bookstore.presentation.view">bookstore.presentation.view</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="bookstore.presentation.view">
<!-- -->
</a>
<h3>Uses of <a href="../../../../bookstore/presentation/view/BookStoreGUI.html" title="class in bookstore.presentation.view">BookStoreGUI</a> in <a href="../../../../bookstore/presentation/view/package-summary.html">bookstore.presentation.view</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../bookstore/presentation/view/BookStoreGUI.html" title="class in bookstore.presentation.view">BookStoreGUI</a> in <a href="../../../../bookstore/presentation/view/package-summary.html">bookstore.presentation.view</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../bookstore/presentation/view/BookStoreGUIImp.html" title="class in bookstore.presentation.view">BookStoreGUIImp</a></strong></code>
<div class="block">Pablo Albaladejo Mestre (pablo.albaladejo.mestre@gmail.com)</div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../bookstore/presentation/view/package-summary.html">bookstore.presentation.view</a> that return <a href="../../../../bookstore/presentation/view/BookStoreGUI.html" title="class in bookstore.presentation.view">BookStoreGUI</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../bookstore/presentation/view/BookStoreGUI.html" title="class in bookstore.presentation.view">BookStoreGUI</a></code></td>
<td class="colLast"><span class="strong">BookStoreGUI.</span><code><strong><a href="../../../../bookstore/presentation/view/BookStoreGUI.html#getInstance()">getInstance</a></strong>()</code>
<div class="block">A unique object wich extends the abstract class</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../bookstore/presentation/view/BookStoreGUI.html" title="class in bookstore.presentation.view">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?bookstore/presentation/view/class-use/BookStoreGUI.html" target="_top">Frames</a></li>
<li><a href="BookStoreGUI.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
pablo-albaladejo/javaee
|
Modulo1/BookStore/dist/javadoc/bookstore/presentation/view/class-use/BookStoreGUI.html
|
HTML
|
gpl-3.0
| 7,407
|
from preprocessing.tests import TestMetabolicStandardScaler
from preprocessing.tests import TestMetabolicChangeScaler
from preprocessing.tests import TestMetabolicSolutionScaler
from preprocessing.tests import TestMostActivePathwayScaler
from classifiers.tests import TestMetaboliteLevelDiseaseClassifier
from classifiers.tests import TestSolutionLevelDiseaseClassifier
from classifiers.tests import TestFromSolutionSolutionLevelDiseaseClassifier
from classifiers.tests import TestDummyClassifier
from clustering.tests import TestMetaboliteLevelDiseaseClustering
from metrics.test import TestExtendedJaccard
from services.tests import TestSolutionService
from services.tests import TestNamingService
from services.tests import TestDataReader
import unittest
if __name__ == "__main__":
unittest.main()
|
MuhammedHasan/disease-diagnosis
|
src/tests.py
|
Python
|
gpl-3.0
| 812
|
import { resolve } from 'path';
import { loadData } from '@common/load';
import { cl /*, select*/ } from '@common/debug-select';
import { IRNGNormalTypeEnum } from '@rng/normal/in01-type';
import { globalUni, RNGKind } from '@rng/global-rng';
import { IRNGTypeEnum } from '@rng/irng-type';
//const rbinomDomainWarns = select('rbinom')("argument out of domain in '%s'");
//rbinomDomainWarns;
import { rbinom } from '..';
describe('rbinom', function () {
beforeAll(() => {
RNGKind(IRNGTypeEnum.MERSENNE_TWISTER, IRNGNormalTypeEnum.INVERSION);
cl.clear('_rbinom');
});
it('n=10, unifrom=Mersenne T, norm=Inversion, size=100, n=10, prob=0.2', () => {
const uni = globalUni();
uni.init(1234);
const actual = rbinom(10, 100, 0.5);
expect(actual).toEqualFloatingPointBinary([47, 40, 48, 47, 48, 53, 52, 53, 53, 47]);
});
it('n=10, size=Inf, prob=0.4', () => {
const uni = globalUni();
uni.init(12345);
const nans = rbinom(10, Infinity, 0.4);
expect(nans).toEqualFloatingPointBinary(Array.from({ length: 10 }, () => NaN));
});
it('n=10, size=10.2 prob=0.4', () => {
const nans = rbinom(10, 10.2, 0.4);
expect(nans).toEqualFloatingPointBinary(Array.from({ length: 10 }, () => NaN));
});
it('n=10, size=10 prob=1.4', () => {
const nans = rbinom(10, 10, 1.4);
expect(nans).toEqualFloatingPointBinary(Array.from({ length: 10 }, () => NaN));
});
it('n=10, size=0 prob=0.4', () => {
const zeros = rbinom(10, 0, 0.4);
expect(zeros).toEqualFloatingPointBinary(Array.from({ length: 10 }, () => 0));
});
it('n=10, size=4 prob=1', () => {
const fours = rbinom(10, 4, 1);
expect(fours).toEqualFloatingPointBinary(
Array.from({ length: 10 }, () => 4));
});
it('n=10, size=Number.MAX_SAFE_INTEGER * 2, prob=0.5', () => {
globalUni().init(12345);
const z = rbinom(10, 2147483647, 0.5);
expect(z).toEqualFloatingPointBinary([
1073728257,
1073715082,
1073725385,
1073713876,
1073744356,
1073764266,
1073752331,
1073741288,
1073727785,
1073688147
]);
});
it('n=100, size=500, prob=0.9', async () => {
const uni = globalUni();
uni.init(12345);
const [y] = await loadData(resolve(__dirname, 'fixture-generation', 'rbinom1.R'), /\s+/, 1);
const actual = rbinom(100, 500, 0.9);
expect(actual).toEqualFloatingPointBinary(y);
});
it('n=100, size=500, prob=0.001', async () => {
const uni = globalUni();
uni.init(12345);
const [y] = await loadData(resolve(__dirname, 'fixture-generation', 'rbinom2.R'), /\s+/, 1);
const actual = rbinom(100, 500, 0.001);
expect(actual).toEqualFloatingPointBinary(y);
});
});
|
jacobbogers/libRmath.js
|
src/lib/distributions/binomial/__test__/rbinom.test.ts
|
TypeScript
|
gpl-3.0
| 2,954
|
/*
* 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 software 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 software. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#define TARGET_BOARD_IDENTIFIER "OBF7"
#define USBD_PRODUCT_STRING "OmnibusF7"
#define LED0 PE0
#define BEEPER PD15
#define BEEPER_INVERTED
#define ACC
#define GYRO
// ICM-20608-G
#define USE_ACC_MPU6500
#define USE_ACC_SPI_MPU6500
#define USE_GYRO_MPU6500
#define USE_GYRO_SPI_MPU6500
#define MPU6500_CS_PIN SPI1_NSS_PIN
#define MPU6500_SPI_INSTANCE SPI1
//#define MPU_INT_EXTI PE8
// MPU6000
#define USE_ACC_MPU6000
#define USE_ACC_SPI_MPU6000
#define USE_GYRO_MPU6000
#define USE_GYRO_SPI_MPU6000
#define MPU6000_CS_PIN SPI3_NSS_PIN
#define MPU6000_SPI_INSTANCE SPI3
//#define MPU_INT_EXTI PD0
#define USE_DUAL_GYRO
#define GYRO_0_CS_PIN MPU6000_CS_PIN
#define GYRO_1_CS_PIN MPU6500_CS_PIN
// TODO: dual gyro support
//#define USE_MPU_DATA_READY_SIGNAL
//#define USE_EXTI
#define USABLE_TIMER_CHANNEL_COUNT 16
#define USE_VCP
#define VBUS_SENSING_PIN PC4
#define USE_UART1
#define UART1_RX_PIN PA10
#define UART1_TX_PIN PA9
//#define AVOID_UART2_FOR_PWM_PPM
//#define USE_UART2
//#define UART2_TX_PIN PA2 //not wired
//#define UART2_RX_PIN PA3
// Assigned to shared output I2C2
#define USE_UART3
#define UART3_RX_PIN PB11
#define UART3_TX_PIN PB10
#define USE_UART6
#define UART6_RX_PIN PC7
#define UART6_TX_PIN PC6
#define SERIAL_PORT_COUNT 4
#define USE_SPI
#define USE_SPI_DEVICE_1
#define USE_SPI_DEVICE_2
#define USE_SPI_DEVICE_3
#define USE_SPI_DEVICE_4
#define SPI1_NSS_PIN PA4
#define SPI1_SCK_PIN PA5
#define SPI1_MISO_PIN PA6
#define SPI1_MOSI_PIN PA7
#define SPI2_NSS_PIN PB12
#define SPI2_SCK_PIN PB13
#define SPI2_MISO_PIN PB14
#define SPI2_MOSI_PIN PB15
#define SPI3_NSS_PIN PA15
#define SPI3_SCK_PIN PC10
#define SPI3_MISO_PIN PC11
#define SPI3_MOSI_PIN PC12
#define SPI4_NSS_PIN PE4
#define SPI4_SCK_PIN PE2
#define SPI4_MISO_PIN PE5
#define SPI4_MOSI_PIN PE6
#define OSD
#define USE_MAX7456
#define MAX7456_SPI_INSTANCE SPI2
#define MAX7456_SPI_CS_PIN SPI2_NSS_PIN
#define MAX7456_SPI_CLK (SPI_CLOCK_STANDARD*2)
#define MAX7456_RESTORE_CLK (SPI_CLOCK_FAST)
#define USE_SDCARD
#define SDCARD_DETECT_INVERTED
#define SDCARD_DETECT_PIN PE3
#define SDCARD_DETECT_EXTI_LINE EXTI_Line3
#define SDCARD_DETECT_EXTI_PIN_SOURCE EXTI_PinSource3
#define SDCARD_DETECT_EXTI_PORT_SOURCE EXTI_PortSourceGPIOE
#define SDCARD_DETECT_EXTI_IRQn EXTI3_IRQn
#define SDCARD_SPI_INSTANCE SPI4
#define SDCARD_SPI_CS_PIN SPI4_NSS_PIN
#define SDCARD_SPI_INITIALIZATION_CLOCK_DIVIDER 256 // 422kHz
// Divide to under 25MHz for normal operation:
#define SDCARD_SPI_FULL_SPEED_CLOCK_DIVIDER 8 // 27MHz
#define SDCARD_DMA_CHANNEL_TX DMA2_Stream1
#define SDCARD_DMA_CHANNEL_TX_COMPLETE_FLAG DMA_FLAG_TCIF1_5
#define SDCARD_DMA_CLK RCC_AHB1Periph_DMA2
#define SDCARD_DMA_CHANNEL DMA_CHANNEL_4
#define USE_I2C
#define USE_I2C_DEVICE_2
#define I2C_DEVICE (I2CDEV_2)
#define BARO
#define USE_BARO_BMP280
#define USE_BARO_SPI_BMP280
#define BMP280_SPI_INSTANCE SPI1
#define BMP280_CS_PIN PA1
#define SENSORS_SET (SENSOR_ACC | SENSOR_BARO)
#define BOARD_HAS_CURRENT_SENSOR
#define BOARD_HAS_VOLTAGE_SENSOR
#define USE_ADC
#define CURRENT_METER_ADC_PIN PC2
#define VBAT_ADC_PIN PC3
#define RSSI_ADC_GPIO_PIN PC5
#define LED_STRIP
#define ENABLE_BLACKBOX_LOGGING_ON_SDCARD_BY_DEFAULT
#define DEFAULT_FEATURES (FEATURE_OSD)
#define DEFAULT_RX_FEATURE FEATURE_RX_SERIAL
#define SERIALRX_PROVIDER SERIALRX_SBUS
#define SERIALRX_UART SERIAL_PORT_USART1
#define USE_SERIAL_4WAY_BLHELI_INTERFACE
#define TARGET_IO_PORTA 0xffff
#define TARGET_IO_PORTB 0xffff
#define TARGET_IO_PORTC 0xffff
#define TARGET_IO_PORTD 0xffff
#define TARGET_IO_PORTE 0xffff
#define USED_TIMERS ( TIM_N(1) | TIM_N(3) | TIM_N(4) )
|
flyinglemonfpv/betaflight
|
src/main/target/OMNIBUSF7/target.h
|
C
|
gpl-3.0
| 4,844
|
# coding: utf-8
from __future__ import unicode_literals
import uuid
from django.db import models
from django.conf import settings
class PricePercentageChange(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
done = models.BooleanField('已经提醒过', default=False)
threshold = models.FloatField(null=True, db_index=True)
increase = models.BooleanField('上涨还是下跌')
owner = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='创建者',
related_name='percent_change', on_delete=models.CASCADE)
period = models.IntegerField('分钟', default=60, db_index=True)
class Meta:
ordering = ["-threshold"]
db_table = 'eosram_price_percent_change'
|
polyrabbit/WeCron
|
WeCron/eosram/models/percent.py
|
Python
|
gpl-3.0
| 763
|
/* GNU Mailutils -- a suite of utilities for electronic mail
Copyright (C) 1999-2002, 2004-2012 Free Software Foundation, Inc.
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with GNU Mailutils. If not, see <http://www.gnu.org/licenses/>. */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#if HAVE_TERMIOS_H
# include <termios.h>
#endif
#include <mailutils/types.h>
#include <mailutils/alloc.h>
#include <mailutils/error.h>
#include <mailutils/errno.h>
#include <mailutils/nls.h>
#include <mailutils/stream.h>
#include <mailutils/sys/stream.h>
#include <mailutils/sys/file_stream.h>
#include <mailutils/util.h>
static int
fd_read (struct _mu_stream *str, char *buf, size_t size, size_t *pret)
{
struct _mu_file_stream *fstr = (struct _mu_file_stream *) str;
ssize_t n = read (fstr->fd, buf, size);
if (n == -1)
return errno;
*pret = n;
return 0;
}
static int
fd_write (struct _mu_stream *str, const char *buf, size_t size, size_t *pret)
{
struct _mu_file_stream *fstr = (struct _mu_file_stream *) str;
ssize_t n = write (fstr->fd, (char*) buf, size);
if (n == -1)
return errno;
*pret = n;
return 0;
}
static int
fd_close (struct _mu_stream *str)
{
struct _mu_file_stream *fstr = (struct _mu_file_stream *) str;
if (fstr->fd != -1)
{
if (!(fstr->flags & _MU_FILE_STREAM_FD_BORROWED) && close (fstr->fd))
return errno;
fstr->fd = -1;
}
return 0;
}
static int
fd_open (struct _mu_stream *str)
{
struct _mu_file_stream *fstr = (struct _mu_file_stream *) str;
int oflg;
int fd;
if (!fstr->filename)
return EINVAL;
if (fstr->fd != -1)
fd_close (str);
/* Map the flags to the system equivalent. */
if ((fstr->stream.flags & MU_STREAM_RDWR) == MU_STREAM_RDWR)
oflg = O_RDWR;
else if (fstr->stream.flags & (MU_STREAM_WRITE|MU_STREAM_APPEND))
oflg = O_WRONLY;
else /* default */
oflg = O_RDONLY;
if (fstr->stream.flags & MU_STREAM_APPEND)
oflg |= O_APPEND;
/* Handle CREAT with care, not to follow symlinks. */
if (fstr->stream.flags & MU_STREAM_CREAT)
{
/* First see if the file already exists. */
fd = open (fstr->filename, oflg);
if (fd == -1)
{
/* Oops bail out. */
if (errno != ENOENT)
return errno;
fd = open (fstr->filename, oflg|O_CREAT|O_EXCL,
0600 | mu_stream_flags_to_mode (fstr->stream.flags, 0));
}
}
else
fd = open (fstr->filename, oflg);
if (fd == -1)
return errno;
if (lseek (fd, 0, SEEK_SET) == -1)
str->flags &= ~MU_STREAM_SEEK;
/* Make sure it will be closed */
fstr->flags &= ~_MU_FILE_STREAM_FD_BORROWED;
fstr->fd = fd;
return 0;
}
int
fd_seek (struct _mu_stream *str, mu_off_t off, mu_off_t *presult)
{
struct _mu_file_stream *fstr = (struct _mu_file_stream *) str;
off = lseek (fstr->fd, off, SEEK_SET);
if (off < 0)
return errno;
*presult = off;
return 0;
}
int
fd_size (struct _mu_stream *str, mu_off_t *psize)
{
struct _mu_file_stream *fstr = (struct _mu_file_stream *) str;
struct stat st;
if (fstat (fstr->fd, &st))
return errno;
*psize = st.st_size;
return 0;
}
void
fd_done (struct _mu_stream *str)
{
struct _mu_file_stream *fstr = (struct _mu_file_stream *) str;
if (fstr->fd != -1)
fd_close (str);
if (fstr->filename && !(fstr->flags & _MU_FILE_STREAM_STATIC_FILENAME))
free (fstr->filename);
if (fstr->echo_state)
free (fstr->echo_state);
}
#ifndef TCSASOFT
# define TCSASOFT 0
#endif
static int
fd_ioctl (struct _mu_stream *str, int code, int opcode, void *ptr)
{
struct _mu_file_stream *fstr = (struct _mu_file_stream *) str;
mu_transport_t *ptrans;
switch (code)
{
case MU_IOCTL_TRANSPORT:
if (!ptr)
return EINVAL;
switch (opcode)
{
case MU_IOCTL_OP_GET:
ptrans = ptr;
ptrans[0] = (mu_transport_t) fstr->fd;
ptrans[1] = NULL;
break;
case MU_IOCTL_OP_SET:
ptrans = ptr;
fstr->fd = (int) ptrans[0];
break;
}
break;
case MU_IOCTL_TRANSPORT_BUFFER:
if (!ptr)
return EINVAL;
else
{
struct mu_buffer_query *qp = ptr;
switch (opcode)
{
case MU_IOCTL_OP_GET:
return mu_stream_get_buffer (str, qp);
case MU_IOCTL_OP_SET:
return mu_stream_set_buffer (str, qp->buftype, qp->bufsize);
}
}
break;
case MU_IOCTL_ECHO:
if (!ptr)
return EINVAL;
switch (opcode)
{
case MU_IOCTL_OP_GET:
*(int*)ptr = fstr->flags & _MU_FILE_STREAM_ECHO_OFF;
break;
case MU_IOCTL_OP_SET:
{
int status;
struct termios t;
int state = *(int*)ptr;
#if HAVE_TCGETATTR
if (state == 0)
{
if (fstr->flags & _MU_FILE_STREAM_ECHO_OFF)
return 0;
status = tcgetattr (fstr->fd, &t);
if (status == 0)
{
fstr->echo_state = malloc (sizeof (t));
if (!fstr->echo_state)
return ENOMEM;
memcpy (fstr->echo_state, &t, sizeof (t));
t.c_lflag &= ~(ECHO | ISIG);
status = tcsetattr (fstr->fd, TCSAFLUSH | TCSASOFT, &t);
if (status == 0)
fstr->flags |= _MU_FILE_STREAM_ECHO_OFF;
}
if (status)
{
status = errno;
if (fstr->echo_state)
{
free (fstr->echo_state);
fstr->echo_state = NULL;
}
}
}
else
{
if (!(fstr->flags & _MU_FILE_STREAM_ECHO_OFF))
return 0;
if (tcsetattr (fstr->fd, TCSAFLUSH | TCSASOFT,
fstr->echo_state))
status = errno;
else
{
status = 0;
free (fstr->echo_state);
fstr->echo_state = NULL;
fstr->flags &= ~_MU_FILE_STREAM_ECHO_OFF;
}
}
return status;
#else
return ENOSYS;
#endif
}
}
break;
case MU_IOCTL_FD:
if (!ptr)
return EINVAL;
switch (opcode)
{
case MU_IOCTL_FD_GET_BORROW:
*(int*) ptr = !!(fstr->flags & _MU_FILE_STREAM_FD_BORROWED);
break;
case MU_IOCTL_FD_SET_BORROW:
if (*(int*)ptr)
fstr->flags |= _MU_FILE_STREAM_FD_BORROWED;
else
fstr->flags &= ~_MU_FILE_STREAM_FD_BORROWED;
break;
}
break;
default:
return ENOSYS;
}
return 0;
}
int
fd_wait (mu_stream_t stream, int *pflags, struct timeval *tvp)
{
struct _mu_file_stream *fstr = (struct _mu_file_stream *) stream;
if (fstr->fd == -1)
return EINVAL;
return mu_fd_wait (fstr->fd, pflags, tvp);
}
int
fd_truncate (mu_stream_t stream, mu_off_t size)
{
struct _mu_file_stream *fstr = (struct _mu_file_stream *) stream;
if (ftruncate (fstr->fd, size))
return errno;
return 0;
}
void
_mu_file_stream_setup (struct _mu_file_stream *str)
{
str->stream.read = fd_read;
str->stream.write = fd_write;
str->stream.open = fd_open;
str->stream.close = fd_close;
str->stream.done = fd_done;
str->stream.seek = fd_seek;
str->stream.size = fd_size;
str->stream.ctl = fd_ioctl;
str->stream.wait = fd_wait;
str->stream.truncate = fd_truncate;
}
int
_mu_file_stream_create (struct _mu_file_stream **pstream, size_t size,
const char *filename, int fd, int flags)
{
struct _mu_file_stream *str =
(struct _mu_file_stream *) _mu_stream_create (size, flags);
if (!str)
return ENOMEM;
_mu_file_stream_setup (str);
if (filename)
str->filename = mu_strdup (filename);
else
str->filename = NULL;
str->fd = fd;
str->flags = 0;
*pstream = str;
return 0;
}
int
mu_file_stream_create (mu_stream_t *pstream, const char *filename, int flags)
{
struct _mu_file_stream *fstr;
int rc = _mu_file_stream_create (&fstr,
sizeof (struct _mu_file_stream),
filename, -1,
flags | MU_STREAM_SEEK);
if (rc == 0)
{
mu_stream_t stream = (mu_stream_t) fstr;
mu_stream_set_buffer (stream, mu_buffer_full, 0);
rc = mu_stream_open (stream);
if (rc)
mu_stream_unref (stream);
else
*pstream = stream;
}
return rc;
}
int
mu_fd_stream_create (mu_stream_t *pstream, char *filename, int fd, int flags)
{
struct _mu_file_stream *fstr;
int rc;
if (flags & MU_STREAM_SEEK)
{
if (lseek (fd, 0, SEEK_SET))
return errno;
}
rc = _mu_file_stream_create (&fstr,
sizeof (struct _mu_file_stream),
filename, fd, flags|_MU_STR_OPEN);
if (rc == 0)
{
mu_stream_t stream = (mu_stream_t) fstr;
mu_stream_set_buffer (stream, mu_buffer_full, 0);
*pstream = stream;
}
return rc;
}
|
Distrotech/mailutils
|
libmailutils/stream/file_stream.c
|
C
|
gpl-3.0
| 8,959
|
<?php
/**
* The template for displaying the footer.
*
* Contains the closing of the #content div and all content after
*
* @package understrap
*/
$the_theme = wp_get_theme();
$container = get_theme_mod( 'understrap_container_type' );
?>
</div><!-- #page -->
<?php wp_footer(); ?>
</body>
</html>
|
igaweb/wpiu
|
wordpress/wp-content/themes/understrap/footer.php
|
PHP
|
gpl-3.0
| 307
|
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<p>Filtering input:</p>
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in names | filter:test | orderBy:'country'">
{{ (x.name | uppercase) + ', ' + x.country }}
</li>
</ul>
</div>
<script src="namesController.js"></script>
</body>
</html>
|
masihtehrani/angular-tutorial-example
|
16/index.html
|
HTML
|
gpl-3.0
| 480
|
$(function() {
var animationDuration = 500;
$('.portal-menu-siblings').each(function() {
var self = $(this);
var parent = $(this).parent();
var a = parent.children('a');
var chevron = parent.find('.icon-chevron-down');
var inTimeout, outTimeout;
var orientation = 0;
parent.hover(function() {
a.addClass('hover');
clearTimeout(outTimeout);
inTimeout = setTimeout(function() {
self.stop(true).css('display', 'block').animate({
left: '100%',
opacity: 1
}, animationDuration);
chevron.stop(true, true);
$({deg: orientation}).animate({deg: -90}, {
step: function(now) {
chevron.css({transform: 'rotate(' + now + 'deg)'});
orientation = now;
},
duration: animationDuration
});
}, 400);
}, function() {
a.removeClass('hover');
clearTimeout(inTimeout);
outTimeout = setTimeout(function() {
self.stop(true).animate({
left: '0',
opacity: 0
}, animationDuration);
outTimeout = setTimeout(function() {
self.css('display', 'none');
}, animationDuration);
chevron.stop(true, true);
$({deg: orientation}).animate({deg: 0}, {
step: function(now) {
chevron.css({transform: 'rotate(' + now + 'deg)'});
orientation = now;
},
duration: animationDuration
});
}, 400);
});
var url = a.attr('href');
var height = parent.height() + 1;
var top = -3;
$(this).children('li').each(function() {
if($(this).children('a').attr('href') == url)
return false;
top -= height;
});
$(this).css('top', top + 'px');
});
});
|
papedaniel/oioioi
|
oioioi/portals/static/common/portal.js
|
JavaScript
|
gpl-3.0
| 2,167
|
/**
* Copyright (C) 2001-2016 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.preprocessing.outlier;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Attributes;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.example.table.AttributeFactory;
import com.rapidminer.operator.OperatorDescription;
import com.rapidminer.operator.OperatorException;
import com.rapidminer.operator.annotation.ResourceConsumptionEstimator;
import com.rapidminer.parameter.ParameterType;
import com.rapidminer.parameter.ParameterTypeCategory;
import com.rapidminer.parameter.ParameterTypeInt;
import com.rapidminer.tools.Ontology;
import com.rapidminer.tools.OperatorResourceConsumptionHandler;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* <p>
* This operator performs a D^k_n Outlier Search according to the outlier detection approach
* recommended by Ramaswamy, Rastogi and Shim in "Efficient Algorithms for Mining Outliers from
* Large Data Sets". It is primarily a statistical outlier search based on a distance measure
* similar to the DB(p,D)-Outlier Search from Knorr and Ng. But it utilizes a distance search
* through the k-th nearest neighbourhood, so it implements some sort of locality as well.
* </p>
*
* <p>
* The method states, that those objects with the largest distance to their k-th nearest neighbours
* are likely to be outliers respective to the data set, because it can be assumed, that those
* objects have a more sparse neighbourhood than the average objects. As this effectively provides a
* simple ranking over all the objects in the data set according to the distance to their k-th
* nearest neighbours, the user can specify a number of n objects to be the top-n outliers in the
* data set.
* </p>
*
* <p>
* The operator supports cosine, sine or squared distances in addition to the euclidian distance
* which can be specified by a distance parameter. The Operator takes an example set and passes it
* on with an boolean top-n D^k outlier status in a new boolean-valued special outlier attribute
* indicating true (outlier) and false (no outlier).
* </p>
*
* @author Stephan Deutsch, Ingo Mierswa
*/
public class DKNOutlierOperator extends AbstractOutlierDetection {
/**
* The parameter name for "Specifies the k value for the k-th nearest neighbours to be the
* analyzed."
*/
public static final String PARAMETER_NUMBER_OF_NEIGHBORS = "number_of_neighbors";
/** The parameter name for "The number of top-n Outliers to be looked for." */
public static final String PARAMETER_NUMBER_OF_OUTLIERS = "number_of_outliers";
/**
* The parameter name for "choose which distance function will be used for calculating
* "
*/
public static final String PARAMETER_DISTANCE_FUNCTION = "distance_function";
private static final String[] distanceFunctionList = { "euclidian distance", "squared distance", "cosine distance",
"inverted cosine distance", "angle" };
public DKNOutlierOperator(OperatorDescription description) {
super(description);
}
/**
* This method implements the main functionality of the Operator but can be considered as a sort
* of wrapper to pass the RapidMiner operator chain data deeper into the search space class, so
* do not expect a lot of things happening here.
*/
@Override
public ExampleSet apply(ExampleSet eSet) throws OperatorException {
// declaration and initializing the necessary fields from input
int k = this.getParameterAsInt(PARAMETER_NUMBER_OF_NEIGHBORS);
int n = this.getParameterAsInt(PARAMETER_NUMBER_OF_OUTLIERS);
n = n - 2; // this has to do with the internal indexing in the SearchSpace's methods
int kindOfDistance = this.getParameterAsInt(PARAMETER_DISTANCE_FUNCTION);
// create a new SearchSpace for the DKN(p,D)-Outlier search
Iterator<Example> reader = eSet.iterator();
int searchSpaceDimension = eSet.getAttributes().size();
SearchSpace sr = new SearchSpace(searchSpaceDimension, k, k);
// now read through the Examples of the ExampleSet
int counter = 0;
while (reader.hasNext()) {
Example example = reader.next(); // read the next example & create a search object
SearchObject so = new SearchObject(searchSpaceDimension, "object" + counter, k, k + 1); // for
// now,
// give
// so
// an
// id
// like
// label
counter++;
int i = 0;
for (Attribute attribute : eSet.getAttributes()) {
so.setVektor(i++, example.getValue(attribute)); // get the attributes for the so
// from example and pass it on
}
sr.addObject(so); // finally add the search object to the search room
}
// set all Outlier Status to ZERO to be sure
sr.resetOutlierStatus();
// find all Containers for the DKN first
sr.findAllKdContainers(kindOfDistance, this);
// perform the outlier search
sr.computeDKN(k, n, this);
// create a new special attribute for the exampleSet
Attribute outlierAttribute = AttributeFactory.createAttribute(Attributes.OUTLIER_NAME, Ontology.BINOMINAL);
outlierAttribute.getMapping().mapString("false");
outlierAttribute.getMapping().mapString("true");
eSet.getExampleTable().addAttribute(outlierAttribute);
eSet.getAttributes().setOutlier(outlierAttribute);
counter = 0; // reset counter to zero
Iterator<Example> reader2 = eSet.iterator();
while (reader2.hasNext()) {
Example example = reader2.next();
if (sr.getSearchObjectOutlierStatus(counter) == true) {
example.setValue(outlierAttribute, outlierAttribute.getMapping().mapString("true"));
} else {
example.setValue(outlierAttribute, outlierAttribute.getMapping().mapString("false"));
}
counter++;
}
return eSet;
}
@Override
public List<ParameterType> getParameterTypes() {
List<ParameterType> types = super.getParameterTypes();
types.add(new ParameterTypeInt(PARAMETER_NUMBER_OF_NEIGHBORS,
"Specifies the k value for the k-th nearest neighbours to be the analyzed."
+ "(default value is 10, minimum 1 and max is set to 1 million)", 1, Integer.MAX_VALUE, 10, false));
types.add(new ParameterTypeInt(PARAMETER_NUMBER_OF_OUTLIERS, "The number of top-n Outliers to be looked for."
+ "(default value is 10, minimum 2 (internal reasons) and max is set to 1 million)", 1, Integer.MAX_VALUE,
10, false));
types.add(new ParameterTypeCategory(PARAMETER_DISTANCE_FUNCTION,
"choose which distance function will be used for calculating " + "the distance between two objects",
distanceFunctionList, 0, false));
return types;
}
@Override
protected Set<String> getOutlierValues() {
HashSet<String> set = new HashSet<>();
set.add("true");
set.add("false");
return set;
}
@Override
public ResourceConsumptionEstimator getResourceConsumptionEstimator() {
return OperatorResourceConsumptionHandler.getResourceConsumptionEstimator(getInputPort(), DKNOutlierOperator.class,
null);
}
}
|
transwarpio/rapidminer
|
rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/operator/preprocessing/outlier/DKNOutlierOperator.java
|
Java
|
gpl-3.0
| 8,123
|
/*
* A manual example using JCalendarButton.
* JCalendarTest.java
* Created on Aug 24, 2009, 10:47:11 PM
* Copyright © 2012 jbundle.org. All rights reserved.
*/
package calendartest;
import java.text.DateFormat;
import java.util.Date;
/**
*
* @author don
*/
public class JCalendarTest extends javax.swing.JFrame {
/** Creates new form NewJFrame */
public JCalendarTest() {
initComponents();
}
/**
* Command line startup
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JCalendarTest().setVisible(true);
}
});
}
/** This method is called from within the constructor to
* initialize the form.
*/
private void initComponents() {
jLabel1 = new javax.swing.JLabel("Name:");
jTextField1 = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel("Date:");
jTextField2 = new javax.swing.JTextField();
jTextField2.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
String date = jTextField2.getText();
setDate(date);
}
});
jLabel3 = new javax.swing.JLabel("Time:");
jTextField3 = new javax.swing.JTextField();
jTextField3.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
String time = jTextField3.getText();
setTime(time);
}
});
jLabel4 = new javax.swing.JLabel("Date and Time:");
jTextField4 = new javax.swing.JTextField();
jTextField4.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
String dateTime = jTextField4.getText();
setDateTime(dateTime);
}
});
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
// Layout components
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE)
.addComponent(jTextField4)
.addComponent(jTextField3)
.addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE))
.addContainerGap(124, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(59, Short.MAX_VALUE))
);
pack();
}
/**
* Validate and set the datetime field on the screen given a datetime string.
* @param dateTime The datetime string
*/
public void setDate(String dateString)
{
Date date = null;
try {
if ((dateString != null) && (dateString.length() > 0))
date = dateFormat.parse(dateString);
} catch (Exception e) {
date = null;
}
this.setDate(date);
}
/**
* Validate and set the datetime field on the screen given a date.
* @param dateTime The datetime object
*/
public void setDate(Date date)
{
String dateString = "";
if (date != null)
dateString = dateFormat.format(date);
jTextField2.setText(dateString);
}
/**
* Validate and set the datetime field on the screen given a datetime string.
* @param dateTime The datetime string
*/
public void setTime(String timeString)
{
Date time = null;
try {
if ((timeString != null) && (timeString.length() > 0))
time = timeFormat.parse(timeString);
} catch (Exception e) {
time = null;
}
this.setTime(time);
}
/**
* Validate and set the datetime field on the screen given a date.
* @param dateTime The datetime object
*/
public void setTime(Date time)
{
String timeString = "";
if (time != null)
timeString = timeFormat.format(time);
jTextField3.setText(timeString);
}
/**
* Validate and set the datetime field on the screen given a datetime string.
* @param dateTime The datetime string
*/
public void setDateTime(String dateTimeString)
{
Date dateTime = null;
try {
if ((dateTimeString != null) && (dateTimeString.length() > 0))
dateTime = dateTimeFormat.parse(dateTimeString);
} catch (Exception e) {
dateTime = null;
}
this.setDateTime(dateTime);
}
/**
* Validate and set the datetime field on the screen given a date.
* @param dateTime The datetime object
*/
public void setDateTime(Date dateTime)
{
String dateTimeString = "";
if (dateTime != null)
dateTimeString = dateTimeFormat.format(dateTime);
jTextField4.setText(dateTimeString);
}
// Variables declaration
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
public static DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
public static DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT);
public static DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
}
|
jbundle/jcalendarbutton
|
jcalendarbutton/src/site/resources/manual/code1/JCalendarTest.java
|
Java
|
gpl-3.0
| 8,107
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ECCentral.BizEntity.Common;
using ECCentral.Service.Utility;
using ECCentral.Service.MKT.IDataAccess;
using System.ServiceModel.Web;
using ECCentral.QueryFilter.MKT;
using ECCentral.BizEntity.MKT;
using ECCentral.Service.MKT.AppService;
using ECCentral.Service.Utility.WCF;
using ECCentral.Service.MKT.IDataAccess.NoBizQuery;
using ECCentral.BizEntity.MKT.PageType;
using ECCentral.BizEntity.MKT;
using System.Data;
namespace ECCentral.Service.MKT.Restful
{
public partial class MKTService
{
[WebInvoke(UriTemplate = "/ProductRecommend/Query", Method = "POST")]
public virtual QueryResult QueryProductRecommend(ProductRecommendQueryFilter filter)
{
int totalCount;
var dt = ObjectFactory<IProductRecommendQueryDA>.Instance.Query(filter, out totalCount);
QueryResult result = new QueryResult();
result.Data = dt;
result.TotalCount = totalCount;
GetInventoryInfoByStock(dt);
dt.Columns.Add("PageTypeName", typeof(string));
dt.Columns.Add("PositionName", typeof(string));
//获取页面类型
var pageTypes = ObjectFactory<PageTypeAppService>.Instance.GetPageType(filter.CompanyCode, filter.ChannelID, ModuleType.ProductRecommend);
Dictionary<string, List<CodeNamePair>> dictPositionCache = new Dictionary<string, List<CodeNamePair>>();
foreach (DataRow dr in result.Data.Rows)
{
string pageTypeID = dr["PageType"].ToString();
var foundPageType = pageTypes.FirstOrDefault(item => item.Code == pageTypeID);
if (foundPageType != null)
{
dr["PageTypeName"] = foundPageType.Name;
}
//根据PageType查询位置信息
List<CodeNamePair> currentPagePosition;
if (!dictPositionCache.TryGetValue(pageTypeID, out currentPagePosition))
{
currentPagePosition = this.GetProductRecommendPosition(pageTypeID);
if(currentPagePosition!=null&¤tPagePosition.Count>0)
{
currentPagePosition.ForEach(v=>
{
if(v.Name.Contains("专卖店--"))
{
v.Name = v.Name.Replace("专卖店--", "");
}
});
}
dictPositionCache.Add(pageTypeID, currentPagePosition);
}
var foundPosition = currentPagePosition.FirstOrDefault(item => item.Code == dr["PositionID"].ToString());
if (foundPosition != null)
{
dr["PositionName"] = foundPosition.Name;
}
}
return result;
}
#region 商品查询合并分仓库存信息
/// <summary>
/// 获取包含分仓库存的数据
/// </summary>
/// <param name="product"></param>
/// <returns></returns>
public virtual void GetInventoryInfoByStock(DataTable product)
{
if (product == null || product.Rows.Count == 0) return;
var stockList = new Dictionary<string, int> {
{ "Shanghai", 51 },
{ "Begjin", 52 },
{ "Guangzhou", 53 }
};
var displayField = new[] { "OnlineQty"};
var columns = (from k in stockList.Keys
from c in displayField
select k + c).ToList();
AddTableColumns(product, columns);
var productSysNoList = (from e in product.AsEnumerable()
select e.Field<int>("ProductSysNo")).ToList();
var prarm = (from k in productSysNoList
from c in stockList.Keys
select new { ProductSysNo = k, Stock = c }).ToList();
prarm.ForEach(v =>
{
var entity = _productRecommendAppService.GetProductInventoryInfoByStock(v.ProductSysNo, stockList[v.Stock]);
var oneProduct = (from e in product.AsEnumerable()
where e.Field<int>("ProductSysNo") == v.ProductSysNo
select e).FirstOrDefault();
displayField.ForEach(k =>
{
int value = 0;
if (entity != null)
{
object tempvalue = null;
var pro = entity.GetType().GetProperty(k);
if (pro != null)
{
tempvalue = Invoker.PropertyGet(entity, k);
}
value = Convert.ToInt32(tempvalue);
}
var columnName = v.Stock + k;
if (oneProduct != null)
oneProduct.SetField(columnName, value);
});
});
}
/// <summary>
/// 合并仓库数据
/// </summary>
/// <param name="product"></param>
/// <param name="columns"></param>
private void AddTableColumns(DataTable product, List<string> columns)
{
if (columns == null || columns.Count == 0) return;
foreach (var item in columns) product.Columns.Add(item).DefaultValue = 0;
}
#endregion
private ProductRecommendAppService _productRecommendAppService = ObjectFactory<ProductRecommendAppService>.Instance;
/// <summary>
/// 创建
/// </summary>
[WebInvoke(UriTemplate = "/ProductRecommend/Create", Method = "POST")]
public virtual void CreateProductRecommend(ProductRecommendInfo entity)
{
_productRecommendAppService.Create(entity);
}
/// <summary>
/// 更新
/// </summary>
[WebInvoke(UriTemplate = "/ProductRecommend/Update", Method = "PUT")]
public virtual void UpdateProductRecommend(ProductRecommendInfo entity)
{
_productRecommendAppService.Update(entity);
}
/// <summary>
/// 加载
/// </summary>
[WebGet(UriTemplate = "/ProductRecommend/Load/{sysNo}")]
public virtual ProductRecommendInfo LoadProductRecommend(string sysNo)
{
int id = int.Parse(sysNo);
return _productRecommendAppService.Load(id);
}
/// <summary>
/// 将商品推荐置为无效
/// </summary>
/// <param name="sysNo">系统编号</param>
[WebInvoke(UriTemplate = "/ProductRecommend/Deactive/{sysNo}", Method = "PUT")]
public virtual void DeactiveProductRecommend(string sysNo)
{
int id = int.Parse(sysNo);
_productRecommendAppService.Deactive(id);
}
[WebGet(UriTemplate = "/ProductRecommend/GetPosition/{pageTypeID}")]
public virtual List<CodeNamePair> GetProductRecommendPosition(string pageTypeID)
{
int pageType = int.Parse(pageTypeID);
var presentationType = PageTypeUtil.ResolvePresentationType(ModuleType.ProductRecommend, pageTypeID);
//if (presentationType == PageTypePresentationType.Brand)
//{
// //当PageType为专卖店时返回空,专卖店有特殊的加载位置信息的逻辑
// return new List<CodeNamePair>();
//}
//商品推荐位置Key格式:ProductRecommend+[PageTypeID],比如ProductRecommend0代表首页的推荐位
var positionConfigKey = ModuleType.ProductRecommend.ToString();
//if (pageType > 100)
//{
// //PageTypeID>100表示是首页domain馆
// positionConfigKey += "-DomainList";
//}
//else
//{
positionConfigKey += pageType.ToString();
//}
var result= CodeNamePairManager.GetList("MKT", positionConfigKey);
return result;
}
[WebGet(UriTemplate = "/ProductRecommend/GetBrandPosition/{pageID}/{comapnyCode}/{channelID}")]
public virtual List<CodeNamePair> GetProductRecommandBrandPosition(string pageID, string comapnyCode, string channelID)
{
var brandLocation = _productRecommendAppService.GetBrandPosition(int.Parse(pageID), comapnyCode, channelID);
List<CodeNamePair> result = new List<CodeNamePair>();
foreach (var loc in brandLocation)
{
result.Add(new CodeNamePair
{
Code = loc.PositionID.ToString(),
Name = string.Format("专卖店--{0}", loc.Description)
});
}
return result;
}
}
}
|
ZeroOne71/ql
|
02_ECCentral/03_Service/03_MKT/ECCentral.Service.MKT.Restful/MKTService_ProductRecommend.cs
|
C#
|
gpl-3.0
| 9,469
|
local load_res = macondo_load('xt 19009')
print(load_res)
local res = macondo_gen('1')
print(res) -- yes CHEW
|
domino14/macondo
|
scripts/parse_xt.lua
|
Lua
|
gpl-3.0
| 110
|
<?php
/**
* @package Rakuun Browsergame
* @copyright Copyright (C) 2012 Sebastian Mayer, Andreas Sicking, Andre Jährling
* @license GNU/GPL, see license.txt
* This file is part of Rakuun.
*
* Rakuun 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.
*
* Rakuun 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 Rakuun. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class Rakuun_Intern_GUI_Panel_Tutor_Tipp extends Rakuun_Intern_GUI_Panel_Tutor_Level {
public function completed() {
return true;
}
}
?>
|
Sebioff/Rakuun
|
source/intern/gui/panel/tutor/tipp.php
|
PHP
|
gpl-3.0
| 998
|
/*
* 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.
*/
/**
*
* @author apavel
*/
public class ABC {
public void TskA() {
System.out.print("Member of ABC, TskA");
}
public void TskB() {
System.out.print("TskB does addition");
}
public void TskC() {
System.out.print("TskC doe mult");
}
}
|
AlexNPavel/APCompSciStuff
|
APCompSciStuffSince Oct13/src/ABC.java
|
Java
|
gpl-3.0
| 490
|
/**
* MutableLong.java
*
* Copyright 2010 Jeffrey Finkelstein
*
* This file is part of jmona.
*
* jmona 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.
*
* jmona 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
* jmona. If not, see <http://www.gnu.org/licenses/>.
*/
package jmona.impl.mutable;
import jmona.DeepCopyable;
/**
* A deep-copyable, mutable long wrapper.
*
* @author Jeffrey Finkelstein
* @since 0.5
*/
public class MutableLong extends org.apache.commons.lang.mutable.MutableLong
implements DeepCopyable<MutableLong> {
/** Default generated serial version UID. */
private static final long serialVersionUID = -270777759872744946L;
/**
* Instantiates this object by calling the default constructor of the
* superclass.
*/
public MutableLong() {
// intentionally unimplemented
}
/**
* Instantiates this object with the specified initial value.
*
* @param initialValue
* The initial value of this object.
*/
public MutableLong(final long initialValue) {
super(initialValue);
}
/**
* Instantiates this object with the specified initial value.
*
* @param initialValue
* The initial value of this object.
*/
public MutableLong(final Number initialValue) {
super(initialValue);
}
/**
* {@inheritDoc}
*
* @return {@inheritDoc}
* @see jmona.DeepCopyable#deepCopy()
*/
@Override
public MutableLong deepCopy() {
return new MutableLong(this);
}
}
|
jfinkels/jmona
|
jmona-model/src/main/java/jmona/impl/mutable/MutableLong.java
|
Java
|
gpl-3.0
| 1,950
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React App Setup</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: left;
padding: 8px;
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<div id="root">
</div>
</body>
</html>
|
MarcoNicolodi/react-data-table
|
index.html
|
HTML
|
gpl-3.0
| 479
|
#include <stddef.h>
#undef offset
#include <kern/cpu_data.h>
#include <os/base.h>
#include <os/object.h>
#include <os/log.h>
#include <stdbool.h>
#include <stdint.h>
#include <vm/vm_kern.h>
#include <mach/vm_statistics.h>
#include <kern/debug.h>
#include <libkern/libkern.h>
#include <libkern/kernel_mach_header.h>
#include <pexpert/pexpert.h>
#include <uuid/uuid.h>
#include <sys/msgbuf.h>
#include <mach/mach_time.h>
#include <kern/thread.h>
#include <kern/simple_lock.h>
#include <kern/kalloc.h>
#include <kern/clock.h>
#include <kern/assert.h>
#include <firehose/tracepoint_private.h>
#include <firehose/chunk_private.h>
#include <os/firehose_buffer_private.h>
#include <os/firehose.h>
#include <os/log_private.h>
#include "trace_internal.h"
#include "log_encode.h"
struct os_log_s {
int a;
};
struct os_log_s _os_log_default;
struct os_log_s _os_log_replay;
extern vm_offset_t kernel_firehose_addr;
extern firehose_chunk_t firehose_boot_chunk;
extern void bsd_log_lock(void);
extern void bsd_log_unlock(void);
extern void logwakeup(void);
decl_lck_spin_data(extern, oslog_stream_lock)
extern void oslog_streamwakeup(void);
void oslog_streamwrite_locked(firehose_tracepoint_id_u ftid,
uint64_t stamp, const void *pubdata, size_t publen);
extern void oslog_streamwrite_metadata_locked(oslog_stream_buf_entry_t m_entry);
extern int oslog_stream_open;
extern void *OSKextKextForAddress(const void *);
/* Counters for persistence mode */
uint32_t oslog_p_total_msgcount = 0;
uint32_t oslog_p_metadata_saved_msgcount = 0;
uint32_t oslog_p_metadata_dropped_msgcount = 0;
uint32_t oslog_p_error_count = 0;
uint32_t oslog_p_saved_msgcount = 0;
uint32_t oslog_p_dropped_msgcount = 0;
uint32_t oslog_p_boot_dropped_msgcount = 0;
/* Counters for streaming mode */
uint32_t oslog_s_total_msgcount = 0;
uint32_t oslog_s_error_count = 0;
uint32_t oslog_s_metadata_msgcount = 0;
static bool oslog_boot_done = false;
extern boolean_t early_boot_complete;
#ifdef XNU_KERNEL_PRIVATE
bool startup_serial_logging_active = true;
uint64_t startup_serial_num_procs = 300;
#endif /* XNU_KERNEL_PRIVATE */
// XXX
firehose_tracepoint_id_t
firehose_debug_trace(firehose_stream_t stream, firehose_tracepoint_id_t trace_id,
uint64_t timestamp, const char *format, const void *pubdata, size_t publen);
static inline firehose_tracepoint_id_t
_firehose_trace(firehose_stream_t stream, firehose_tracepoint_id_u ftid,
uint64_t stamp, const void *pubdata, size_t publen);
static oslog_stream_buf_entry_t
oslog_stream_create_buf_entry(oslog_stream_link_type_t type, firehose_tracepoint_id_u ftid,
uint64_t stamp, const void* pubdata, size_t publen);
static void
_os_log_with_args_internal(os_log_t oslog __unused, os_log_type_t type __unused,
const char *format, va_list args, void *addr, void *dso);
static void
_os_log_to_msgbuf_internal(const char *format, va_list args, bool safe, bool logging);
static void
_os_log_to_log_internal(os_log_t oslog, os_log_type_t type,
const char *format, va_list args, void *addr, void *dso);
static void
_os_log_actual(os_log_t oslog, os_log_type_t type, const char *format, void
*dso, void *addr, os_log_buffer_context_t context);
bool
os_log_info_enabled(os_log_t log __unused)
{
return true;
}
bool
os_log_debug_enabled(os_log_t log __unused)
{
return true;
}
os_log_t
os_log_create(const char *subsystem __unused, const char *category __unused)
{
return &_os_log_default;
}
bool
_os_log_string_is_public(const char *str __unused)
{
return true;
}
__attribute__((noinline,not_tail_called)) void
_os_log_internal(void *dso, os_log_t log, uint8_t type, const char *message, ...)
{
va_list args;
void *addr = __builtin_return_address(0);
va_start(args, message);
_os_log_with_args_internal(log, type, message, args, addr, dso);
va_end(args);
return;
}
#pragma mark - shim functions
__attribute__((noinline,not_tail_called)) void
os_log_with_args(os_log_t oslog, os_log_type_t type, const char *format, va_list args, void *addr)
{
// if no address passed, look it up
if (addr == NULL) {
addr = __builtin_return_address(0);
}
_os_log_with_args_internal(oslog, type, format, args, addr, NULL);
}
static void
_os_log_with_args_internal(os_log_t oslog, os_log_type_t type,
const char *format, va_list args, void *addr, void *dso)
{
uint32_t logging_config = atm_get_diagnostic_config();
boolean_t safe;
boolean_t logging;
if (format[0] == '\0') {
return;
}
/* early boot can log to dmesg for later replay (27307943) */
safe = (!early_boot_complete || oslog_is_safe());
if (logging_config & ATM_TRACE_DISABLE || logging_config & ATM_TRACE_OFF) {
logging = false;
} else {
logging = true;
}
if (oslog != &_os_log_replay) {
_os_log_to_msgbuf_internal(format, args, safe, logging);
}
if (safe && logging) {
_os_log_to_log_internal(oslog, type, format, args, addr, dso);
}
}
static void
_os_log_to_msgbuf_internal(const char *format, va_list args, bool safe, bool logging)
{
static int msgbufreplay = -1;
va_list args_copy;
bsd_log_lock();
if (!safe) {
if (-1 == msgbufreplay) msgbufreplay = msgbufp->msg_bufx;
} else if (logging && (-1 != msgbufreplay)) {
uint32_t i;
uint32_t localbuff_size;
int newl, position;
char *localbuff, *p, *s, *next, ch;
position = msgbufreplay;
msgbufreplay = -1;
localbuff_size = (msgbufp->msg_size + 2); /* + '\n' + '\0' */
/* Size for non-blocking */
if (localbuff_size > 4096) localbuff_size = 4096;
bsd_log_unlock();
/* Allocate a temporary non-circular buffer */
if ((localbuff = (char *)kalloc_noblock(localbuff_size))) {
/* in between here, the log could become bigger, but that's fine */
bsd_log_lock();
/*
* The message buffer is circular; start at the replay pointer, and
* make one loop up to write pointer - 1.
*/
p = msgbufp->msg_bufc + position;
for (i = newl = 0; p != msgbufp->msg_bufc + msgbufp->msg_bufx - 1; ++p) {
if (p >= msgbufp->msg_bufc + msgbufp->msg_size)
p = msgbufp->msg_bufc;
ch = *p;
if (ch == '\0') continue;
newl = (ch == '\n');
localbuff[i++] = ch;
if (i >= (localbuff_size - 2)) break;
}
bsd_log_unlock();
if (!newl) localbuff[i++] = '\n';
localbuff[i++] = 0;
s = localbuff;
while ((next = strchr(s, '\n'))) {
next++;
ch = next[0];
next[0] = 0;
os_log(&_os_log_replay, "%s", s);
next[0] = ch;
s = next;
}
kfree(localbuff, localbuff_size);
}
bsd_log_lock();
}
va_copy(args_copy, args);
vprintf_log_locked(format, args_copy);
va_end(args_copy);
bsd_log_unlock();
if (safe) logwakeup();
}
static void
_os_log_to_log_internal(os_log_t oslog, os_log_type_t type,
const char *format, va_list args, void *addr, void *dso)
{
struct os_log_buffer_context_s context;
unsigned char buffer_data[OS_LOG_BUFFER_MAX_SIZE] __attribute__((aligned(8)));
os_log_buffer_t buffer = (os_log_buffer_t)buffer_data;
uint8_t pubdata[OS_LOG_BUFFER_MAX_SIZE];
va_list args_copy;
if (dso == NULL) {
dso = (void *) OSKextKextForAddress(format);
if (dso == NULL) {
return;
}
}
if (!_os_trace_addr_in_text_segment(dso, format)) {
return;
}
if (addr == NULL) {
return;
}
void *dso_addr = (void *) OSKextKextForAddress(addr);
if (dso != dso_addr) {
return;
}
memset(&context, 0, sizeof(context));
memset(buffer, 0, OS_LOG_BUFFER_MAX_SIZE);
context.shimmed = true;
context.buffer = buffer;
context.content_sz = OS_LOG_BUFFER_MAX_SIZE - sizeof(*buffer);
context.pubdata = pubdata;
context.pubdata_sz = sizeof(pubdata);
va_copy(args_copy, args);
(void)hw_atomic_add(&oslog_p_total_msgcount, 1);
if (_os_log_encode(format, args_copy, 0, &context)) {
_os_log_actual(oslog, type, format, dso, addr, &context);
}
else {
(void)hw_atomic_add(&oslog_p_error_count, 1);
}
va_end(args_copy);
}
static inline size_t
_os_trace_write_location_for_address(uint8_t buf[static sizeof(uint64_t)],
void *dso, const void *address, firehose_tracepoint_flags_t *flags)
{
kernel_mach_header_t *mh = dso;
if (mh->filetype == MH_EXECUTE) {
*flags = _firehose_tracepoint_flags_pc_style_main_exe;
memcpy(buf, (uint32_t[]){ (uintptr_t)address - (uintptr_t)dso },
sizeof(uint32_t));
return sizeof(uint32_t);
} else {
*flags = _firehose_tracepoint_flags_pc_style_absolute;
memcpy(buf, (uintptr_t[]){ VM_KERNEL_UNSLIDE(address) }, sizeof(uintptr_t));
#if __LP64__
return 6; // 48 bits are enough
#else
return sizeof(uintptr_t);
#endif
}
}
OS_ALWAYS_INLINE
static inline size_t
_os_log_buffer_pack(uint8_t *buffdata, size_t buffdata_sz,
os_log_buffer_context_t ctx)
{
os_log_buffer_t buffer = ctx->buffer;
size_t buffer_sz = sizeof(*ctx->buffer) + ctx->content_sz;
size_t total_sz = buffer_sz + ctx->pubdata_sz;
if (total_sz > buffdata_sz) {
return 0;
}
memcpy(buffdata, buffer, buffer_sz);
memcpy(&buffdata[buffer_sz], ctx->pubdata, ctx->pubdata_sz);
return total_sz;
}
static void
_os_log_actual(os_log_t oslog __unused, os_log_type_t type, const char *format,
void *dso, void *addr, os_log_buffer_context_t context)
{
firehose_stream_t stream;
firehose_tracepoint_flags_t flags = 0;
firehose_tracepoint_id_u trace_id;
uint8_t buffdata[OS_LOG_BUFFER_MAX_SIZE];
size_t addr_len = 0, buffdata_sz;
uint64_t timestamp;
uint64_t thread_id;
// dso == the start of the binary that was loaded
addr_len = _os_trace_write_location_for_address(buffdata, dso, addr, &flags);
buffdata_sz = _os_log_buffer_pack(buffdata + addr_len,
sizeof(buffdata) - addr_len, context);
if (buffdata_sz == 0) {
return;
}
buffdata_sz += addr_len;
timestamp = firehose_tracepoint_time(firehose_activity_flags_default);
thread_id = thread_tid(current_thread());
// create trace_id after we've set additional flags
trace_id.ftid_value = FIREHOSE_TRACE_ID_MAKE(firehose_tracepoint_namespace_log,
type, flags, _os_trace_offset(dso, format, flags));
if (FALSE) {
firehose_debug_trace(stream, trace_id.ftid_value, timestamp,
format, buffdata, buffdata_sz);
}
if (type == OS_LOG_TYPE_INFO || type == OS_LOG_TYPE_DEBUG) {
stream = firehose_stream_memory;
}
else {
stream = firehose_stream_persist;
}
_firehose_trace(stream, trace_id, timestamp, buffdata, buffdata_sz);
}
static inline firehose_tracepoint_id_t
_firehose_trace(firehose_stream_t stream, firehose_tracepoint_id_u ftid,
uint64_t stamp, const void *pubdata, size_t publen)
{
const uint16_t ft_size = offsetof(struct firehose_tracepoint_s, ft_data);
const size_t _firehose_chunk_payload_size =
sizeof(((struct firehose_chunk_s *)0)->fc_data);
firehose_tracepoint_t ft;
if (slowpath(ft_size + publen > _firehose_chunk_payload_size)) {
// We'll need to have some handling here. For now - return 0
(void)hw_atomic_add(&oslog_p_error_count, 1);
return 0;
}
if (oslog_stream_open && (stream != firehose_stream_metadata)) {
lck_spin_lock(&oslog_stream_lock);
if (!oslog_stream_open) {
lck_spin_unlock(&oslog_stream_lock);
goto out;
}
oslog_s_total_msgcount++;
oslog_streamwrite_locked(ftid, stamp, pubdata, publen);
lck_spin_unlock(&oslog_stream_lock);
oslog_streamwakeup();
}
out:
ft = __firehose_buffer_tracepoint_reserve(stamp, stream, (uint16_t)publen, 0, NULL);
if (!fastpath(ft)) {
if (oslog_boot_done) {
if (stream == firehose_stream_metadata) {
(void)hw_atomic_add(&oslog_p_metadata_dropped_msgcount, 1);
}
else {
// If we run out of space in the persistence buffer we're
// dropping the message.
(void)hw_atomic_add(&oslog_p_dropped_msgcount, 1);
}
return 0;
}
firehose_chunk_t fbc = firehose_boot_chunk;
long offset;
//only stream available during boot is persist
offset = firehose_chunk_tracepoint_try_reserve(fbc, stamp,
firehose_stream_persist, 0, publen, 0, NULL);
if (offset <= 0) {
(void)hw_atomic_add(&oslog_p_boot_dropped_msgcount, 1);
return 0;
}
ft = firehose_chunk_tracepoint_begin(fbc, stamp, publen,
thread_tid(current_thread()), offset);
memcpy(ft->ft_data, pubdata, publen);
firehose_chunk_tracepoint_end(fbc, ft, ftid);
(void)hw_atomic_add(&oslog_p_saved_msgcount, 1);
return ftid.ftid_value;
}
if (!oslog_boot_done) {
oslog_boot_done = true;
}
memcpy(ft->ft_data, pubdata, publen);
__firehose_buffer_tracepoint_flush(ft, ftid);
if (stream == firehose_stream_metadata) {
(void)hw_atomic_add(&oslog_p_metadata_saved_msgcount, 1);
}
else {
(void)hw_atomic_add(&oslog_p_saved_msgcount, 1);
}
return ftid.ftid_value;
}
static oslog_stream_buf_entry_t
oslog_stream_create_buf_entry(oslog_stream_link_type_t type, firehose_tracepoint_id_u ftid,
uint64_t stamp, const void* pubdata, size_t publen)
{
oslog_stream_buf_entry_t m_entry = NULL;
firehose_tracepoint_t ft = NULL;
size_t m_entry_len = 0;
if (!pubdata) {
return NULL;
}
m_entry_len = sizeof(struct oslog_stream_buf_entry_s) +
sizeof(struct firehose_tracepoint_s) + publen;
m_entry = (oslog_stream_buf_entry_t) kalloc(m_entry_len);
if (!m_entry) {
return NULL;
}
m_entry->type = type;
m_entry->timestamp = stamp;
m_entry->size = sizeof(struct firehose_tracepoint_s) + publen;
ft = m_entry->metadata;
ft->ft_thread = thread_tid(current_thread());
ft->ft_id.ftid_value = ftid.ftid_value;
ft->ft_length = publen;
memcpy(ft->ft_data, pubdata, publen);
return m_entry;
}
#ifdef KERNEL
void
firehose_trace_metadata(firehose_stream_t stream, firehose_tracepoint_id_u ftid,
uint64_t stamp, const void *pubdata, size_t publen)
{
oslog_stream_buf_entry_t m_entry = NULL;
// If streaming mode is not on, only log the metadata
// in the persistence buffer
lck_spin_lock(&oslog_stream_lock);
if (!oslog_stream_open) {
lck_spin_unlock(&oslog_stream_lock);
goto finish;
}
lck_spin_unlock(&oslog_stream_lock);
// Setup and write the stream metadata entry
m_entry = oslog_stream_create_buf_entry(oslog_stream_link_type_metadata, ftid,
stamp, pubdata, publen);
if (!m_entry) {
(void)hw_atomic_add(&oslog_s_error_count, 1);
goto finish;
}
lck_spin_lock(&oslog_stream_lock);
if (!oslog_stream_open) {
lck_spin_unlock(&oslog_stream_lock);
kfree(m_entry, sizeof(struct oslog_stream_buf_entry_s) +
sizeof(struct firehose_tracepoint_s) + publen);
goto finish;
}
oslog_s_metadata_msgcount++;
oslog_streamwrite_metadata_locked(m_entry);
lck_spin_unlock(&oslog_stream_lock);
finish:
_firehose_trace(stream, ftid, stamp, pubdata, publen);
}
#endif
firehose_tracepoint_id_t
firehose_debug_trace(firehose_stream_t stream, firehose_tracepoint_id_t trace_id,
uint64_t timestamp, const char *format, const void *pubdata, size_t publen)
{
kprintf("[os_log stream 0x%x trace_id 0x%llx timestamp %llu format '%s' data %p len %lu]\n",
(unsigned int)stream, (unsigned long long)trace_id, timestamp,
format, pubdata, publen);
size_t i;
const unsigned char *cdata = (const unsigned char *)pubdata;
for (i=0; i < publen; i += 8) {
kprintf(">oslog 0x%08x: 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x 0x%02x\n",
(unsigned int)i,
(i+0) < publen ? cdata[i+0] : 0,
(i+1) < publen ? cdata[i+1] : 0,
(i+2) < publen ? cdata[i+2] : 0,
(i+3) < publen ? cdata[i+3] : 0,
(i+4) < publen ? cdata[i+4] : 0,
(i+5) < publen ? cdata[i+5] : 0,
(i+6) < publen ? cdata[i+6] : 0,
(i+7) < publen ? cdata[i+7] : 0
);
}
return trace_id;
}
void
__firehose_buffer_push_to_logd(firehose_buffer_t fb __unused, bool for_io __unused) {
oslogwakeup();
return;
}
void
__firehose_allocate(vm_offset_t *addr, vm_size_t size __unused)
{
firehose_chunk_t kernel_buffer = (firehose_chunk_t)kernel_firehose_addr;
if (kernel_firehose_addr) {
*addr = kernel_firehose_addr;
}
else {
*addr = 0;
return;
}
// Now that we are done adding logs to this chunk, set the number of writers to 0
// Without this, logd won't flush when the page is full
firehose_boot_chunk->fc_pos.fcp_refcnt = 0;
memcpy(&kernel_buffer[FIREHOSE_BUFFER_KERNEL_CHUNK_COUNT - 1], (const void *)firehose_boot_chunk, FIREHOSE_CHUNK_SIZE);
return;
}
// There isnt a lock held in this case.
void
__firehose_critical_region_enter(void) {
disable_preemption();
return;
}
void
__firehose_critical_region_leave(void) {
enable_preemption();
return;
}
|
p01arst0rm/decorum-linux
|
_resources/kernels/xnu-x86/libkern/os/log.c
|
C
|
gpl-3.0
| 17,043
|
/**
* @author : cromarmot (yexiaorain@gmail.com)
* @license : GPL
* @created : 星期一 2月 03, 2020 14:39:46 CST
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define ten5 100000+10
#define MOD 1000000007
#define rep(i,a,n) for (int i=a;i<n;i++)
#define iif(c,t,f) ((c)?(t):(f))
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
const double pi = acos(-1.0);
// 1-9
// 10-99
// 100-999
int idx =1;
int d[1'001'000];
int len(int v){
int ret = 0;
while(v){
ret++;
v/=10;
}
return ret;
}
int main(){
int i = 0;
while(idx <= 1'000'001){
int l = len(i);
int ii = i;
rep(j,0,l){
d[idx+l-1-j] = ii%10;
ii/=10;
}
i++;
idx+=l;
}
int pos=1;
int ans =1;
while(pos <= 1'000'000){
cout<<pos<<":"<<d[pos]<<endl;
ans*=d[pos];
pos*=10;
}
cout<<ans<<endl;
return 0;
}
/*
*
* hash prime
61,83,113,151,211,281,379,509683,911
1217,1627,2179,2909,3881,6907,9209
12281,16381,21841,29123,38833,51787,69061,92083
122777,163729,218357,291143,388211,517619,690163,999983
1226959,1635947,2181271,2908361,3877817,5170427,6893911,9191891
12255871,16341163,21788233,29050993,38734667,51646229,68861641,91815541
122420729,163227661,217636919,290182597,386910137,515880193,687840301,917120411
1000000007,1000000009
* */
|
CroMarmot/MyOICode
|
ProjectEuler/p040.cpp
|
C++
|
gpl-3.0
| 1,387
|
####################################################################################################
#
# PyDvi - A Python Library to Process DVI Stream.
# Copyright (C) 2009 Salvaire Fabrice
#
####################################################################################################
####################################################################################################
#
# Audit
#
# - 16/01/2010 fabrice
#
####################################################################################################
####################################################################################################
__ALL__ = ['mime_extensions', 'mime_copyright']
####################################################################################################
from Logging import format_card, remove_enclosing_new_line
####################################################################################################
mime_extensions = (
('sh', ('py', 'sh')),
('c', ('c', 'h', 'cpp', 'hpp', 'cxx', 'hxx', 'i')),
)
###################################################
copyright_text = remove_enclosing_new_line('''
PyDvi - A Python Library to Process DVI Stream.
Copyright (C) 2009 Salvaire Fabrice
''')
width = 100
mime_copyright = {}
###################################################
mime_copyright['sh'] = format_card(copyright_text,
centered=True,
width=width,
rule_char='#',
border = True,
)
###################################################
def format_c(text):
text += '\\'
formated_text = ''
first_line = True
for line in text.split('\n'):
if first_line:
formated_text += '\\'
first_line = False
else:
formated_text += ' '
formated_text += line + '\n'
return formated_text
mime_copyright['c'] = format_c(format_card(copyright_text,
centered=True,
width=width,
rule_char='*',
border = True,
))
####################################################################################################
#
# End
#
####################################################################################################
|
FabriceSalvaire/PyDVI
|
tools/CopyrightConfig.py
|
Python
|
gpl-3.0
| 2,557
|
package jeql.jts.geodetic;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.MultiLineString;
public class GeodeticSplitter
{
private Geometry line;
public GeodeticSplitter(Geometry line)
{
this.line = line;
}
public Geometry split()
{
MultiCoordinateList mcl = new MultiCoordinateList(false);
Coordinate[] pts = line.getCoordinates();
mcl.add(pts[0]);
for (int i = 1; i < pts.length; i++) {
Coordinate p0 = pts[i-1];
Coordinate p1 = pts[i];
if (crossesDateLine(p0, p1)) {
double latCross = latitudeOfCrossing(p0, p1);
if (p0.x < 0) {
mcl.add(new Coordinate(-180, latCross));
mcl.finish();
mcl.add(new Coordinate(180, latCross));
}
else {
mcl.add(new Coordinate(180, latCross));
mcl.finish();
mcl.add(new Coordinate(-180, latCross));
}
}
mcl.add(p1);
}
return toMultiLineString(mcl);
}
private static boolean crossesDateLine(Coordinate p0, Coordinate p1)
{
if (p0.x < -90 && p1.x > 90) return true;
if (p1.x < -90 && p0.x > 90) return true;
return false;
}
private static double latitudeOfCrossing(Coordinate p0, Coordinate p1)
{
// compute in the lon-lat plane - which isn't accurate for long lines
double x0 = p0.x;
double y0 = p0.y;
double x1 = p1.x + 360;;
double y1 = p1.y;
if (p0.x < 0) {
x0 = p1.x;
y0 = p1.y;
x1 = p0.x + 360;
y1 = p0.y;
}
double dx = x1 - x0;
double dy = y1 - y0;
double x = 180 - x0;
double y = dy/dx * x;
return y + y0;
}
private MultiLineString toMultiLineString(MultiCoordinateList mcl)
{
Coordinate[][] pts = mcl.toCoordinateArrays();
LineString[] lines = new LineString[pts.length];
for (int i = 0; i < pts.length; i++) {
lines[i] = toLineString(pts[i]);
}
return line.getFactory().createMultiLineString(lines);
}
private LineString toLineString(Coordinate[] pts)
{
// prevent lines of length 1
if (pts.length == 1) {
pts = new Coordinate[] { pts[0], new Coordinate(pts[0]) };
}
return line.getFactory().createLineString(pts);
}
}
|
dr-jts/jeql
|
modules/jeql/src/main/java/jeql/jts/geodetic/GeodeticSplitter.java
|
Java
|
gpl-3.0
| 2,350
|
page = [];
term = new Terminal();
sTerm = new Terminal();
page.server = "http://molly/moiras/server-terminal.php";
//- - - - - Pop
page.loaded = function(){
//------------ configuracao
term = new Terminal();
sTerm = new Terminal();
term.server = page.server;
sTerm.server = page.server;
sTerm.on();
term.on();
//------------------
user.get();
}
//---- config
page.config = function(){
page.popContent(page.tConfig);
page.popUp();
}
//---- bakup
page.backupOpen = function(){
page.popContent(page.tFormBeckup);
}
page.beckup = function(){
window.open('server-terminal.php?comander=dado.dump()', '_blank');
}
//- - - - - PopUp
page.checkPop = false;
page.popUp = function(){
//console.log("pop");
this.checkPop = !this.checkPop;
if(this.checkPop){
document.getElementById("popUp").className = "popUP-true";
}
else{
document.getElementById("popUp").className = "popUP-false";
}
}
page.popContent = function(content){
document.getElementById("popUp-content").innerHTML = content;
}
page.drop = function(id){
com = "dado.drop(" + id + ")";
console.log(com);
term.com(com,page.rDrop);
};
page.rDrop = function(msg){
console.log(msg);
page.search();
}
page.replace = function(base,dados){
var dadosK=Object.keys(dados);
for (var i = 0; i < dadosK.length; i++) {
base = base.replace(new RegExp("{" + dadosK[i] + "}", 'g'),dados[dadosK[i]]);
}
return base;
}
//------------
page.tConfig = document.getElementById("tConfig").innerHTML;
page.tFormBeckup = document.getElementById("formBeckup").innerHTML;
page.tFirstDado = "<dado onclick='page.novaNota()'><id>Novo Dado</id><valor><img src='resources/img/new.svg'></valor></dado>";
page.notaform = "<div id=\"fNotaCabecario\"></div><form><label>Dado</label><textarea id=\"fNotaDado\"></textarea><label>Tags</label><textarea id=\"fNotaTag\"></textarea><input id=\"fNotaAplic\" onclick=\"\" value=\"Salvar\" type=\"button\"><input id=\"fNotaAplic\" onclick=\"page.popUp()\" value=\"Cancelar\" type=\"button\"></form>";
page.loginform = "<form><label>Dado</label><textarea id=\"novaNotaDado\"></textarea><label>Tags</label><textarea id=\"novaNotaTag\"></textarea><input onclick=\"page.novaNotaAplic()\" value=\"Salvar\" type=\"button\"></form>";
console.log("page.js");
|
CupBlack/Moiras
|
resources/js/page.js
|
JavaScript
|
gpl-3.0
| 2,263
|
package com.ricky30.prispongemine.commands;
import java.util.UUID;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;
import com.flowpowered.math.vector.Vector3i;
import com.ricky30.prispongemine.config.ManageMines;
import com.ricky30.prispongemine.events.interactionevents;
import ninja.leaping.configurate.ConfigurationNode;
public class commandSave implements CommandExecutor
{
@Override
public CommandResult execute(CommandSource src, CommandContext args)
throws CommandException
{
final String Name = args.<String>getOne("name").get();
final Player player = (Player) src;
final UUID world = player.getWorld().getUniqueId();
final boolean OK = ManageMines.SaveMine(Name, false);
final ConfigurationNode config = ManageMines.getConfig();
if (!OK)
{
src.sendMessage(Text.of("Mine ", Name, " already saved. Use update instead or change name."));
return CommandResult.empty();
}
if (interactionevents.IsreadytoFill(player))
{
final Vector3i positiondepart = interactionevents.getFirst(player);
final Vector3i positionfin = interactionevents.getSecond(player);
config.getNode("world").setValue(world.toString());
config.getNode("depart_X").setValue(positiondepart.getX());
config.getNode("depart_Y").setValue(positiondepart.getY());
config.getNode("depart_Z").setValue(positiondepart.getZ());
config.getNode("fin_X").setValue(positionfin.getX());
config.getNode("fin_Y").setValue(positionfin.getY());
config.getNode("fin_Z").setValue(positionfin.getZ());
config.getNode("renewtime").setValue(24);
config.getNode("renewformat").setValue("HOURS");
config.getNode("autorun").setValue(false);
config.getNode("random").setValue(false);
config.getNode("set").setValue(0);
config.getNode("startupdelay").setValue(300);
ManageMines.SaveMine(Name, true);
src.sendMessage(Text.of("Mine " , Name, " saved"));
return CommandResult.success();
}
else
{
src.sendMessage(Text.of("Not ready to save yet"));
}
return CommandResult.empty();
}
}
|
rickyminecraft/prispongemine
|
src/main/java/com/ricky30/prispongemine/commands/commandSave.java
|
Java
|
gpl-3.0
| 2,354
|
/*
* Copyright 2010-2013 Eric Kok et al.
*
* Transdroid 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.
*
* Transdroid 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 Transdroid. If not, see <http://www.gnu.org/licenses/>.
*/
package org.transdroid.core.seedbox;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import org.transdroid.core.app.settings.ServerSetting;
import org.transdroid.daemon.Daemon;
import org.transdroid.daemon.OS;
/**
* Implementation of {@link SeedboxSettings} for Dediseedbox seedboxes.
* @author Eric Kok
*/
public class DediseedboxSettings extends SeedboxSettingsImpl implements SeedboxSettings {
@Override
public String getName() {
return "Dediseedbox";
}
@Override
public ServerSetting getServerSetting(SharedPreferences prefs, int orderOffset, int order) {
// @formatter:off
String server = prefs.getString("seedbox_dediseedbox_server_" + order, null);
if (server == null) {
return null;
}
String user = prefs.getString("seedbox_dediseedbox_user_" + order, null);
String pass = prefs.getString("seedbox_dediseedbox_pass_" + order, null);
return new ServerSetting(
orderOffset + order,
prefs.getString("seedbox_dediseedbox_name_" + order, null),
Daemon.rTorrent,
server,
null,
443,
null,
443,
true,
false,
null,
"/rutorrent/plugins/httprpc/action.php",
true,
user,
pass,
null,
OS.Linux,
"/",
"ftp://" + user + "@" + server + "/",
pass,
6,
true,
true,
true);
// @formatter:on
}
@Override
public Intent getSettingsActivityIntent(Context context) {
return DediseedboxSettingsActivity_.intent(context).get();
}
@Override
public int getMaxSeedboxOrder(SharedPreferences prefs) {
return getMaxSeedboxOrder(prefs, "seedbox_dediseedbox_server_");
}
@Override
public void removeServerSetting(SharedPreferences prefs, int order) {
removeServerSetting(prefs, "seedbox_dediseedbox_server_", new String[] { "seedbox_dediseedbox_name_",
"seedbox_dediseedbox_server_", "seedbox_dediseedbox_user_", "seedbox_dediseedbox_pass_" }, order);
}
}
|
0359xiaodong/transdroid
|
app/src/main/java/org/transdroid/core/seedbox/DediseedboxSettings.java
|
Java
|
gpl-3.0
| 2,641
|
#!/usr/bin/env python
#coding=utf-8
# Nathive (and this file) 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 newer.
#
# You should have received a copy of the GNU General Public License along with
# this file. If not, see <http://www.gnu.org/licenses/>.
import gtk
import webbrowser
from nathive.lib.plugin import *
class Home(PluginLauncher):
def __init__(self):
# Subclass it.
PluginLauncher.__init__(self)
# Common attributes.
self.name = 'home'
self.author = 'nathive-dev'
self.type = 'launcher'
self.menu = 'help'
self.label = _('Nathive website')
self.icon = 'gtk-home'
def callback(self):
"""To do when the plugin is called."""
webbrowser.open('http://www.nathive.org')
|
johnnyLadders/Nathive_CITA
|
nathive/plugins/home.py
|
Python
|
gpl-3.0
| 933
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SNet.Net
{
public enum PacketFlags : ushort
{
None = 0,
ISerializable = 1,
Raw = 2
}
}
|
sanderele1/FileHub
|
Tcp16/SNet_Net/Networking/PacketFlags.cs
|
C#
|
gpl-3.0
| 253
|
/*
* ================================
* eli960@qq.com
* http://www.mailhonor.com/
* 2015-11-20
* ================================
*/
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#include "zcc.h"
#include <signal.h>
#include <sys/types.h>
#include <dirent.h>
bool var_test_mode = false;
namespace zcc
{
static master_event_server *___instance;
static bool flag_init = false;
static bool flag_run = false;
static bool flag_inner_event_loop = false;
static bool flag_clear = false;
static pid_t parent_pid = 0;
static event_io *ev_status = 0;
static std::list<event_io *> event_ios;
static void load_global_config_by_dir(config &cf, const char *config_path)
{
DIR *dir;
struct dirent ent, *ent_list;
char *fn, *p;
char pn[4100];
dir = opendir(config_path);
if (!dir) {
return;
}
while ((!readdir_r(dir, &ent, &ent_list)) && (ent_list)) {
fn = ent.d_name;
if (fn[0] == '.') {
continue;
}
p = strrchr(fn, '.');
if ((!p) || (strcasecmp(p + 1, "gcf"))) {
continue;
}
snprintf(pn, 4096, "%s/%s", config_path, fn);
cf.load_by_filename(pn);
}
closedir(dir);
}
static char *stop_file = 0;
static void stop_file_check(event_timer &tm)
{
if (file_get_size(stop_file) < 0) {
var_proc_stop = true;
} else {
tm.start(stop_file_check, 1000 * 1);
}
}
static void on_master_reload(event_io &ev)
{
var_proc_stop = true;
}
static void ___inet_server_accept(event_io &ev)
{
int fd, listen_fd = ev.get_fd();
void (*cb)(int) = (void(*)(int))ev.get_context();
fd = inet_accept(listen_fd);
if (fd < 0) {
if (errno != EAGAIN) {
zcc_fatal("inet_server_accept: %m");
}
return;
}
nonblocking(fd);
close_on_exec(fd);
if (cb) {
cb(fd);
} else {
___instance->simple_service(fd);
}
}
static void ___unix_server_accept(event_io &ev)
{
int fd, listen_fd = ev.get_fd();
void (*cb)(int) = (void(*)(int))ev.get_context();
fd = unix_accept(listen_fd);
if (fd < 0) {
if (errno != EAGAIN) {
zcc_fatal("unix_server_accept: %m");
}
return;
}
nonblocking(fd);
close_on_exec(fd);
if (cb) {
cb(fd);
} else {
___instance->simple_service(fd);
}
}
static void ___fifo_server_accept(event_io &ev)
{
int listen_fd = ev.get_fd();
void (*cb)(int) = (void(*)(int))ev.get_context();
if (cb) {
cb(listen_fd);
} else {
___instance->simple_service(listen_fd);
}
}
master_event_server::master_event_server()
{
if (!flag_init) {
signal(SIGPIPE, SIG_IGN);
flag_init = true;
flag_run = false;
parent_pid = getppid();
ev_status = 0;
/* private */
flag_inner_event_loop = false;
flag_clear = false;
}
}
master_event_server::~master_event_server()
{
}
void master_event_server::clear()
{
if (flag_clear) {
return;
}
flag_clear = true;
if (ev_status) {
/* The master would receive the signal of closing ZMASTER_SERVER_STATUS_FD. */
delete ev_status;
ev_status = 0;
close(var_master_server_status_fd);
close(var_master_master_status_fd);
}
std_list_walk_begin(event_ios, eio) {
int fd = eio->get_fd();
delete eio;
close(fd);
} std_list_walk_end;
event_ios.clear();
}
void master_event_server::stop_notify()
{
var_proc_stop = true;
default_evbase.notify();
}
void master_event_server::alone_register(char *alone_url)
{
char service_buf[1024];
char *service, *url, *p;
strtok splitor(alone_url);
while(splitor.tok(" \t,;\r\n")) {
if (splitor.size() > 1000) {
zcc_fatal("alone_register: url too long");
}
memcpy(service_buf, splitor.ptr(), splitor.size());
service_buf[splitor.size()] = 0;
p = strstr(service_buf, "://");
if (p) {
*p=0;
service = service_buf;
url = p+3;
} else {
service = blank_buffer;
url = service_buf;
}
int fd_type;
int fd = listen(url, &fd_type);
if (fd < 0) {
zcc_fatal("alone_register: open %s(%m)", alone_url);
}
close_on_exec(fd);
nonblocking(fd);
service_register(service, fd, fd_type);
}
}
void master_event_server::master_register(char *master_url)
{
zcc::argv service_argv;
service_argv.split(master_url, ",");
for (size_t i = 0; i < service_argv.size(); i++) {
char *service_name, *typefd;
zcc::argv stfd;
stfd.split(service_argv[i], ":");
if (stfd.size() == 1) {
service_name = blank_buffer;
typefd = stfd[0];
} else {
service_name = stfd[0];
typefd = stfd[1];
}
int fdtype = typefd[0];
switch(fdtype) {
case var_tcp_listen_type_inet:
case var_tcp_listen_type_unix:
case var_tcp_listen_type_fifo:
break;
default:
zcc_fatal("master_event_server: unknown service type %c", fdtype);
break;
}
int fd = atoi(typefd+1);
if (fd < var_master_server_listen_fd) {
zcc_fatal("master_event_server: fd(%s) is invalid", typefd+1);
}
close_on_exec(fd);
nonblocking(fd);
service_register(service_name, fd, fdtype);
}
}
void master_event_server::before_service()
{
}
void master_event_server::event_loop()
{
flag_inner_event_loop = true;
}
void master_event_server::before_exit()
{
}
void master_event_server::simple_service(int fd)
{
zcc_fatal("must be make a new simple_service when use simpe mode");
}
event_io *master_event_server::general_service_register(int fd, int fd_type
, void (*service) (int) , event_base &eb)
{
event_io *ev = new event_io();
ev->bind(fd, eb);
ev->set_context((void *)service);
if (fd_type == var_tcp_listen_type_inet) {
ev->enable_read(___inet_server_accept);
} else if (fd_type == var_tcp_listen_type_unix) {
ev->enable_read(___unix_server_accept);
} else if (fd_type == var_tcp_listen_type_fifo) {
ev->enable_read(___fifo_server_accept);
}
event_ios.push_back(ev);
return ev;
}
void master_event_server::service_register(const char *service_name, int fd, int fd_type)
{
general_service_register(fd, fd_type, 0);
}
void master_event_server::run(int argc, char ** argv)
{
if (flag_run) {
zcc_fatal("master_event_server:: only run one time");
}
flag_run = true;
___instance = this;
char *attr;
main_parameter_run(argc, argv);
attr = default_config.get_str("server-config-path", "");
if (!empty(attr)) {
config cf;
load_global_config_by_dir(cf, attr);
cf.load_another(default_config);
default_config.load_another(cf);
}
var_masterlog_listen = default_config.get_str("master-log-listen", "");
stop_file = default_config.get_str("stop-file", "");
log_use_by(argv[0], default_config.get_str("server-log"));
if (default_config.get_bool("MASTER", false)) {
ev_status = new event_io();
close_on_exec(var_master_master_status_fd);
nonblocking(var_master_master_status_fd);
ev_status->bind(var_master_master_status_fd);
ev_status->enable_read(on_master_reload);
ev_status->set_context(this);
if (!empty(stop_file)) {
event_timer *stop_file_timer = new event_timer();
stop_file_timer->bind();
stop_file_timer->start(stop_file_check, 1000 * 1);
}
}
before_service();
if (!default_config.get_bool("MASTER", false)) {
alone_register(default_config.get_str("server-service", ""));
} else {
master_register(default_config.get_str("server-service", ""));
}
attr = default_config.get_str("server-user", "");
if (!empty(attr)) {
if(!chroot_user(0, attr)) {
zcc_fatal("ERR chroot_user %s", attr);
}
}
while (1) {
if (var_proc_stop) {
break;
}
default_evbase.dispatch();
if (var_proc_stop) {
break;
}
if (!flag_inner_event_loop) {
event_loop();
}
}
clear();
before_exit();
}
}
|
mailhonor/zcc
|
src/master/event_server.cpp
|
C++
|
gpl-3.0
| 8,544
|
-- Copyright 2013 Valentin David
-- This file is part of Luagll.
-- Luagll 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.
-- Luagll 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
u = require "gll.utils"
require "gll.generator"
require "gll.loader"
local rules = {S = {{"Identifiers", "layout", cons="Start"}},
Identifiers = {{"Identifiers", "layout", "IDorKeyword", cons="Conc"},
{cons="Nil"}},
letter = u.range("a", "z"),
cletter = u.range("A", "Z"),
idfchar = {{"letter"}, {"cletter"}, {u.t("_")}},
digit = u.range("0", "9"),
idchar = {{"idfchar"}, {"digit"}},
idchars = {{"idchar", "idchars"},
{}},
Keyword = {u.keyword("foo"),u.keyword("bar")},
IDorKeyword = {{"ID"}, {"Keyword", cons="Keyword"}},
ID = {{"idfchar", "idchars", cons="ID"}},
layout = {{"LAYOUT", "layout", cons="layout"}, {}},
LAYOUT = {{u.t(" ")}, {u.t("\n")}, {u.t("\r")}, {u.t("\t")}}
}
local function dump(table, indent, traversed)
if not traversed then
traversed = {}
end
if traversed[table] then
assert(false)
end
traversed[table] = true
if not indent then
indent = 0
end
if table.cons then
io.write(table.cons)
indent = indent + #(table.cons)
end
indent = indent + 1
if #table > 0 then
io.write("(")
for i=1, #table do
dump(table[i], indent, traversed)
io.write("\n")
io.write(string.rep(" ", indent))
end
io.write(")")
end
if table.startp or table.endp then
io.write("[")
io.write(tostring(table.startp))
io.write("-")
io.write(tostring(table.endp))
io.write("]")
end
end
local input = { string.rep(" a dewq dwqmjwdqojidwqji j barx bar foo ffoo iowdq ji foo dwfoooiqjdw jp ", 10) }
local function parsed(node)
if node.cons == "layout" then
local la = string.sub(input[1], node.endp+1, node.endp+1)
if la == " " or la == "\n" or la == "\r" or la == "\t" then
return false
end
elseif node.cons == "ID" or node.cons == "Keyword" then
local la = string.sub(input[1], node.endp+1, node.endp+1)
if string.len(la) > 0 then
local bla = string.byte(la)
if bla >= string.byte("a") and bla <= string.byte("z") then
return false
end
if bla >= string.byte("A") and bla <= string.byte("Z") then
return false
end
if bla >= string.byte("0") and bla <= string.byte("9") then
return false
end
if bla == string.byte("_") then
return false
end
end
end
local ret = { startp = node.startp,
endp = node.endp,
cons = node.cons }
if node.cons == "ID" then
ret[1] = {cons=string.format("%q", string.sub(input[1], node.startp+1, node.endp))}
if ret[1].cons == "\"foo\"" or ret[1].cons == "\"bar\"" then
return false
end
elseif node.cons == "Conc" then
ret.cons = "List"
for i=1, #(node[1]) do
ret[#ret+1] = node[1][i]
end
ret[#ret+1] = node[3]
else
for i=1, #node do
if node[i].cons ~= "layout" then
ret[#ret+1] = node[i]
end
end
end
return true, ret
end
local function get(pos, stream, endp)
if not endp then
endp = pos
end
if pos < #(stream[1]) then
return string.sub(stream[1], 1+pos, 1+endp)
else
return nil
end
end
local tmp = io.open("tmp.lua", "w")
gll.generator.generate(rules, tmp)
tmp:close()
local parser = gll.loader.load_grammar("tmp.lua", {parsed = parsed, get = get})
local done = false
local function finished(stack, la, i, stream, returned_nodes)
if (la == nil) then
dump(returned_nodes)
io.write("\n")
if done then
error("Ambiguous")
end
done = true
end
end
local stack = { { [2] = finished }, found = {} }
parser(stack, input)
|
valentindavid/luagll
|
example.lua
|
Lua
|
gpl-3.0
| 4,260
|
package de.dorianscholz.openlibre;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import de.dorianscholz.openlibre.model.GlucoseData;
import de.dorianscholz.openlibre.model.RawTagData;
import de.dorianscholz.openlibre.model.ReadingData;
import io.realm.Realm;
import io.realm.RealmResults;
import io.realm.Sort;
import static de.dorianscholz.openlibre.OpenLibre.parseRawData;
import static de.dorianscholz.openlibre.OpenLibre.realmConfigProcessedData;
import static de.dorianscholz.openlibre.OpenLibre.realmConfigRawData;
import static de.dorianscholz.openlibre.OpenLibre.setupRealm;
import static de.dorianscholz.openlibre.model.ReadingData.historyIntervalInMinutes;
import static de.dorianscholz.openlibre.model.ReadingData.numHistoryValues;
import static de.dorianscholz.openlibre.model.ReadingData.numTrendValues;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
@RunWith(AndroidJUnit4.class)
public class ReadingDataTest {
private static final int MAX_READINGS_TO_TEST = 1000;
private Realm realmRawData;
private Realm realmProcessedData;
private ArrayList<ReadingData> readingDataList = new ArrayList<>();
private ArrayList<RawTagData> rawTagDataList = new ArrayList<>();
@Before
public void setUp() throws Exception {
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
Realm.init(context);
setupRealm(context);
realmRawData = Realm.getInstance(realmConfigRawData);
}
private void parseTestData() {
// open empty processed data realm for use in parsing data
Realm.deleteRealm(realmConfigProcessedData);
realmProcessedData = Realm.getInstance(realmConfigProcessedData);
// get all raw data
RealmResults<RawTagData> rawTags = realmRawData.where(RawTagData.class).findAllSorted(RawTagData.DATE, Sort.ASCENDING);
// reduce data set to just the raw data of the most recent sensor
String tagId = rawTags.last().getTagId();
rawTags = rawTags.where().equalTo(RawTagData.TAG_ID, tagId).findAllSorted(RawTagData.DATE, Sort.ASCENDING);
// reduce data set further to only MAX_READINGS_TO_TEST sensor readings
for (int i = 0; i < min(MAX_READINGS_TO_TEST, rawTags.size()); i++) {
addDataIfValid(rawTags.get(i));
}
/*
// add oldest readings of sensor
for (int i = 0; i < min(MAX_READINGS_TO_TEST / 2, rawTags.size() / 2); i++) {
addDataIfValid(rawTags.get(i));
}
// add newest readings of sensor
for (int i = max(rawTags.size() / 2, rawTags.size() - 1 - MAX_READINGS_TO_TEST / 2); i < rawTags.size() - 1; i++) {
addDataIfValid(rawTags.get(i));
}
*/
assertThat(realmRawData.isEmpty(), is(false));
assertThat(readingDataList.size(), greaterThan(0));
}
private void addDataIfValid(RawTagData rawTagData) {
// check if sensor has been initialized and is not yet over due date
if (rawTagData.getSensorAgeInMinutes() < numHistoryValues * historyIntervalInMinutes ||
rawTagData.getSensorAgeInMinutes() > TimeUnit.DAYS.toMinutes(14))
return;
// check if data contains enough history and trend data for the tests to work
ReadingData readingData = new ReadingData(rawTagData);
if (readingData.getHistory().size() < numHistoryValues ||
readingData.getTrend().size() != numTrendValues) {
//Log.d("OpenLibre::Test", "history size: " + readingData.getHistory().size() + " trend size: " + readingData.getTrend().size());
return;
}
// add reading to realm, so when parsing the next reading, it can access this data
realmProcessedData.beginTransaction();
realmProcessedData.copyToRealmOrUpdate(readingData);
realmProcessedData.commitTransaction();
rawTagDataList.add(rawTagData);
readingDataList.add(readingData);
}
@After
public void tearDown() {
realmRawData.close();
// if any test opened the processed data realm, close it and delete the data
if (realmProcessedData != null) {
realmProcessedData.close();
Realm.deleteRealm(realmConfigProcessedData);
}
}
//@Ignore
@Test
public void testReparseAllData() {
// delete all parsed readings before the tests
Realm.deleteRealm(realmConfigProcessedData);
// reparse all readings from raw data
parseRawData();
Realm realmProcessedData = Realm.getInstance(realmConfigProcessedData);
assertThat(realmProcessedData.isEmpty(), is(false));
realmProcessedData.close();
}
@Test
public void testTrendIndexVsSensorAge() {
parseTestData();
ArrayList<Integer> results = new ArrayList<>();
for (RawTagData rawTagData : rawTagDataList) {
int diff = ((rawTagData.getSensorAgeInMinutes() % numTrendValues) - rawTagData.getIndexTrend() + numTrendValues) % numTrendValues;
results.add(diff);
if (diff > 1) Log.w("OpenLibre::TEST", "failed for: sensorAge: " + rawTagData.getSensorAgeInMinutes() + " trendIndex: " + rawTagData.getIndexTrend());
}
Log.d("OpenLibre::TEST", "sensorAge % numTrendValues - trendIndex: " + results);
assertThat("trend index drifted away from sensor age more than one minute", results, everyItem(lessThanOrEqualTo(1)));
}
@Test
public void testHistoryDatesMatchOnOverlappingReadings() {
parseTestData();
ArrayList<Integer> results = new ArrayList<>();
ReadingData oldReadingData = readingDataList.get(0);
results.add(0);
for (ReadingData readingData : readingDataList.subList(1, readingDataList.size())) {
GlucoseData oldGlucoseData = oldReadingData.getHistory().last();
boolean found = false;
for (GlucoseData glucoseData : readingData.getHistory()) {
if (oldGlucoseData.glucose() == glucoseData.glucose()) {
if (oldGlucoseData.getAgeInSensorMinutes() - glucoseData.getAgeInSensorMinutes() == 0) {
// well matched
results.add(0);
found = true;
break;
} else if (abs(oldGlucoseData.getAgeInSensorMinutes() - glucoseData.getAgeInSensorMinutes()) < historyIntervalInMinutes) {
results.add(oldGlucoseData.getAgeInSensorMinutes() - glucoseData.getAgeInSensorMinutes());
found = true;
break;
}
}
}
if (!found)
results.add(0);
oldReadingData = readingData;
}
Log.d("OpenLibre::TEST", "age diff: " + results);
assertThat("history dates on overlapping readings don't match", results, everyItem(equalTo(0)));
assertThat("no overlapping readings found", results.size(), greaterThan(0));
}
@Test
public void testHistoryDatesFitTrendData() {
parseTestData();
ArrayList<Integer> firstTrendResults = new ArrayList<>();
ArrayList<Integer> lastTrendResults = new ArrayList<>();
for (ReadingData readingData : readingDataList) {
GlucoseData lastHistory = readingData.getHistory().get(readingData.getHistory().size() - 1);
GlucoseData firstTrend = readingData.getTrend().get(0);
GlucoseData lastTrend = readingData.getTrend().get(readingData.getTrend().size() - 1);
long lastHistoryMinutes = TimeUnit.MILLISECONDS.toMinutes(lastHistory.getDate());
long lastTrendMinutes = TimeUnit.MILLISECONDS.toMinutes(lastTrend.getDate());
long firstTrendMinutes = TimeUnit.MILLISECONDS.toMinutes(firstTrend.getDate());
firstTrendResults.add((int)(lastHistoryMinutes - firstTrendMinutes));
lastTrendResults.add((int)(lastTrendMinutes - lastHistoryMinutes));
}
Log.d("OpenLibre::TEST", "last history - first trend date: " + firstTrendResults);
Log.d("OpenLibre::TEST", "last trend - last history date: " + lastTrendResults);
assertThat("history ends more than 3 minutes before first trend", firstTrendResults, everyItem(greaterThanOrEqualTo(-3)));
assertThat("history ends after last trend", lastTrendResults, everyItem(greaterThanOrEqualTo(0)));
}
@Test
public void testHistoryValuesFitTrendData() {
parseTestData();
ArrayList<Float> minTrendResults = new ArrayList<>();
ArrayList<Float> maxTrendResults = new ArrayList<>();
for (ReadingData readingData : readingDataList) {
GlucoseData lastHistory = readingData.getHistory().get(readingData.getHistory().size() - 1);
ArrayList<Float> trendValues = new ArrayList<>();
for (GlucoseData glucoseData : readingData.getTrend()) {
trendValues.add(glucoseData.glucose(false));
}
minTrendResults.add(lastHistory.glucose(false) - Collections.min(trendValues));
maxTrendResults.add(Collections.max(trendValues) - lastHistory.glucose(false));
}
Log.d("OpenLibre::TEST", "last history - min trend value: " + minTrendResults);
Log.d("OpenLibre::TEST", "max trend value - last history: " + maxTrendResults);
assertThat("last history value far smaller than trend values", minTrendResults, everyItem(greaterThanOrEqualTo(-10f)));
assertThat("last history value far greater than trend values", maxTrendResults, everyItem(greaterThanOrEqualTo(-10f)));
}
}
|
DorianScholz/OpenLibre
|
app/src/androidTest/java/de/dorianscholz/openlibre/ReadingDataTest.java
|
Java
|
gpl-3.0
| 10,467
|
class CreateCharacters < ActiveRecord::Migration
def self.up
create_table :characters do |t|
t.string :name
t.string :path
t.string :virtue
t.string :vice
t.integer :cabal_id, :null => false, :options => "CONSTRAINT fk_character_cabals REFERENCES cabal(id)"
t.integer :order_id, :null => false, :options => "CONSTRAINT fk_character_order REFERENCES order(id)"
t.text :description
t.text :background
t.integer :intelligence
t.integer :strength
t.integer :presence
t.integer :wits
t.integer :dexterity
t.integer :manipulation
t.integer :resolve
t.integer :stamina
t.integer :composure
t.integer :academics
t.integer :athletics
t.integer :animal_ken
t.integer :computer
t.integer :brawl
t.integer :empathy
t.integer :crafts
t.integer :drive
t.integer :expression
t.integer :investigation
t.integer :firearms
t.integer :intimidation
t.integer :medicine
t.integer :larceny
t.integer :persuasion
t.integer :occult
t.integer :stealth
t.integer :socialize
t.integer :politics
t.integer :survival
t.integer :streetwise
t.integer :science
t.integer :weaponry
t.integer :subterfuge
t.text :skill_specialties
t.string :health
t.string :willpower
t.integer :speed
t.integer :initiative
t.integer :defense
t.integer :armor
t.integer :wisdom
t.text :derangements
t.text :merits
t.integer :gnosis
t.integer :death
t.integer :fate
t.integer :forces
t.integer :life
t.integer :matter
t.integer :mind
t.integer :prime
t.integer :space
t.integer :spirit
t.integer :time
t.text :equipment
t.text :common_spells
t.timestamps
end
end
def self.down
drop_table :characters
end
end
|
yithian/personae
|
db/migrate/20090507003935_create_characters.rb
|
Ruby
|
gpl-3.0
| 1,968
|
import os
import sys
import numpy as np
from copy import deepcopy
import argparse
sys.path.append(os.path.join(os.path.dirname(__file__),"../projects/tools"))
import msh
import executable_paths as exe
def parse():
parser = argparse.ArgumentParser(description="Creates mandible and masseter files for the database creation")
parser.add_argument("-i", "--input", help="input .mesh object", type=str, required=True)
parser.add_argument("-t", "--template", help="template mandible in full size", type=str, required=True)
return parser.parse_args()
def checkArgs(args):
if not os.path.isfile(args.input):
print args.input + " is not a valid file"
sys.exit()
if not os.path.splitext(args.input)[1] == ".mesh":
print args.input + " is not a .mesh file"
sys.exit()
if not os.path.isfile(args.template):
print args.template + " is not a valid file"
sys.exit()
if not os.path.splitext(args.template)[1] == ".mesh":
print args.template + " is not a .mesh file"
sys.exit()
def command(cmd, displayOutput=False):
err = 1
print "Running the command '" + cmd + "'"
if displayOutput:
err = os.system(cmd)
else:
err = os.system(cmd + " > tmp_out.txt 2>tmp_err.txt")
if err:
print "An error happened while executing:\n"+cmd+"\nLook in tmp_out.txt or tmp_err.txt for info\nExiting..."
sys.exit()
else:
os.system("rm tmp_out.txt tmp_err.txt >/dev/null 2>&1")
if __name__=="__main__":
args = parse()
checkArgs(args)
# 3 - Align to the template full mandibule
command(exe.align + " -i " + args.input + " " + args.template + " -d 50 -o 0.95", displayOutput=True)
command(exe.pythonICP + " -s " + args.input + " -t " + args.template + " -m mat_PythonICP.txt")
# 1 - Reading the input file
fullMandible = msh.Mesh(args.input)
fullMandible.applyMatrix(matFile="mat_Super4PCS.txt")
fullMandible.applyMatrix(matFile="mat_PythonICP.txt")
# 2 - Scale to [0,1]
MAT = fullMandible.toUnitMatrix()
np.savetxt("mat_toUnit.txt",MAT)
fullMandible.applyMatrix(mat=MAT)
fullMandible.write("mandible.mesh")
# 4 - Cut the mandible in two
rightMandible = deepcopy(fullMandible)
leftMandible = fullMandible
#Generate the mask
mask = [1 for i in range(len(leftMandible.tris))]
mid = np.mean(leftMandible.verts,axis=0)[0]
print mid
for i,t in enumerate(leftMandible.tris):
for v in t:
x = leftMandible.verts[v][0]
if x < mid:
mask[i] = 0
#Create the left mandible
leftMandible.tris = np.array([t for i,t in enumerate(leftMandible.tris) if mask[i]==1])
print len(leftMandible.tris)
leftMandible.discardUnused()
leftMAT = leftMandible.toUnitMatrix()
np.savetxt("1_leftMandibleToUnit.txt", leftMAT)
leftMandible.applyMatrix(mat=leftMAT)
leftMandible.write("leftMandible.mesh")
#And the right one, symetrized
rightMandible.tris = np.array([t for i,t in enumerate(rightMandible.tris) if mask[i]==0])
rightMandible.discardUnused()
rightMAT = rightMandible.toUnitMatrix()
np.savetxt("1_rightMandibleToUnit.txt", rightMAT)
rightMandible.applyMatrix(mat=rightMAT)
rightMandible.verts[:,0] = 1-rightMandible.verts[:,0]
rightMandible.write("rightMandible.mesh")
# 5 - Create the shells for left and right mandibles
#command(exe.boundingMesh + " leftMandible.mesh", displayOutput=True)
command(exe.shell + " -i leftMandible.mesh -o leftShell.mesh -c", displayOutput=True)
command(exe.shell + " -i rightMandible.mesh -o rightShell.mesh -c", displayOutput=True)
sys.exit()
# 6 - Warp the shell to the mandibles
command(exe.warping + " leftMandible.shell.mesh leftMandible.mesh")
command(exe.warping + " rightMandible.shell.mesh rightMandible.mesh")
# 7 - Create a domain for mshdist computation
#Right mandible
cube=msh.Mesh(cube=[0,1,0,1,0,1])
cube.write("rightBox.mesh")
command( "tetgen -pgANEF rightBox.mesh")
command( "mmg3d_O3 rightBox.1.mesh -hausd " + str(np.max(mesh.dims)/25) + " -hmax " + str(np.max(mesh.dims)/25))
command( "mshdist -ncpu 4 -noscale rightBox.1.o.mesh rightMandible.warped.mesh")
# 9 - Morphing the template_mandibule surface to the computed boxes
command(morphing + " template_halfMandible_volume.mesh rightBox.1.o.mesh")
# 10 - Extract the surface from the morphing results
morphed = msh.Mesh("morphed.mesh")
morphed.readSol()
morphed.extractSurfaces#Placeholder
|
ISCDtoolbox/FaciLe
|
pipeline/processMandibleAndMasseter.py
|
Python
|
gpl-3.0
| 4,598
|
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
namespace HelpDesk.WorkerWebApp.Identity
{
// Чтобы добавить данные профиля для пользователя, можно добавить дополнительные свойства в класс ApplicationUser. Дополнительные сведения см. по адресу: http://go.microsoft.com/fwlink/?LinkID=317594.
public class ApplicationUser : IUser<long>
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, long> manager)
{
// Обратите внимание, что authenticationType должен совпадать с типом, определенным в CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Здесь добавьте утверждения пользователя
return userIdentity;
}
public string Password { get; set; }
public string UserName { get; set; }
public long Id { get; set; }
public string Email { get; set; }
}
}
|
knyazkov-ma/HelpDesk
|
WebApp/HelpDesk.WorkerWebApp/Identity/ApplicationUser.cs
|
C#
|
gpl-3.0
| 1,310
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Charts module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL$
** 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 General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 or (at your option) 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.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-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>
#include <QtCharts/QChartView>
#include <QtCharts/QBarSeries>
#include <QtCharts/QBarSet>
#include <QtCharts/QLegend>
#include <QtCharts/QBarCategoryAxis>
#include <QtCharts/QStackedBarSeries>
QT_CHARTS_USE_NAMESPACE
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//![1]
QBarSet *low = new QBarSet("Min");
QBarSet *high = new QBarSet("Max");
*low << -52 << -50 << -45.3 << -37.0 << -25.6 << -8.0 << -6.0 << -11.8 << -19.7 << -32.8 << -43.0 << -48.0;
*high << 11.9 << 12.8 << 18.5 << 26.5 << 32.0 << 34.8 << 38.2 << 34.8 << 29.8 << 20.4 << 15.1 << 11.8;
//![1]
//![2]
QStackedBarSeries *series = new QStackedBarSeries();
series->append(low);
series->append(high);
//![2]
//![3]
QChart *chart = new QChart();
chart->addSeries(series);
chart->setTitle("Temperature records in celcius");
chart->setAnimationOptions(QChart::SeriesAnimations);
//![3]
//![4]
QStringList categories;
categories << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun" << "Jul" << "Aug" << "Sep" << "Oct" << "Nov" << "Dec";
QBarCategoryAxis *axis = new QBarCategoryAxis();
axis->append(categories);
axis->setTitleText("Month");
chart->createDefaultAxes();
chart->setAxisX(axis, series);
chart->axisY(series)->setRange(-52, 52);
chart->axisY(series)->setTitleText("Temperature [°C]");
//![4]
//![5]
chart->legend()->setVisible(true);
chart->legend()->setAlignment(Qt::AlignBottom);
//![5]
//![6]
QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);
//![6]
//![7]
QMainWindow window;
window.setCentralWidget(chartView);
window.resize(600, 300);
window.show();
//![7]
return a.exec();
}
|
geminy/aidear
|
oss/qt/qt-everywhere-opensource-src-5.9.0/qtcharts/examples/charts/temperaturerecords/main.cpp
|
C++
|
gpl-3.0
| 3,166
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>atlas: /home/ran/atlas_project/latest_branch_07182016/sources/interpreter/axis-types.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="e8dynkintransparent.gif"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">atlas
 <span id="projectnumber">0.6</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_6c3c7928da1cdc197ab3853ddad7be41.html">latest_branch_07182016</a></li><li class="navelem"><a class="el" href="dir_9423311babe90635fab29e5efa88abf4.html">sources</a></li><li class="navelem"><a class="el" href="dir_cd5d8c37b93e737ff19639b88f22308c.html">interpreter</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#nested-classes">Classes</a> |
<a href="#namespaces">Namespaces</a> |
<a href="#define-members">Macros</a> |
<a href="#typedef-members">Typedefs</a> |
<a href="#enum-members">Enumerations</a> |
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<div class="title">axis-types.h File Reference</div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><code>#include <memory></code><br />
<code>#include "<a class="el" href="sl__list_8h_source.html">sl_list.h</a>"</code><br />
<code>#include <iostream></code><br />
<code>#include <vector></code><br />
<code>#include <cassert></code><br />
<code>#include <iterator></code><br />
<code>#include <stdexcept></code><br />
<code>#include <csignal></code><br />
</div><div class="textblock"><div class="dynheader">
Include dependency graph for axis-types.h:</div>
<div class="dyncontent">
<div class="center"><img src="axis-types_8h__incl.png" border="0" usemap="#_2home_2ran_2atlas__project_2latest__branch__07182016_2sources_2interpreter_2axis-types_8h" alt=""/></div>
<!-- MAP 0 -->
</div>
</div><div class="textblock"><div class="dynheader">
This graph shows which files directly or indirectly include this file:</div>
<div class="dyncontent">
<div class="center"><img src="axis-types_8h__dep__incl.png" border="0" usemap="#_2home_2ran_2atlas__project_2latest__branch__07182016_2sources_2interpreter_2axis-types_8hdep" alt=""/></div>
<!-- MAP 1 -->
</div>
</div>
<p><a href="axis-types_8h_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="nested-classes"></a>
Classes</h2></td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1type__expr.html">atlas::interpreter::type_expr</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1func__type.html">atlas::interpreter::func_type</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1value__base.html">atlas::interpreter::value_base</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1row__value.html">atlas::interpreter::row_value</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1tuple__value.html">atlas::interpreter::tuple_value</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classatlas_1_1interpreter_1_1evaluation__context.html">atlas::interpreter::evaluation_context</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1expression__base.html">atlas::interpreter::expression_base</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1conversion__info.html">atlas::interpreter::conversion_info</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classatlas_1_1interpreter_1_1conversion.html">atlas::interpreter::conversion</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1conversion__record.html">atlas::interpreter::conversion_record</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classatlas_1_1interpreter_1_1voiding.html">atlas::interpreter::voiding</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1error__base.html">atlas::interpreter::error_base</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1logic__error.html">atlas::interpreter::logic_error</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1program__error.html">atlas::interpreter::program_error</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1runtime__error.html">atlas::interpreter::runtime_error</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1expr__error.html">atlas::interpreter::expr_error</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1type__error.html">atlas::interpreter::type_error</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1balance__error.html">atlas::interpreter::balance_error</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1loop__break.html">atlas::interpreter::loop_break</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1function__return.html">atlas::interpreter::function_return</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">struct  </td><td class="memItemRight" valign="bottom"><a class="el" href="structatlas_1_1interpreter_1_1user__interrupt.html">atlas::interpreter::user_interrupt</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="namespaces"></a>
Namespaces</h2></td></tr>
<tr class="memitem:namespaceatlas"><td class="memItemLeft" align="right" valign="top">  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas.html">atlas</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:namespaceatlas_1_1interpreter"><td class="memItemLeft" align="right" valign="top">  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html">atlas::interpreter</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="define-members"></a>
Macros</h2></td></tr>
<tr class="memitem:ae57ef91e0ea0c0a30856eb04577e3587"><td class="memItemLeft" align="right" valign="top">#define </td><td class="memItemRight" valign="bottom"><a class="el" href="axis-types_8h.html#ae57ef91e0ea0c0a30856eb04577e3587">AXIS_TYPES_H</a>   /*3:*/</td></tr>
<tr class="separator:ae57ef91e0ea0c0a30856eb04577e3587"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="typedef-members"></a>
Typedefs</h2></td></tr>
<tr class="memitem:ae315f3fdbd04bf8b9a0f49bf40587c63"><td class="memItemLeft" align="right" valign="top">typedef type_expr * </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#ae315f3fdbd04bf8b9a0f49bf40587c63">atlas::interpreter::type_p</a></td></tr>
<tr class="separator:ae315f3fdbd04bf8b9a0f49bf40587c63"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a37bd1d18b0ab5ed35059c5c07c2176a5"><td class="memItemLeft" align="right" valign="top">typedef const type_expr * </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a37bd1d18b0ab5ed35059c5c07c2176a5">atlas::interpreter::const_type_p</a></td></tr>
<tr class="separator:a37bd1d18b0ab5ed35059c5c07c2176a5"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab8734c1dbbab638e9b792881c5a8fa33"><td class="memItemLeft" align="right" valign="top">typedef std::unique_ptr< type_expr > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#ab8734c1dbbab638e9b792881c5a8fa33">atlas::interpreter::type_ptr</a></td></tr>
<tr class="separator:ab8734c1dbbab638e9b792881c5a8fa33"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a57dba99eb7c5e9f5a9ee09152ec820db"><td class="memItemLeft" align="right" valign="top">typedef containers::simple_list< type_expr > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a57dba99eb7c5e9f5a9ee09152ec820db">atlas::interpreter::type_list</a></td></tr>
<tr class="separator:a57dba99eb7c5e9f5a9ee09152ec820db"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a7f97378133d0ee5f8e075081df4d3370"><td class="memItemLeft" align="right" valign="top">typedef <a class="el" href="structatlas_1_1containers_1_1sl__node.html">atlas::containers::sl_node</a>< type_expr > * </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a7f97378133d0ee5f8e075081df4d3370">atlas::interpreter::raw_type_list</a></td></tr>
<tr class="separator:a7f97378133d0ee5f8e075081df4d3370"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a59217b6bdc8f04ad34c0660c16c2b861"><td class="memItemLeft" align="right" valign="top">typedef containers::sl_list< type_expr > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a59217b6bdc8f04ad34c0660c16c2b861">atlas::interpreter::dressed_type_list</a></td></tr>
<tr class="separator:a59217b6bdc8f04ad34c0660c16c2b861"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a0d85b16cf89fe40469b21472e2dd7841"><td class="memItemLeft" align="right" valign="top">typedef containers::weak_sl_list_const_iterator< type_expr > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a0d85b16cf89fe40469b21472e2dd7841">atlas::interpreter::wtl_const_iterator</a></td></tr>
<tr class="separator:a0d85b16cf89fe40469b21472e2dd7841"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a3747f44c4e72e8ac63d4c6d4372a485a"><td class="memItemLeft" align="right" valign="top">typedef containers::weak_sl_list_iterator< type_expr > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a3747f44c4e72e8ac63d4c6d4372a485a">atlas::interpreter::wtl_iterator</a></td></tr>
<tr class="separator:a3747f44c4e72e8ac63d4c6d4372a485a"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a5b10a9ef47b95fa1aac4e2158d3ce84c"><td class="memItemLeft" align="right" valign="top">typedef func_type * </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a5b10a9ef47b95fa1aac4e2158d3ce84c">atlas::interpreter::func_type_p</a></td></tr>
<tr class="separator:a5b10a9ef47b95fa1aac4e2158d3ce84c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a6e43df650364e62767e0786a9d61a977"><td class="memItemLeft" align="right" valign="top">typedef std::unique_ptr< func_type > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a6e43df650364e62767e0786a9d61a977">atlas::interpreter::func_type_ptr</a></td></tr>
<tr class="separator:a6e43df650364e62767e0786a9d61a977"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab49d924e0f6d2552982f02ea59362298"><td class="memItemLeft" align="right" valign="top">typedef value_base * </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#ab49d924e0f6d2552982f02ea59362298">atlas::interpreter::value</a></td></tr>
<tr class="separator:ab49d924e0f6d2552982f02ea59362298"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a28e26141d73b1dd9273f228d7fdd78f8"><td class="memItemLeft" align="right" valign="top">typedef std::shared_ptr< const value_base > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a28e26141d73b1dd9273f228d7fdd78f8">atlas::interpreter::shared_value</a></td></tr>
<tr class="separator:a28e26141d73b1dd9273f228d7fdd78f8"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a7b22609c005ccd9e330e69b0c80447c7"><td class="memItemLeft" align="right" valign="top">typedef std::shared_ptr< value_base > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a7b22609c005ccd9e330e69b0c80447c7">atlas::interpreter::own_value</a></td></tr>
<tr class="separator:a7b22609c005ccd9e330e69b0c80447c7"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad3c2a4c742de571e44aec370cc68cd05"><td class="memItemLeft" align="right" valign="top">typedef std::shared_ptr< const row_value > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#ad3c2a4c742de571e44aec370cc68cd05">atlas::interpreter::shared_row</a></td></tr>
<tr class="separator:ad3c2a4c742de571e44aec370cc68cd05"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa78197ab8a54488d120fb2c7af21720c"><td class="memItemLeft" align="right" valign="top">typedef std::shared_ptr< row_value > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#aa78197ab8a54488d120fb2c7af21720c">atlas::interpreter::own_row</a></td></tr>
<tr class="separator:aa78197ab8a54488d120fb2c7af21720c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a51790aded5668910de05981a0509076c"><td class="memItemLeft" align="right" valign="top">typedef std::unique_ptr< tuple_value > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a51790aded5668910de05981a0509076c">atlas::interpreter::tuple_ptr</a></td></tr>
<tr class="separator:a51790aded5668910de05981a0509076c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a085312f3fdf8b31644302ae3002b5d8f"><td class="memItemLeft" align="right" valign="top">typedef std::shared_ptr< const tuple_value > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a085312f3fdf8b31644302ae3002b5d8f">atlas::interpreter::shared_tuple</a></td></tr>
<tr class="separator:a085312f3fdf8b31644302ae3002b5d8f"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a804e91bb04d5f90a59679713a27f7581"><td class="memItemLeft" align="right" valign="top">typedef std::shared_ptr< tuple_value > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a804e91bb04d5f90a59679713a27f7581">atlas::interpreter::own_tuple</a></td></tr>
<tr class="separator:a804e91bb04d5f90a59679713a27f7581"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a0453a7e4bd0f6a3652b99ac16b35446b"><td class="memItemLeft" align="right" valign="top">typedef std::shared_ptr< class evaluation_context > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a0453a7e4bd0f6a3652b99ac16b35446b">atlas::interpreter::shared_context</a></td></tr>
<tr class="separator:a0453a7e4bd0f6a3652b99ac16b35446b"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a1aa8858041482b6fba44d752cf1c7cbe"><td class="memItemLeft" align="right" valign="top">typedef expression_base * </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a1aa8858041482b6fba44d752cf1c7cbe">atlas::interpreter::expression</a></td></tr>
<tr class="separator:a1aa8858041482b6fba44d752cf1c7cbe"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:adb028a3b379a8c910f8ee12ff2ceff1c"><td class="memItemLeft" align="right" valign="top">typedef std::unique_ptr< expression_base > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#adb028a3b379a8c910f8ee12ff2ceff1c">atlas::interpreter::expression_ptr</a></td></tr>
<tr class="separator:adb028a3b379a8c910f8ee12ff2ceff1c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ac109cb3b47c580e893fcb75bb74bed48"><td class="memItemLeft" align="right" valign="top">typedef std::shared_ptr< expression_base > </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#ac109cb3b47c580e893fcb75bb74bed48">atlas::interpreter::shared_expression</a></td></tr>
<tr class="separator:ac109cb3b47c580e893fcb75bb74bed48"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="enum-members"></a>
Enumerations</h2></td></tr>
<tr class="memitem:a97600ec84a94bf95b426698cc0c78e19"><td class="memItemLeft" align="right" valign="top">enum  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a97600ec84a94bf95b426698cc0c78e19">atlas::interpreter::type_tag</a> { <br />
  <a class="el" href="namespaceatlas_1_1interpreter.html#a97600ec84a94bf95b426698cc0c78e19afb3b481175d3c22fd5234eaae00a72b5">atlas::interpreter::undetermined_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#a97600ec84a94bf95b426698cc0c78e19af708c09b885d38930f53b295677e05dc">atlas::interpreter::primitive_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#a97600ec84a94bf95b426698cc0c78e19aab894953750ba466aa036c92eee5606f">atlas::interpreter::row_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#a97600ec84a94bf95b426698cc0c78e19a8ed29a1e31bbaca3ac3c75c774ba88ae">atlas::interpreter::tuple_type</a>,
<br />
  <a class="el" href="namespaceatlas_1_1interpreter.html#a97600ec84a94bf95b426698cc0c78e19a6a235b0f1b7d5bcfd9cba2835aa023b7">atlas::interpreter::function_type</a>
<br />
}</td></tr>
<tr class="separator:a97600ec84a94bf95b426698cc0c78e19"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:abee9e4b193b475e977b774b551e9f50b"><td class="memItemLeft" align="right" valign="top">enum  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50b">atlas::interpreter::primitive_tag</a> { <br />
  <a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50ba9b49bb89c2beb2cb6e3fc79227670e9c">atlas::interpreter::integral_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50badef88a02d9da519e59b7442b6c339a2c">atlas::interpreter::rational_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50ba230b074518f09cec51996b65b1571565">atlas::interpreter::string_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50bab427ed43a86ec58a4400fe9a7a8c23ed">atlas::interpreter::boolean_type</a>,
<br />
  <a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50ba8f4895d2a64e07c9c43c0412d467fd2e">atlas::interpreter::vector_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50bae1f314dbcb87ee9e426cfa1924607fee">atlas::interpreter::matrix_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50ba0862cd585ce614492a329c83e3354856">atlas::interpreter::rational_vector_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50ba05f3d5381439bd9b630fcc10a4f2d6d2">atlas::interpreter::complex_lie_type_type</a>,
<br />
  <a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50ba10e5e2b735b4cbc44ed08b102e5f2c49">atlas::interpreter::root_datum_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50ba7972afb20cb6a2b738026633c68a7b8c">atlas::interpreter::inner_class_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50ba2acae19794845da50737342e61031090">atlas::interpreter::real_form_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50ba40f9956aa236a2df683e23aeade105db">atlas::interpreter::Cartan_class_type</a>,
<br />
  <a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50babfab64019b4b9b86367bafc05c1b4141">atlas::interpreter::KGB_element_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50ba2e78df361da0454886b84f8ae9a8045a">atlas::interpreter::block_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50bac5cc2c8bc369df48867f01bdad6ec9e0">atlas::interpreter::module_parameter_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50ba7d905e2ce9fe8da57c9b1981b430a41b">atlas::interpreter::split_integer_type</a>,
<br />
  <a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50ba44e7ffcbc4d947fa6a95f8b5c0cb91b6">atlas::interpreter::virtual_module_type</a>,
<a class="el" href="namespaceatlas_1_1interpreter.html#abee9e4b193b475e977b774b551e9f50badd13f474de1431208af2fb9f2d488656">atlas::interpreter::nr_of_primitive_types</a>
<br />
}</td></tr>
<tr class="separator:abee9e4b193b475e977b774b551e9f50b"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:a04a1f2fccefc8b8a9779db002f66e87b"><td class="memItemLeft" align="right" valign="top">type_ptr </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a04a1f2fccefc8b8a9779db002f66e87b">atlas::interpreter::acquire</a> (const type_expr *t)</td></tr>
<tr class="separator:a04a1f2fccefc8b8a9779db002f66e87b"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aa56b3a8cc38892f2bff7af31280d1484"><td class="memItemLeft" align="right" valign="top">type_list </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#aa56b3a8cc38892f2bff7af31280d1484">atlas::interpreter::empty_tuple</a> ()</td></tr>
<tr class="separator:aa56b3a8cc38892f2bff7af31280d1484"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae1e375494a72daa419751fd1ca64f61b"><td class="memItemLeft" align="right" valign="top">type_list & </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#ae1e375494a72daa419751fd1ca64f61b">atlas::interpreter::prefix</a> (type_expr &&t, type_list &dst)</td></tr>
<tr class="separator:ae1e375494a72daa419751fd1ca64f61b"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a9824f82953c27fd3b3d32c305bc040cf"><td class="memItemLeft" align="right" valign="top">dressed_type_list & </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a9824f82953c27fd3b3d32c305bc040cf">atlas::interpreter::prefix</a> (type_expr &&t, dressed_type_list &dst)</td></tr>
<tr class="separator:a9824f82953c27fd3b3d32c305bc040cf"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ac537d4cd6855f4c7017b6729500349f2"><td class="memItemLeft" align="right" valign="top">std::ostream & </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#ac537d4cd6855f4c7017b6729500349f2">atlas::interpreter::operator<<</a> (std::ostream &<a class="el" href="cweave_8c.html#ab64524e68d64961bed2c5cae73835b72">out</a>, const type_expr &t)</td></tr>
<tr class="separator:ac537d4cd6855f4c7017b6729500349f2"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ae84bd9b209d2a5021220d541e82dc640"><td class="memItemLeft" align="right" valign="top">std::ostream & </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#ae84bd9b209d2a5021220d541e82dc640">atlas::interpreter::operator<<</a> (std::ostream &<a class="el" href="cweave_8c.html#ab64524e68d64961bed2c5cae73835b72">out</a>, const func_type &<a class="el" href="structf.html">f</a>)</td></tr>
<tr class="separator:ae84bd9b209d2a5021220d541e82dc640"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a23164c23073bf98e94abcb1dbd3897a2"><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a23164c23073bf98e94abcb1dbd3897a2">atlas::interpreter::operator==</a> (const type_expr &x, const type_expr &y)</td></tr>
<tr class="separator:a23164c23073bf98e94abcb1dbd3897a2"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab02f3b48a767fc68f7c5ef4032d42ebc"><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#ab02f3b48a767fc68f7c5ef4032d42ebc">atlas::interpreter::operator!=</a> (const type_expr &x, const type_expr &y)</td></tr>
<tr class="separator:ab02f3b48a767fc68f7c5ef4032d42ebc"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af86bdcb9676fdb7bcca76235558ed046"><td class="memItemLeft" align="right" valign="top">type_ptr </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#af86bdcb9676fdb7bcca76235558ed046">atlas::interpreter::mk_prim_type</a> (primitive_tag <a class="el" href="lists_8cpp.html#abd2d52b80732d210e00ca2adef4352be">p</a>)</td></tr>
<tr class="separator:af86bdcb9676fdb7bcca76235558ed046"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a38d0c948f6a218a6fdd51f7d7d9db055"><td class="memItemLeft" align="right" valign="top">type_ptr </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a38d0c948f6a218a6fdd51f7d7d9db055">atlas::interpreter::mk_row_type</a> (type_ptr &&c)</td></tr>
<tr class="separator:a38d0c948f6a218a6fdd51f7d7d9db055"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a10f9e618f190a08b87f2348b31fb723c"><td class="memItemLeft" align="right" valign="top">type_ptr </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a10f9e618f190a08b87f2348b31fb723c">atlas::interpreter::mk_tuple_type</a> (type_list &&l)</td></tr>
<tr class="separator:a10f9e618f190a08b87f2348b31fb723c"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aea7e962222f1ffd0d60fc12709eabcb0"><td class="memItemLeft" align="right" valign="top">type_ptr </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#aea7e962222f1ffd0d60fc12709eabcb0">atlas::interpreter::mk_function_type</a> (type_expr &&a, type_expr &&r)</td></tr>
<tr class="separator:aea7e962222f1ffd0d60fc12709eabcb0"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ac467b4ee4ff367ccb12ce055bb18c6ab"><td class="memItemLeft" align="right" valign="top">type_p </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#ac467b4ee4ff367ccb12ce055bb18c6ab">atlas::interpreter::make_prim_type</a> (unsigned int <a class="el" href="lists_8cpp.html#abd2d52b80732d210e00ca2adef4352be">p</a>)</td></tr>
<tr class="separator:ac467b4ee4ff367ccb12ce055bb18c6ab"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a5011b8e064071948e40e4cc813e81078"><td class="memItemLeft" align="right" valign="top">type_p </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a5011b8e064071948e40e4cc813e81078">atlas::interpreter::make_row_type</a> (type_p c)</td></tr>
<tr class="separator:a5011b8e064071948e40e4cc813e81078"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a8b8d66cc2b6b2e146222ee9f0f5cabef"><td class="memItemLeft" align="right" valign="top">type_p </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a8b8d66cc2b6b2e146222ee9f0f5cabef">atlas::interpreter::make_tuple_type</a> (raw_type_list l)</td></tr>
<tr class="separator:a8b8d66cc2b6b2e146222ee9f0f5cabef"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aed7805bcd278972c6d32db5cbc7bb161"><td class="memItemLeft" align="right" valign="top">type_p </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#aed7805bcd278972c6d32db5cbc7bb161">atlas::interpreter::make_function_type</a> (type_p a, type_p r)</td></tr>
<tr class="separator:aed7805bcd278972c6d32db5cbc7bb161"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:abb0a75e577fb35c79efe17ef8c46c3f9"><td class="memItemLeft" align="right" valign="top">raw_type_list </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#abb0a75e577fb35c79efe17ef8c46c3f9">atlas::interpreter::make_type_singleton</a> (type_p t)</td></tr>
<tr class="separator:abb0a75e577fb35c79efe17ef8c46c3f9"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aac3714c26befc1bb178d9c27ea048a80"><td class="memItemLeft" align="right" valign="top">raw_type_list </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#aac3714c26befc1bb178d9c27ea048a80">atlas::interpreter::make_type_list</a> (raw_type_list l, type_p t)</td></tr>
<tr class="separator:aac3714c26befc1bb178d9c27ea048a80"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2c77dc4fd2d25a1d7bef31e0bafdc398"><td class="memItemLeft" align="right" valign="top">type_ptr </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a2c77dc4fd2d25a1d7bef31e0bafdc398">atlas::interpreter::mk_type</a> (const char *s)</td></tr>
<tr class="separator:a2c77dc4fd2d25a1d7bef31e0bafdc398"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a593d0932e9f5679aa7d32b82ec60ee04"><td class="memItemLeft" align="right" valign="top">type_expr </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a593d0932e9f5679aa7d32b82ec60ee04">atlas::interpreter::mk_type_expr</a> (const char *s)</td></tr>
<tr class="separator:a593d0932e9f5679aa7d32b82ec60ee04"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a73b24fff3b5d72fe1134515c6a74e5d4"><td class="memItemLeft" align="right" valign="top">type_expr </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a73b24fff3b5d72fe1134515c6a74e5d4">atlas::interpreter::unknown_tuple</a> (size_t <a class="el" href="axis_8cpp.html#a62054673f9ef1f1fedc9642feb1df2c0">n</a>)</td></tr>
<tr class="separator:a73b24fff3b5d72fe1134515c6a74e5d4"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:adea928fe75a2382c0cf75d0d1164122f"><td class="memItemLeft" align="right" valign="top">std::ostream & </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#adea928fe75a2382c0cf75d0d1164122f">atlas::interpreter::operator<<</a> (std::ostream &<a class="el" href="cweave_8c.html#ab64524e68d64961bed2c5cae73835b72">out</a>, const value_base &<a class="el" href="graph_8cpp.html#a796e5c390de2ad622ad0fdd3d12a4c07">v</a>)</td></tr>
<tr class="separator:adea928fe75a2382c0cf75d0d1164122f"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a3923ef314ba36b0cd439b14d7c03bd46"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a3923ef314ba36b0cd439b14d7c03bd46">atlas::interpreter::push_tuple_components</a> ()</td></tr>
<tr class="separator:a3923ef314ba36b0cd439b14d7c03bd46"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a8cf4593bcd367f60cebb02a8b22c8660"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a8cf4593bcd367f60cebb02a8b22c8660">atlas::interpreter::wrap_tuple</a> (size_t <a class="el" href="axis_8cpp.html#a62054673f9ef1f1fedc9642feb1df2c0">n</a>)</td></tr>
<tr class="separator:a8cf4593bcd367f60cebb02a8b22c8660"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a6e35412363bc5921c8a9ff920b8be350"><td class="memItemLeft" align="right" valign="top">std::ostream & </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a6e35412363bc5921c8a9ff920b8be350">atlas::interpreter::operator<<</a> (std::ostream &<a class="el" href="cweave_8c.html#ab64524e68d64961bed2c5cae73835b72">out</a>, const expression_base &<a class="el" href="axis_8cpp.html#af017b5029e4109d3876818aa6c57f1d2">e</a>)</td></tr>
<tr class="separator:a6e35412363bc5921c8a9ff920b8be350"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ac6bed14c1845220bdc23fc2171b085b7"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#ac6bed14c1845220bdc23fc2171b085b7">atlas::interpreter::push_expanded</a> (expression_base::level l, const shared_value &<a class="el" href="graph_8cpp.html#a796e5c390de2ad622ad0fdd3d12a4c07">v</a>)</td></tr>
<tr class="separator:ac6bed14c1845220bdc23fc2171b085b7"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a732c1aafbc55e820d37253ee7f451224"><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a732c1aafbc55e820d37253ee7f451224">atlas::interpreter::coerce</a> (const type_expr &from_type, const type_expr &to_type, expression_ptr &<a class="el" href="axis_8cpp.html#af017b5029e4109d3876818aa6c57f1d2">e</a>)</td></tr>
<tr class="separator:a732c1aafbc55e820d37253ee7f451224"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a93545601d7efd04517bd7769cd177c6f"><td class="memItemLeft" align="right" valign="top">expression_ptr </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a93545601d7efd04517bd7769cd177c6f">atlas::interpreter::conform_types</a> (const type_expr &found, type_expr &required, expression_ptr &&d, const expr &<a class="el" href="axis_8cpp.html#af017b5029e4109d3876818aa6c57f1d2">e</a>)</td></tr>
<tr class="separator:a93545601d7efd04517bd7769cd177c6f"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a34ba3f27d50dc13f6ded1072946b1e41"><td class="memItemLeft" align="right" valign="top">const conversion_record * </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a34ba3f27d50dc13f6ded1072946b1e41">atlas::interpreter::row_coercion</a> (const type_expr &final_type, type_expr &component_type)</td></tr>
<tr class="separator:a34ba3f27d50dc13f6ded1072946b1e41"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ac1807c0ea0e5ecf241db266ae2ffa8e5"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#ac1807c0ea0e5ecf241db266ae2ffa8e5">atlas::interpreter::coercion</a> (const type_expr &from, const type_expr &to, const char *s, conversion_info::conv_f <a class="el" href="structf.html">f</a>)</td></tr>
<tr class="separator:ac1807c0ea0e5ecf241db266ae2ffa8e5"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a7c7b901b4dfc2669ad8328f79b976a7f"><td class="memItemLeft" align="right" valign="top">unsigned int </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a7c7b901b4dfc2669ad8328f79b976a7f">atlas::interpreter::is_close</a> (const type_expr &x, const type_expr &y)</td></tr>
<tr class="separator:a7c7b901b4dfc2669ad8328f79b976a7f"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a2ff70c675276c00336b17b3be4c65690"><td class="memItemLeft" align="right" valign="top">bool </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a2ff70c675276c00336b17b3be4c65690">atlas::interpreter::broader_eq</a> (const type_expr &a, const type_expr &b)</td></tr>
<tr class="separator:a2ff70c675276c00336b17b3be4c65690"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a85f7f7bcdc9a67cc575042f222a597fe"><td class="memTemplParams" colspan="2">template<typename T > </td></tr>
<tr class="memitem:a85f7f7bcdc9a67cc575042f222a597fe"><td class="memTemplItemLeft" align="right" valign="top">T & </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a85f7f7bcdc9a67cc575042f222a597fe">atlas::interpreter::as_lvalue</a> (T &&rvalue)</td></tr>
<tr class="separator:a85f7f7bcdc9a67cc575042f222a597fe"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a02bc9d3d50b57fa07baf12442c997105"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a02bc9d3d50b57fa07baf12442c997105">atlas::interpreter::push_value</a> (const shared_value &<a class="el" href="graph_8cpp.html#a796e5c390de2ad622ad0fdd3d12a4c07">v</a>)</td></tr>
<tr class="separator:a02bc9d3d50b57fa07baf12442c997105"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ab7316898114bd5d53a940bd83607f9ad"><td class="memItemLeft" align="right" valign="top">void </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#ab7316898114bd5d53a940bd83607f9ad">atlas::interpreter::push_value</a> (shared_value &&<a class="el" href="graph_8cpp.html#a796e5c390de2ad622ad0fdd3d12a4c07">v</a>)</td></tr>
<tr class="separator:ab7316898114bd5d53a940bd83607f9ad"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a1ecf793ee20e67cdce09224c06c9d8a8"><td class="memItemLeft" align="right" valign="top">shared_value </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a1ecf793ee20e67cdce09224c06c9d8a8">atlas::interpreter::pop_value</a> ()</td></tr>
<tr class="separator:a1ecf793ee20e67cdce09224c06c9d8a8"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a83c233b6f94fe38a4965dc7901f79d3f"><td class="memTemplParams" colspan="2">template<typename D > </td></tr>
<tr class="memitem:a83c233b6f94fe38a4965dc7901f79d3f"><td class="memTemplItemLeft" align="right" valign="top">std::shared_ptr< const D > </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a83c233b6f94fe38a4965dc7901f79d3f">atlas::interpreter::get</a> () throw (logic_error)</td></tr>
<tr class="separator:a83c233b6f94fe38a4965dc7901f79d3f"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:afa4b40215bd3dc65ca63f5834adeca48"><td class="memTemplParams" colspan="2">template<typename D > </td></tr>
<tr class="memitem:afa4b40215bd3dc65ca63f5834adeca48"><td class="memTemplItemLeft" align="right" valign="top">std::shared_ptr< D > </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#afa4b40215bd3dc65ca63f5834adeca48">atlas::interpreter::non_const_get</a> () throw (logic_error)</td></tr>
<tr class="separator:afa4b40215bd3dc65ca63f5834adeca48"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aee8010948615f91da6e7895d12c86063"><td class="memTemplParams" colspan="2">template<typename D > </td></tr>
<tr class="memitem:aee8010948615f91da6e7895d12c86063"><td class="memTemplItemLeft" align="right" valign="top">D * </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#aee8010948615f91da6e7895d12c86063">atlas::interpreter::force</a> (value <a class="el" href="graph_8cpp.html#a796e5c390de2ad622ad0fdd3d12a4c07">v</a>) throw (logic_error)</td></tr>
<tr class="separator:aee8010948615f91da6e7895d12c86063"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a3e72c28f17e11936013e5871099924d5"><td class="memTemplParams" colspan="2">template<typename D > </td></tr>
<tr class="memitem:a3e72c28f17e11936013e5871099924d5"><td class="memTemplItemLeft" align="right" valign="top">const D * </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a3e72c28f17e11936013e5871099924d5">atlas::interpreter::force</a> (const value_base *<a class="el" href="graph_8cpp.html#a796e5c390de2ad622ad0fdd3d12a4c07">v</a>) throw (logic_error)</td></tr>
<tr class="separator:a3e72c28f17e11936013e5871099924d5"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a7a702c92f5000ac191ae8a20be4a7150"><td class="memTemplParams" colspan="2">template<typename D > </td></tr>
<tr class="memitem:a7a702c92f5000ac191ae8a20be4a7150"><td class="memTemplItemLeft" align="right" valign="top">std::shared_ptr< D > </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a7a702c92f5000ac191ae8a20be4a7150">atlas::interpreter::get_own</a> () throw (logic_error)</td></tr>
<tr class="separator:a7a702c92f5000ac191ae8a20be4a7150"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a1b390a3375fe39d5da7b8311aa4b0c56"><td class="memItemLeft" align="right" valign="top">value </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a1b390a3375fe39d5da7b8311aa4b0c56">atlas::interpreter::uniquify</a> (shared_value &<a class="el" href="graph_8cpp.html#a796e5c390de2ad622ad0fdd3d12a4c07">v</a>)</td></tr>
<tr class="separator:a1b390a3375fe39d5da7b8311aa4b0c56"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a69a933aa84d40702fb69ccd8c45a70a0"><td class="memTemplParams" colspan="2">template<unsigned int> </td></tr>
<tr class="memitem:a69a933aa84d40702fb69ccd8c45a70a0"><td class="memTemplItemLeft" align="right" valign="top">void </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a69a933aa84d40702fb69ccd8c45a70a0">atlas::interpreter::wrap_tuple</a> ()</td></tr>
<tr class="separator:a69a933aa84d40702fb69ccd8c45a70a0"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af73acb123719dd5353380f2b3069c5fc"><td class="memTemplParams" colspan="2">template<unsigned int> </td></tr>
<tr class="memitem:af73acb123719dd5353380f2b3069c5fc"><td class="memTemplItemLeft" align="right" valign="top">void </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#af73acb123719dd5353380f2b3069c5fc">atlas::interpreter::do_wrap</a> (std::vector< shared_value >::iterator it)</td></tr>
<tr class="separator:af73acb123719dd5353380f2b3069c5fc"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a158bfd8d894dd1cbed1a7626b7c8af3d"><td class="memTemplParams" colspan="2">template<> </td></tr>
<tr class="memitem:a158bfd8d894dd1cbed1a7626b7c8af3d"><td class="memTemplItemLeft" align="right" valign="top">void </td><td class="memTemplItemRight" valign="bottom"><a class="el" href="namespaceatlas_1_1interpreter.html#a158bfd8d894dd1cbed1a7626b7c8af3d">atlas::interpreter::do_wrap< 0u ></a> (std::vector< shared_value >::iterator it)</td></tr>
<tr class="separator:a158bfd8d894dd1cbed1a7626b7c8af3d"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Macro Definition Documentation</h2>
<a class="anchor" id="ae57ef91e0ea0c0a30856eb04577e3587"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">#define AXIS_TYPES_H   /*3:*/</td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.11
</small></address>
</body>
</html>
|
jeffreyadams/atlasofliegroups-docs
|
atlas_static/doxygen/axis-types_8h.html
|
HTML
|
gpl-3.0
| 52,328
|
#!/usr/bin/perl
##use: perl_script.pl input(Trinity fasta file) out_file
use warnings;
use strict;
#use Data::Dumper;
open(OUT, ">$ARGV[1]");
open(IN, $ARGV[0]);
my %Tri_contigs_length;
while (my $line = <IN>) {
chomp($line);
if ($line =~ m/^>/) {
my @split = split(" ", $line);
foreach (@split) {
s/>//;
s/>//;
}
my @length = ($line =~ m/len\=(.*?)\s/);
$Tri_contigs_length{$split[0]} = "@length";
}
}
#print the contigs length values##
for my $contig (keys %Tri_contigs_length) {
print OUT "$Tri_contigs_length{$contig}\n";
}
close(IN);
close(OUT);
|
AnanasAssembler/AnanasAssembler
|
scripts/SimulatedData/Trinity_GetContigsLength.pl
|
Perl
|
gpl-3.0
| 651
|
#include "RepRapFirmware.h"
#include "DriveMovement.h"
// The remaining functions are speed-critical, so use full optimisation
#pragma GCC optimize ("O3")
// Fast 62-bit integer square root function (thanks dmould)
uint32_t isqrt64(uint64_t num)
{
uint32_t numHigh = (uint32_t)(num >> 32);
if (numHigh == 0)
{
// 32-bit square root - thanks to Wilco Dijksra for this efficient ARM algorithm
uint32_t num32 = (uint32_t)num;
uint32_t res = 0;
#define iter32(N) \
{ \
uint32_t temp = res | (1 << N); \
if (num32 >= temp << N) \
{ \
num32 -= temp << N; \
res |= 2 << N; \
} \
}
// We need to do 16 iterations
iter32(15); iter32(14); iter32(13); iter32(12);
iter32(11); iter32(10); iter32(9); iter32(8);
iter32(7); iter32(6); iter32(5); iter32(4);
iter32(3); iter32(2); iter32(1); iter32(0);
return res >> 1;
}
else if ((numHigh & (3u << 30)) != 0)
{
// Input out of range - probably negative, so return -1
return 0xFFFFFFFF;
}
else
{
// 62-bit square root
uint32_t res = 0;
#define iter64a(N) \
{ \
res <<= 1; \
uint32_t temp = (res | 1) << (N); \
if (numHigh >= temp) \
{ \
numHigh -= temp; \
res |= 2; \
} \
}
// We need to do 15 iterations (not 16 because we have eliminated the top 2 bits)
iter64a(28) iter64a(26) iter64a(24)
iter64a(22) iter64a(20) iter64a(18) iter64a(16)
iter64a(14) iter64a(12) iter64a(10) iter64a(8)
iter64a(6) iter64a(4) iter64a(2) iter64a(0)
// resHigh is twice the square root of the msw, in the range 0..2^17-1
uint64_t numAll = ((uint64_t)numHigh << 32) | (uint32_t)num;
#define iter64b(N) \
{ \
res <<= 1; \
uint64_t temp = ((uint64_t)res | 1) << (N); \
if (numAll >= temp) \
{ \
numAll -= temp; \
res |= 2; \
} \
}
// We need to do 16 iterations.
// After the last iteration, numAll may be between 0 and (1 + 2 * res) inclusive.
// So to take square roots of numbers up to 64 bits, we need to do all these iterations using 64 bit maths.
// If we restricted the input to e.g. 48 bits, then we could do some of the final iterations using 32-bit maths.
iter64b(30) iter64b(28) iter64b(26) iter64b(24)
iter64b(22) iter64b(20) iter64b(18) iter64b(16)
iter64b(14) iter64b(12) iter64b(10) iter64b(8)
iter64b(6) iter64b(4) iter64b(2) iter64b(0)
return res >> 1;
#undef iter64a
#undef iter64b
}
}
#if 0
// Fast 64-bit integer square root function
uint32_t isqrt2(uint64_t num)
{
uint32_t numHigh = (uint32_t)(num >> 32);
uint32_t resHigh = 0;
#define iter64a(N) \
{ \
uint32_t temp = resHigh + (1 << (N)); \
if (numHigh >= temp << (N)) \
{ \
numHigh -= temp << (N); \
resHigh |= 2 << (N); \
} \
}
// We need to do 16 iterations
iter64a(15); iter64a(14); iter64a(13); iter64a(12);
iter64a(11); iter64a(10); iter64a(9); iter64a(8);
iter64a(7); iter64a(6); iter64a(5); iter64a(4);
iter64a(3); iter64a(2); iter64a(1); iter64a(0);
// resHigh is twice the square root of the msw, in the range 0..2^17-1
uint64_t res = (uint64_t)resHigh << 16;
uint64_t numAll = ((uint64_t)numHigh << 32) | (uint32_t)num;
#define iter64b(N) \
{ \
uint64_t temp = res | (1 << (N)); \
if (numAll >= temp << (N)) \
{ \
numAll -= temp << (N); \
res |= 2 << (N); \
} \
}
// We need to do 16 iterations.
// After the last iteration, numAll may be between 0 and (1 + 2 * res) inclusive.
// So to take square roots of numbers up to 64 bits, we need to do all these iterations using 64 bit maths.
// If we restricted the input to e.g. 48 bits, then we could do some of the final iterations using 32-bit maths.
iter64b(15) iter64b(14) iter64b(13) iter64b(12)
iter64b(11) iter64b(10) iter64b(9) iter64b(8)
iter64b(7) iter64b(6) iter64b(5) iter64b(4)
iter64b(3) iter64b(2) iter64b(1) iter64b(0)
return (uint32_t)(res >> 1);
#undef iter64a
#undef iter64b
#undef iter32
}
uint32_t sqSum1 = 0, sqSum2 = 0, sqCount = 0, sqErrors = 0, lastRes1 = 0, lastRes2 = 0;
uint64_t lastNum = 0;
/* static */ uint32_t isqrt64(uint64_t num)
{
irqflags_t flags = cpu_irq_save();
uint32_t t2 = Platform::GetInterruptClocks();
uint32_t res1 = isqrt1(num);
uint32_t t3 = Platform::GetInterruptClocks();
uint32_t res2 = isqrt2(num);
uint32_t t4 = Platform::GetInterruptClocks();
cpu_irq_restore(flags);
sqSum1 += (t3 - t2);
sqSum2 += (t4 - t3);
++sqCount;
if (res1 != res2)
{
++sqErrors;
lastNum = num;
lastRes1 = res1;
lastRes2 = res2;
}
return res2;
}
#endif
// End
|
dcnewman/RepRapFirmware
|
src/Isqrt.cpp
|
C++
|
gpl-3.0
| 4,744
|
# No Loop.
#
# The noLoop() function causes draw() to only
# execute once. Without calling noLoop(), draw()
# executed continually.
attr_reader :y
def setup
sketch_title 'No Loop'
@y = height / 2
stroke 255
frame_rate 30
no_loop
end
def draw
background 0
@y = y - 1
@y = height if y < 0
line 0, y, width, y
end
def settings
size 640, 360
end
|
ruby-processing/JRubyArt-examples
|
processing_app/basics/structure/noloop.rb
|
Ruby
|
gpl-3.0
| 365
|
package com.travelport.service.hotel_v29_0;
/**
* Please modify this class to meet your needs
* This class is not complete
*/
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.bind.annotation.XmlSeeAlso;
/**
* This class was generated by Apache CXF 2.7.12
* 2014-09-19T15:09:40.850-06:00
* Generated source version: 2.7.12
*
*/
public final class RetrieveHotelSearchAvailabilityServicePortType_RetrieveHotelSearchAvailabilityServicePort_Client {
private static final QName SERVICE_NAME = new QName("http://www.travelport.com/service/hotel_v29_0", "HotelService");
private RetrieveHotelSearchAvailabilityServicePortType_RetrieveHotelSearchAvailabilityServicePort_Client() {
}
public static void main(String args[]) throws java.lang.Exception {
URL wsdlURL = HotelService.WSDL_LOCATION;
if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
File wsdlFile = new File(args[0]);
try {
if (wsdlFile.exists()) {
wsdlURL = wsdlFile.toURI().toURL();
} else {
wsdlURL = new URL(args[0]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
HotelService ss = new HotelService(wsdlURL, SERVICE_NAME);
RetrieveHotelSearchAvailabilityServicePortType port = ss.getRetrieveHotelSearchAvailabilityServicePort();
{
System.out.println("Invoking service...");
com.travelport.schema.hotel_v29_0.RetrieveHotelSearchAvailabilityReq _service_parameters = null;
try {
com.travelport.schema.hotel_v29_0.RetrieveHotelSearchAvailabilityRsp _service__return = port.service(_service_parameters);
System.out.println("service.result=" + _service__return);
} catch (HotelFaultMessage e) {
System.out.println("Expected exception: HotelFaultMessage has occurred.");
System.out.println(e.toString());
}
}
System.exit(0);
}
}
|
angecab10/travelport-uapi-tutorial
|
src/com/travelport/service/hotel_v29_0/RetrieveHotelSearchAvailabilityServicePortType_RetrieveHotelSearchAvailabilityServicePort_Client.java
|
Java
|
gpl-3.0
| 2,307
|
***

***
_The PlayStation 2 is a home video game console released by Sony in 2000._
***
| Emulator | Rom Folder | Extension | BIOS | Controller Config |
| :---: | :---: | :---: | :---: | :---: |
| [PCSX2](http://pcsx2.net/) | ps2 | .iso .img .bin .mdf .z .z2 .bz2 .dump .cso .ima .gz | rom1.bin, rom2.bin, erom.bin, SCPH-XXXXX.nvm | |
> **Note This is only for x86/x86_64 builds- Not the Raspberry Pi!.**
## Emulators: [PCSX2](http://pcsx2.net/)
## ROMS
Accepted File Extensions: **.iso .img .bin .mdf .z .z2 .bz2 .dump .cso .ima .gz**
Place your PlayStation 2 ROMs in
```
/home/pi/RetroPie/roms/ps2
```
## BIOS
Place your Playstation 2 BIOS in
```
/home/pi/.config/PCSX2/bios/
```
On first run the GUI will ask you to select which BIOS to use. Select the appropriate one and use iso' that match that region.
## Controls

|
RetroPie/RetroPie-Docs
|
docs/Playstation-2.md
|
Markdown
|
gpl-3.0
| 1,080
|
package org.thoughtcrime.securesms.database.helpers;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteDatabaseHook;
import net.sqlcipher.database.SQLiteOpenHelper;
import org.thoughtcrime.securesms.ApplicationContext;
import org.thoughtcrime.securesms.crypto.DatabaseSecret;
import org.thoughtcrime.securesms.crypto.MasterSecret;
import org.thoughtcrime.securesms.database.AttachmentDatabase;
import org.thoughtcrime.securesms.database.DraftDatabase;
import org.thoughtcrime.securesms.database.GroupDatabase;
import org.thoughtcrime.securesms.database.GroupReceiptDatabase;
import org.thoughtcrime.securesms.database.IdentityDatabase;
import org.thoughtcrime.securesms.database.MmsDatabase;
import org.thoughtcrime.securesms.database.OneTimePreKeyDatabase;
import org.thoughtcrime.securesms.database.PushDatabase;
import org.thoughtcrime.securesms.database.RecipientDatabase;
import org.thoughtcrime.securesms.database.SearchDatabase;
import org.thoughtcrime.securesms.database.SessionDatabase;
import org.thoughtcrime.securesms.database.SignedPreKeyDatabase;
import org.thoughtcrime.securesms.database.SmsDatabase;
import org.thoughtcrime.securesms.database.ThreadDatabase;
import org.thoughtcrime.securesms.jobs.RefreshPreKeysJob;
import org.thoughtcrime.securesms.service.KeyCachingService;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import java.io.File;
public class SQLCipherOpenHelper extends SQLiteOpenHelper {
@SuppressWarnings("unused")
private static final String TAG = SQLCipherOpenHelper.class.getSimpleName();
private static final int RECIPIENT_CALL_RINGTONE_VERSION = 2;
private static final int MIGRATE_PREKEYS_VERSION = 3;
private static final int MIGRATE_SESSIONS_VERSION = 4;
private static final int NO_MORE_IMAGE_THUMBNAILS_VERSION = 5;
private static final int ATTACHMENT_DIMENSIONS = 6;
private static final int QUOTED_REPLIES = 7;
private static final int SHARED_CONTACTS = 8;
private static final int FULL_TEXT_SEARCH = 9;
private static final int BAD_IMPORT_CLEANUP = 10;
private static final int DATABASE_VERSION = 10;
private static final String DATABASE_NAME = "signal.db";
private final Context context;
private final DatabaseSecret databaseSecret;
public SQLCipherOpenHelper(@NonNull Context context, @NonNull DatabaseSecret databaseSecret) {
super(context, DATABASE_NAME, null, DATABASE_VERSION, new SQLiteDatabaseHook() {
@Override
public void preKey(SQLiteDatabase db) {
db.rawExecSQL("PRAGMA cipher_default_kdf_iter = 1;");
db.rawExecSQL("PRAGMA cipher_default_page_size = 4096;");
}
@Override
public void postKey(SQLiteDatabase db) {
db.rawExecSQL("PRAGMA kdf_iter = '1';");
db.rawExecSQL("PRAGMA cipher_page_size = 4096;");
}
});
this.context = context.getApplicationContext();
this.databaseSecret = databaseSecret;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SmsDatabase.CREATE_TABLE);
db.execSQL(MmsDatabase.CREATE_TABLE);
db.execSQL(AttachmentDatabase.CREATE_TABLE);
db.execSQL(ThreadDatabase.CREATE_TABLE);
db.execSQL(IdentityDatabase.CREATE_TABLE);
db.execSQL(DraftDatabase.CREATE_TABLE);
db.execSQL(PushDatabase.CREATE_TABLE);
db.execSQL(GroupDatabase.CREATE_TABLE);
db.execSQL(RecipientDatabase.CREATE_TABLE);
db.execSQL(GroupReceiptDatabase.CREATE_TABLE);
db.execSQL(OneTimePreKeyDatabase.CREATE_TABLE);
db.execSQL(SignedPreKeyDatabase.CREATE_TABLE);
db.execSQL(SessionDatabase.CREATE_TABLE);
for (String sql : SearchDatabase.CREATE_TABLE) {
db.execSQL(sql);
}
executeStatements(db, SmsDatabase.CREATE_INDEXS);
executeStatements(db, MmsDatabase.CREATE_INDEXS);
executeStatements(db, AttachmentDatabase.CREATE_INDEXS);
executeStatements(db, ThreadDatabase.CREATE_INDEXS);
executeStatements(db, DraftDatabase.CREATE_INDEXS);
executeStatements(db, GroupDatabase.CREATE_INDEXS);
executeStatements(db, GroupReceiptDatabase.CREATE_INDEXES);
if (context.getDatabasePath(ClassicOpenHelper.NAME).exists()) {
ClassicOpenHelper legacyHelper = new ClassicOpenHelper(context);
android.database.sqlite.SQLiteDatabase legacyDb = legacyHelper.getWritableDatabase();
SQLCipherMigrationHelper.migratePlaintext(context, legacyDb, db);
MasterSecret masterSecret = KeyCachingService.getMasterSecret(context);
if (masterSecret != null) SQLCipherMigrationHelper.migrateCiphertext(context, masterSecret, legacyDb, db, null);
else TextSecurePreferences.setNeedsSqlCipherMigration(context, true);
if (!PreKeyMigrationHelper.migratePreKeys(context, db)) {
ApplicationContext.getInstance(context).getJobManager().add(new RefreshPreKeysJob(context));
}
SessionStoreMigrationHelper.migrateSessions(context, db);
PreKeyMigrationHelper.cleanUpPreKeys(context);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database: " + oldVersion + ", " + newVersion);
db.beginTransaction();
try {
if (oldVersion < RECIPIENT_CALL_RINGTONE_VERSION) {
db.execSQL("ALTER TABLE recipient_preferences ADD COLUMN call_ringtone TEXT DEFAULT NULL");
db.execSQL("ALTER TABLE recipient_preferences ADD COLUMN call_vibrate INTEGER DEFAULT " + RecipientDatabase.VibrateState.DEFAULT.getId());
}
if (oldVersion < MIGRATE_PREKEYS_VERSION) {
db.execSQL("CREATE TABLE signed_prekeys (_id INTEGER PRIMARY KEY, key_id INTEGER UNIQUE, public_key TEXT NOT NULL, private_key TEXT NOT NULL, signature TEXT NOT NULL, timestamp INTEGER DEFAULT 0)");
db.execSQL("CREATE TABLE one_time_prekeys (_id INTEGER PRIMARY KEY, key_id INTEGER UNIQUE, public_key TEXT NOT NULL, private_key TEXT NOT NULL)");
if (!PreKeyMigrationHelper.migratePreKeys(context, db)) {
ApplicationContext.getInstance(context).getJobManager().add(new RefreshPreKeysJob(context));
}
}
if (oldVersion < MIGRATE_SESSIONS_VERSION) {
db.execSQL("CREATE TABLE sessions (_id INTEGER PRIMARY KEY, address TEXT NOT NULL, device INTEGER NOT NULL, record BLOB NOT NULL, UNIQUE(address, device) ON CONFLICT REPLACE)");
SessionStoreMigrationHelper.migrateSessions(context, db);
}
if (oldVersion < NO_MORE_IMAGE_THUMBNAILS_VERSION) {
ContentValues update = new ContentValues();
update.put("thumbnail", (String)null);
update.put("aspect_ratio", (String)null);
update.put("thumbnail_random", (String)null);
try (Cursor cursor = db.query("part", new String[] {"_id", "ct", "thumbnail"}, "thumbnail IS NOT NULL", null, null, null, null)) {
while (cursor != null && cursor.moveToNext()) {
long id = cursor.getLong(cursor.getColumnIndexOrThrow("_id"));
String contentType = cursor.getString(cursor.getColumnIndexOrThrow("ct"));
if (contentType != null && !contentType.startsWith("video")) {
String thumbnailPath = cursor.getString(cursor.getColumnIndexOrThrow("thumbnail"));
File thumbnailFile = new File(thumbnailPath);
thumbnailFile.delete();
db.update("part", update, "_id = ?", new String[] {String.valueOf(id)});
}
}
}
}
if (oldVersion < ATTACHMENT_DIMENSIONS) {
db.execSQL("ALTER TABLE part ADD COLUMN width INTEGER DEFAULT 0");
db.execSQL("ALTER TABLE part ADD COLUMN height INTEGER DEFAULT 0");
}
if (oldVersion < QUOTED_REPLIES) {
db.execSQL("ALTER TABLE mms ADD COLUMN quote_id INTEGER DEFAULT 0");
db.execSQL("ALTER TABLE mms ADD COLUMN quote_author TEXT");
db.execSQL("ALTER TABLE mms ADD COLUMN quote_body TEXT");
db.execSQL("ALTER TABLE mms ADD COLUMN quote_attachment INTEGER DEFAULT -1");
db.execSQL("ALTER TABLE part ADD COLUMN quote INTEGER DEFAULT 0");
}
if (oldVersion < SHARED_CONTACTS) {
db.execSQL("ALTER TABLE mms ADD COLUMN shared_contacts TEXT");
}
if (oldVersion < FULL_TEXT_SEARCH) {
for (String sql : SearchDatabase.CREATE_TABLE) {
db.execSQL(sql);
}
Log.i(TAG, "Beginning to build search index.");
long start = SystemClock.elapsedRealtime();
db.execSQL("INSERT INTO sms_fts (rowid, body) SELECT _id, body FROM sms");
long smsFinished = SystemClock.elapsedRealtime();
Log.i(TAG, "Indexing SMS completed in " + (smsFinished - start) + " ms");
db.execSQL("INSERT INTO mms_fts (rowid, body) SELECT _id, body FROM mms");
long mmsFinished = SystemClock.elapsedRealtime();
Log.i(TAG, "Indexing MMS completed in " + (mmsFinished - smsFinished) + " ms");
Log.i(TAG, "Indexing finished. Total time: " + (mmsFinished - start) + " ms");
}
if (oldVersion < BAD_IMPORT_CLEANUP) {
String trimmedCondition = " NOT IN (SELECT _id FROM mms)";
db.delete("group_receipts", "mms_id" + trimmedCondition, null);
String[] columns = new String[] { "_id", "unique_id", "_data", "thumbnail"};
try (Cursor cursor = db.query("part", columns, "mid" + trimmedCondition, null, null, null, null)) {
while (cursor != null && cursor.moveToNext()) {
db.delete("part", "_id = ? AND unique_id = ?", new String[] { String.valueOf(cursor.getLong(0)), String.valueOf(cursor.getLong(1)) });
String data = cursor.getString(2);
String thumbnail = cursor.getString(3);
if (!TextUtils.isEmpty(data)) {
new File(data).delete();
}
if (!TextUtils.isEmpty(thumbnail)) {
new File(thumbnail).delete();
}
}
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
if (oldVersion < MIGRATE_PREKEYS_VERSION) {
PreKeyMigrationHelper.cleanUpPreKeys(context);
}
}
public SQLiteDatabase getReadableDatabase() {
return getReadableDatabase(databaseSecret.asString());
}
public SQLiteDatabase getWritableDatabase() {
return getWritableDatabase(databaseSecret.asString());
}
public void markCurrent(SQLiteDatabase db) {
db.setVersion(DATABASE_VERSION);
}
private void executeStatements(SQLiteDatabase db, String[] statements) {
for (String statement : statements)
db.execSQL(statement);
}
}
|
FeuRenard/Signal-Android
|
src/org/thoughtcrime/securesms/database/helpers/SQLCipherOpenHelper.java
|
Java
|
gpl-3.0
| 10,969
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 23 13:52:07 2016
@author: huliqun
"""
import unittest
import json
import binascii
from falcon import testing
import sys
sys.path.append('..')
from workserver.util.AES_PKCS7_extension import Cryptor
from MainServer import app
class TestAuth(testing.TestCase):
def setUp(self):
self.api = app
# def test_regUser(self):
# headers = {'content-type':'application/json'}
# body = '{"username":"wahaha@qq.com","displayname":"wahaha","email":"wahaha@qq.com","password":"123456","mobile":"18698729476"}'
# result =self.simulate_post('/api/users',headers=headers,body=body )
# self.assertEqual(result.status_code, 201)
def test_auth(self):
import hashlib
def md5(s):
m = hashlib.md5()
m.update(s.encode("utf-8"))
return m.hexdigest()
# print("pwd : %s" % md5('123456'))
iv, encrypted = Cryptor.encrypt('aaa', md5('12345678'))
print(md5('12345678'))
# print("iv : %s" % iv.decode())
# print("encrypted : %s" % binascii.b2a_base64(encrypted).rstrip())
print(Cryptor.decrypt(encrypted,md5('12345678'), iv))
# headers = {'content-type':'application/json'}
# body = {
# 'oid': 2,
# 'username':'admin',
# 'identifyCode':encrypted,
# 'magicNo':iv.decode()
# }
# result =self.simulate_post('/api/auth',headers=headers,body=json.dumps(body) )
# self.assertEqual(result.status_code, 200)
# print(result.text)
# should raise an exception for an immutable sequence
# self.assertRaises(TypeError, random.shuffle, (1,2,3))
if __name__ == '__main__':
unittest.main()
|
LiqunHu/MVPN
|
testing/testAuth.py
|
Python
|
gpl-3.0
| 1,873
|
#region PRODUCTION READY® ELEFLEX® Software License. Copyright © 2015 Production Ready, LLC. All Rights Reserved.
//Copyright © 2015 Production Ready, LLC. All Rights Reserved.
//For more information, visit http://www.ProductionReady.com
//This file is part of PRODUCTION READY® ELEFLEX®.
//
//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
//You should have received a copy of the GNU Affero General Public License
//along with this program. If not, see <http://www.gnu.org/licenses/>.
#endregion
using System;
using Eleflex.Security.Message;
using Eleflex.Services;
namespace Eleflex.Security.Message.RoleCommand
{
/// <summary>
/// Delete response.
/// </summary>
public class RoleDeleteResponse : ServiceCommandResponse
{
}
}
|
ProductionReady/Eleflex
|
V2.1/src/Security Module/Eleflex.Security.Message/RoleCommand/RoleDeleteResponse.cs
|
C#
|
gpl-3.0
| 1,226
|
//
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: /Users/tball/tmp/j2objc/guava/sources/com/google/common/base/Platform.java
//
// Created by tball on 11/23/13.
//
#import "JreEmulation.h"
#if !ComGoogleCommonBasePlatform_RESTRICT
#define ComGoogleCommonBasePlatform_INCLUDE_ALL 1
#endif
#undef ComGoogleCommonBasePlatform_RESTRICT
#if !defined (_ComGoogleCommonBasePlatform_) && (ComGoogleCommonBasePlatform_INCLUDE_ALL || ComGoogleCommonBasePlatform_INCLUDE)
#define _ComGoogleCommonBasePlatform_
@class ComGoogleCommonBaseCharMatcher;
@class IOSCharArray;
@class JavaLangThreadLocal;
@interface ComGoogleCommonBasePlatform : NSObject {
}
+ (JavaLangThreadLocal *)DEST_TL;
- (id)init;
+ (IOSCharArray *)charBufferFromThreadLocal;
+ (long long int)systemNanoTime;
+ (ComGoogleCommonBaseCharMatcher *)precomputeCharMatcherWithComGoogleCommonBaseCharMatcher:(ComGoogleCommonBaseCharMatcher *)matcher;
@end
#endif
#if !defined (_ComGoogleCommonBasePlatform_$1_) && (ComGoogleCommonBasePlatform_INCLUDE_ALL || ComGoogleCommonBasePlatform_$1_INCLUDE)
#define _ComGoogleCommonBasePlatform_$1_
@class IOSCharArray;
#define JavaLangThreadLocal_RESTRICT 1
#define JavaLangThreadLocal_INCLUDE 1
#include "java/lang/ThreadLocal.h"
@interface ComGoogleCommonBasePlatform_$1 : JavaLangThreadLocal {
}
- (IOSCharArray *)initialValue OBJC_METHOD_FAMILY_NONE;
- (id)init;
@end
#endif
|
appnativa/rare
|
sdk/j2objc/include/com/google/common/base/Platform.h
|
C
|
gpl-3.0
| 1,400
|
package sprax.aligns;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeMap;
import sprax.files.FileUtil;
import sprax.files.TextFileReader;
import sprax.sprout.Sx;
/**
* TODO: Separate classes for dictionary parsing and storage?
* TODO: abstract and wrap the gets and puts, and guard against
* multiple entries for same key. Merge the value sets. Add
* Spanish word list to check for loan words triggering the
* "no Spanish definition" check.
*
* @author sprax
*/
public abstract class Lexicon
{
String mTitle;
final String mSrcLanguageCode;
final String mDstLanguageCode;
final String mSourceLanguage;
final String mTargetLanguage;
TreeMap<String, Set<String>> mDict_1_1;
TreeMap<String, Set<String>> mDict_2_1;
TreeMap<String, Set<String>> mDict_3_1;
// HashMap<String, ArrayList<String>> mDict_1_2;
// HashMap<String, ArrayList<String>> mDict_1_3;
// HashMap<String, ArrayList<String>> mDict_2_2;
// HashMap<String, ArrayList<String>> mDict_3_3;
// HashMap<String, ArrayList<String>> mDict_N_N;
TreeMap<String, String> mPastTenseToRoot;
String getSrcCode() { return mSrcLanguageCode; }
String getDstCode() { return mDstLanguageCode; }
String getTitle() { return mTitle; }
static int sDbg = 2;
static char sSepTermsDefns = ':';
static char sSepDefinitions = ';';
final String mFsSourceWordList;
final String mFsTargetWordList;
static WordSet sSourceWordSet;
static WordSet sTargetWordSet;
/**
* Is first char of string upper case?
* No error checking.
*/
static boolean isCapitalized(String str) {
return Character.isUpperCase(str.charAt(0));
}
/**
* If the supplied word is a capitalized form of a word
* whose lower-case form is in the (source/target lexicon,
* return the lower-case form; otherwise, return null.
*/
String sourceUnCapitalized(String wordA)
{
if (isCapitalized(wordA)) {
String uncappedA = wordA.toLowerCase();
if (isSourceWord(uncappedA))
return uncappedA;
}
return null;
}
String targetUnCapitalized(String wordB)
{
if (isCapitalized(wordB)) {
String uncappedB = wordB.toLowerCase();
if (isTargetWord(uncappedB))
return uncappedB;
String lowSingB = targetSingular(uncappedB);
if (lowSingB != null && isTargetWord(lowSingB))
return uncappedB;
String lowPresB = targetPresent(uncappedB);
if (lowPresB != null && isTargetWord(lowPresB))
return uncappedB;
}
return null;
}
/**
* If the argument is a known plural word, return the singular form;
* otherwise, return null.
* TODO: Use look-up table, either loaded or memoized on the fly.
* @param possibly plural form of a word in the source language
* @return singular form of the same word, if known
*/
String defaultSingular(String word)
{
int lastIdx = word.length() - 1;
char lastChar = word.charAt(lastIdx);
if (lastChar == 's')
return word.substring(0, lastIdx);
return null;
}
String sourceSingular(String word) { return defaultSingular(word); }
String targetSingular(String word) { return defaultSingular(word); }
/**
* If the argument is a known past tense word,
* return the present tense form;
* otherwise, return null.
*/
String defaultUnPast(String word)
{
int lastIdx = word.length() - 1;
if (lastIdx < 3)
return null;
char lastChar = word.charAt(lastIdx);
if (lastChar == 'd') {
int punultIdx = lastIdx - 1;
char penultChar = word.charAt(punultIdx);
if (penultChar == 'e') {
String sansD = word.substring(0, lastIdx);
if (isSourceWord(sansD))
return sansD;
String sansED = word.substring(0, punultIdx);
if (isSourceWord(sansED))
return sansED;
}
}
return null;
}
String sourceUnPast(String word) { return defaultUnPast(word); }
String targetUnPast(String word) { return defaultUnPast(word); }
/**
* If the argument is a known present participle,
* return the present tense form;
* otherwise, return null.
*/
String defaultUnPresentParticiple(String word)
{
int lastIdx = word.length() - 1;
if (lastIdx < 5)
return null;
char lastChar = word.charAt(lastIdx);
if (lastChar == 'g' && word.endsWith("ing")) {
String sansING = word.substring(0, lastIdx-2);
if (isSourceWord(sansING))
return sansING;
String plusE = sansING.concat("e");
if (isSourceWord(plusE))
return plusE;
}
return null;
}
String sourceUnPresentParticiple(String word) { return defaultUnPresentParticiple(word); }
String targetUnPresentParticiple(String word) { return defaultUnPresentParticiple(word); }
/**
* If the argument is a known past or future tense word,
* return the present tense form;
* otherwise, return null.
*/
String sourcePresent(String word)
{
String present;
if (null != (present = sourceUnPast(word)))
return present;
if (null != (present = sourceUnPresentParticiple(word)))
return present;
return null;
}
String targetPresent(String word)
{
String present;
if (null != (present = targetUnPast(word)))
return present;
if (null != (present = targetUnPresentParticiple(word)))
return present;
return null;
}
Lexicon(final String srcLangCode, final String dstLangCode)
{
mSrcLanguageCode = srcLangCode;
mDstLanguageCode = dstLangCode;
mSourceLanguage = languageNameFromCode(srcLangCode);
mTargetLanguage = languageNameFromCode(dstLangCode);
mFsSourceWordList = FileUtil.getTextFilePath(mSrcLanguageCode + "/" + mSrcLanguageCode + "NamesWords.txt");
mFsTargetWordList = FileUtil.getTextFilePath(mDstLanguageCode + "/" + mDstLanguageCode + "NamesWords.txt");
mPastTenseToRoot = new TreeMap<String, String>();
}
/**
* Get language name from 2-letter code
* TODO: Use enum const strings
*/
static String languageNameFromCode(final String code)
{
if (code.equals("En"))
return "English";
if (code.equals("Es"))
return "Spanish";
return "unsupported language";
}
boolean isSourceWord(String word) { return getSourceWordSet().contains(word); }
boolean isTargetWord(String word) { return getTargetWordSet().contains(word); }
WordSet getSourceWordSet()
{
if (sSourceWordSet == null)
sSourceWordSet = readWordList(mFsSourceWordList, mSourceLanguage);
return sSourceWordSet;
}
WordSet getTargetWordSet()
{
if (sTargetWordSet == null)
sTargetWordSet = readWordList(mFsTargetWordList, mTargetLanguage);
return sTargetWordSet;
}
static WordSet readWordList(String textFileSpec, String languageName)
{
WordSet wordSet = new WordSet();
TextFileReader tfr = new TextFileReader(textFileSpec);
Sx.debug(2, "Reading %s words from file: %s, ", languageName, textFileSpec);
int numWords = tfr.readIntoStringCollector(wordSet);
if (numWords == 0) {
throw new IllegalStateException("Invalid "+languageName+" word list file: "+textFileSpec);
} else {
Sx.debug(2, "found %6d entries.\n", numWords);
if (sDbg > 8) {
for (String word : wordSet.getCollector() )
Sx.puts(word);
}
}
return wordSet;
}
static void compareWordListFiles(String wordListFileA, String wordListFileB)
{
HashSet<String> wordsA = TextFileReader.readFileIntoHashSet(wordListFileA);
HashSet<String> wordsB = TextFileReader.readFileIntoHashSet(wordListFileB);
compareWordLists(wordsA, wordsB);
}
// TODO: make symmetric
static void compareWordLists(Collection<String> wordsA, Collection<String> wordsB)
{
for (String wordB : wordsB) {
if ( ! wordsA.contains(wordB))
Sx.puts(wordB);
}
}
void compareWordListFilesWithSource(String wordListFileA, String wordListFileB)
{
HashSet<String> wordsA = TextFileReader.readFileIntoHashSet(wordListFileA);
HashSet<String> wordsB = TextFileReader.readFileIntoHashSet(wordListFileB);
compareWordLists(wordsA, wordsB, getSourceWordSet().getCollector());
}
// TODO: make symmetric
static void compareWordLists(Collection<String> wordsA, Collection<String> wordsB, Collection<String> wordsC)
{
for (String wordB : wordsB) {
if ( ! wordsA.contains(wordB) && ! wordsC.contains(wordB))
Sx.puts(wordB);
}
}
public static void main(String[] args) { DictionaryRawFileParserEnEs.unit_test(2); }
}
|
sprax/java
|
aligns/Lexicon.java
|
Java
|
gpl-3.0
| 9,573
|
/*
canvas.lineWidth=int;
canvas.rect()
canvas.fillRect()
window.onorientationchange
*/
var position=[0,0,0,0];//---位置信息
//-------------------------------------------功能绑定区
canvas_View.addEventListener('touchstart',function(){//---把开始触摸点定为起点
if(config.type=='pen'){
drawTable.getStarPosition(2);
}
else if(config.type=='rect_new'||config.type=='coordinate'){
drawTable.getStarPosition(0);
rect_box.style.display='block';
rect_box.style.border=canvas.lineWidth+'px '+drawTable.colorOpacity(config.color,config.opacity)+' solid';
}
});
canvas_View.addEventListener('click',function(){//---画点
if(config.type!='pen')return;
var x=event.pageX;//--click主要是不与划线时的位置混淆
var y=event.pageY;
if(config.dot[2]==0){//--没有记录时添加一个记录
config.dot[0]=x;
config.dot[1]=y;
}
config.dot[2]+=1;
drawTable.dot(x,y);//--其实是画圆
if(config.dot[2]==2){
config.dot[2]=0;//--重置
drawTable.matchDot(x,y);//--连线开始
}
});
canvas_View.addEventListener('touchmove',function(){//---更新位置信息
if(config.type=='pen'){
position[0]=position[2];
position[1]=position[3];
drawTable.getPosition();
drawTable.pen();
}
else if(config.type=='rect_new'||config.type=='coordinate'){
drawTable.getPosition();
drawTable.rect_new();
if(config.type=='coordinate'){
rect_box.style.borderTop='none';
rect_box.style.borderRight='none';
}
}
event.preventDefault();//---阻止默认事件
});
canvas_View.addEventListener('touchend',function(){//----写入结束,保存入栈
if(config.type=='rect_new'||config.type=='coordinate'){
drawTable.getPosition();
drawTable.rect_new();
if(config.type=='coordinate'){
drawTable.coordinate();
}
else
drawTable.rect();
rect_box.style.cssText='display:none;left:0;top:0;width0;height:0;';
}
drawTable.createImg();
});
color_View.addEventListener('touchstart',function(){//----指定坐标,获取颜色
position[2]=event.touches[0].pageX;
position[3]=event.touches[0].pageY;
drawTable.getColor();
});
color_View.addEventListener('touchmove',function(){//---获取移动坐标,获取颜色
drawTable.getPosition();
drawTable.getColor();
event.preventDefault();
});
lineW.addEventListener('click',function(){//---划线粗细显示选项
span_layout();
range.value=range.nextElementSibling.innerText=canvas.lineWidth;
range.max=config.lineWidth[1];//--设置最大值
config.rangeType='lineWidth';
});
line.addEventListener('click',function(){//---默认模式
config.type='pen';
});
rect.addEventListener('click',function(){//---矩形模式
config.type='rect_new';
});
clear.addEventListener('click',function(){//---清空
drawTable.clear();
});
cure.addEventListener('click',function(){//----回复
drawTable.cure();
});
download.addEventListener('click',function(){//----下载【pc】
drawTable.download();
});
opacity.addEventListener('click',function(){
span_layout();
range.max=100;//--设置最大值
range.value=(range.nextElementSibling.innerText=config.opacity)*100;//init
config.rangeType='opacity';
});
coordinate.addEventListener('click',function(){
ul_coordinate.style.display=ul_coordinate.style.display!='block'?'block':'none';
});
ul_coordinate.getElementsByTagName('li')[0].addEventListener('click',function(){
mathFunction.style.display='block';
});
calculate.addEventListener('click',function(){//--进行计算
drawTable.coordinate();
drawTable.mathFunction(equation.value);
drawTable.createImg();//--可恢复
});
close_equation.addEventListener('click',function(){//--关闭窗口
mathFunction.style.display='none';
});
ul_coordinate.getElementsByTagName('li')[1].addEventListener('click',function(){
config.type='coordinate';
});
character.addEventListener('click',function(){//--弹出字体写入框
if(rect_box.style.display!='block'){//--显示
rect_box.innerHTML="<div id='sureButton'></div><input placeholder='text' type='text' style='width:100px'>";
rect_box.style.cssText='width:120px;display:block;background:rgba(240,240,240,0.7);padding:30px;left:100px;top:100px;';
}
else{//--关闭并还原rect_box
rect_box.innerHTML='';
rect_box.style.cssText='display:none;left:0;top:0;width:0;height:0;';
rangeBox.style.display='none';
return;
}
var inputText=rect_box.getElementsByTagName('input')[0];
var sureButton=document.getElementById('sureButton');
inputText.style.cssText="font-size:"+config.fontSize+"px;width:120px;background:rgba(255,255,255,.3);border:none;";
inputText.focus();
inputText.addEventListener('click',function(){
event.cancelBubble=true;
})
//--rect_box里面再加入一层元素
sureButton.addEventListener('click',function(){//--确定
event.cancelBubble=true;
var x=rect_box.offsetLeft+30;
var y=rect_box.offsetTop+sureButton.clientHeight+30+inputText.clientHeight;
drawTable.fillText(inputText.value,x,y);
});
rect_box.addEventListener('click',function(){//--弹出字体大小选择框
span_layout();
range.nextElementSibling.innerText=(range.value=config.fontSize)+'px';
range.max=config.maxFontSize//--设置最大值
config.rangeType='font';
});
rect_box.addEventListener('touchstart',function(){
drawTable.getStarPosition(2);
});
rect_box.addEventListener('touchmove',function(){event.preventDefault();
position[0]=position[2];
position[1]=position[3];
drawTable.getPosition();
drawTable.move(rect_box);
});
rect_box.addEventListener('touchend',function(){
drawTable.getStarPosition[2];
});
});
rangeBox_drag.addEventListener('click',function(){
rangeBox.style.display='none';
});
rangeBox_drag.addEventListener('touchstart',function(){
drawTable.getStarPosition(2);
});
rangeBox_drag.addEventListener('touchmove',function(){event.preventDefault();
position[0]=position[2];
position[1]=position[3];
drawTable.getPosition();
drawTable.move(rangeBox);
});
range.addEventListener('touchmove',function(){
if(config.rangeType=='opacity'){
range.nextElementSibling.innerText=range.value/100;
}else if(config.rangeType=='font'){
range.nextElementSibling.innerText=rect_box.getElementsByTagName('input')[0].style.fontSize=range.value+'px';
}
else{
range.nextElementSibling.innerText=range.value;
}
});
range.addEventListener('touchend',function(){
switch(config.rangeType){
case 'lineWidth':canvas.lineWidth=range.value;;break;
case 'opacity':config.opacity=range.value/100;break;
case 'font':config.fontSize=range.value;break;
}
});
//-----------------------------------------------------------------
var operate = function(){//----操作函数集合
canvas = canvas_View.getContext('2d');//---init
canvas_tmp = canvas_tmp_View.getContext('2d');//---init
var color_c = color_View.getContext('2d');
var linear = color_c.createLinearGradient(0,0,config.size[0],0);
linear.addColorStop(0, 'rgb(255,0,0)'); //红
linear.addColorStop(0.5, 'rgb(0,255,0)');//绿
linear.addColorStop(1, 'rgb(0,0,255)'); //蓝
color_c.fillStyle=linear;
color_c.fillRect(0,0,config.size[0],40);
this.colorOpacity=function(color,opacity){
var start=color.lastIndexOf(',');
var end=color.lastIndexOf(')');
var res=color.substr(0,start+1)+opacity+color.substr(end);
return res;
}
this.pen=function(x1,y1,x2,y2){//----划线
var X1=x1||position[0],Y1=y1||position[1],X2=x2||position[2],Y2=y2||position[3];
canvas.beginPath();//--上行为缺省值
canvas.moveTo(X1,Y1);
canvas.lineTo(X2,Y2);
canvas.strokeStyle=drawTable.colorOpacity(config.color,config.opacity);
canvas.closePath();
canvas.stroke();
}
this.rect_new=function(){//--矩形div模拟
rect_box.style.left=position[0]+'px';
rect_box.style.top=position[1]+'px';
rect_box.style.width=position[2]-position[0]-1+'px';
rect_box.style.height=position[3]-position[1]-1+'px';
}
this.rect=function(){//----写入矩形
if(position[0]==position[2])return;
canvas.beginPath();
canvas.strokeStyle=drawTable.colorOpacity(config.color,config.opacity);
canvas.rect(position[0]+canvas.lineWidth/2,position[1]+canvas.lineWidth/2,position[2]-position[0]+canvas.lineWidth,position[3]-position[1]+canvas.lineWidth);
//---div元素的border和画矩形的边框不是同一个机制
canvas.closePath();
canvas.stroke();
}
this.dot=function(x,y,type){//--点的生成 用于连线
canvas.beginPath();
var type=type||'stroke';
if(type=='fill'){
canvas.fillStyle=drawTable.colorOpacity(config.color,config.opacity);
canvas.arc(x,y,config.radius,0,Math.PI*2,false);
}
if(type=='stroke'){
canvas.strokeStyle=config.color;
canvas.arc(x,y,config.radius,0,Math.PI*2,false);
canvas.stroke();
}
canvas.closePath();
}
this.matchDot=function(x,y){//--连接两个点
canvas.beginPath();
canvas.strokeStyle=drawTable.colorOpacity(config.color,config.opacity);
canvas.moveTo(config.dot[0],config.dot[1]);
canvas.lineTo(x,y);
canvas.closePath();
canvas.stroke();
}
this.coordinate=function(){//--建立坐标
//---在进行画矩形时,只保留邻边就可以自定义建立起简易坐标
drawTable.pen(position[0],position[3],position[0],position[1]);
drawTable.pen(position[0],position[3],position[2],position[3]);
config.basePoint[0]=position[0];//--保存坐标轴基本点
config.basePoint[1]=position[3];
config.basePoint[2]=position[0];
config.basePoint[3]=position[1];
config.basePoint[4]=position[2];
config.basePoint[5]=position[3];
}
this.mathFunction=function(equation){//---数学函数y=2*x
var equation=equation||"0.5*x";var y;
//--标准转换式 y=k*x --> y=-k*(x-config.basePoint[0])+config.basePoint[1] //--将坐标轴的方向进行转换
//--存在转换缺陷,x*x时图形完全不形象,需要缩短x,y轴
equation=equation.replace('x','(x-'+config.basePoint[0]+')');//--x值进行替换
equation='-1*('+equation+')+'+config.basePoint[1];
for(var x=config.basePoint[0];x<config.basePoint[4];x+=0.01){//--0.01为精度
eval('y='+equation);//---y=k*x
drawTable.pen(x,y,++x,eval('y='+equation));//--传入两个坐标
}
}
this.move=function(obj){
var obj_left=rPx(getComputedStyle(obj)['left'],'left');
var obj_top=rPx(getComputedStyle(obj)['top'],'top');
obj.style.left=obj_left+position[2]-position[0]+'px';
obj.style.top=obj_top+position[3]-position[1]+'px';
}
this.fillText=function(text,x,y,type){//---生成文字
var x=x||10,y=y||10,type=type||'fill';
canvas.font='normal '+config.fontSize+'px 微软雅黑';
if(config.fontSize<16){
var compatibility=0;
}else{
var compatibility=config.fontSize/3;
}
if(type='fill'){
canvas.fillStyle=drawTable.colorOpacity(config.color,config.opacity);
canvas.fillText(text,x,y-compatibility);
}else{
canvas.strokeText(text,x,y);
}
drawTable.createImg();
}
this.getColor=function(){//---获取点击处的颜色[rgba模式,a/255为可用a]
var offsetT=color_View.offsetTop;
var color=color_c.getImageData(position[2],position[3]-config.size[1]-3,1,1).data;
cure.style.background="rgba("+color[0]+','+color[1]+','+color[2]+','+color[3]/255+")";
config.color="rgba("+color[0]+','+color[1]+','+color[2]+','+color[3]/255+")";
}
this.getStarPosition=function(offset){
position[offset]=event.touches[0].pageX;
position[offset+1]=event.touches[0].pageY;
}
this.getPosition=function(){
position[2]=event.changedTouches[0].pageX;
position[3]=event.changedTouches[0].pageY;
}
this.clear=function(val){//---清除最后操作
if(val==0){
canvas.clearRect(0,0,config.size[0],config.size[1]);
}
else if(true){//----清除所有操作和记录
config.stage='null';
config.stage=[];
canvas.clearRect(0,0,config.size[0],config.size[1]);
config.pointer=-1;
drawTable.createImg();
}
}
this.cure=function(){//---回复上一步
if(config.pointer>=1){
config.dot[2]=0;
config.img_tmp = new Image();
config.img_tmp.src=config.stage[config.pointer-1];
config.img_tmp.onload=function(){//---加载完成再清除不会出现闪烁
drawTable.clear(0);//---清空,不改变记录
canvas.drawImage(config.img_tmp,0,0);//---加载上一步
}
config.pointer--;//--指针减一
}
}
this.createImg=function(){//---canvas生成base64码
//---64码保存在数组中,指针指向当前画面
if(config.pointer>=config.cure_len-1){//---超出长度就清除最前面的操作,再最后追加最新操作
for(var i=0;i<config.cure_len-1;i++){
config.stage[i]=config.stage[i+1];
}
}
if(config.pointer<config.cure_len-1){//--指针后移
config.pointer++;
}
config.stage[config.pointer]=canvas_View.toDataURL();
}
this.download=function(){//-----下载图片
var a=document.createElement('a');
a.href=config.stage[config.pointer].replace('png','octet-stream');
a.download="save.png";
a.click();
}
}
{//---所有初始化操作
drawTable = new operate();//---初始化功能函数
drawTable.createImg();//---第一个图片保存
canvas.lineWidth=3;
canvas.font='normal '+config.fontSize+'px 微软雅黑';
}
|
DFFXT/DFFXT.github.io
|
canvas/css_js/main.js
|
JavaScript
|
gpl-3.0
| 13,453
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_20) on Sat Jul 30 23:35:11 CEST 2011 -->
<TITLE>
API Help
</TITLE>
<META NAME="date" CONTENT="2011-07-30">
<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="API Help";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Help</B></FONT> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index.html?help-doc.html" target="_top"><B>FRAMES</B></A>
<A HREF="help-doc.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H1>
How This API Document Is Organized</H1>
</CENTER>
This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.<H3>
Overview</H3>
<BLOCKQUOTE>
<P>
The <A HREF="overview-summary.html">Overview</A> page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.</BLOCKQUOTE>
<H3>
Package</H3>
<BLOCKQUOTE>
<P>
Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain four categories:<UL>
<LI>Interfaces (italic)<LI>Classes<LI>Enums<LI>Exceptions<LI>Errors<LI>Annotation Types</UL>
</BLOCKQUOTE>
<H3>
Class/Interface</H3>
<BLOCKQUOTE>
<P>
Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:<UL>
<LI>Class inheritance diagram<LI>Direct Subclasses<LI>All Known Subinterfaces<LI>All Known Implementing Classes<LI>Class/interface declaration<LI>Class/interface description
<P>
<LI>Nested Class Summary<LI>Field Summary<LI>Constructor Summary<LI>Method Summary
<P>
<LI>Field Detail<LI>Constructor Detail<LI>Method Detail</UL>
Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.</BLOCKQUOTE>
</BLOCKQUOTE>
<H3>
Annotation Type</H3>
<BLOCKQUOTE>
<P>
Each annotation type has its own separate page with the following sections:<UL>
<LI>Annotation Type declaration<LI>Annotation Type description<LI>Required Element Summary<LI>Optional Element Summary<LI>Element Detail</UL>
</BLOCKQUOTE>
</BLOCKQUOTE>
<H3>
Enum</H3>
<BLOCKQUOTE>
<P>
Each enum has its own separate page with the following sections:<UL>
<LI>Enum declaration<LI>Enum description<LI>Enum Constant Summary<LI>Enum Constant Detail</UL>
</BLOCKQUOTE>
<H3>
Tree (Class Hierarchy)</H3>
<BLOCKQUOTE>
There is a <A HREF="overview-tree.html">Class Hierarchy</A> page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with <code>java.lang.Object</code>. The interfaces do not inherit from <code>java.lang.Object</code>.<UL>
<LI>When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.<LI>When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.</UL>
</BLOCKQUOTE>
<H3>
Deprecated API</H3>
<BLOCKQUOTE>
The <A HREF="deprecated-list.html">Deprecated API</A> page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.</BLOCKQUOTE>
<H3>
Index</H3>
<BLOCKQUOTE>
The <A HREF="index-all.html">Index</A> contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.</BLOCKQUOTE>
<H3>
Prev/Next</H3>
These links take you to the next or previous class, interface, package, or related page.<H3>
Frames/No Frames</H3>
These links show and hide the HTML frames. All pages are available with or without frames.
<P>
<H3>
Serialized Form</H3>
Each serializable or externalizable class has a description of its serialization fields and methods. This information is of interest to re-implementors, not to developers using the API. While there is no link in the navigation bar, you can get to this information by going to any serialized class and clicking "Serialized Form" in the "See also" section of the class description.
<P>
<H3>
Constant Field Values</H3>
The <a href="constant-values.html">Constant Field Values</a> page lists the static final fields and their values.
<P>
<FONT SIZE="-1">
<EM>
This help file applies to API documentation generated using the standard doclet.</EM>
</FONT>
<BR>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Package</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Help</B></FONT> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index.html?help-doc.html" target="_top"><B>FRAMES</B></A>
<A HREF="help-doc.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
|
rtts/connect-forever
|
app/docs/help-doc.html
|
HTML
|
gpl-3.0
| 8,982
|
from nltk.chat.util import Chat, reflections
pairs = [
[
r"My name is (.*)",
['hello %1', '%1 mabuhay ka'],
],
[
r'hi',
['hello', 'kamusta', 'mabuhay',],
],
[
r'(.*) (hungry|sleepy|groot)',
[
"%1 %2"
]
],
[
r'(.*)(mahal|love)(.*)',
[
"https://goo.gl/ndTZVq",
"I always thought Love was a static class until you made an instance of it.",
"I love user interfaces it's because that's where U and I are always together.",
],
],
[
r'(.*)(relationship)(.*)',
[
"Mabuti pa sa database may relationship. Eh tayo, wala.",
],
],
[
r'(meron|mayron|ano|does|is there|what) (.*) (forever)(.*)',
[
"Loading...",
"None",
"while True: pass",
],
],
[
r'(.*)', # default response if no patterns from above is found
[
"http://lmgtfy.com/?q=%1",
"Sorry I don't know what `%1` is?",
],
],
]
def hugot_bot():
print("Hi what's your name?")
chat = Chat(pairs, reflections)
chat.converse()
if __name__ == "__main__":
hugot_bot()
|
davidam/python-examples
|
nlp/nltk/hugotbot.py
|
Python
|
gpl-3.0
| 1,251
|
package it.unisannio.catman.screens.inbox.client;
import java.util.List;
import it.unisannio.catman.common.client.AbstractQuery;
import it.unisannio.catman.common.client.App;
import it.unisannio.catman.common.client.DataStore;
import it.unisannio.catman.common.client.Query;
import it.unisannio.catman.common.client.QueryDataProvider;
import it.unisannio.catman.common.client.cell.InteractiveCellAdapter;
import it.unisannio.catman.common.client.ui.DataList;
import it.unisannio.catman.domain.workflow.client.CustomerProxy;
import com.github.gwtbootstrap.client.ui.Button;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.requestfactory.shared.Request;
public class MasterView extends Composite {
private static MasterViewUiBinder uiBinder = GWT.create(MasterViewUiBinder.class);
interface MasterViewUiBinder extends UiBinder<Widget, MasterView> {
}
@UiField Button makeNew;
@UiField DataList<CustomerProxy> dataList;
private Inbox.Master activity;
public MasterView(Inbox.Master activity) {
initWidget(uiBinder.createAndBindUi(this));
this.activity = activity;
dataList.setPageSize(20);
dataList.setCellAdapter(new InteractiveCellAdapter<CustomerProxy>() {
@Override
public SafeHtml getNorth(CustomerProxy object) {
return new SafeHtmlBuilder().appendEscaped(object.getName()).toSafeHtml();
}
});
final DataStore store = App.getInstance().getDataStore();
Query<CustomerProxy> query = new AbstractQuery<CustomerProxy>() {
@Override
public Request<List<CustomerProxy>> list(int start, int length) {
return store.customers().listAll(start, length);
}
@Override
public Request<Integer> count() {
return store.customers().count();
}
};
dataList.setDataProvider(new QueryDataProvider<CustomerProxy>(query));
}
@UiHandler("makeNew")
void handleNew(ClickEvent e) {
activity.openNewDialog();
}
@UiHandler("dataList")
void handleCellClick(ClickEvent e) {
Window.alert("Hello "+ ((CustomerProxy) e.getSource()).getName());
}
}
|
danilox6/catman
|
src/it/unisannio/catman/screens/inbox/client/MasterView.java
|
Java
|
gpl-3.0
| 2,489
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <string>
namespace facebook {
namespace flipper {
void log(const std::string& message);
} // namespace flipper
} // namespace facebook
|
rneiss/PocketTorah
|
ios/Pods/Flipper/xplat/Flipper/Log.h
|
C
|
gpl-3.0
| 350
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_27) on Sat Oct 06 02:59:28 EDT 2012 -->
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>
Uses of Class org.apache.lucene.codecs.simpletext.SimpleTextNormsFormat (Lucene 4.0.0 API)
</TITLE>
<META NAME="date" CONTENT="2012-10-06">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.lucene.codecs.simpletext.SimpleTextNormsFormat (Lucene 4.0.0 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/lucene/codecs/simpletext/SimpleTextNormsFormat.html" title="class in org.apache.lucene.codecs.simpletext"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/lucene/codecs/simpletext//class-useSimpleTextNormsFormat.html" target="_top"><B>FRAMES</B></A>
<A HREF="SimpleTextNormsFormat.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.lucene.codecs.simpletext.SimpleTextNormsFormat</B></H2>
</CENTER>
No usage of org.apache.lucene.codecs.simpletext.SimpleTextNormsFormat
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/lucene/codecs/simpletext/SimpleTextNormsFormat.html" title="class in org.apache.lucene.codecs.simpletext"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/lucene/codecs/simpletext//class-useSimpleTextNormsFormat.html" target="_top"><B>FRAMES</B></A>
<A HREF="SimpleTextNormsFormat.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<address>Copyright © 2000-2012 Apache Software Foundation. All Rights Reserved.</address>
<script src='../../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</BODY>
</HTML>
|
dburgmann/fbRecommender
|
lib/lucene-4.0.0/docs/codecs/org/apache/lucene/codecs/simpletext/class-use/SimpleTextNormsFormat.html
|
HTML
|
gpl-3.0
| 6,562
|
/**
* include/sys/stat.h
*
* (C) Copyright 2013 Michael Sippel
*
* 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/>.
*/
#ifndef _STAT_H
#define _STAT_H
#include <sys/types.h>
#include <stdint.h>
#include <stddef.h>
#include <time.h>
#define S_MODE_DIR 0x1
#define S_MODE_CHR 0x2
#define S_MODE_LNK 0x4
#define S_MAO 0x4 // mode: access offset
#define S_IRUSR (0x001 << S_MAO) //user-read
#define S_IWUSR (0x002 << S_MAO) // -write
#define S_IXUSR (0x004 << S_MAO) // -execute
#define S_IRGRP (0x008 << S_MAO) //group-read
#define S_IWGRP (0x010 << S_MAO) // -write
#define S_IXGRP (0x020 << S_MAO) // -execute
#define S_IROTH (0x040 << S_MAO) //other-read
#define S_IWOTH (0x080 << S_MAO) // -write
#define S_IXOTH (0x100 << S_MAO) // -execute
#define S_ISREG(x) ((x.mode & S_MODE_DIR) ? 0 : 1)
#define S_ISDIR(x) ((x.mode & S_MODE_DIR) ? 1 : 0)
#define S_ISCHR(x) ((x.mode & S_MODE_CHR) ? 1 : 0)
#define S_ISBLK(x) ((x.mode & S_MODE_CHR) ? 0 : 1)
#define S_ISLNK(x) ((x.mode & S_MODE_LNK) ? 1 : 0)
typedef struct stat {
mode_t mode;
size_t size;
id_t id;
uid_t uid;
gid_t gid;
time_t atime;
time_t mtime;
time_t ctime;
} stat_t;
#endif
|
michamimosa/FruityOrange
|
include/sys/stat.h
|
C
|
gpl-3.0
| 1,778
|
/*
* Copyright (C) 2010 The Sipdroid Open Source Project
*
* This file is part of Sipdroid (http://www.sipdroid.org)
*
* Sipdroid 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 source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this source code; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.sipdroid.codecs;
import java.util.HashMap;
import java.util.Vector;
import com.sipgate.R;
import com.sipgate.sipua.ui.Receiver;
import com.sipgate.sipua.ui.Settings;
import org.zoolu.sdp.MediaField;
import org.zoolu.sdp.SessionDescriptor;
import org.zoolu.sdp.AttributeField;
import android.content.Context;
import android.content.res.Resources;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.ListPreference;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
public class Codecs {
private static final Vector<Codec> codecs = new Vector<Codec>() {/**
*
*/
private static final long serialVersionUID = 5423816327968842601L;
{
add(new G722());
add(new SILK24());
add(new SILK16());
add(new SILK8());
add(new alaw());
add(new ulaw());
add(new Speex());
add(new GSM());
add(new BV16());
}};
private static final HashMap<Integer, Codec> codecsNumbers;
private static final HashMap<String, Codec> codecsNames;
static {
final int size = codecs.size();
codecsNumbers = new HashMap<Integer, Codec>(size);
codecsNames = new HashMap<String, Codec>(size);
for (Codec c : codecs) {
codecsNames.put(c.name(), c);
codecsNumbers.put(c.number(), c);
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext);
String prefs = sp.getString(Settings.PREF_CODECS, Settings.DEFAULT_CODECS);
if (prefs == null) {
String v = "";
SharedPreferences.Editor e = sp.edit();
for (Codec c : codecs)
v = v + c.number() + " ";
e.putString(Settings.PREF_CODECS, v);
e.commit();
} else {
String[] vals = prefs.split(" ");
for (String v: vals) {
try {
int i = Integer.parseInt(v);
Codec c = codecsNumbers.get(i);
/* moves the codec to the end
* of the list so we end up
* with the new codecs (if
* any) at the top and the
* remaining ones ordered
* according to the user */
codecs.remove(c);
codecs.add(c);
} catch (Exception e) {
// do nothing (expecting
// NumberFormatException and
// indexnot found
}
}
}
}
public static Codec get(int key) {
return codecsNumbers.get(key);
}
public static Codec getName(String name) {
return codecsNames.get(name);
}
public static void check() {
HashMap<String, String> old = new HashMap<String, String>(codecs.size());
for(Codec c : codecs) {
old.put(c.name(), c.getValue());
if (!c.isLoaded()) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext);
SharedPreferences.Editor e = sp.edit();
e.putString(c.key(), "never");
e.commit();
}
}
for(Codec c : codecs)
if (!old.get(c.name()).equals("never")) {
c.init();
if (c.isLoaded()) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext);
SharedPreferences.Editor e = sp.edit();
e.putString(c.key(), old.get(c.name()));
e.commit();
c.init();
} else
c.fail();
}
}
private static void addPreferences(PreferenceScreen ps) {
Context cx = ps.getContext();
Resources r = cx.getResources();
ps.setOrderingAsAdded(true);
for(Codec c : codecs) {
ListPreference l = new ListPreference(cx);
l.setEntries(r.getStringArray(R.array.compression_display_values));
l.setEntryValues(r.getStringArray(R.array.compression_values));
l.setKey(c.key());
l.setPersistent(true);
l.setEnabled(!c.isFailed());
c.setListPreference(l);
if (c.number() == 9)
if (ps.getSharedPreferences().getString(Settings.PREF_SERVER, Settings.DEFAULT_SERVER).equals(Settings.DEFAULT_SERVER))
l.setSummary(l.getEntry()+" ("+r.getString(R.string.settings_improve2)+")");
else
l.setSummary(l.getEntry()+" ("+r.getString(R.string.settings_hdvoice)+")");
else
l.setSummary(l.getEntry());
l.setTitle(c.getTitle());
ps.addPreference(l);
}
}
public static int[] getCodecs() {
Vector<Integer> v = new Vector<Integer>(codecs.size());
for (Codec c : codecs) {
if (!c.isValid())
continue;
v.add(c.number());
}
int i[] = new int[v.size()];
for (int j = 0; j < i.length; j++)
i[j] = v.elementAt(j);
return i;
}
public static class Map {
public int number;
public Codec codec;
Vector<Integer> numbers;
Vector<Codec> codecs;
Map(int n, Codec c, Vector<Integer> ns, Vector<Codec> cs) {
number = n;
codec = c;
numbers = ns;
codecs = cs;
}
public boolean change(int n) {
int i = numbers.indexOf(n);
if (i >= 0 && codecs.elementAt(i) != null) {
codec.close();
number = n;
codec = codecs.elementAt(i);
return true;
}
return false;
}
public String toString() {
return "Codecs.Map { " + number + ": " + codec + "}";
}
};
public static Map getCodec(SessionDescriptor offers) {
MediaField m = offers.getMediaDescriptor("audio").getMedia();
if (m==null)
return null;
String proto = m.getTransport();
//see http://tools.ietf.org/html/rfc4566#page-22, paragraph 5.14, <fmt> description
if ( proto.equals("RTP/AVP") || proto.equals("RTP/SAVP") ) {
Vector<String> formats = m.getFormatList();
Vector<String> names = new Vector<String>(formats.size());
Vector<Integer> numbers = new Vector<Integer>(formats.size());
Vector<Codec> codecmap = new Vector<Codec>(formats.size());
//add all avail formats with empty names
for (String fmt : formats) {
try {
int number = Integer.parseInt(fmt);
numbers.add(number);
names.add("");
codecmap.add(null);
} catch (NumberFormatException e) {
// continue ... remote sent bogus rtp setting
}
};
//if we have attrs for format -> set name
Vector<AttributeField> attrs = offers.getMediaDescriptor("audio").getAttributes("rtpmap");
for (AttributeField a : attrs) {
String s = a.getValue();
// skip over "rtpmap:"
s = s.substring(7, s.indexOf("/"));
int i = s.indexOf(" ");
try {
String name = s.substring(i + 1);
int number = Integer.parseInt(s.substring(0, i));
int index = numbers.indexOf(number);
if (index >=0)
names.set(index, name.toLowerCase());
} catch (NumberFormatException e) {
// continue ... remote sent bogus rtp setting
}
}
Codec codec = null;
int index = formats.size() + 1;
for (Codec c : codecs) {
if (!c.isValid())
continue;
//search current codec in offers by name
int i = names.indexOf(c.userName().toLowerCase());
if (i >= 0) {
codecmap.set(i, c);
if ( (codec==null) || (i < index) ) {
codec = c;
index = i;
continue;
}
}
//search current codec in offers by number
i = numbers.indexOf(c.number());
if (i >= 0) {
if ( names.elementAt(i).equals("")) {
codecmap.set(i, c);
if ( (codec==null) || (i < index) ) {
//fmt number has no attr with name
codec = c;
index = i;
continue;
}
}
}
}
if (codec!=null)
return new Map(numbers.elementAt(index), codec, numbers, codecmap);
else
// no codec found ... we can't talk
return null;
} else
/*formats of other protocols not supported yet*/
return null;
}
public static class CodecSettings extends PreferenceActivity {
private static final int MENU_UP = 0;
private static final int MENU_DOWN = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.codec_settings);
// for long-press gesture on a profile preference
registerForContextMenu(getListView());
addPreferences(getPreferenceScreen());
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle(R.string.codecs_move);
menu.add(Menu.NONE, MENU_UP, 0,
R.string.codecs_move_up);
menu.add(Menu.NONE, MENU_DOWN, 0,
R.string.codecs_move_down);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
int posn = (int)((AdapterContextMenuInfo)item.getMenuInfo()).position;
Codec c = codecs.elementAt(posn);
if (item.getItemId() == MENU_UP) {
if (posn == 0)
return super.onContextItemSelected(item);
Codec tmp = codecs.elementAt(posn - 1);
codecs.set(posn - 1, c);
codecs.set(posn, tmp);
} else if (item.getItemId() == MENU_DOWN) {
if (posn == codecs.size() - 1)
return super.onContextItemSelected(item);
Codec tmp = codecs.elementAt(posn + 1);
codecs.set(posn + 1, c);
codecs.set(posn, tmp);
}
PreferenceScreen ps = getPreferenceScreen();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext);
String v = "";
SharedPreferences.Editor e = sp.edit();
for (Codec d : codecs)
v = v + d.number() + " ";
e.putString(Settings.PREF_CODECS, v);
e.commit();
ps.removeAll();
addPreferences(ps);
return super.onContextItemSelected(item);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen ps, Preference p) {
ListPreference l = (ListPreference) p;
for (Codec c : codecs)
if (c.key().equals(l.getKey())) {
c.init();
if (!c.isLoaded()) {
l.setValue("never");
c.fail();
l.setEnabled(false);
l.setSummary(l.getEntry());
if (l.getDialog() != null)
l.getDialog().dismiss();
}
}
return super.onPreferenceTreeClick(ps,p);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterForContextMenu(getListView());
}
}
}
|
sipgate/sipgate-for-android
|
src/org/sipdroid/codecs/Codecs.java
|
Java
|
gpl-3.0
| 10,906
|
from urlparse import urlparse
import sys
import socket
import os
import re
class HttpClient(object):
def __init__(self,proxy=None,logfile='headers.log'):
self.proxy = proxy
self.LOGFILE = logfile
self.parsed_url = None # Instance of class urlparse
self.http_version = "HTTP/1.1"
self.buffer = 4096
self.separador = '\r\n\r\n' # Separador de header y content de la respuesta HTTP
self.download_file = 'download.part'
self._header_detected = False
self._url = None
try:
# Si quedo una descarga trunca, la limpiamos
with open(self.download_file):
os.remove(self.download_file)
except IOError:
pass
def _get_host(self,use_proxy=False):
"""Devuelve el hostname de la url de forma inteligente(?)"""
if use_proxy:
return urlparse(self.proxy).hostname
else:
if self.parsed_url is None:
return 'localhost'
else:
if self.parsed_url.hostname in (None,''):
return 'localhost'
else:
return self.parsed_url.hostname
def _get_port(self,use_proxy=False):
"""Devuelve el puerto de la url de forma inteligente(?)"""
if use_proxy:
return urlparse(self.proxy).port
else:
if self.parsed_url is None:
return 80
else:
if self.parsed_url.port in (None,''):
return 80
else:
return self.parsed_url.port
def _get_path(self):
"""Devuelve el path de la url de forma inteligente(?)"""
if self.proxy is not None:
return self.parsed_url.scheme + '://' + self.parsed_url.netloc + self.parsed_url.path
else:
if self.parsed_url is None:
return '/'
else:
if self.parsed_url.path in (None,''):
return '/'
else:
return self.parsed_url.path
def retrieve(self,url=None,method="GET"):
"""Punto de acceso del cliente, crea la peticion, la envia al servidor, y guarda la respuesta.
Maneja redireccion 301 (movido permanente)."""
if url:
self._retrieve(url=url,method=method)
#~ Soporta redireccion infinita, lo cual es un problema. Deberia tener un contador. Maximo?
while self.headers["status"] == "301":
self._retrieve(url=self.headers["Location"],method=method)
else:
raise Exception("Expect parameter url")
def _retrieve(self,url=None,method="GET"):
"""Metodo de alto nivel que recupera la url solicitada"""
if url:
self._url = url
self.parsed_url = urlparse(url)
if self.parsed_url.scheme is '':
raise Exception("Formato de url incorrecto. Formato esperado: (http|ftp|https)://url[:port][/path_to_resource]")
self.method = method # GET o HEAD
self._conect() # self.s socket created
self._build_request() # self.request string created
self._send_request() # Realiza la peticion y gestiona la descarga del recurso
else:
raise Exception("Expect parameter url")
def _conect(self):
"""Crea el socket con el servidor"""
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
if self.proxy:
self.s.connect((self._get_host(use_proxy=True) , self._get_port(use_proxy=True)))
else:
self.s.connect((self._get_host() , self._get_port()))
except socket.error, msg:
sys.stderr.write("[ERROR] %s\n" % msg[1])
sys.exit(2)
def _build_request(self):
"""Construye el str de request para el servidor"""
self.request = "%(method)s %(path)s %(http_version)s\r\n"
self.request += "Host: %(host)s\r\n"
self.request += "User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0) Gecko/20100101 Firefox/23.0\r\n"
self.request += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
self.request += "Accept-Language: es-ar,es;q=0.8,en-us;q=0.5,en;q=0.3\r\n"
#~ self.request += "Accept-Encoding: gzip, deflate\r\n" # No soporta encoding en esta version
self.request += "Connection: keep-alive\r\n\r\n"
self.request = self.request % { 'method':self.method, \
'path':self._get_path(), \
'http_version':self.http_version, \
'host':self._get_host()}
def _send_request(self):
"""Envia el request y recibe la respuesta"""
self.s.sendall(self.request)
response = self.s.recv(self.buffer)
self.data = ""
self._header_detected = False
while len(response):
self.data += response
# Se controla que detecte solo la primera vez las cabeceras
if not self._header_detected:
self._header_detect()
if not self.method == "HEAD":
self._sync_data()
if self.headers.has_key("status"):
if self.headers["status"] == "301":
break
response = self.s.recv(self.buffer)
if not self.method == "HEAD" and not self.headers["status"] == "301":
self._sync_data()
self._save_file() # Guardar el archivo
self._log_headers() # Logs a un header
def _sync_data(self):
""" Este metodo se encarga de descargar la memoria si el archivo
que se descarga es demasiado grande"""
if len(self.data) > 100000:
f = open(self.download_file,'a')
f.write(self.data)
self.data = ""
f.close()
def _header_detect(self):
"""Metodo que detecta si en la descarga se encuentra el header.
En caso afirmativo, lo carga en la instancia y lo elimina del
stream de descarga."""
headers = self.data.split(self.separador)
# Si len es mayor a 1, el header ya esta completo
if len(headers) > 1:
self.data = self.separador.join(headers[1:]) # Arma la informacion de descarga sin el header
self.str_headers = headers[0]
self.headers = dict(re.findall(r"(?P<name>.*?): (?P<value>.*?)\r\n", self.str_headers)) # Arma un dic con los headers
# Primer linea del header HTTP/1.1
self.headers["http"] = headers[0].split('\r\n')[0]
self.headers["http_version"] = self.headers["http"].split(' ')[0]
self.headers["status"] = self.headers["http"].split(' ')[1]
self.headers["status_message"] = ' '.join(self.headers["http"].split(' ')[2:])
self._header_detected = True
def _log_headers(self):
"""Descarga las cabeceras de response a un archivo de log"""
if self.LOGFILE is not None:
f = open(self.LOGFILE,'a')
f.write("== HEADER: Response from %s\n" % self._url)
f.write("== Method: %s\n" % self.method)
f.write("%s\n" % self.str_headers)
f.close()
def _save_file(self):
"""Guarda el archivo a disco, teniendo en cuenta si la descarga ya lo hizo o no"""
file_in_disk = self._saved_file()
filename = self._filename()
if file_in_disk:
os.rename(self.download_file, filename)
else:
f = open(filename,'w')
f.write(self.data)
f.close()
def _content_encoding(self):
"""Soporte para encoding de contenido con gzip. No soportado"""
if self.headers.has_key('Content-Encoding'):
return self.headers['Content-Encoding']
else:
return None
def _file_type(self):
"""Retorna la extension segun el tipo de archivo"""
if self.headers.has_key('Content-Type'):
return '.' + self.headers['Content-Type'].split('; ')[0].split('/')[1]
else:
return '.html' # Que habria que devolver por default? vacio?
def _filename(self):
"""Retorna el mejor nombre de archivo en funcion de la informacion disponible"""
if self.headers["status"] == "404":
return "error_page_404.html"
else:
extension = self._file_type()
if self.proxy is not None:
resource_name = self._get_path().split('/')
if resource_name[-1] is not '':
return resource_name[-1] + extension
else:
return resource_name[-2] + extension
else:
if self._get_path() in ('/', ''):
return self._get_host() + extension
else:
return self._get_path().split('/')[-1]
def _saved_file(self):
"""Controla si durante la descarga el archivo fue bajado temporalmente a disco"""
try:
open(self.download_file)
except:
return False
return True
|
tomasdelvechio/py-net-dev
|
Protocolos/3 - http client/http_client_object.py
|
Python
|
gpl-3.0
| 9,464
|
/**
* 支持ArcGIS Online地图
*/
max.Layer.AGSTileLayer = function (serviceUrl) {
this.serviceUrl = serviceUrl;
this._imageList = [];
this.cors=false;
this.fullExtent = new max.Extent({
xmin:-20037508.3427892,
ymin:-20037508.3427892,
xmax:20037508.3427892,
ymax:20037508.3427892
});
this.originPoint = {
x:-20037508.3427892,
y:20037508.3427892
}
this.picWidth = 256;
this.picHeight = 256;
this.wkid = 102100;
this.resolutions = [1591657527.591555,78271.51696402031, 39135.75848201016, 19567.87924100508, 9783.939620502539, 4891.96981025127, 2445.984905125635, 1222.992452562817, 611.4962262814087, 305.7481131407043, 152.8740565703522, 76.43702828517608, 38.21851414258804, 19.10925707129402, 9.554628535647009];
this.init();
}
max.Layer.AGSTileLayer.prototype = new max.Layer.TileLayer();
max.Layer.AGSTileLayer.prototype._updateImageList = function (rule) {
this._imageList = [];
for (var i = rule.lmin; i <= rule.lmax; ++i) {
for (var j = rule.dmin; j <= rule.dmax; ++j) {
if(this.serviceUrl[this.serviceUrl.length-1]!=="/"){
this.serviceUrl+="/";
}
var url = this.serviceUrl+"tile/"+(rule.z-1)+"/"+j+"/"+i;
var xmin = i * this.picWidth * rule.resolution + this.originPoint.x;
var ymax = this.originPoint.y-j * this.picHeight * rule.resolution;
for (var k in this._imageList) {
var _image = this._imageList[k];
if (_image.url === url) {
break;
}
}
var image = new max.Layer._TitleImage(url, this, i, j, rule.z, xmin, ymax);
this._imageList.push(image);
}
}
return this._imageList;
}
|
Maxgis/maxCanvasMap
|
src/Layer/AGSTileLayer.js
|
JavaScript
|
gpl-3.0
| 1,811
|
/*
* Copyright 2010-16 Fraunhofer ISE
*
* This file is part of jMBus.
* For more information visit http://www.openmuc.org
*
* jMBus 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.
*
* jMBus 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 jMBus. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openmuc.jmbus;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.HashMap;
abstract class AbstractWMBusSap implements WMBusSap {
final static int BUFFER_LENGTH = 1000;
final byte[] outputBuffer = new byte[BUFFER_LENGTH];
final byte[] inputBuffer = new byte[BUFFER_LENGTH];
final WMBusListener listener;
final WMBusMode mode;
SerialTransceiver serialTransceiver;
final HashMap<String, byte[]> keyMap = new HashMap<String, byte[]>();
volatile boolean closed = true;
DataOutputStream os;
DataInputStream is;
AbstractWMBusSap(WMBusMode mode, WMBusListener listener) {
this.listener = listener;
this.mode = mode;
}
@Override
public void close() {
if (closed) {
return;
}
closed = true;
serialTransceiver.close();
}
@Override
public void setKey(SecondaryAddress address, byte[] key) {
keyMap.put(HexConverter.toShortHexString(address.asByteArray()), key);
}
@Override
public void removeKey(SecondaryAddress address) {
keyMap.remove(HexConverter.toShortHexString(address.asByteArray()));
}
}
|
pokerazor/jmbus
|
src/main/java/org/openmuc/jmbus/AbstractWMBusSap.java
|
Java
|
gpl-3.0
| 1,961
|
/* keybox-dump.c - Debug helpers
* Copyright (C) 2001, 2003 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG 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.
*
* GnuPG 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 <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "keybox-defs.h"
#include <gcrypt.h>
#include "host2net.h"
/* Argg, we can't include ../common/util.h */
char *bin2hexcolon (const void *buffer, size_t length, char *stringbuf);
#define get32(a) buf32_to_ulong ((a))
#define get16(a) buf16_to_ulong ((a))
void
print_string (FILE *fp, const byte *p, size_t n, int delim)
{
for ( ; n; n--, p++ )
{
if (*p < 0x20 || (*p >= 0x7f && *p < 0xa0) || *p == delim)
{
putc('\\', fp);
if( *p == '\n' )
putc('n', fp);
else if( *p == '\r' )
putc('r', fp);
else if( *p == '\f' )
putc('f', fp);
else if( *p == '\v' )
putc('v', fp);
else if( *p == '\b' )
putc('b', fp);
else if( !*p )
putc('0', fp);
else
fprintf(fp, "x%02x", *p );
}
else
putc(*p, fp);
}
}
static int
print_checksum (const byte *buffer, size_t length, size_t unhashed, FILE *fp)
{
const byte *p;
int i;
int hashlen;
unsigned char digest[20];
fprintf (fp, "Checksum: ");
if (unhashed && unhashed < 20)
{
fputs ("[specified unhashed sized too short]\n", fp);
return 0;
}
if (!unhashed)
{
unhashed = 16;
hashlen = 16;
}
else
hashlen = 20;
if (length < 5+unhashed)
{
fputs ("[blob too short for a checksum]\n", fp);
return 0;
}
p = buffer + length - hashlen;
for (i=0; i < hashlen; p++, i++)
fprintf (fp, "%02x", *p);
if (hashlen == 16) /* Compatibility method. */
{
gcry_md_hash_buffer (GCRY_MD_MD5, digest, buffer, length - 16);
if (!memcmp (buffer + length - 16, digest, 16))
fputs (" [valid]\n", fp);
else
fputs (" [bad]\n", fp);
}
else
{
gcry_md_hash_buffer (GCRY_MD_SHA1, digest, buffer, length - unhashed);
if (!memcmp (buffer + length - hashlen, digest, hashlen))
fputs (" [valid]\n", fp);
else
fputs (" [bad]\n", fp);
}
return 0;
}
static int
dump_header_blob (const byte *buffer, size_t length, FILE *fp)
{
unsigned long n;
if (length < 32)
{
fprintf (fp, "[blob too short]\n");
return -1;
}
fprintf (fp, "Version: %d\n", buffer[5]);
n = get16 (buffer + 6);
fprintf( fp, "Flags: %04lX", n);
if (n)
{
int any = 0;
fputs (" (", fp);
if ((n & 2))
{
if (any)
putc (',', fp);
fputs ("openpgp", fp);
any++;
}
putc (')', fp);
}
putc ('\n', fp);
if ( memcmp (buffer+8, "KBXf", 4))
fprintf (fp, "[Error: invalid magic number]\n");
n = get32 (buffer+16);
fprintf( fp, "created-at: %lu\n", n );
n = get32 (buffer+20);
fprintf( fp, "last-maint: %lu\n", n );
return 0;
}
/* Dump one block to FP */
int
_keybox_dump_blob (KEYBOXBLOB blob, FILE *fp)
{
const byte *buffer;
size_t length;
int type, i;
ulong n, nkeys, keyinfolen;
ulong nuids, uidinfolen;
ulong nsigs, siginfolen;
ulong rawdata_off, rawdata_len;
ulong nserial;
ulong unhashed;
const byte *p;
buffer = _keybox_get_blob_image (blob, &length);
if (length < 32)
{
fprintf (fp, "[blob too short]\n");
return -1;
}
n = get32( buffer );
if (n > length)
fprintf (fp, "[blob larger than length - output truncated]\n");
else
length = n; /* ignore the rest */
fprintf (fp, "Length: %lu\n", n );
type = buffer[4];
switch (type)
{
case KEYBOX_BLOBTYPE_EMPTY:
fprintf (fp, "Type: Empty\n");
return 0;
case KEYBOX_BLOBTYPE_HEADER:
fprintf (fp, "Type: Header\n");
return dump_header_blob (buffer, length, fp);
case KEYBOX_BLOBTYPE_PGP:
fprintf (fp, "Type: OpenPGP\n");
break;
case KEYBOX_BLOBTYPE_X509:
fprintf (fp, "Type: X.509\n");
break;
default:
fprintf (fp, "Type: %d\n", type);
fprintf (fp, "[can't dump this blob type]\n");
return 0;
}
fprintf (fp, "Version: %d\n", buffer[5]);
if (length < 40)
{
fprintf (fp, "[blob too short]\n");
return -1;
}
n = get16 (buffer + 6);
fprintf( fp, "Blob-Flags: %04lX", n);
if (n)
{
int any = 0;
fputs (" (", fp);
if ((n & 1))
{
fputs ("secret", fp);
any++;
}
if ((n & 2))
{
if (any)
putc (',', fp);
fputs ("ephemeral", fp);
any++;
}
putc (')', fp);
}
putc ('\n', fp);
rawdata_off = get32 (buffer + 8);
rawdata_len = get32 (buffer + 12);
fprintf( fp, "Data-Offset: %lu\n", rawdata_off );
fprintf( fp, "Data-Length: %lu\n", rawdata_len );
if (rawdata_off > length || rawdata_len > length
|| rawdata_off+rawdata_len > length
|| rawdata_len + 4 > length
|| rawdata_off+rawdata_len + 4 > length)
fprintf (fp, "[Error: raw data larger than blob]\n");
unhashed = length - rawdata_off - rawdata_len;
fprintf (fp, "Unhashed: %lu\n", unhashed);
nkeys = get16 (buffer + 16);
fprintf (fp, "Key-Count: %lu\n", nkeys );
if (!nkeys)
fprintf (fp, "[Error: no keys]\n");
if (nkeys > 1 && type == KEYBOX_BLOBTYPE_X509)
fprintf (fp, "[Error: only one key allowed for X509]\n");
keyinfolen = get16 (buffer + 18 );
fprintf (fp, "Key-Info-Length: %lu\n", keyinfolen);
/* fixme: check bounds */
p = buffer + 20;
for (n=0; n < nkeys; n++, p += keyinfolen)
{
ulong kidoff, kflags;
fprintf (fp, "Key-Fpr[%lu]: ", n );
for (i=0; i < 20; i++ )
fprintf (fp, "%02X", p[i]);
kidoff = get32 (p + 20);
fprintf (fp, "\nKey-Kid-Off[%lu]: %lu\n", n, kidoff );
fprintf (fp, "Key-Kid[%lu]: ", n );
/* fixme: check bounds */
for (i=0; i < 8; i++ )
fprintf (fp, "%02X", buffer[kidoff+i] );
kflags = get16 (p + 24 );
fprintf( fp, "\nKey-Flags[%lu]: %04lX\n", n, kflags);
}
/* serial number */
fputs ("Serial-No: ", fp);
nserial = get16 (p);
p += 2;
if (!nserial)
fputs ("none", fp);
else
{
for (; nserial; nserial--, p++)
fprintf (fp, "%02X", *p);
}
putc ('\n', fp);
/* user IDs */
nuids = get16 (p);
fprintf (fp, "Uid-Count: %lu\n", nuids );
uidinfolen = get16 (p + 2);
fprintf (fp, "Uid-Info-Length: %lu\n", uidinfolen);
/* fixme: check bounds */
p += 4;
for (n=0; n < nuids; n++, p += uidinfolen)
{
ulong uidoff, uidlen, uflags;
uidoff = get32( p );
uidlen = get32( p+4 );
if (type == KEYBOX_BLOBTYPE_X509 && !n)
{
fprintf (fp, "Issuer-Off: %lu\n", uidoff );
fprintf (fp, "Issuer-Len: %lu\n", uidlen );
fprintf (fp, "Issuer: \"");
}
else if (type == KEYBOX_BLOBTYPE_X509 && n == 1)
{
fprintf (fp, "Subject-Off: %lu\n", uidoff );
fprintf (fp, "Subject-Len: %lu\n", uidlen );
fprintf (fp, "Subject: \"");
}
else
{
fprintf (fp, "Uid-Off[%lu]: %lu\n", n, uidoff );
fprintf (fp, "Uid-Len[%lu]: %lu\n", n, uidlen );
fprintf (fp, "Uid[%lu]: \"", n );
}
print_string (fp, buffer+uidoff, uidlen, '\"');
fputs ("\"\n", fp);
uflags = get16 (p + 8);
if (type == KEYBOX_BLOBTYPE_X509 && !n)
{
fprintf (fp, "Issuer-Flags: %04lX\n", uflags );
fprintf (fp, "Issuer-Validity: %d\n", p[10] );
}
else if (type == KEYBOX_BLOBTYPE_X509 && n == 1)
{
fprintf (fp, "Subject-Flags: %04lX\n", uflags );
fprintf (fp, "Subject-Validity: %d\n", p[10] );
}
else
{
fprintf (fp, "Uid-Flags[%lu]: %04lX\n", n, uflags );
fprintf (fp, "Uid-Validity[%lu]: %d\n", n, p[10] );
}
}
nsigs = get16 (p);
fprintf (fp, "Sig-Count: %lu\n", nsigs );
siginfolen = get16 (p + 2);
fprintf (fp, "Sig-Info-Length: %lu\n", siginfolen );
/* fixme: check bounds */
p += 4;
{
int in_range = 0;
ulong first = 0;
for (n=0; n < nsigs; n++, p += siginfolen)
{
ulong sflags;
sflags = get32 (p);
if (!in_range && !sflags)
{
in_range = 1;
first = n;
continue;
}
if (in_range && !sflags)
continue;
if (in_range)
{
fprintf (fp, "Sig-Expire[%lu-%lu]: [not checked]\n", first, n-1);
in_range = 0;
}
fprintf (fp, "Sig-Expire[%lu]: ", n );
if (!sflags)
fputs ("[not checked]", fp);
else if (sflags == 1 )
fputs ("[missing key]", fp);
else if (sflags == 2 )
fputs ("[bad signature]", fp);
else if (sflags < 0x10000000)
fprintf (fp, "[bad flag %0lx]", sflags);
else if (sflags == (ulong)(-1))
fputs ("[good - does not expire]", fp );
else
fprintf (fp, "[good - expires at %lu]", sflags);
putc ('\n', fp );
}
if (in_range)
fprintf (fp, "Sig-Expire[%lu-%lu]: [not checked]\n", first, n-1);
}
fprintf (fp, "Ownertrust: %d\n", p[0] );
fprintf (fp, "All-Validity: %d\n", p[1] );
p += 4;
n = get32 (p);
p += 4;
fprintf (fp, "Recheck-After: %lu\n", n );
n = get32 (p );
p += 4;
fprintf( fp, "Latest-Timestamp: %lu\n", n );
n = get32 (p );
p += 4;
fprintf (fp, "Created-At: %lu\n", n );
n = get32 (p );
fprintf (fp, "Reserved-Space: %lu\n", n );
if (n >= 4 && unhashed >= 24)
{
n = get32 ( buffer + length - unhashed);
fprintf (fp, "Storage-Flags: %08lx\n", n );
}
print_checksum (buffer, length, unhashed, fp);
return 0;
}
/* Compute the SHA-1 checksum of the rawdata in BLOB and put it into
DIGEST. */
static int
hash_blob_rawdata (KEYBOXBLOB blob, unsigned char *digest)
{
const unsigned char *buffer;
size_t n, length;
int type;
ulong rawdata_off, rawdata_len;
buffer = _keybox_get_blob_image (blob, &length);
if (length < 32)
return -1;
n = get32 (buffer);
if (n < length)
length = n; /* Blob larger than length in header - ignore the rest. */
type = buffer[4];
switch (type)
{
case KEYBOX_BLOBTYPE_PGP:
case KEYBOX_BLOBTYPE_X509:
break;
case KEYBOX_BLOBTYPE_EMPTY:
case KEYBOX_BLOBTYPE_HEADER:
default:
memset (digest, 0, 20);
return 0;
}
if (length < 40)
return -1;
rawdata_off = get32 (buffer + 8);
rawdata_len = get32 (buffer + 12);
if (rawdata_off > length || rawdata_len > length
|| rawdata_off+rawdata_off > length)
return -1; /* Out of bounds. */
gcry_md_hash_buffer (GCRY_MD_SHA1, digest, buffer+rawdata_off, rawdata_len);
return 0;
}
struct file_stats_s
{
unsigned long too_short_blobs;
unsigned long too_large_blobs;
unsigned long total_blob_count;
unsigned long empty_blob_count;
unsigned long header_blob_count;
unsigned long pgp_blob_count;
unsigned long x509_blob_count;
unsigned long unknown_blob_count;
unsigned long non_flagged;
unsigned long secret_flagged;
unsigned long ephemeral_flagged;
unsigned long skipped_long_blobs;
};
static int
update_stats (KEYBOXBLOB blob, struct file_stats_s *s)
{
const unsigned char *buffer;
size_t length;
int type;
unsigned long n;
buffer = _keybox_get_blob_image (blob, &length);
if (length < 32)
{
s->too_short_blobs++;
return -1;
}
n = get32( buffer );
if (n > length)
s->too_large_blobs++;
else
length = n; /* ignore the rest */
s->total_blob_count++;
type = buffer[4];
switch (type)
{
case KEYBOX_BLOBTYPE_EMPTY:
s->empty_blob_count++;
return 0;
case KEYBOX_BLOBTYPE_HEADER:
s->header_blob_count++;
return 0;
case KEYBOX_BLOBTYPE_PGP:
s->pgp_blob_count++;
break;
case KEYBOX_BLOBTYPE_X509:
s->x509_blob_count++;
break;
default:
s->unknown_blob_count++;
return 0;
}
if (length < 40)
{
s->too_short_blobs++;
return -1;
}
n = get16 (buffer + 6);
if (n)
{
if ((n & 1))
s->secret_flagged++;
if ((n & 2))
s->ephemeral_flagged++;
}
else
s->non_flagged++;
return 0;
}
static FILE *
open_file (const char **filename, FILE *outfp)
{
FILE *fp;
if (!*filename)
{
*filename = "-";
fp = stdin;
}
else
fp = fopen (*filename, "rb");
if (!fp)
{
int save_errno = errno;
fprintf (outfp, "can't open '%s': %s\n", *filename, strerror(errno));
gpg_err_set_errno (save_errno);
}
return fp;
}
int
_keybox_dump_file (const char *filename, int stats_only, FILE *outfp)
{
FILE *fp;
KEYBOXBLOB blob;
int rc;
unsigned long count = 0;
struct file_stats_s stats;
memset (&stats, 0, sizeof stats);
if (!(fp = open_file (&filename, outfp)))
return gpg_error_from_syserror ();
for (;;)
{
rc = _keybox_read_blob (&blob, fp);
if (gpg_err_code (rc) == GPG_ERR_TOO_LARGE
&& gpg_err_source (rc) == GPG_ERR_SOURCE_KEYBOX)
{
if (stats_only)
stats.skipped_long_blobs++;
else
{
fprintf (outfp, "BEGIN-RECORD: %lu\n", count );
fprintf (outfp, "# Record too large\nEND-RECORD\n");
}
count++;
continue;
}
if (rc)
break;
if (stats_only)
{
update_stats (blob, &stats);
}
else
{
fprintf (outfp, "BEGIN-RECORD: %lu\n", count );
_keybox_dump_blob (blob, outfp);
fprintf (outfp, "END-RECORD\n");
}
_keybox_release_blob (blob);
count++;
}
if (rc == -1)
rc = 0;
if (rc)
fprintf (outfp, "# error reading '%s': %s\n", filename, gpg_strerror (rc));
if (fp != stdin)
fclose (fp);
if (stats_only)
{
fprintf (outfp,
"Total number of blobs: %8lu\n"
" header: %8lu\n"
" empty: %8lu\n"
" openpgp: %8lu\n"
" x509: %8lu\n"
" non flagged: %8lu\n"
" secret flagged: %8lu\n"
" ephemeral flagged: %8lu\n",
stats.total_blob_count,
stats.header_blob_count,
stats.empty_blob_count,
stats.pgp_blob_count,
stats.x509_blob_count,
stats.non_flagged,
stats.secret_flagged,
stats.ephemeral_flagged);
if (stats.skipped_long_blobs)
fprintf (outfp, " skipped long blobs: %8lu\n",
stats.skipped_long_blobs);
if (stats.unknown_blob_count)
fprintf (outfp, " unknown blob types: %8lu\n",
stats.unknown_blob_count);
if (stats.too_short_blobs)
fprintf (outfp, " too short blobs: %8lu (error)\n",
stats.too_short_blobs);
if (stats.too_large_blobs)
fprintf (outfp, " too large blobs: %8lu (error)\n",
stats.too_large_blobs);
}
return rc;
}
struct dupitem_s
{
unsigned long recno;
unsigned char digest[20];
};
static int
cmp_dupitems (const void *arg_a, const void *arg_b)
{
struct dupitem_s *a = (struct dupitem_s *)arg_a;
struct dupitem_s *b = (struct dupitem_s *)arg_b;
return memcmp (a->digest, b->digest, 20);
}
int
_keybox_dump_find_dups (const char *filename, int print_them, FILE *outfp)
{
FILE *fp;
KEYBOXBLOB blob;
int rc;
unsigned long recno = 0;
unsigned char zerodigest[20];
struct dupitem_s *dupitems;
size_t dupitems_size, dupitems_count, lastn, n;
char fprbuf[3*20+1];
(void)print_them;
memset (zerodigest, 0, sizeof zerodigest);
if (!(fp = open_file (&filename, outfp)))
return gpg_error_from_syserror ();
dupitems_size = 1000;
dupitems = malloc (dupitems_size * sizeof *dupitems);
if (!dupitems)
{
gpg_error_t tmperr = gpg_error_from_syserror ();
fprintf (outfp, "error allocating array for '%s': %s\n",
filename, strerror(errno));
return tmperr;
}
dupitems_count = 0;
while ( !(rc = _keybox_read_blob (&blob, fp)) )
{
unsigned char digest[20];
if (hash_blob_rawdata (blob, digest))
fprintf (outfp, "error in blob %ld of '%s'\n", recno, filename);
else if (memcmp (digest, zerodigest, 20))
{
if (dupitems_count >= dupitems_size)
{
struct dupitem_s *tmp;
dupitems_size += 1000;
tmp = realloc (dupitems, dupitems_size * sizeof *dupitems);
if (!tmp)
{
gpg_error_t tmperr = gpg_error_from_syserror ();
fprintf (outfp, "error reallocating array for '%s': %s\n",
filename, strerror(errno));
free (dupitems);
return tmperr;
}
dupitems = tmp;
}
dupitems[dupitems_count].recno = recno;
memcpy (dupitems[dupitems_count].digest, digest, 20);
dupitems_count++;
}
_keybox_release_blob (blob);
recno++;
}
if (rc == -1)
rc = 0;
if (rc)
fprintf (outfp, "error reading '%s': %s\n", filename, gpg_strerror (rc));
if (fp != stdin)
fclose (fp);
qsort (dupitems, dupitems_count, sizeof *dupitems, cmp_dupitems);
for (lastn=0, n=1; n < dupitems_count; lastn=n, n++)
{
if (!memcmp (dupitems[lastn].digest, dupitems[n].digest, 20))
{
bin2hexcolon (dupitems[lastn].digest, 20, fprbuf);
fprintf (outfp, "fpr=%s recno=%lu", fprbuf, dupitems[lastn].recno);
do
fprintf (outfp, " %lu", dupitems[n].recno);
while (++n < dupitems_count
&& !memcmp (dupitems[lastn].digest, dupitems[n].digest, 20));
putc ('\n', outfp);
n--;
}
}
free (dupitems);
return rc;
}
/* Print records with record numbers FROM to TO to OUTFP. */
int
_keybox_dump_cut_records (const char *filename, unsigned long from,
unsigned long to, FILE *outfp)
{
FILE *fp;
KEYBOXBLOB blob;
int rc;
unsigned long recno = 0;
if (!(fp = open_file (&filename, stderr)))
return gpg_error_from_syserror ();
while ( !(rc = _keybox_read_blob (&blob, fp)) )
{
if (recno > to)
break; /* Ready. */
if (recno >= from)
{
if ((rc = _keybox_write_blob (blob, outfp)))
{
fprintf (stderr, "error writing output: %s\n",
gpg_strerror (rc));
goto leave;
}
}
_keybox_release_blob (blob);
recno++;
}
if (rc == -1)
rc = 0;
if (rc)
fprintf (stderr, "error reading '%s': %s\n", filename, gpg_strerror (rc));
leave:
if (fp != stdin)
fclose (fp);
return rc;
}
|
ingochris/InfinityEncryption
|
gnupg-2.1.11/kbx/keybox-dump.c
|
C
|
gpl-3.0
| 19,914
|
CREATE TABLE "midas_2005_2009_synthesized_group_quarters_people" (
"p_id" real,
"gq_id" text,
"gq_type" text,
"sporder" real,
"age" real,
"sex" real
);
|
talos/docker4data
|
data/socrata/data.raleighnc.gov/midas_2005_2009_synthesized_group_quarters_people/schema.sql
|
SQL
|
gpl-3.0
| 158
|
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016-2018 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import yaml
from testtools.matchers import Equals
import snapcraft.internal
from tests import unit
class StageStateBaseTestCase(unit.TestCase):
def setUp(self):
super().setUp()
class Project:
pass
self.project = Project()
self.files = {"foo"}
self.directories = {"bar"}
self.part_properties = {
"filesets": {"qux": "quux"},
"override-stage": "touch override-stage",
"stage": ["baz"],
}
self.state = snapcraft.internal.states.StageState(
self.files, self.directories, self.part_properties, self.project
)
class StateStageTestCase(StageStateBaseTestCase):
def test_yaml_conversion(self):
state_from_yaml = yaml.load(yaml.dump(self.state))
self.assertThat(state_from_yaml, Equals(self.state))
def test_comparison(self):
other = snapcraft.internal.states.StageState(
self.files, self.directories, self.part_properties, self.project
)
self.assertTrue(self.state == other, "Expected states to be identical")
def test_properties_of_interest(self):
properties = self.state.properties_of_interest(self.part_properties)
self.assertThat(len(properties), Equals(3))
self.assertThat(properties["filesets"], Equals({"qux": "quux"}))
self.assertThat(properties["override-stage"], Equals("touch override-stage"))
self.assertThat(properties["stage"], Equals(["baz"]))
def test_project_options_of_interest(self):
self.assertFalse(self.state.project_options_of_interest(self.project))
class StageStateNotEqualTestCase(StageStateBaseTestCase):
scenarios = [
("no files", dict(other_property="files", other_value=set())),
("no directories", dict(other_property="directories", other_value=set())),
(
"no part properties",
dict(other_property="part_properties", other_value=None),
),
]
def test_comparison_not_equal(self):
setattr(self, self.other_property, self.other_value)
other_state = snapcraft.internal.states.StageState(
self.files, self.directories, self.part_properties, self.project
)
self.assertFalse(self.state == other_state, "Expected states to be different")
|
cprov/snapcraft
|
tests/unit/states/test_stage.py
|
Python
|
gpl-3.0
| 3,005
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace OV7725调车上位机.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
|
BugAngel/-
|
WIFI上位机/OV7725调车上位机/Properties/Settings.Designer.cs
|
C#
|
gpl-3.0
| 1,078
|
/*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* 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 com.watabou.legacy.actors.mobs;
import java.util.HashSet;
import com.watabou.legacy.Badges;
import com.watabou.legacy.Dungeon;
import com.watabou.legacy.Statistics;
import com.watabou.legacy.actors.Char;
import com.watabou.legacy.actors.blobs.ToxicGas;
import com.watabou.legacy.actors.buffs.Burning;
import com.watabou.legacy.actors.buffs.Frost;
import com.watabou.legacy.actors.buffs.Paralysis;
import com.watabou.legacy.actors.buffs.Roots;
import com.watabou.legacy.items.food.MysteryMeat;
import com.watabou.legacy.levels.Level;
import com.watabou.legacy.sprites.PiranhaSprite;
import com.watabou.utils.Random;
public class Piranha extends Mob {
{
name = "giant piranha";
spriteClass = PiranhaSprite.class;
baseSpeed = 2f;
EXP = 0;
}
public Piranha() {
super();
HP = HT = 10 + Dungeon.depth * 5;
defenseSkill = 10 + Dungeon.depth * 2;
}
@Override
protected boolean act() {
if (!Level.water[pos]) {
die( null );
return true;
} else {
return super.act();
}
}
@Override
public int damageRoll() {
return Random.NormalIntRange( Dungeon.depth, 4 + Dungeon.depth * 2 );
}
@Override
public int attackSkill( Char target ) {
return 20 + Dungeon.depth * 2;
}
@Override
public int dr() {
return Dungeon.depth;
}
@Override
public void die( Object cause ) {
Dungeon.level.drop( new MysteryMeat(), pos ).sprite.drop();
super.die( cause );
Statistics.piranhasKilled++;
Badges.validatePiranhasKilled();
}
@Override
public boolean reset() {
return true;
}
@Override
protected boolean getCloser( int target ) {
if (rooted) {
return false;
}
int step = Dungeon.findPath( this, pos, target,
Level.water,
Level.fieldOfView );
if (step != -1) {
move( step );
return true;
} else {
return false;
}
}
@Override
protected boolean getFurther( int target ) {
int step = Dungeon.flee( this, pos, target,
Level.water,
Level.fieldOfView );
if (step != -1) {
move( step );
return true;
} else {
return false;
}
}
@Override
public String description() {
return
"These carnivorous fish are not natural inhabitants of underground pools. " +
"They were bred specifically to protect flooded treasure vaults.";
}
private static final HashSet<Class<?>> IMMUNITIES = new HashSet<Class<?>>();
static {
IMMUNITIES.add( Burning.class );
IMMUNITIES.add( Paralysis.class );
IMMUNITIES.add( ToxicGas.class );
IMMUNITIES.add( Roots.class );
IMMUNITIES.add( Frost.class );
}
@Override
public HashSet<Class<?>> immunities() {
return IMMUNITIES;
}
}
|
sloanr333/opd-legacy
|
src/com/watabou/legacy/actors/mobs/Piranha.java
|
Java
|
gpl-3.0
| 3,326
|
/**
* Copyright (C) 2007-2011, Jens Lehmann
*
* This file is part of DL-Learner.
*
* DL-Learner 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.
*
* DL-Learner 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.dllearner.core;
import java.text.DecimalFormat;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import org.dllearner.core.owl.Description;
import org.dllearner.learningproblems.PosNegLPStandard;
import org.dllearner.utilities.datastructures.DescriptionSubsumptionTree;
import org.dllearner.utilities.owl.ConceptComparator;
import org.dllearner.utilities.owl.ConceptTransformation;
import org.dllearner.utilities.owl.EvaluatedDescriptionSet;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Abstract superclass of all class expression learning algorithm implementations.
* Includes support for anytime learning algorithms and resumable
* learning algorithms. Provides methods for filtering the best
* descriptions found by the algorithm. As results of the algorithm,
* you can either get only descriptions or evaluated descriptions.
* Evaluated descriptions have information about accuracy and
* example coverage associated with them. However, retrieving those
* may require addition reasoner queries, because the learning
* algorithms usually use but do not necessarily store this information.
*
* Changes (March/April 2011): Learning algorithms no longer have to use
* this class, but it still serves as a prototypical template for class
* expression learning algorithms.
*
* @author Jens Lehmann
*
*/
public abstract class AbstractCELA extends AbstractComponent implements ClassExpressionLearningAlgorithm, StoppableLearningAlgorithm {
protected EvaluatedDescriptionSet bestEvaluatedDescriptions = new EvaluatedDescriptionSet(AbstractCELA.MAX_NR_OF_RESULTS);
protected DecimalFormat dfPercent = new DecimalFormat("0.00%");
protected ConceptComparator descriptionComparator = new ConceptComparator();
protected String baseURI;
protected Map<String, String> prefixes;
/**
* The learning problem variable, which must be used by
* all learning algorithm implementations.
*/
protected AbstractLearningProblem learningProblem;
/**
* The reasoning service variable, which must be used by
* all learning algorithm implementations.
*/
protected AbstractReasonerComponent reasoner;
/**
* Default Constructor
*/
public AbstractCELA(){
}
/**
* Each learning algorithm gets a learning problem and
* a reasoner as input.
* @param learningProblem The learning problem to solve.
* @param reasoningService The reasoner connecting to the
* underlying knowledge base.
*/
public AbstractCELA(AbstractLearningProblem learningProblem, AbstractReasonerComponent reasoningService) {
this.learningProblem = learningProblem;
this.reasoner = reasoningService;
baseURI = reasoner.getBaseURI();
prefixes = reasoner.getPrefixes();
}
/**
* Call this when you want to change the learning problem, but
* leave everything else as is. Method can be used to apply
* a configured algorithm to different learning problems.
* Implementations, which do not only use the provided learning
* algorithm variable, must make sure that a call to this method
* indeed changes the learning problem.
* @param learningProblem The new learning problem.
*/
public void changeLearningProblem(AbstractLearningProblem learningProblem) {
this.learningProblem = learningProblem;
}
/**
* Call this when you want to change the reasoning service, but
* leave everything else as is. Method can be used to use
* a configured algorithm with different reasoners.
* Implementations, which do not only use the provided reasoning
* service class variable, must make sure that a call to this method
* indeed changes the reasoning service.
* @param reasoningService The new reasoning service.
*/
public void changeReasonerComponent(AbstractReasonerComponent reasoningService) {
this.reasoner = reasoningService;
}
/**
* This is the maximum number of results, which the learning
* algorithms are asked to store. (Note, that algorithms are not
* required to store any results except the best one, so this limit
* is used to limit the performance cost for those which
* choose to store results.)
*/
public static final int MAX_NR_OF_RESULTS = 100;
/**
* Every algorithm must be able to return the score of the
* best solution found.
*
* @return Best score.
*/
// @Deprecated
// public abstract Score getSolutionScore();
/**
* @see #getCurrentlyBestEvaluatedDescription()
* @return The best class description found by the learning algorithm so far.
*/
public abstract Description getCurrentlyBestDescription();
/**
* @see #getCurrentlyBestEvaluatedDescriptions()
* @return The best class descriptions found by the learning algorithm so far.
*/
public List<Description> getCurrentlyBestDescriptions() {
List<Description> ds = new LinkedList<Description>();
ds.add(getCurrentlyBestDescription());
return ds;
}
/**
* @see #getCurrentlyBestEvaluatedDescriptions(int)
* @param nrOfDescriptions Limit for the number or returned descriptions.
* @return The best class descriptions found by the learning algorithm so far.
*/
public synchronized List<Description> getCurrentlyBestDescriptions(int nrOfDescriptions) {
return getCurrentlyBestDescriptions(nrOfDescriptions, false);
}
/**
* @see #getCurrentlyBestEvaluatedDescriptions(int,double,boolean)
* @param nrOfDescriptions Limit for the number or returned descriptions.
* @param filterNonMinimalDescriptions Remove non-minimal descriptions (e.g. those which can be shortened
* to an equivalent concept) from the returned set.
* @return The best class descriptions found by the learning algorithm so far.
*/
public synchronized List<Description> getCurrentlyBestDescriptions(int nrOfDescriptions, boolean filterNonMinimalDescriptions) {
List<Description> currentlyBest = getCurrentlyBestDescriptions();
List<Description> returnList = new LinkedList<Description>();
for(Description ed : currentlyBest) {
if(returnList.size() >= nrOfDescriptions) {
return returnList;
}
if(!filterNonMinimalDescriptions || ConceptTransformation.isDescriptionMinimal(ed)) {
returnList.add(ed);
}
}
return returnList;
}
/**
* Returns the best descriptions obtained so far.
* @return Best class description found so far.
*/
public abstract EvaluatedDescription getCurrentlyBestEvaluatedDescription();
/**
* Returns a sorted set of the best descriptions found so far. We
* assume that they are ordered such that the best ones come in
* last. (In Java, iterators traverse a SortedSet in ascending order.)
* @return Best class descriptions found so far.
*/
public TreeSet<? extends EvaluatedDescription> getCurrentlyBestEvaluatedDescriptions() {
TreeSet<EvaluatedDescription> ds = new TreeSet<EvaluatedDescription>();
ds.add(getCurrentlyBestEvaluatedDescription());
return ds;
}
/**
* Returns a filtered list of currently best class descriptions.
*
* @param nrOfDescriptions Maximum number of restrictions. Use Integer.MAX_VALUE
* if you do not want this filter to be active.
*
* @param accuracyThreshold Minimum accuracy. All class descriptions with lower
* accuracy are disregarded. Specify a value between 0.0 and 1.0. Use 0.0 if
* you do not want this filter to be active.
*
* @param filterNonMinimalDescriptions If true, non-minimal descriptions are
* filtered, e.g. ALL r.TOP (being equivalent to TOP), male AND male (can be
* shortened to male). Currently, non-minimal descriptions are just skipped,
* i.e. they are completely omitted from the return list. Later, implementation
* might be changed to return shortened versions of those descriptions.
*
* @return A list of currently best class descriptions.
*/
public synchronized List<? extends EvaluatedDescription> getCurrentlyBestEvaluatedDescriptions(int nrOfDescriptions, double accuracyThreshold, boolean filterNonMinimalDescriptions) {
TreeSet<? extends EvaluatedDescription> currentlyBest = getCurrentlyBestEvaluatedDescriptions();
List<EvaluatedDescription> returnList = new LinkedList<EvaluatedDescription>();
for(EvaluatedDescription ed : currentlyBest.descendingSet()) {
// once we hit a description with a below threshold accuracy, we simply return
// because learning algorithms are advised to order descriptions by accuracy,
// so we won't find any concept with higher accuracy in the remaining list
// if(ed.getAccuracy() < accuracyThreshold) {
if(ed.getAccuracy() < accuracyThreshold) {
return returnList;
}
// return if we have sufficiently many descriptions
if(returnList.size() >= nrOfDescriptions) {
return returnList;
}
if(!filterNonMinimalDescriptions || ConceptTransformation.isDescriptionMinimal(ed.getDescription())) {
// before we add the description we replace EXISTS r.TOP with
// EXISTS r.range(r) if range(r) is atomic
// (we need to clone, otherwise we change descriptions which could
// be in the search of the learning algorith, which leads to
// unpredictable behaviour)
Description d = ed.getDescription().clone();
//commented out because reasoner is called. leads in swing applications sometimes to exceptions
// ConceptTransformation.replaceRange(d, reasoner);
ed.setDescription(d);
returnList.add(ed);
}
}
return returnList;
}
/**
* Return the best currently found concepts up to some maximum
* count (no minimality filter used).
* @param nrOfDescriptions Maximum number of descriptions returned.
* @return Return value is getCurrentlyBestDescriptions(nrOfDescriptions, 0.0, false).
*/
public synchronized List<? extends EvaluatedDescription> getCurrentlyBestEvaluatedDescriptions(int nrOfDescriptions) {
return getCurrentlyBestEvaluatedDescriptions(nrOfDescriptions, 0.0, false);
}
/**
* Returns a fraction of class descriptions with sufficiently high accuracy.
* @param accuracyThreshold Only return solutions with this accuracy or higher.
* @return Return value is getCurrentlyBestDescriptions(Integer.MAX_VALUE, accuracyThreshold, false).
*/
public synchronized List<? extends EvaluatedDescription> getCurrentlyBestEvaluatedDescriptions(double accuracyThreshold) {
return getCurrentlyBestEvaluatedDescriptions(Integer.MAX_VALUE, accuracyThreshold, false);
}
public synchronized List<? extends EvaluatedDescription> getCurrentlyBestMostGeneralEvaluatedDescriptions() {
List<? extends EvaluatedDescription> l = getCurrentlyBestEvaluatedDescriptions(getCurrentlyBestEvaluatedDescriptions().last().getAccuracy());
DescriptionSubsumptionTree t = new DescriptionSubsumptionTree(reasoner);
t.insert(l);
return t.getMostGeneralDescriptions(true);
}
/**
* Returns all learning problems supported by this component. This can be used to indicate that, e.g.
* an algorithm is only suitable for positive only learning.
* @return All classes implementing learning problems, which are supported by this learning algorithm.
*/
public static Collection<Class<? extends AbstractLearningProblem>> supportedLearningProblems() {
return new LinkedList<Class<? extends AbstractLearningProblem>>();
}
// central function for printing description
protected String descriptionToString(Description description) {
return description.toManchesterSyntaxString(baseURI, prefixes);
}
protected String getSolutionString() {
int current = 1;
String str = "";
for(EvaluatedDescription ed : bestEvaluatedDescriptions.getSet().descendingSet()) {
// temporary code
if(learningProblem instanceof PosNegLPStandard) {
str += current + ": " + descriptionToString(ed.getDescription()) + " (pred. acc.: " + dfPercent.format(((PosNegLPStandard)learningProblem).getPredAccuracyOrTooWeakExact(ed.getDescription(),1)) + ", F-measure: "+ dfPercent.format(((PosNegLPStandard)learningProblem).getFMeasureOrTooWeakExact(ed.getDescription(),1)) + ")\n";
} else {
str += current + ": " + descriptionToString(ed.getDescription()) + " " + dfPercent.format(ed.getAccuracy()) + "\n";
// System.out.println(ed);
}
current++;
}
return str;
}
/**
* The learning problem variable, which must be used by
* all learning algorithm implementations.
*/
@Override
public AbstractLearningProblem getLearningProblem() {
return learningProblem;
}
@Autowired
@Override
public void setLearningProblem(LearningProblem learningProblem) {
this.learningProblem = (AbstractLearningProblem) learningProblem;
}
/**
* The reasoning service variable, which must be used by
* all learning algorithm implementations.
*/
public AbstractReasonerComponent getReasoner() {
return reasoner;
}
@Autowired
public void setReasoner(AbstractReasonerComponent reasoner) {
this.reasoner = reasoner;
}
}
|
daftano/dl-learner
|
components-core/src/main/java/org/dllearner/core/AbstractCELA.java
|
Java
|
gpl-3.0
| 13,698
|
package preez.uva;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class UVA496 {
static ArrayList<char[]> a;
static int N, M, T, qi, qj;
// S,SE,E,NE,N,NW,W,SW neighbors
static int dr[] = { 1, 1, 0, -1, -1, -1, 0, 1 };
static int dc[] = { 0, 1, 1, 1, 0, -1, -1, -1 };
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pr = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer st;
static int floodFill(int i, int j, char c1, char c2) {
if (i >= N || i < 0 || j >= M || j < 0 || a.get(i)[j] != c1)
return 0;
a.get(i)[j] = c2;
int ans = 1;
for (int k = 0; k < dr.length; k++)
ans += floodFill(i + dr[k], j + dc[k], c1, c2);
return ans;
}
public static void main(String[] args) throws NumberFormatException, IOException {
T = Integer.parseInt(br.readLine());
br.readLine();
while (T-- > 0) {
String s = br.readLine();
a = new ArrayList<>();
while (s.charAt(0) == 'W' || s.charAt(0) == 'L') {
a.add(s.toCharArray());
s = br.readLine();
}
N = a.size();
M = a.get(0).length;
while (s != null && s.length() != 0) {
st = new StringTokenizer(s);
qi = Integer.parseInt(st.nextToken()) - 1;
qj = Integer.parseInt(st.nextToken()) - 1;
System.out.println(floodFill(qi, qj, 'W', '.'));
floodFill(qi, qj, '.', 'W');
s = br.readLine();
}
if(T>0)
System.out.println();
}
br.close();
}
}
|
msskzx/preez
|
src/preez/uva/UVA496.java
|
Java
|
gpl-3.0
| 1,630
|
module mbpolmod
implicit none
! does not compile with pgi due to sqrt - DJW
! double precision, parameter :: maxdOO=3.5D0**2, maxdOH=2.45D0**2, maxcosOOH=sqrt(3.D0)/2.D0
double precision, parameter :: maxdOO=3.5D0**2, maxdOH=2.45D0**2, maxcosOOH=0.8660254037844386D0
integer :: nnode
public :: mbpolinit, mbpol, mbpolstep
private
contains
subroutine mbpolinit()
use commons, only : natoms
implicit none
nnode=natoms/3
end subroutine mbpolinit
subroutine mbpol(coordinates, energy, gradient, gradt)
implicit none
logical, intent(in) :: gradt
double precision, intent(in) :: coordinates(nnode*9)
double precision, intent(out) :: gradient(nnode*9), energy
if (gradt) then
call mbpolenergygradient(nnode,energy,coordinates,gradient)
else
call mbpolenergy(nnode,energy,coordinates)
endif
end subroutine mbpol
subroutine mbpolstep(coordinates,displacement,angle,translate,rotate)
implicit none
logical, intent(in) :: translate, rotate
double precision, intent(in) :: displacement, angle
double precision, intent(inout) :: coordinates(nnode*9)
call mbpolhbondgeometric(coordinates)
end subroutine mbpolstep
subroutine mbpolhbondgeometric(coordinates)
use graph_mod, only: digraph_adj_cycle
implicit none
double precision :: coordinates(nnode*9)
integer :: adjacency(nnode,nnode)
double precision :: hydrogenbonds(nnode*6,2), dOO, dOH, cosOOH, dprand
integer :: mol1, mol2, nmol, hydrogen, oxygen
! arguments for digraphadjcycle
integer :: adj2(nnode,nnode), dad(nnode), order(nnode)
adjacency=0
do mol1=1,nnode
do mol2=mol1+1,nnode
dOO=sum((coordinates(mol1*9-8:mol1*9-6)-coordinates(mol2*9-8:mol2*9-6))**2)
if (dOO<maxdOO) then
dOO=sqrt(dOO)
!1H1O2
dOH=sum((coordinates(mol1*9-5:mol1*9-3)-coordinates(mol2*9-8:mol2*9-6))**2)
if (dOH<maxdOH) then
dOH=sqrt(dOH)
cosOOH=dot_product((coordinates(mol1*9-8:mol1*9-6)-coordinates(mol2*9-8:mol2*9-6)),&
(coordinates(mol1*9-8:mol1*9-6)-coordinates(mol1*9-5:mol1*9-3)))/(dOH*dOO)
if (cosOOH<maxcosOOH) then
write(*,*)(mol1-1)*3,(mol1-1)*3+1,(mol2-1)*3
adjacency(mol1,mol2)=(mol1-1)*3+1
endif
endif
!2H1O2
dOH=sum((coordinates(mol1*9-2:mol1*9-0)-coordinates(mol2*9-8:mol2*9-6))**2)
if (dOH<maxdOH) then
dOH=sqrt(dOH)
cosOOH=dot_product((coordinates(mol1*9-8:mol1*9-6)-coordinates(mol2*9-8:mol2*9-6)),&
(coordinates(mol1*9-8:mol1*9-6)-coordinates(mol1*9-2:mol1*9-0)))/(dOH*dOO)
if (cosOOH<maxcosOOH) then
write(*,*)(mol1-1)*3,(mol1-1)*3+2,(mol2-1)*3
adjacency(mol1,mol2)=(mol1-1)*3+2
endif
endif
!1H2O1
dOH=sum((coordinates(mol2*9-5:mol2*9-3)-coordinates(mol1*9-8:mol1*9-6))**2)
if (dOH<maxdOH) then
dOH=sqrt(dOH)
cosOOH=dot_product((coordinates(mol2*9-8:mol2*9-6)-coordinates(mol1*9-8:mol1*9-6)),&
(coordinates(mol2*9-8:mol2*9-6)-coordinates(mol2*9-5:mol2*9-3)))/(dOH*dOO)
if (cosOOH<maxcosOOH) then
write(*,*)(mol2-1)*3,(mol2-1)*3+1,(mol1-1)*3
adjacency(mol2,mol1)=(mol2-1)*3+1
endif
endif
!2H1O1
dOH=sum((coordinates(mol2*9-2:mol2*9-0)-coordinates(mol1*9-8:mol1*9-6))**2)
if (dOH<maxdOH) then
dOH=sqrt(dOH)
cosOOH=dot_product((coordinates(mol2*9-8:mol2*9-6)-coordinates(mol1*9-8:mol1*9-6)),&
(coordinates(mol2*9-8:mol2*9-6)-coordinates(mol2*9-2:mol2*9-0)))/(dOH*dOO)
if (cosOOH<maxcosOOH) then
write(*,*)(mol2-1)*3,(mol2-1)*3+2,(mol1-1)*3
adjacency(mol2,mol1)=(mol2-1)*3+2
endif
endif
endif
enddo
enddo
write(*,"(10(I2,1X))")adjacency
call digraph_adj_cycle(adjacency,nnode,nnode,adj2,dad,order)
write(*,*)
write(*,"(10(I2,1X))")adj2
write(*,*)
write(*,"(10(I2,1X))")dad
write(*,*)
write(*,"(10(I2,1X))")order
end subroutine mbpolhbondgeometric
end module mbpolmod
|
marktoakley/LamarckiAnt
|
GMIN/source/mbpol.f90
|
FORTRAN
|
gpl-3.0
| 3,937
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' Allgemeine Informationen über eine Assembly werden über die folgenden
' Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
' die mit einer Assembly verknüpft sind.
' Die Werte der Assemblyattribute überprüfen
<Assembly: AssemblyTitle("Prowl.API")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("NuGardt")>
<Assembly: AssemblyProduct("Prowl.API")>
<Assembly: AssemblyCopyright("Copyright © NuGardt 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
<Assembly: Guid("918b261d-33a6-4e40-8627-b04505723711")>
' Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
'
' Hauptversion
' Nebenversion
' Buildnummer
' Revision
'
' Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
' übernehmen, indem Sie "*" eingeben:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.1")>
<Assembly: AssemblyFileVersion("1.0.0.1")>
|
NuGardt/prowl-api
|
Lib/Prowl.API/My Project/AssemblyInfo.vb
|
Visual Basic
|
gpl-3.0
| 1,242
|
#pragma once
namespace MVC{
namespace Item{
class CItemGroup;
class CPropertySource;
class CItem
{
public:
enum{
SRC_TYPE_MEM = 0,
SRC_TYPE_IO = 1
};
private:
UINT m_uiID; // ±äÁ¿IDºÅ
CString m_strName; // ±äÁ¿Ãû³Æ
CString m_strTag; // ±äÁ¿±êÇ©
CString m_strValue; // ×Ö·û´®ÐÎʽ´æ´¢µÄ±äÁ¿Öµ
CString m_strIOValue; // ×Ö·û´®ÐÎʽ´æ´¢µÄ±äÁ¿Ôʼֵ
CString m_strDescription; // ±äÁ¿µÄ±¸×¢ÐÅÏ¢
CComVariant m_cvrDefaultValue; // ±äÁ¿Ä¬ÈÏÖµ
CComVariant m_cvrValue; // ±äÁ¿Öµ
CComVariant m_cvrValueOld; // ±äÁ¿Öµ£¬±äÁ¿¸Õ²ÅµÄÖµ£¬ÕâÀïÒª±¸·ÝÒ»¸ö
CComVariant m_cvrIOValue; // ±äÁ¿Ôʼֵ
CComVariant m_cvrIOValueOld; // ±äÁ¿Ôʼֵ£¬±äÁ¿¸Õ²ÅµÄÔʼֵ£¬ÕâÀïÒª±¸·ÝÒ»¸ö
UINT m_uiGroupID; // ±äÁ¿ËùÊô±äÁ¿×éµÄIDºÅ
UINT m_uiValType; // ±äÁ¿ÀàÐÍ£¬0-bit£¬1-char£¬2-byte£¬3-short£¬4-word£¬5-int£¬6-dword£¬7-float£¬8-double
UINT m_uiSrcType; // Êý¾ÝÔ´ÀàÐÍ£¬0ÄÚ´æ±äÁ¿£¬1I/O±äÁ¿
UINT m_uiAccessRight; // ·ÃÎÊȨÏÞ£¬0¿É¶Á¿Éд£¬1Ö»¶Á£¬2ֻд£¬3ÎÞ·¨·ÃÎÊ
BOOL m_bReservFlag; // ÊÇ·ñÉèÖóɱ£ÁôÖµ£¬trueÉèÖã¬false²»ÉèÖÃ
BOOL m_bReservDB; // ÊÇ·ñ±£´æÀúÊ·Êý¾Ý
std::shared_ptr<CPropertySource> m_spSrcInfo; // Ô´ÊôÐÔ
SYSTEMTIME m_stUpdateTime; // ×îºóÒ»´ÎÐÞ¸Äʱ¼ä
SYSTEMTIME m_stCreateTime; // ´´½¨Ê±¼ä
UINT m_uiIRefCount; // ÒýÓüÆÊý£¬¾ÍÊDZ»Ê¹ÓõĴÎÊý
public:
UINT getID(){return m_uiID;} // »ñµÃ±äÁ¿ID±àºÅ
CString getName(){return m_strName;} // »ñµÃ±äÁ¿Ãû³Æ
CString getTag(){return m_strTag;} // »ñµÃ±äÁ¿±êÇ©
CString getDescription(){return m_strDescription;} // »ñµÃ±äÁ¿±¸×¢ÐÅÏ¢
CComVariant getDefault(){return m_cvrDefaultValue;} // »ñµÃ±äÁ¿µÄĬÈÏÖµ
CComVariant getValue(){return m_cvrValue;} // »ñµÃ±äÁ¿µÄµ±Ç°Öµ
CComVariant getIOValue(){return m_cvrIOValue;} // »ñµÃ±äÁ¿µÄµ±Ç°Ôʼֵ
CString getStrValue(bool ishex); //!<»ñµÃ±äÁ¿µÄ×Ö·ûÐÎʽµÄµ±Ç°Öµ
CString getStrIOValue(bool ishex); //!<»ñµÃ±äÁ¿µÄ×Ö·ûÐÎʽµÄµ±Ç°Ôʼֵ
CString GetFloatStr(float flt); // »ñµÃ¸¡µã×Ö·û´®
UINT getMyGroupID(){return m_uiGroupID;} // ±äÁ¿ËùÊô±äÁ¿×éµÄIDºÅ
UINT getSrcType(){return m_uiSrcType;} // »ñµÃ±äÁ¿Êý¾ÝÔ´ÀàÐÍ£¬0Äڴ棬1I/O
UINT getValType(){return m_uiValType;} // »ñµÃÖµµÄÀàÐÍ
UINT getAccessRight(){return m_uiAccessRight;} // »ñµÃ±äÁ¿µÄ·ÃÎÊÀàÐÍ£¬0¿É¶Á¿Éд£¬1Ö»¶Á£¬2ֻд
BOOL getReservFlag(){return m_bReservFlag;} // »ñµÃ±äÁ¿ÊÇ·ñÉèÖÃΪ±£ÁôÖµ
BOOL getReservDB(){return m_bReservDB;} // »ñµÃ±äÁ¿ÊÇ·ñ±£´æÀúÊ·Êý¾Ý
std::shared_ptr<CPropertySource> getSrcInfo(){return m_spSrcInfo;} // »ñµÃÊý¾ÝÔ´ÊôÐÔ¶ÔÏóµÄÖÇÄÜÖ¸Õë
SYSTEMTIME getCreateTime(){return m_stCreateTime;} // »ñµÃ±äÁ¿µÄ´´½¨Ê±¼ä
SYSTEMTIME getUpdateTime(){return m_stUpdateTime;} // »ñµÃ±äÁ¿µÄÐÞ¸Äʱ¼ä
void setID(UINT id){m_uiID = id;} // ÉèÖñäÁ¿µÄID±àºÅ
void setItemName(CString name){m_strName = name;} // ÉèÖñäÁ¿µÄÃû³Æ
void setTag(CString tag){m_strTag = tag;} // ÉèÖñäÁ¿µÄ±êÇ©
void setDescription(CString dsp){m_strDescription = dsp;} // ÉèÖñäÁ¿±¸×¢ÐÅÏ¢
void setDefault(CComVariant default_value){m_cvrDefaultValue=default_value;}// ÉèÖñäÁ¿µÄĬÈÏÖµ
void setMyGroupID(UINT id){m_uiGroupID = id;} // ±äÁ¿ËùÊô±äÁ¿×éµÄIDºÅ
void setSrcType(UINT type){m_uiSrcType = type;} // ÉèÖñäÁ¿µÄÊý¾ÝÔ´ÀàÐÍ
void setAccessRight(UINT type){m_uiAccessRight = type;} // ÉèÖñäÁ¿µÄ·ÃÎÊȨÏÞ
void setReservFlag(BOOL flag){m_bReservFlag = flag;} // ÉèÖñäÁ¿ÊÇ·ñ±£ÁôÖµ
void setReservDB(BOOL flag){m_bReservDB = flag;} // ÉèÖñäÁ¿ÊÇ·ñ±£´æÀúÊ·Êý¾Ý
void OnUpdateInfo(){GetLocalTime(&m_stUpdateTime);} // ÉèÖñäÁ¿±»Ð޸ĺóµÄÐÞ¸Äʱ¼ä
void setUpdateTime(SYSTEMTIME st){m_stUpdateTime=st;} // ÉèÖøüÐÂʱ¼ä
void setCreateTime(SYSTEMTIME st){m_stCreateTime=st;} // ÉèÖô´½¨Ê±¼ä
void setValue(CComVariant value){m_cvrValue=value;} // ÉèÖñäÁ¿µÄµ±Ç°Öµ
void setIOValue(CComVariant value){m_cvrIOValue = value;} // ÉèÖñäÁ¿µÄµ±Ç°Ôʼֵ
void OnAdd(){m_uiIRefCount++;} // ¼ÓÔØµ½×éÖУ¬²¢²»ÊÇÕæÕýµÄÌí¼Ó
void OnDeleteFGroup(){/*ÂÔ*/;} // ´Ó×éÖÐÈ¥µô£¬µ±ÒýÓüÆÊý¹éÁãʱ£¬³¹µ×ɾ³ý
void OnDelete(){;} // ³¹µ×ɾ³ýÒ»¸ö±äÁ¿£¬²»¿¼ÂÇÒýÓüÆÊý£¬±éÀúËùÓбäÁ¿×飬ȥµô¹ØÓڸñäÁ¿µÄ¼Ç¼
UINT getRefCount(){return m_uiIRefCount;} // »ñµÃÒýÓüÆÊý
public:
CItem(CString name); //
~CItem(void);
void setValType(UINT type); // ÉèÖñäÁ¿µÄÖµÀàÐÍ
void setValType(CString strType); // ÉèÖñäÁ¿µÄÖµÀàÐÍ
void SetVarType(); // È·ÈϱäÁ¿µÄÀàÐÍ
void ChangeVarType(UINT type); // ¸ù¾ÝvalType¶¨ÒåµÄÀàÐÍ£¬½«±äÁ¿¸÷ÖÖvariantÀàÐ͵ÄÊôÐÔת³ÉÕæÕý¶ÔÓ¦µÄÊôÐÔ
bool Serialize(CArchive& ar); // ±£´æ¶þ½øÖÆÐÅÏ¢
bool SerializeXml(TiXmlElement* pNode, bool bRead, bool iExport = false); // ±£´æxml¸ñʽµÄ±à¼ÐÅÏ¢,iExport=falseÕý³££¬trueµ¼Èëµ¼³ö
bool ReadFromConfig(CString strLine, int devID); // ´ÓConfigµ¼³öµÄ±äÁ¿±íÖжÁÈ¡±äÁ¿
bool ReadFromPM(CString strLine, int devID); // ´ÓPMµ¼³öµÄ±äÁ¿±íÖжÁÈ¡±äÁ¿
CItem& operator = (CItem& item); // ¸³Öµ²Ù×÷£¬°üÀ¨IDºÍÃû³ÆÒ²È«¶¼¸³¹ýÈ¥ÁË
bool operator == (CItem& item) const; // Åжϱ¾±äÁ¿ÊÇ·ñÓëitemÊôÐÔÒ»Ñù
bool OnCloneMe(CItem& item, int index, int addrUnit, int nType = 0); // Òª¿Ë¡һ¸ö×Ô¼º£¬nType=0ÕûÊýÃüÃû£¬1СÊýÃüÃû
CString GetCheckValue(); // »ñµÃÒ»¸ö¼ìÑéÖµ,ÓÃÓÚÄÚ´æ½Å±¾¼ìÑéµÄ
CString GetValTypeStr(); // ÒÔ×Ö·û´®µÄÐÎʽ·µ»Ø¹¤³ÌÖµÀàÐÍ
CString GetGroupName(); // ·µ»Ø±äÁ¿ËùÊô×éµÄÃû³Æ
bool IsValueChange(); // ÅжϱäÁ¿ÖµÊÇ·ñ¸Ä±ä
bool IsIOValueChange(); // ÅжϱäÁ¿ÔʼֵÊÇ·ñ¸Ä±ä
void WatchInit(); // ¼à¿Ø³õʼ»¯£¬Çå³þ״̬
bool DoSearch(CString str, bool bMatchWhole, bool bAllCase, bool bRegex = false); // ²éÕÒ±¾±äÁ¿£¬ÒªÆ¥ÅäµÄÎı¾£¬È«×Ö·ûÆ¥Å䣬´óСдƥÅä
private:
};
}
}
|
atlaser/Tools
|
PMEditor/main/PM/Item.h
|
C
|
gpl-3.0
| 5,759
|
"""
Author: Tom Daniels, Kaitlin Keenan
Purpose: Creates a force graph of IP addresses and any connections they made
"""
import igraph
import json
import plotly
import plotly.graph_objs as pg
import sys
GEN_INFO = 0 # General information
PHYS = 1 # Physical layer information
DATA = 2 # Data link layer information
NET = 3 # Network layer information
TRANS = 4 # Transport layer information
SRC_IP = 12
DST_IP=14
LOWER_MULTICAST = 224 # First octect of the lowest multicast addresses
UPPER_MULTICAST = 240 # First octect of the highest multicast addresses
BROADCAST = 255
f = open('jsonOut.json', 'rb')
jsonData = json.loads(f.read())
packets = jsonData['pdml']['packet']
nodeID = {} # Maps: Node -> ID
nodes = [] # List of nodes
mapping = {} # Maps: Node interation with Node -> # times
nodeNumber = 0 # Give the Nodes an ID
nodeCounter = {} # Maps: Node -> # of times we've seen it
for packet in packets:
if(len(packet['proto']) > NET and packet['proto'][NET]['@name'] == 'ip'):
src = packet['proto'][NET]['field'][SRC_IP]['@show'].encode('ascii')
dst = packet['proto'][NET]['field'][DST_IP]['@show'].encode('ascii')
# If either address is multi/broadcast address, ignore it
if(LOWER_MULTICAST <= int(src.split('.')[0]) < UPPER_MULTICAST or
LOWER_MULTICAST <= int(dst.split('.')[0]) < UPPER_MULTICAST or
int(dst.split('.')[3]) == 255):
continue
# Add the address(es) to our database if they're not in them
if(not(nodeID.has_key(src))):
nodes.append(src)
nodeID[src] = nodeNumber
nodeNumber = nodeNumber + 1
if(not(nodeID.has_key(dst))):
nodes.append(dst)
nodeID[dst] = nodeNumber
nodeNumber = nodeNumber + 1
# Increment the counter for the number of times we've seen this node
if(nodeCounter.has_key(src)):
nodeCounter[src] += 1
else:
nodeCounter[src] = 1
if(nodeCounter.has_key(dst)):
nodeCounter[dst] += 1
else:
nodeCounter[dst] = 1
# Replace string IP addresses with numbers
src = str(nodeID[src])
dst = str(nodeID[dst])
# Add the mapping to the dictionary
if(not(mapping.has_key(src + ':' + dst) and mapping.has_key(dst + ':' + src))):
mapping[src + ':' + dst] = 1
totalPackets = len(packets)
colors = []
# Set the colors for each node based on how many packets they sent out
for node in nodes:
colors.append(nodeCounter[node] / float(totalPackets))
edges = [(int(key.split(':')[0]), int(key.split(':')[1])) for key in mapping.keys()]
graph = igraph.Graph(edges, directed=False)
layout = graph.layout('kk', dim=3)
length = len(nodes)
Xn = [layout[i][0] for i in range(length)]
Yn = [layout[i][1] for i in range(length)]
Zn = [layout[i][2] for i in range(length)]
Xe = []
Ye = []
Ze = []
for e in edges:
Xe+=[layout[e[0]][0], layout[e[1]][0], None]
Ye+=[layout[e[0]][1], layout[e[1]][1], None]
Ze+=[layout[e[0]][2], layout[e[1]][2], None]
# Makes the edges
trace1 = pg.Scatter3d(x=Xe, y=Ye, z=Ze, mode='lines',
line=pg.Line(color='rgb(125,125,125)', width=1),
hoverinfo='none')
# Makes the nodes
trace2 = pg.Scatter3d(x=Xn, y=Yn, z=Zn, mode='markers',
name='IP Addresses',
marker=pg.Marker(symbol='dot',size=6,
line=pg.Line(color='rgb(50,50,50)',
width=0.5), colorscale=[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']],
color=colors),
text=nodes, hoverinfo='text')
axis = dict(showbackground=False, showline=False, zeroline=False, showgrid=False,
showticklabels=False, title='')
trueLayout = pg.Layout(title='test', width=1000, height=1000, showlegend=False,
scene=pg.Scene(xaxis=pg.XAxis(axis),
yaxis=pg.YAxis(axis),
zaxis=pg.ZAxis(axis)),
margin=pg.Margin(t=100), hovermode='closest')
plotly.offline.plot(pg.Figure(data=pg.Data([trace1, trace2]), layout=trueLayout),
filename=sys.argv[1] + '/' + 'forceGraph.html')
|
TRDan6577/networkStatistics
|
networkNodes.py
|
Python
|
gpl-3.0
| 4,386
|
/*
* Demo application using USBtinLib, the Java Library for USBtin
* http://www.fischl.de/usbtin
*
* Copyright (C) 2014 Thomas Fischl
*
* 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 USBtinLibDemo;
import de.fischl.usbtin.*;
/**
* Demo application using USBtinLib, the Java Library for USBtin.
*
* @author Thomas Fischl
*/
public class USBtinLibDemo implements CANMessageListener {
/** CAN message identifier we look for */
static final int WATCHID = 0x002;
/**
* This method is called every time a CAN message is received.
*
* @param canmsg Received CAN message
*/
@Override
public void receiveCANMessage(CANMessage canmsg) {
// In this example we look for CAN messages with given ID
if (canmsg.getId() == WATCHID) {
// juhuu.. match!
// print out message infos
System.out.println("Watched message: " + canmsg);
System.out.println(
" id:" + canmsg.getId()
+ " dlc:" + canmsg.getData().length
+ " ext:" + canmsg.isExtended()
+ " rtr:" + canmsg.isRtr());
// and now print payload
for (byte b : canmsg.getData()) {
System.out.print(" " + b);
}
System.out.println();
} else {
// no match, just print the message string
System.out.println(canmsg);
}
}
/**
* Entry method for our demo programm
*
* @param args Arguments
*/
public static void main(String[] args) {
try {
// create the instances
USBtin usbtin = new USBtin();
USBtinLibDemo libDemo = new USBtinLibDemo();
// connect to USBtin and open CAN channel with 10kBaud in Active-Mode
usbtin.connect("/dev/ttyACM1"); // Windows e.g. "COM3"
usbtin.addMessageListener(libDemo);
usbtin.openCANChannel(10000, USBtin.OpenMode.ACTIVE);
// send an example CAN message (standard)
usbtin.send(new CANMessage(0x100, new byte[]{0x11, 0x22, 0x33}));
// send an example CAN message (extended)
usbtin.send(new CANMessage(0x101, new byte[]{0x44}, true, false));
// now wait for user input
System.out.println("Listen for CAN messages (watch id=" + WATCHID + ") ... press ENTER to exit!");
System.in.read();
// close the CAN channel and close the connection
usbtin.closeCANChannel();
usbtin.disconnect();
} catch (USBtinException ex) {
// Ohh.. something goes wrong while accessing/talking to USBtin
System.err.println(ex);
} catch (java.io.IOException ex) {
// this we need because of the System.in.read()
System.err.println(ex);
}
}
}
|
EmbedME/USBtinLibDemo
|
src/USBtinLibDemo.java
|
Java
|
gpl-3.0
| 3,657
|
// Copyright 2015-2022, University of Colorado Boulder
/**
* Class that represents messenger ribonucleic acid, or mRNA, in the model. This class is fairly complex, due to the
* need for mRNA to wind up and unwind as it is transcribed, translated, and destroyed.
*
* @author John Blanco
* @author Mohamed Safi
* @author Aadish Gupta
*/
import BooleanProperty from '../../../../axon/js/BooleanProperty.js';
import Vector2 from '../../../../dot/js/Vector2.js';
import { Shape } from '../../../../kite/js/imports.js';
import geneExpressionEssentials from '../../geneExpressionEssentials.js';
import GEEConstants from '../GEEConstants.js';
import MessengerRnaAttachmentStateMachine from './attachment-state-machines/MessengerRnaAttachmentStateMachine.js';
import AttachmentSite from './AttachmentSite.js';
import FlatSegment from './FlatSegment.js';
import MessengerRnaDestroyer from './MessengerRnaDestroyer.js';
import PlacementHint from './PlacementHint.js';
import Ribosome from './Ribosome.js';
import WindingBiomolecule from './WindingBiomolecule.js';
// constants
const RIBOSOME_CONNECTION_DISTANCE = 400; // picometers - distance within which this will connect to a ribosome
const MRNA_DESTROYER_CONNECT_DISTANCE = 400; // picometers - Distance within which this will connect to a mRNA destroyer
const INITIAL_MRNA_SHAPE = Shape.circle( 0, 0, 0.1 ); // tiny circle until the strand starts to grow
const MIN_LENGTH_TO_ATTACH = 75; // picometers - min length before attachments are allowed
class MessengerRna extends WindingBiomolecule {
/**
* Constructor. This creates the mRNA as a single point, with the intention of growing it.
*
* @param {GeneExpressionModel} model
* @param {Protein} proteinPrototype
* @param {Vector2} position
* @param {Object} [options]
*/
constructor( model, proteinPrototype, position, options ) {
super( model, INITIAL_MRNA_SHAPE, position, options );
// @private {Object} - object that maps from ribosomes to the shape segment to which they are attached
this.mapRibosomeToShapeSegment = {};
// @public {BooleanProperty} - externally visible indicator for whether this mRNA is being synthesized, assumes that
// it is being synthesized when initially created
this.beingSynthesizedProperty = new BooleanProperty( true ); //@public
// @private - protein prototype, used to keep track of protein that should be synthesized from this particular
// strand of mRNA
this.proteinPrototype = proteinPrototype;
// @private - local reference to the non-generic state machine used by this molecule
this.mRnaAttachmentStateMachine = this.attachmentStateMachine;
// @private - mRNA destroyer that is destroying this mRNA. Null until and unless destruction has begun.
this.messengerRnaDestroyer = null;
// @private - Shape segment where the mRNA destroyer is connected. This is null until destruction has begun.
this.segmentBeingDestroyed = null;
// @private {AttachmentSite} - site where ribosomes or mRNA destroyers can attach
this.attachmentSite = new AttachmentSite( this, new Vector2( 0, 0 ), 1 );
// set the initial position
this.setPosition( position );
// Add the first segment to the shape segment list. This segment will contain the "leader" for the mRNA.
const segment = new FlatSegment( this, Vector2.ZERO );
segment.setCapacity( GEEConstants.LEADER_LENGTH );
this.shapeSegments.push( segment );
// Add the placement hints for the positions where the user can attach a ribosome or an mRNA destroyer.
const ribosome = new Ribosome( model );
this.ribosomePlacementHint = new PlacementHint( ribosome ); //@public(read-only)
this.mRnaDestroyerPlacementHint = new PlacementHint( new MessengerRnaDestroyer( model ) ); //@public(read-only)
const updateHintPositions = shape => {
// All hints always sit at the beginning of the RNA strand and are positioned relative to its center.
const strandStartPosition = new Vector2( shape.bounds.minX, shape.bounds.maxY );
this.ribosomePlacementHint.setPosition( strandStartPosition.minus( ribosome.offsetToTranslationChannelEntrance ) );
this.mRnaDestroyerPlacementHint.setPosition( strandStartPosition );
};
this.shapeProperty.link( updateHintPositions );
// update the attachment site position when the mRNA moves or changes shape
const attachmentSitePositionUpdater = this.updateAttachmentSitePosition.bind( this );
this.positionProperty.link( attachmentSitePositionUpdater );
this.shapeProperty.link( attachmentSitePositionUpdater );
this.disposeMessengerRna = function() {
this.shapeProperty.unlink( updateHintPositions );
this.shapeProperty.unlink( attachmentSitePositionUpdater );
this.positionProperty.unlink( attachmentSitePositionUpdater );
};
}
/**
* @public
*/
dispose() {
this.mapRibosomeToShapeSegment = null;
this.disposeMessengerRna();
super.dispose();
}
/**
* Command this mRNA strand to fade away when it has become fully formed. This was created for use in the 2nd
* screen, where mRNA is never translated once it is produced.
* @param {boolean} fadeAwayWhenFormed
* @public
*/
setFadeAwayWhenFormed( fadeAwayWhenFormed ) {
// Just pass this through to the state machine.
this.mRnaAttachmentStateMachine.setFadeAwayWhenFormed( fadeAwayWhenFormed );
}
/**
* Advance the translation of the mRNA through the given ribosome by the specified length. The given ribosome must
* already be attached to the mRNA.
* @param {Ribosome} ribosome - The ribosome by which the mRNA is being translated.
* @param {number} length - The amount of mRNA to move through the translation channel.
* @returns - true if the mRNA is completely through the channel, indicating, that transcription is complete, and false
* if not.
* @public
*/
advanceTranslation( ribosome, length ) {
const segmentToAdvance = this.mapRibosomeToShapeSegment[ ribosome.id ];
// Error checking.
assert && assert( segmentToAdvance !== null ); // Should never happen, since it means that the ribosome isn't attached.
// Advance the translation by advancing the position of the mRNA in the segment that corresponds to the translation
// channel of the ribosome.
segmentToAdvance.advance( length, this, this.shapeSegments );
// Realign the segments, since they may well have changed shape.
if ( this.shapeSegments.indexOf( segmentToAdvance ) !== -1 ) {
this.realignSegmentsFrom( segmentToAdvance );
this.recenter();
}
// Since the sizes and relationships of the segments probably changed, the winding algorithm needs to be rerun.
this.windPointsThroughSegments();
// If there is anything left in this segment, then transcription is not yet complete.
return segmentToAdvance.getContainedLength() <= 0;
}
/**
* Advance the destruction of the mRNA by the specified length. This pulls the strand into the lead segment much like
* translation does, but does not move the points into new segment, it just gets rid of them.
* @param {number} length
* @returns {boolean}
* @public
*/
advanceDestruction( length ) {
// Error checking.
assert && assert(
this.segmentBeingDestroyed !== null,
'error - attempt to advance the destruction of mRNA that has no content left'
);
// Advance the destruction by reducing the length of the mRNA.
this.reduceLength( length );
// Realign the segments, since they may well have changed shape.
if ( this.shapeSegments.indexOf( this.segmentBeingDestroyed ) !== -1 ) {
this.realignSegmentsFrom( this.segmentBeingDestroyed );
}
if ( this.shapeSegments.length > 0 ) {
// Since the sizes and relationships of the segments probably changed, the winding algorithm needs to be rerun.
this.windPointsThroughSegments();
}
// If there is any length left, then the destruction is not yet complete. This is a quick way to test this.
return this.firstShapeDefiningPoint === this.lastShapeDefiningPoint;
}
/**
* Reduce the length of the mRNA. This handles both the shape segments and the shape-defining points.
* @param {number} reductionAmount
* @private
*/
reduceLength( reductionAmount ) {
if ( reductionAmount >= this.getLength() ) {
// Reduce length to be zero.
this.lastShapeDefiningPoint = this.firstShapeDefiningPoint;
this.lastShapeDefiningPoint.setNextPoint( null );
this.shapeSegments.length = 0;
}
else {
// Remove the length from the shape segments.
this.segmentBeingDestroyed.advanceAndRemove( reductionAmount, this, this.shapeSegments );
// Remove the length from the shape defining points.
for ( let amountRemoved = 0; amountRemoved < reductionAmount; ) {
if ( this.lastShapeDefiningPoint.getTargetDistanceToPreviousPoint() <= reductionAmount - amountRemoved ) {
// Remove the last point from the list.
amountRemoved += this.lastShapeDefiningPoint.getTargetDistanceToPreviousPoint();
this.lastShapeDefiningPoint = this.lastShapeDefiningPoint.getPreviousPoint();
this.lastShapeDefiningPoint.setNextPoint( null );
}
else {
// Reduce the distance of the last point from the previous point.
this.lastShapeDefiningPoint.setTargetDistanceToPreviousPoint( this.lastShapeDefiningPoint.getTargetDistanceToPreviousPoint() - ( reductionAmount - amountRemoved ) );
amountRemoved = reductionAmount;
}
}
}
}
/**
* @private
*/
updateAttachmentSitePosition() {
if ( this.shapeSegments.length > 0 ) {
const leadingShapeSegment = this.shapeSegments[ 0 ];
this.attachmentSite.positionProperty.set( new Vector2(
this.positionProperty.get().x + leadingShapeSegment.bounds.minX,
this.positionProperty.get().y + leadingShapeSegment.bounds.minY
) );
}
else {
this.attachmentSite.positionProperty.set( this.positionProperty.get() );
}
}
/**
* Create a new version of the protein that should result when this strand of mRNA is translated.
* @returns {Protein}
* @public
*/
getProteinPrototype() {
return this.proteinPrototype;
}
/**
* Get the point in model space where the entrance of the given ribosome's translation channel should be in order to
* be correctly attached to this strand of messenger RNA. This allows the ribosome to "follow" the mRNA if it is
* moving or changing shape.
* @param {Ribosome} ribosome
* @returns {Vector2}
* @public
*/
getRibosomeGenerateInitialPosition3D( ribosome ) {
assert && assert(
this.mapRibosomeToShapeSegment[ ribosome.id ],
'attempt made to get attachment position for unattached ribosome'
);
let generateInitialPosition3D;
const mRnaPosition = this.positionProperty.get();
const segment = this.mapRibosomeToShapeSegment[ ribosome.id ];
let segmentCornerPosition;
if ( this.getPreviousShapeSegment( segment ) === null ) {
// There is no previous segment, which means that the segment to which this ribosome is attached is the leader
// segment. The attachment point is thus the leader length from its rightmost edge.
segmentCornerPosition = segment.getLowerRightCornerPosition();
generateInitialPosition3D = mRnaPosition.plusXY(
segmentCornerPosition.x - GEEConstants.LEADER_LENGTH,
segmentCornerPosition.y
);
}
else {
// The segment has filled up the channel, so calculate the position based on its left edge.
segmentCornerPosition = segment.getUpperLeftCornerPosition();
generateInitialPosition3D = mRnaPosition.plusXY(
segmentCornerPosition.x + ribosome.getTranslationChannelLength(),
segmentCornerPosition.y
);
}
return generateInitialPosition3D;
}
/**
* Release this mRNA from a ribosome. If this is the only ribosome to which the mRNA is connected, the mRNA will
* start wandering.
* @param {Ribosome} ribosome
* @public
*/
releaseFromRibosome( ribosome ) {
delete this.mapRibosomeToShapeSegment[ ribosome.id ];
if ( _.keys( this.mapRibosomeToShapeSegment ).length === 0 ) {
this.mRnaAttachmentStateMachine.allRibosomesDetached();
}
}
/**
* Release this mRNA from the polymerase which is, presumably, transcribing it.
* @public
*/
releaseFromPolymerase() {
this.mRnaAttachmentStateMachine.detach();
}
/**
* This override checks to see if the mRNA is about to be translated and destroyed and, if so, aborts those
* operations. If translation or destruction are in progress, nothing is done, since those can't be stopped once
* they've started.
* @override
* @public
*/
handleGrabbedByUser() {
const attachedOrAttachingMolecule = this.attachmentSite.attachedOrAttachingMoleculeProperty.get();
if ( attachedOrAttachingMolecule instanceof Ribosome ) {
// if a ribosome is moving towards this mRNA strand but translation hasn't started, call off the wedding
if ( !attachedOrAttachingMolecule.isTranslating() ) {
attachedOrAttachingMolecule.cancelTranslation();
this.releaseFromRibosome( attachedOrAttachingMolecule );
this.attachmentStateMachine.forceImmediateUnattachedAndAvailable();
}
}
else if ( attachedOrAttachingMolecule instanceof MessengerRnaDestroyer ) {
// state checking
assert && assert(
this.messengerRnaDestroyer === attachedOrAttachingMolecule,
'something isn\t right - the destroyer for the attachment site doesn\'t match the expected reference'
);
// if an mRNA destroyer is moving towards this mRNA strand but translation hasn't started, call off the wedding
if ( !this.isDestructionInProgress() ) {
attachedOrAttachingMolecule.cancelMessengerRnaDestruction();
this.messengerRnaDestroyer = null;
this.attachmentStateMachine.forceImmediateUnattachedAndAvailable();
}
}
}
/**
* Activate the placement hint(s) as appropriate for the given biomolecule.
* @param {MobileBiomolecule} biomolecule - instance of the type of biomolecule for which any matching hints
* should be activated.
* @public
*/
activateHints( biomolecule ) {
this.ribosomePlacementHint.activateIfMatch( biomolecule );
this.mRnaDestroyerPlacementHint.activateIfMatch( biomolecule );
}
/**
* Deactivate placement hints for all biomolecules
* @public
*/
deactivateAllHints() {
this.ribosomePlacementHint.activeProperty.set( false );
this.mRnaDestroyerPlacementHint.activeProperty.set( false );
}
/**
* Initiate the translation process by setting up the segments as needed. This should only be called after a ribosome
* that was moving to attach with this mRNA arrives at the attachment point.
* @param {Ribosome} ribosome
* @public
*/
initiateTranslation( ribosome ) {
assert && assert( this.mapRibosomeToShapeSegment[ ribosome.id ] ); // State checking.
// Set the capacity of the first segment to the size of the channel through which it will be pulled plus the
// leader length.
const firstShapeSegment = this.shapeSegments[ 0 ];
assert && assert( firstShapeSegment.isFlat() );
firstShapeSegment.setCapacity( ribosome.getTranslationChannelLength() + GEEConstants.LEADER_LENGTH );
}
/**
* Initiate the destruction of this mRNA strand by setting up the segments as needed. This should only be called
* after an mRNA destroyer has attached to the front of the mRNA strand. Once initiated, destruction cannot be stopped.
* @param {MessengerRnaDestroyer} messengerRnaDestroyer
* @public
*/
initiateDestruction( messengerRnaDestroyer ) {
assert && assert( this.messengerRnaDestroyer === messengerRnaDestroyer ); // Shouldn't get this from unattached destroyers.
// Set the capacity of the first segment to the size of the channel through which it will be pulled plus the leader length.
this.segmentBeingDestroyed = this.shapeSegments[ 0 ];
assert && assert( this.segmentBeingDestroyed.isFlat() );
this.segmentBeingDestroyed.setCapacity(
this.messengerRnaDestroyer.getDestructionChannelLength() + GEEConstants.LEADER_LENGTH
);
}
/**
* returns true if destruction has started, false if not - note that destruction must actually have started, and
* the state where an mRNA destroyer is moving towards the mRNA doesn't count
* @private
*/
isDestructionInProgress() {
return this.segmentBeingDestroyed !== null;
}
/**
* Get the proportion of the entire mRNA that has been translated by the given ribosome.
* @param {Ribosome} ribosome
* @returns {number}
* @public
*/
getProportionOfRnaTranslated( ribosome ) {
const translatedLength = this.getLengthOfRnaTranslated( ribosome );
return Math.max( translatedLength / this.getLength(), 0 );
}
/**
* Get the length of the mRNA that has been translated by the given ribosome.
* @param {Ribosome} ribosome
* @returns {number}
* @public
*/
getLengthOfRnaTranslated( ribosome ) {
assert && assert( this.mapRibosomeToShapeSegment[ ribosome.id ] ); // Makes no sense if ribosome isn't attached.
let translatedLength = 0;
const segmentInRibosomeChannel = this.mapRibosomeToShapeSegment[ ribosome.id ];
assert && assert( segmentInRibosomeChannel.isFlat() ); // Make sure things are as we expect.
// Add the length for each segment that precedes this ribosome.
for ( let i = 0; i < this.shapeSegments.length; i++ ) {
const shapeSegment = this.shapeSegments[ i ];
if ( shapeSegment === segmentInRibosomeChannel ) {
break;
}
translatedLength += shapeSegment.getContainedLength();
}
// Add the length for the segment that is inside the translation channel of this ribosome.
translatedLength += segmentInRibosomeChannel.getContainedLength() -
( segmentInRibosomeChannel.getLowerRightCornerPosition().x -
segmentInRibosomeChannel.attachmentSite.positionProperty.get().x );
return translatedLength;
}
/**
* returns true if this messenger RNA is in a state where attachments can occur
* @returns {boolean}
* @private
*/
attachmentAllowed() {
// For an attachment proposal to be considered, the mRNA can't be controlled by the user, too short, or in the
// process of being destroyed.
return !this.userControlledProperty.get() &&
this.getLength() >= MIN_LENGTH_TO_ATTACH &&
this.messengerRnaDestroyer === null;
}
/**
* Consider proposal from ribosome, and, if the proposal is accepted, return the attachment position
* @param {Ribosome} ribosome
* @returns {AttachmentSite}
* @public
*/
considerProposalFromRibosome( ribosome ) {
assert && assert( !this.mapRibosomeToShapeSegment[ ribosome.id ] ); // Shouldn't get redundant proposals from a ribosome.
let returnValue = null;
if ( this.attachmentAllowed() ) {
// See if the attachment site at the leading edge of the mRNA is available and close by.
if ( this.attachmentSite.attachedOrAttachingMoleculeProperty.get() === null &&
this.attachmentSite.positionProperty.get().distance( ribosome.getEntranceOfRnaChannelPosition() ) < RIBOSOME_CONNECTION_DISTANCE ) {
// This attachment site is in range and available.
returnValue = this.attachmentSite;
// Update the attachment state machine.
this.mRnaAttachmentStateMachine.attachedToRibosome();
// Enter this connection in the map.
this.mapRibosomeToShapeSegment[ ribosome.id ] = this.shapeSegments[ 0 ];
}
}
return returnValue;
}
/**
* Consider proposal from mRnaDestroyer and if it can attach return the attachment position
* @param {MessengerRnaDestroyer} messengerRnaDestroyer
* @returns {AttachmentSite}
* @public
*/
considerProposalFromMessengerRnaDestroyer( messengerRnaDestroyer ) {
assert && assert( this.messengerRnaDestroyer !== messengerRnaDestroyer ); // Shouldn't get redundant proposals from same destroyer.
let returnValue = null;
if ( this.attachmentAllowed() ) {
// See if the attachment site at the leading edge of the mRNA is available and close by.
if ( this.attachmentSite.attachedOrAttachingMoleculeProperty.get() === null &&
this.attachmentSite.positionProperty.get().distance( messengerRnaDestroyer.getPosition() ) <
MRNA_DESTROYER_CONNECT_DISTANCE ) {
// This attachment site is in range and available.
returnValue = this.attachmentSite;
// Update the attachment state machine.
this.mRnaAttachmentStateMachine.attachToDestroyer();
// Keep track of the destroyer.
this.messengerRnaDestroyer = messengerRnaDestroyer;
}
}
return returnValue;
}
/**
* Aborts the destruction process, used if the mRNA destroyer was on its way to the mRNA but the user picked up
* once of the two biomolecules before destruction started.
* @public
*/
abortDestruction() {
this.messengerRnaDestroyer = null;
this.attachmentStateMachine.forceImmediateUnattachedAndAvailable();
}
/**
* @override
* @returns {MessengerRnaAttachmentStateMachine}
* @public
*/
createAttachmentStateMachine() {
return new MessengerRnaAttachmentStateMachine( this );
}
/**
* Get the point in model space where the entrance of the given destroyer's translation channel should be in order to
* be correctly attached to this strand of messenger RNA.
* @returns {Vector2}
* @public
*/
getDestroyerGenerateInitialPosition3D() {
// state checking - shouldn't be called before this is set
assert && assert( this.segmentBeingDestroyed !== null );
// the attachment position is at the right most side of the segment minus the leader length
return this.attachmentSite.positionProperty.get();
}
}
geneExpressionEssentials.register( 'MessengerRna', MessengerRna );
export default MessengerRna;
|
phetsims/gene-expression-essentials
|
js/common/model/MessengerRna.js
|
JavaScript
|
gpl-3.0
| 22,291
|
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
/**************************************************************************
* The {@code TagQuery} class.
*
* @author Jonathan A. Henly
**/
public class TagQuery {
// TODO: Remove the line of debugging code following this
private static PrintWriter log;
// TODO: Remove the static block of debugging code following this
static {
try {
log = new PrintWriter("./zout/out_QUERY");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**************************************************************************
*
* @author Jonathan A. Henly
**/
public static class InvalidQueryException extends Exception {
private static final long serialVersionUID = -6002360782575126129L;
public InvalidQueryException(String query, int index) {
super("Parsing of the query: \"" + query + "\" failed at character index: " + index + "\n");
}
}
private static enum QueryType {
CLASS, ID, TAG, TAG_CLASS, TAG_ID
}
private Tag root;
private Stack<Tag> result;
private Stack<Tag> sub;
private Stack<String> instructions;
public TagQuery() {
this.root = null;
this.instructions = null;
this.sub = null;
this.result = new Stack<Tag>();
}
public TagQuery(FileReader file) {
this();
init(file);
}
public TagQuery(URL url) throws IOException {
this();
init(url.openStream());
}
public TagQuery(InputStream stream) {
this();
init(stream);
}
private void init(FileReader file) {
StringBuilder sb = new StringBuilder();
Scanner inFile = new Scanner(file);
while(inFile.hasNextLine()) {
sb.append(inFile.nextLine());
}
inFile.close();
this.root = Tag.parseTags(sb);
}
private void init(InputStream stream) {
StringBuilder sb = new StringBuilder();
Scanner inFile = new Scanner(stream);
while(inFile.hasNextLine()) {
sb.append(inFile.nextLine());
}
inFile.close();
this.root = Tag.parseTags(sb);
}
/**************************************************************************
*
*
*
* @param file -
* @return a reference to this {@code TagQuery} object.
**/
public TagQuery loadSource(FileReader file) {
init(file);
return this;
}
/**************************************************************************
*
*
*
* @param url -
* @return a reference to this {@code TagQuery} object.
* @throws IOException
**/
public TagQuery loadSource(URL url) throws IOException {
init(url.openStream());
return this;
}
/**************************************************************************
*
*
*
* @param stream -
* @return a reference to this {@code TagQuery} object.
* @throws IOException
**/
public TagQuery loadSource(InputStream stream) {
init(stream);
return this;
}
/**************************************************************************
*
*
*
* @param query -
* @return a reference to this object.
* @throws InvalidQueryException
**/
public List<Tag> query(String query) throws InvalidQueryException {
this.instructions = this.buildQuery(query);
this.runInstructions();
return this.getResult();
}
private Stack<String> buildQuery(String query) throws InvalidQueryException {
Stack<String> tasks = new Stack<String>();
String task = "";
char[] command;
boolean space = false;
boolean comma = false;
boolean dot = false;
boolean hash = false;
query = query.trim();
command = query.toCharArray();
for(int i = 0; i < query.length(); i++) {
switch(command[i]) {
case ' ':
if(space || comma) {
continue;
}
space = true;
dot = false;
hash = false;
tasks.push(task);
tasks.push(" ");
task = "";
break;
case ',':
if(comma || (i == query.length() - 1)) {
throw new InvalidQueryException(query, i);
}
comma = true;
space = false;
dot = false;
hash = false;
tasks.push(task);
tasks.push(",");
task = "";
break;
case '.':
if(dot) {
throw new InvalidQueryException(query, i);
}
dot = true;
task += command[i];
break;
case '#':
if(hash) {
throw new InvalidQueryException(query, i);
}
hash = true;
task += command[i];
break;
default :
space = false;
comma = false;
dot = false;
hash = false;
task += command[i];
break;
}
}
if(!task.isEmpty()) {
tasks.push(task);
}
return tasks;
}
private void runInstructions() {
String instruction = "";
int height = 0;
this.sub = new Stack<Tag>();
while(this.instructions.size() > 0) {
instruction = this.instructions.pop();
if(" ".equals(instruction)) {
height += 1;
} else if(",".equals(instruction)) {
height = 0;
this.result.addAll(this.sub);
this.sub = new Stack<Tag>();
} else {
if(height > 0) {
this.runQuery(instruction, height);
} else {
this.runInitQuery(instruction);
}
}
}
this.result.addAll(this.sub);
}
private void runQuery(String q, int height) {
if(q.indexOf('.') == q.indexOf('#')) {
this.find(height, q, QueryType.TAG);
} else if(q.indexOf('#') >= 0) {
if(q.indexOf('#') == 0) {
q = q.substring(1);
this.find(height, q, QueryType.ID);
} else {
this.find(height, q, QueryType.TAG_ID);
}
} else if(q.indexOf('.') >= 0) {
if(q.indexOf('.') == 0) {
q = q.substring(1);
this.find(height, q, QueryType.CLASS);
} else {
this.find(height, q, QueryType.TAG_CLASS);
}
}
}
private void runInitQuery(String q) {
if(q.indexOf('.') == q.indexOf('#')) {
this.findInit(this.root, q, QueryType.TAG);
} else if(q.indexOf('#') >= 0) {
if(q.indexOf('#') == 0) {
q = q.substring(1);
this.findInit(this.root, q, QueryType.ID);
} else {
this.findInit(this.root, q, QueryType.TAG_ID);
}
} else if(q.indexOf('.') >= 0) {
if(q.indexOf('.') == 0) {
q = q.substring(1);
this.findInit(this.root, q, QueryType.CLASS);
} else {
this.findInit(this.root, q, QueryType.TAG_CLASS);
}
}
}
private void find(int height, String q, QueryType qt) {
Stack<Tag> tmp = new Stack<Tag>();
Tag t = null;
Tag p = null;
nullParent:
while(!this.sub.isEmpty()) {
t = this.sub.pop();
p = t;
for(int pCount = 0; pCount < height; pCount++) {
if(p == null) {
continue nullParent;
}
p = p.getParent();
}
switch(qt) {
case TAG:
if(q.equals(p.getName())) {
tmp.push(t);
}
break;
case CLASS:
if(p.hasClass(q)) {
tmp.push(t);
}
break;
case ID:
if(t.hasID(q)) {
tmp.push(t);
}
break;
case TAG_CLASS:
if(p.getName().equals(q.substring(0, q.indexOf('.')))) {
if(p.hasClass(q.substring(q.indexOf('.') + 1))) {
tmp.push(t);
}
}
break;
case TAG_ID:
if(p.getName().equals(q.substring(0, q.indexOf('#')))) {
if(p.hasClass(q.substring(q.indexOf('#') + 1))) {
tmp.push(t);
}
}
break;
}
}
this.sub = tmp;
}
private void findInit(Tag t, String q, QueryType qt) {
if(t.hasChildren()) {
List<Tag> c = t.getChildren();
for(Tag child : c) {
if(!child.isStartTag()) {
continue;
}
this.findInit(child, q, qt);
}
}
switch(qt) {
case TAG:
if(q.equals(t.getName())) {
this.sub.push(t);
}
break;
case CLASS:
if(t.hasClass(q)) {
this.sub.push(t);
}
break;
case ID:
if(t.hasID(q)) {
this.sub.push(t);
}
break;
case TAG_CLASS:
if(t.getName().equals(q.substring(0, q.indexOf('.')))) {
if(t.hasClass(q.substring(q.indexOf('.') + 1))) {
this.sub.push(t);
}
}
break;
case TAG_ID:
if(t.getName().equals(q.substring(0, q.indexOf('#')))) {
if(t.hasClass(q.substring(q.indexOf('#') + 1))) {
this.sub.push(t);
}
}
break;
}
}
public List<Tag> getResult() {
return this.result;
}
public void reset() {
this.result = new Stack<Tag>();
}
}
|
JonathanHenly/HTMLParser
|
src/TagQuery.java
|
Java
|
gpl-3.0
| 8,311
|
#include "qemu-common.h"
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include <signal.h>
#include "tcg.h"
#include "kltrace.h"
#include "tainting/taint_memory.h"
#include "config-target.h"
#include "helper.h" // Taint helper functions, plus I386 IN/OUT helpers
#include "DECAF_callback_common.h"
#include "DECAF_callback_to_QEMU.h"
#include "tcg_track.h"
/* Target-specific metadata buffers are extern'd here so that the taint
IR insertions can update them. */
#if defined(TARGET_I386)
extern uint8_t gen_opc_cc_op[OPC_BUF_SIZE];
#elif defined(TARGET_ARM)
extern uint32_t gen_opc_condexec_bits[OPC_BUF_SIZE];
#endif /* TARGET_I386 */
uint16_t *gen_old_opc_ptr;
TCGArg *gen_old_opparam_ptr;
extern TCGv_ptr cpu_env;
uint32_t block_count = 0; // AWH - Debugging
// Typedef the CPU state struct to make tempidx ld/st cleaner
#if defined(TARGET_I386)
typedef CPUX86State OurCPUState;
#elif defined(TARGET_ARM)
typedef CPUARMState OurCPUState;
#elif defined(TARGET_MIPS)
typedef CPUMIPSState OurCPUState;
#endif /* TARGET_I386/ARM */
// AWH - Declare variables specific to this arch's helper funcs
#define HELPER_SECTION_ONE
#include "helper_arch_check.h"
// AWH - In development
//#define USE_TCG_OPTIMIZATIONS 1
#define LOG_TAINTED_EIP
// AWH - Change these to change taint/pointer rules
#define TAINT_EXPENSIVE_ADDSUB 1
#define TCG_BITWISE_TAINT 1
//#define TAINT_NEW_POINTER 1
//#if defined(LOG_TAINTED_EIP)
#define MAX_TAINT_LOG_TEMPS 10
static TCGArg helper_arg_array[MAX_TAINT_LOG_TEMPS];
static TCGv taint_log_temps[MAX_TAINT_LOG_TEMPS];
static inline void set_con_i32(int index, TCGv arg)
{
TCGv tmp;
#if TCG_TARGET_REG_BITS == 32
tmp = tcg_temp_new_i32();
#else
tmp = tcg_temp_new_i64();
#endif
tcg_gen_mov_i32(tmp, arg);
helper_arg_array[index] = tmp;
}
static inline void set_con_i64(int index, TCGv arg)
{
TCGv tmp;
#if TCG_TARGET_REG_BITS == 32
tmp = tcg_temp_new_i32();
#else
tmp = tcg_temp_new_i64();
#endif
tcg_gen_mov_i64(tmp, arg);
helper_arg_array[index] = tmp;
}
static inline void set_coni_i32(int index, TCGArg arg)
{
TCGv tmp;
#if TCG_TARGET_REG_BITS == 32
tmp = tcg_temp_new_i32();
#else
tmp = tcg_temp_new_i64();
#endif
tcg_gen_movi_i32(tmp, arg);
helper_arg_array[index] = tmp;
}
static inline void set_coni_i64(int index, TCGArg arg)
{
TCGv tmp;
#if TCG_TARGET_REG_BITS == 32
tmp = tcg_temp_new_i32();
#else
tmp = tcg_temp_new_i64();
#endif
tcg_gen_movi_i64(tmp, arg);
helper_arg_array[index] = tmp;
}
//#endif
// Exposed externs
TCGv shadow_arg[TCG_MAX_TEMPS];
TCGv tempidx, tempidx2;
// Extern in translate.c
extern TCGv_ptr cpu_env;
/*static*/ TCGv find_shadow_arg(TCGv arg)
{
if (arg < tcg_ctx.nb_globals)
return shadow_arg[arg];
/* Check if this temp is allocated in the context */
if (!tcg_ctx.temps[arg].temp_allocated)
return 0;
if (!tcg_ctx.temps[shadow_arg[arg]].temp_allocated) {
if (tcg_ctx.temps[arg].temp_local)
#if TCG_TARGET_REG_BITS == 32
shadow_arg[arg] = tcg_temp_local_new_i32();
else
shadow_arg[arg] = tcg_temp_new_i32();
#else
shadow_arg[arg] = tcg_temp_local_new_i64();
else
shadow_arg[arg] = tcg_temp_new_i64();
#endif
// CLEAR TAINT ON CREATION
tcg_ctx.temps[shadow_arg[arg]].val = 0;
}
return shadow_arg[arg];
}
void clean_shadow_arg(void)
{
bzero(&shadow_arg[tcg_ctx.nb_globals], sizeof(shadow_arg[0]) * (TCG_MAX_TEMPS - tcg_ctx.nb_globals));
}
/* AWH - Dummy generic taint rule to make sure we have the proper
shadow taint temps in place */
static void DUMMY_TAINT(int nb_oargs, int nb_args)
{
TCGv arg0, orig0;
int i = 0;
for (i = 0; i < nb_oargs; i++)
{
arg0 = find_shadow_arg(gen_opparam_ptr[(-1 * nb_args) + i]);
orig0 = gen_opparam_ptr[(-1 * nb_args) + i];
if (arg0) {
#if TCG_TARGET_REG_BITS == 32
tcg_gen_movi_i32(arg0, 0);
#else
tcg_gen_movi_i64(arg0, 0);
#endif
}
}
}
static inline check_mod_addr(TCGArg addr, int label) {
/* if(addr < mod_addr) goto label1; */
tcg_gen_brcondi_tl(TCG_COND_LTU, addr, mod_addr, label);
/* if(addr > mod_addr + mod_size) goto label1; */
tcg_gen_brcondi_tl(TCG_COND_GTU, addr, mod_addr + mod_size, label);
}
static inline mark_tb_head(TCGArg addr, TCGArg size, int cnst)
{
int label = gen_new_label();
//check_mod_addr(addr, label);
if (cnst)
set_coni_i64(0, addr);
else
set_con_i64(0, addr);
set_coni_i64(1, size);
set_coni_i64(2, IS_START);
tcg_gen_helperN(add_change, 0, 0,
TCG_CALL_DUMMY_ARG, 3, helper_arg_array);
/* label1: */
//gen_set_label(label);
}
static inline access_register_common_arg(size_t mode, uint8_t w, int size,
TCGArg base, TCGArg offset, TCGv value)
{
TCGArg size_a;
size_a = size;
/* FIXME: */
if (offset == 0x80 && w == 1) {
/* Jump to next instruction */
//mark_tb_head(value, size, 0);
}
// else {
// if (mode == 32) {
// set_con_i32(0, base);
// set_coni_i32(1, offset);
// set_con_i32(2, value);
// set_coni_i32(3, size_a);
// }
// else if (mode == 64) {
// set_con_i64(0, base);
// set_coni_i64(1, offset);
// set_con_i64(2, value);
// set_coni_i64(3, size_a);
// }
// if (w == 1) {
// tcg_gen_helperN(helper_DECAF_invoke_register_write_callback, 0, 0,
// TCG_CALL_DUMMY_ARG, 4, helper_arg_array);
// }
// else {
// tcg_gen_helperN(helper_DECAF_invoke_register_read_callback, 0, 0,
// TCG_CALL_DUMMY_ARG, 4, helper_arg_array);
// }
// }
}
static inline access_register_common(size_t mode, uint8_t w, int size) {
access_register_common_arg(mode, w, size, gen_opparam_ptr[-2], gen_opparam_ptr[-1],gen_opparam_ptr[-3]);
}
static inline read_register_32(int size) {
access_register_common(32, 0, size);
}
static inline write_register_32(int size) {
access_register_common(32, 1, size);
}
static inline read_register_64(int size) {
access_register_common(64, 0, size);
}
static inline write_register_64(int size) {
access_register_common(64, 1, size);
}
static void gen_kltrace_mov(TCGContext *ctx, TCGArg *args) {
TCGTemp *ts, *ots;
TCGv value;
ots = &ctx->temps[args[0]];
ts = &ctx->temps[args[1]];
if (ts->val_type == TEMP_VAL_MEM) {
#if TCG_TARGET_REG_BITS == 32
value = tcg_temp_new_i32();
#else
value = tcg_temp_new_i64();
#endif
tcg_gen_ld_tl(value, cpu_env, ts->mem_offset);
if (ts->type == TCG_TYPE_I32)
access_register_common_arg(32, 0, 32, ts->mem_reg, ts->mem_offset, value);
if (ts->type == TCG_TYPE_I64)
access_register_common_arg(64, 0, 64, ts->mem_reg, ts->mem_offset, value);
}
}
static void gen_kltrace_op(TCGContext *ctx, TCGArg *args, TCGOpDef *def) {
int i,k;
TCGArg arg;
TCGTemp *ts;
TCGv value;
int nb_oargs = def->nb_oargs;
int nb_iargs = def->nb_iargs;
for(k = 0; k < nb_iargs; k++) {
i = def->sorted_args[nb_oargs + k];
arg = args[i];
ts = &ctx->temps[arg];
if (ts->val_type == TEMP_VAL_MEM) {
#if TCG_TARGET_REG_BITS == 32
value = tcg_temp_new_i32();
#else
value = tcg_temp_new_i64();
#endif
tcg_gen_ld_tl(value, cpu_env, ts->mem_offset);
if (ts->type == TCG_TYPE_I32) {
access_register_common_arg(32, 0, 32, ts->mem_reg, ts->mem_offset, value);
}
if (ts->type == TCG_TYPE_I64) {
access_register_common_arg(64, 0, 64, ts->mem_reg, ts->mem_offset, value);
}
}
}
}
static short tb_head = 1;
static inline int gen_kltrace_insn(TCGContext *ctx, TranslationBlock *tb, int search_pc)
{
/* Opcode and parameter buffers */
static uint16_t gen_old_opc_buf[OPC_BUF_SIZE];
static TCGArg gen_old_opparam_buf[OPPARAM_BUF_SIZE];
/* Metadata buffers for "search_pc" TBs */
static target_ulong gen_old_opc_pc[OPC_BUF_SIZE];
static uint8_t gen_old_opc_instr_start[OPC_BUF_SIZE];
static uint16_t gen_old_opc_icount[OPC_BUF_SIZE];
#if defined(TARGET_I386)
static uint8_t gen_old_opc_cc_op[OPC_BUF_SIZE];
#elif defined(TARGET_ARM)
static uint32_t gen_old_opc_condexec_bits[OPC_BUF_SIZE];
#endif /* TARGET check */
int metabuffer_offset = 0;
int nb_opc = gen_opc_ptr - gen_old_opc_ptr;
int return_lj = -1;
int nb_args=0;
int opc_index=0, opparam_index=0;
int i=0/*, x=0*/;
uint16_t opc=0;
int nb_oargs=0, nb_iargs=0, nb_cargs=0;
TCGv arg0, arg1, arg2, arg3, arg4, arg5;
TCGv t0, t1, t2, t3, t4, t_zero;
#if defined(TARGET_I386)
TCGv arg6, t5, t6;
#endif /* TARGET check */
TCGv orig0, orig1, orig2, orig3, orig4, orig5;
TCGArg *args;
TCGOpDef *def;
/* Copy all of the existing ops/parms into a new buffer to back them up. */
memcpy(gen_old_opc_buf, gen_old_opc_ptr, sizeof(uint16_t)*(nb_opc));
memcpy(gen_old_opparam_buf, gen_old_opparam_ptr, sizeof(TCGArg)* (gen_opparam_ptr - gen_old_opparam_ptr));
/* If we're inserting taint IR into a searchable TB, copy all of the
existing metadata for the TB into a new buffer to back them up. */
if (search_pc) {
/* Figure out where we're starting in the metabuffers */
metabuffer_offset = gen_old_opc_ptr - gen_opc_buf;
/* Make our backup copies of the metadata buffers */
memcpy(gen_old_opc_pc, (gen_opc_pc + metabuffer_offset), sizeof(target_ulong)*(nb_opc));
memcpy(gen_old_opc_instr_start, (gen_opc_instr_start + metabuffer_offset), sizeof(uint8_t)*(nb_opc));
memcpy(gen_old_opc_icount, (gen_opc_icount + metabuffer_offset), sizeof(uint16_t)*(nb_opc));
#if defined(TARGET_I386)
memcpy(gen_old_opc_cc_op, (gen_opc_cc_op + metabuffer_offset), sizeof(uint8_t)*(nb_opc));
#elif defined(TARGET_ARM)
memcpy(gen_old_opc_condexec_bits, (gen_opc_condexec_bits + metabuffer_offset), sizeof(uint32_t)*(nb_opc));
#endif /* TARGET check */
memset(gen_opc_instr_start + metabuffer_offset, 0, sizeof(uint8_t) * (OPC_BUF_SIZE - metabuffer_offset));
}
/* Reset the ops/parms buffers */
gen_opc_ptr = gen_old_opc_ptr;
gen_opparam_ptr = gen_old_opparam_ptr;
//#if defined(LOG_TAINTED_EIP)
/* Allocate our temps for logging taint */
for (i=0; i < MAX_TAINT_LOG_TEMPS; i++)
#if TCG_TARGET_REG_BITS == 32
taint_log_temps[i] = tcg_temp_new_i32();
#else
taint_log_temps[i] = tcg_temp_new_i64();
#endif /* TCG_TARGET_REG_BITS */
//#endif /* LOG_ check */
/* Copy and instrument the opcodes that need taint tracking */
while(opc_index < nb_opc) {
/* If needed, copy all of the appropriate metadata */
if (search_pc && (gen_old_opc_instr_start[opc_index] == 1)) {
return_lj = gen_opc_ptr - gen_opc_buf;
gen_opc_pc[return_lj] = gen_old_opc_pc[opc_index];
gen_opc_instr_start[return_lj] = 1;
gen_opc_icount[return_lj] = gen_old_opc_icount[opc_index];
#if defined(TARGET_I386)
gen_opc_cc_op[return_lj] = gen_old_opc_cc_op[opc_index];
#elif defined(TARGET_ARM)
gen_opc_condexec_bits[return_lj] = gen_old_opc_condexec_bits[opc_index];
#endif /* TARGET check */
}
/* Copy the opcode to be instrumented */
opc = gen_old_opc_buf[opc_index];
def = &tcg_op_defs[opc];
/* Determine the number and type of arguments for the opcode */
if (opc == INDEX_op_call) {
TCGArg arg = gen_old_opparam_buf[opparam_index];
nb_oargs = arg >> 16;
nb_iargs = arg & 0xffff;
nb_cargs = tcg_op_defs[opc].nb_cargs;
nb_args = nb_oargs + nb_iargs + nb_cargs + 1;
} else if (opc == INDEX_op_nopn) {
nb_args = nb_cargs = gen_old_opparam_buf[opparam_index];
nb_oargs = nb_iargs = 0;
} else {
nb_args = tcg_op_defs[opc].nb_args;
nb_oargs = tcg_op_defs[opc].nb_oargs;
nb_iargs = tcg_op_defs[opc].nb_iargs;
nb_cargs = tcg_op_defs[opc].nb_cargs;
}
args = (TCGArg*)malloc(sizeof(TCGArg) * nb_args);
for(i=0; i<nb_args; i++)
args[i] = gen_old_opparam_buf[opparam_index + i];
/* Instrument indicator of head address per TB.
This operation let kldbg know current address. */
if (tb_head) {
mark_tb_head(tb->pc, tb->size, 1);
tb_head = 0;
}
// /* ### Instrument before operations ### */
// switch (opc) {
// /* QEMU-specific operations. */
// case INDEX_op_mov_i32:
// case INDEX_op_mov_i64:
// gen_kltrace_mov(ctx,args);
// break;
// case INDEX_op_ld8u_i32:
// case INDEX_op_ld8s_i32:
// case INDEX_op_ld16u_i32:
// case INDEX_op_ld16s_i32:
// case INDEX_op_ld_i32:
// case INDEX_op_ld8u_i64:
// case INDEX_op_ld8s_i64:
// case INDEX_op_ld16u_i64:
// case INDEX_op_ld16s_i64:
// case INDEX_op_ld32u_i64:
// case INDEX_op_ld32s_i64:
// case INDEX_op_ld_i64:
// case INDEX_op_st8_i32:
// case INDEX_op_st16_i32:
// case INDEX_op_st_i32:
// case INDEX_op_st8_i64:
// case INDEX_op_st16_i64:
// case INDEX_op_st32_i64:
// case INDEX_op_st_i64:
// break;
// default:
// gen_kltrace_op(ctx, args, def);
// break;
// }
*(gen_opc_ptr++) = gen_old_opc_buf[opc_index++];
/* Copy the appropriate number of arguments for the opcode */
for(i=0; i<nb_args; i++)
*(gen_opparam_ptr++) = gen_old_opparam_buf[opparam_index++];
/* Copy the current gen_opc_ptr. After we instrument this IR,
we compare the copy of gen_opc_ptr against its current value.
If it has increased, that means we inserted additional IR and,
if this is a "search_pc" TB, that means we know how many extra
entries we need to put in the metadata buffers to keep
everything in sync. */
/* ### Instrument after operations ### */
gen_old_opc_ptr = gen_opc_ptr;
// switch (opc) {
// /* QEMU-specific operations. */
// case INDEX_op_ld8u_i32:
// case INDEX_op_ld8s_i32:
// read_register_32(8);
// case INDEX_op_ld16u_i32:
// case INDEX_op_ld16s_i32:
// read_register_32(16);
// case INDEX_op_ld_i32:
// read_register_32(32);
// break;
// case INDEX_op_ld8u_i64:
// case INDEX_op_ld8s_i64:
// read_register_64(8);
// case INDEX_op_ld16u_i64:
// case INDEX_op_ld16s_i64:
// read_register_64(16);
// case INDEX_op_ld32u_i64:
// case INDEX_op_ld32s_i64:
// read_register_64(32);
// case INDEX_op_ld_i64:
// read_register_64(64);
// break;
// case INDEX_op_st8_i32:
// write_register_32(8);
// case INDEX_op_st16_i32:
// write_register_32(16);
// case INDEX_op_st_i32:
// write_register_32(32);
// break;
// case INDEX_op_st8_i64:
// write_register_64(8);
// case INDEX_op_st16_i64:
// write_register_64(16);
// case INDEX_op_st32_i64:
// write_register_64(32);
// case INDEX_op_st_i64:
// write_register_64(64);
// break;
// }
}
free(args);
return return_lj;
}
int kltrace(TCGContext *ctx, TranslationBlock *tb, int search_pc) {
printf("kltrace\n");
int retVal = 0;
block_count++;
retVal = gen_kltrace_insn(ctx, tb, search_pc);
return retVal;
}
static inline int gen_taintcheck_insn(int search_pc)
{
#ifdef CONFIG_TCG_TAINT
/* Opcode and parameter buffers */
static uint16_t gen_old_opc_buf[OPC_BUF_SIZE];
static TCGArg gen_old_opparam_buf[OPPARAM_BUF_SIZE];
/* Metadata buffers for "search_pc" TBs */
static target_ulong gen_old_opc_pc[OPC_BUF_SIZE];
static uint8_t gen_old_opc_instr_start[OPC_BUF_SIZE];
static uint16_t gen_old_opc_icount[OPC_BUF_SIZE];
#if defined(TARGET_I386)
static uint8_t gen_old_opc_cc_op[OPC_BUF_SIZE];
#if 0 // AWH - in helper_i386_check.h
/* For INB, INW, INL helper functions */
int in_helper_func = 0;
/* For OUTB, OUTW, OUTL helper functions */
int out_helper_func = 0;
/* For CMPXCHG helper function */
int cmpxchg_helper_func = 0;
#endif // AWH
#elif defined(TARGET_ARM)
static uint32_t gen_old_opc_condexec_bits[OPC_BUF_SIZE];
#endif /* TARGET check */
int metabuffer_offset = 0;
int nb_opc = gen_opc_ptr - gen_old_opc_ptr;
int return_lj = -1;
int nb_args=0;
int opc_index=0, opparam_index=0;
int i=0/*, x=0*/;
uint16_t opc=0;
int nb_oargs=0, nb_iargs=0, nb_cargs=0;
TCGv arg0, arg1, arg2, arg3, arg4, arg5;
TCGv t0, t1, t2, t3, t4, t_zero;
#if defined(TARGET_I386)
TCGv arg6, t5, t6;
#endif /* TARGET check */
TCGv orig0, orig1, orig2, orig3, orig4, orig5;
/* Copy all of the existing ops/parms into a new buffer to back them up. */
memcpy(gen_old_opc_buf, gen_old_opc_ptr, sizeof(uint16_t)*(nb_opc));
memcpy(gen_old_opparam_buf, gen_old_opparam_ptr, sizeof(TCGArg)* (gen_opparam_ptr - gen_old_opparam_ptr));
/* If we're inserting taint IR into a searchable TB, copy all of the
existing metadata for the TB into a new buffer to back them up. */
if (search_pc) {
/* Figure out where we're starting in the metabuffers */
metabuffer_offset = gen_old_opc_ptr - gen_opc_buf;
/* Make our backup copies of the metadata buffers */
memcpy(gen_old_opc_pc, (gen_opc_pc + metabuffer_offset), sizeof(target_ulong)*(nb_opc));
memcpy(gen_old_opc_instr_start, (gen_opc_instr_start + metabuffer_offset), sizeof(uint8_t)*(nb_opc));
memcpy(gen_old_opc_icount, (gen_opc_icount + metabuffer_offset), sizeof(uint16_t)*(nb_opc));
#if defined(TARGET_I386)
memcpy(gen_old_opc_cc_op, (gen_opc_cc_op + metabuffer_offset), sizeof(uint8_t)*(nb_opc));
#elif defined(TARGET_ARM)
memcpy(gen_old_opc_condexec_bits, (gen_opc_condexec_bits + metabuffer_offset), sizeof(uint32_t)*(nb_opc));
#endif /* TARGET check */
memset(gen_opc_instr_start + metabuffer_offset, 0, sizeof(uint8_t) * (OPC_BUF_SIZE - metabuffer_offset));
}
/* Reset the ops/parms buffers */
gen_opc_ptr = gen_old_opc_ptr;
gen_opparam_ptr = gen_old_opparam_ptr;
#if defined(LOG_TAINTED_EIP)
/* Allocate our temps for logging taint */
for (i=0; i < MAX_TAINT_LOG_TEMPS; i++)
#if TCG_TARGET_REG_BITS == 32
taint_log_temps[i] = tcg_temp_new_i32();
#else
taint_log_temps[i] = tcg_temp_new_i64();
#endif /* TCG_TARGET_REG_BITS */
#endif /* LOG_ check */
/* Copy and instrument the opcodes that need taint tracking */
while(opc_index < nb_opc) {
/* If needed, copy all of the appropriate metadata */
if (search_pc && (gen_old_opc_instr_start[opc_index] == 1)) {
return_lj = gen_opc_ptr - gen_opc_buf;
gen_opc_pc[return_lj] = gen_old_opc_pc[opc_index];
gen_opc_instr_start[return_lj] = 1;
gen_opc_icount[return_lj] = gen_old_opc_icount[opc_index];
#if defined(TARGET_I386)
gen_opc_cc_op[return_lj] = gen_old_opc_cc_op[opc_index];
#elif defined(TARGET_ARM)
gen_opc_condexec_bits[return_lj] = gen_old_opc_condexec_bits[opc_index];
#endif /* TARGET check */
}
/* Copy the opcode to be instrumented */
opc = *(gen_opc_ptr++) = gen_old_opc_buf[opc_index++];
/* Determine the number and type of arguments for the opcode */
if (opc == INDEX_op_call) {
TCGArg arg = gen_old_opparam_buf[opparam_index];
nb_oargs = arg >> 16;
nb_iargs = arg & 0xffff;
nb_cargs = tcg_op_defs[opc].nb_cargs;
nb_args = nb_oargs + nb_iargs + nb_cargs + 1;
} else if (opc == INDEX_op_nopn) {
nb_args = nb_cargs = gen_old_opparam_buf[opparam_index];
nb_oargs = nb_iargs = 0;
} else {
nb_args = tcg_op_defs[opc].nb_args;
nb_oargs = tcg_op_defs[opc].nb_oargs;
nb_iargs = tcg_op_defs[opc].nb_iargs;
nb_cargs = tcg_op_defs[opc].nb_cargs;
}
/* Copy the appropriate number of arguments for the opcode */
for(i=0; i<nb_args; i++)
*(gen_opparam_ptr++) = gen_old_opparam_buf[opparam_index++];
/* Copy the current gen_opc_ptr. After we instrument this IR,
we compare the copy of gen_opc_ptr against its current value.
If it has increased, that means we inserted additional IR and,
if this is a "search_pc" TB, that means we know how many extra
entries we need to put in the metadata buffers to keep
everything in sync. */
gen_old_opc_ptr = gen_opc_ptr;
switch(opc)
{
/* The following opcodes propagate no taint */
case INDEX_op_end:
case INDEX_op_nop:
case INDEX_op_nop1:
case INDEX_op_nop2:
case INDEX_op_nop3:
case INDEX_op_nopn:
case INDEX_op_set_label:
case INDEX_op_debug_insn_start:
case INDEX_op_goto_tb:
case INDEX_op_exit_tb:
case INDEX_op_jmp:
case INDEX_op_br:
case INDEX_op_brcond_i32:
#if (TCG_TARGET_REG_BITS == 32)
case INDEX_op_brcond2_i32:
#endif /* TCG_TARGET_REG_BITS */
case INDEX_op_brcond_i64:
break;
case INDEX_op_discard: // Remove associated shadow reg
orig0 = gen_opparam_ptr[-1];
arg0 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg0) {
tcg_gen_discard_tl(arg0);
}
break;
case INDEX_op_call: // Always bit taint
// Call is a bit different, because it has a constant arg
// that comes before the input args (if any). That constant
// says how many arguments follow, since the Call op has a
// variable number of arguments
// [OP][# of args breakdown(const)][arg0(I/O][arg1(I/O)]...
// [argN(I)][# of args (const)]
#define HELPER_SECTION_THREE
#include "helper_arch_check.h"
for (i=0; i < nb_oargs; i++) {
arg0 = find_shadow_arg(gen_opparam_ptr[
(-1 * nb_args) /* Position of first argument in opcode stream */
+ 1 /* Skip first argument (which has # of arguments breakdown) */
+ i /* Skip to the output parm that we are interested in */
]);
if (arg0) {
orig0 = gen_opparam_ptr[(-1 * nb_args) + 1 + i];
// Check if this is a call to a helper function.
// Section 4: Handle tempidx
#define HELPER_SECTION_FOUR
#include "helper_arch_check.h"
tcg_gen_movi_i32(arg0, 0);
}
}
// Section 5: Handle any CPU reg cleaning and helper-specific logic
#define HELPER_SECTION_FIVE
#include "helper_arch_check.h"
break;
case INDEX_op_deposit_i32: // Always bitwise taint
arg0 = find_shadow_arg(gen_opparam_ptr[-5]); // Output
if (arg0) {
int pos, len; // Constant parameters
arg1 = find_shadow_arg(gen_opparam_ptr[-4]); // Input1
arg2 = find_shadow_arg(gen_opparam_ptr[-3]); // Input2
/* Store opcode parms */
orig0 = gen_opparam_ptr[-5];
orig1 = gen_opparam_ptr[-4];
orig2 = gen_opparam_ptr[-3];
pos = gen_opparam_ptr[-2]; // Position of mask
len = gen_opparam_ptr[-1]; // Length of mask
/* Rewind the instruction stream */
gen_opparam_ptr -= 5;
gen_opc_ptr--;
/* Insert taint IR */
// Handle special 32-bit transfer case (copy arg2 taint)
if (len == 32)
tcg_gen_mov_i32(arg0, arg2);
// Handle special 0-bit transfer case (copy arg1 taint)
else if (len == 0)
tcg_gen_mov_i32(arg0, arg1);
// Handle general case
else
tcg_gen_deposit_tl(arg0, arg1, arg2, pos, len);
/* Reinsert the original IR */
tcg_gen_deposit_i32(orig0, orig1, orig2, pos, len);
}
break;
#if TCG_TARGET_REG_BITS == 32
case INDEX_op_setcond2_i32: // All-Around: UifU64() w/ mkPCastTo()
arg0 = find_shadow_arg(gen_opparam_ptr[-6]); // Output
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-5]); // Input1 low
arg2 = find_shadow_arg(gen_opparam_ptr[-4]); // Input1 high
arg3 = find_shadow_arg(gen_opparam_ptr[-3]); // Input2 low
arg4 = find_shadow_arg(gen_opparam_ptr[-2]); // Input2 high
/* Store opcode parms */
orig0 = gen_opparam_ptr[-6];
orig1 = gen_opparam_ptr[-5];
orig2 = gen_opparam_ptr[-4];
orig3 = gen_opparam_ptr[-3];
orig4 = gen_opparam_ptr[-2];
orig5 = gen_opparam_ptr[-1];
/* Rewind the instruction stream */
gen_opparam_ptr -= 6;
gen_opc_ptr--;
/* Insert taint IR */
// Combine high/low taint of Input 1 into t2
t2 = tcg_temp_new_i32();
if (arg1 && arg2)
tcg_gen_or_i32(t2, arg1, arg2);
else if (arg1)
tcg_gen_mov_i32(t2, arg1);
else if (arg2)
tcg_gen_mov_i32(t2, arg2);
else
tcg_gen_movi_i32(t2, 0);
// Combine high/low taint of Input 2 into t3
t3 = tcg_temp_new_i32();
if (arg3 && arg4)
tcg_gen_or_i32(t3, arg3, arg4);
else if (arg3)
tcg_gen_mov_i32(t3, arg3);
else if (arg4)
tcg_gen_mov_i32(t3, arg4);
else
tcg_gen_movi_i32(t3, 0);
// Determine if there is any taint
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new_i32();
tcg_gen_or_i32(t0, t2, t3);
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t2, t0, t_zero); // Reuse t2
tcg_gen_neg_i32(arg0, t2);
/* Reinsert original opcode */
tcg_gen_op6i_i32(INDEX_op_setcond2_i32, orig0, orig1, orig2, orig3, orig4, orig5);
}
break;
#endif /* TCG_TARGET_REG_BITS */
case INDEX_op_movi_i32: // Always bit taint
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
#ifdef TARGET_I386
#define HELPER_SECTION_TWO
#include "helper_i386_check.h"
#if 0 // AWH
/* Check if the constant is a helper function for IN* opcodes */
if ( (gen_opparam_ptr[-1] == (tcg_target_ulong)helper_inb) ||
(gen_opparam_ptr[-1] == (tcg_target_ulong)helper_inw) ||
(gen_opparam_ptr[-1] == (tcg_target_ulong)helper_inl) )
{
in_helper_func = 1;
//fprintf(stderr, "tcg_taint.c: movi_i32 in helper func\n");
}
/* Check if the constant is a helper function for OUT* opcodes */
else if ( (gen_opparam_ptr[-1] == (tcg_target_ulong)helper_outb) ||
(gen_opparam_ptr[-1] == (tcg_target_ulong)helper_outw) ||
(gen_opparam_ptr[-1] == (tcg_target_ulong)helper_outl) )
{
out_helper_func = 1;
//fprintf(stderr, "tcg_taint.c: movi_i32 out helper func\n");
}
/* Check if the constant is a helper function for CMPXCHG */
else if (gen_opparam_ptr[-1] == (tcg_target_ulong)helper_DECAF_taint_cmpxchg)
{
cmpxchg_helper_func = 1;
}
#endif
#endif /* TARGET_I386 */
/* Store opcode parms */
orig0 = gen_opparam_ptr[-2];
orig1 = gen_opparam_ptr[-1];
/* Rewind the instruction stream */
gen_opparam_ptr -= 2;
gen_opc_ptr--;
/* Insert taint propagation */
tcg_gen_movi_i32(arg0, 0);
/* Reinsert original opcode */
tcg_gen_movi_i32(orig0, orig1);
}
break;
case INDEX_op_mov_i32: // Always bit taint
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg0) {
/* Store opcode parms */
orig0 = gen_opparam_ptr[-2];
orig1 = gen_opparam_ptr[-1];
/* Rewind the instruction stream */
gen_opparam_ptr -= 2;
gen_opc_ptr--;
/* Insert taint propagation */
tcg_gen_mov_i32(arg0, arg1);
/* Reinsert original opcode */
tcg_gen_mov_i32(orig0, orig1);
}
break;
/* Load/store operations (32 bit). */
/* MemCheck: mkLazyN() (Just load/store taint from/to memory) */
case INDEX_op_qemu_ld8u:
case INDEX_op_qemu_ld8s:
case INDEX_op_qemu_ld16u:
case INDEX_op_qemu_ld16s:
#if TCG_TARGET_REG_BITS == 64
case INDEX_op_qemu_ld32u:
case INDEX_op_qemu_ld32s:
#endif /* TCG_TARGET_REG_BITS == 64 */
case INDEX_op_qemu_ld32:
// TARGET_REG_BITS = 64 OR (TARGET_REG_BITS = 32, TARGET_LONG_BITS = 32)
if (nb_iargs == 1) arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
// TARGET_REG_BITS = 32, TARGET_LONG_BITS = 64
else tcg_abort(); // Not supported
if (arg0) {
/* Patch qemu_ld* opcode into taint_qemu_ld* */
gen_opc_ptr[-1] += (INDEX_op_taint_qemu_ld8u - INDEX_op_qemu_ld8u);
orig0 = gen_opparam_ptr[-3];
/* Are we doing pointer tainting? */
if (taint_load_pointers_enabled) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
// int addr = gen_opparam_ptr[-2];
if (arg1) {
#if (TCG_TARGET_REG_BITS == 64)
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
t3 = tcg_temp_new_i64();
/* Load taint from tempidx */
tcg_gen_ld32u_tl(t3, cpu_env, offsetof(OurCPUState,tempidx));
#ifndef TAINT_NEW_POINTER //more selective pointer tainting
/* Check for pointer taint */
t_zero = tcg_temp_new_i64();
tcg_gen_movi_i64(t_zero, 0);
tcg_gen_setcond_i64(TCG_COND_NE, t2, arg1, t_zero);
#else
t4 = tcg_temp_new_i64();
tcg_gen_movi_i64(t2, 0xffff0000);
tcg_gen_and_i64(t0, arg1, t2);//t0 = H_taint
tcg_gen_movi_i64(t2, 0);
tcg_gen_setcond_i64(TCG_COND_EQ, t1, t0, t2); //t1=(H_taint==0) cond1
tcg_gen_setcond_i64(TCG_COND_NE, t4, arg1, t2); //t4=(P_taint!=0) cond2
tcg_gen_and_i64(t2, t1, t4); //t2 = cond1 & cond2
#endif
tcg_gen_neg_i64(t0, t2);
/* Combine pointer and tempidx taint */
tcg_gen_or_i64(arg0, t0, t3);
#else
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
t3 = tcg_temp_new_i32();
/* Load taint from tempidx */
tcg_gen_ld_i32(t3, cpu_env, offsetof(OurCPUState,tempidx));
/* Check for pointer taint */
#ifndef TAINT_NEW_POINTER
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t2, arg1, t_zero);
#else
t4 = tcg_temp_new_i32();
tcg_gen_movi_i32(t2, 0xffff0000); //??
tcg_gen_and_i32(t0, arg1, t2);//t0 = H_taint
tcg_gen_movi_i32(t2, 0);
tcg_gen_setcond_i32(TCG_COND_EQ, t1, t0, t2); //t1=(H_taint==0) cond1
tcg_gen_setcond_i32(TCG_COND_NE, t4, arg1, t2); //t4=(P_taint!=0) cond2
tcg_gen_and_i32(t2, t1, t4); //t2 = cond1 & cond2
#endif
tcg_gen_neg_i32(t0, t2);
/* Combine pointer and tempidx taint */
tcg_gen_or_i32(arg0, t0, t3);
#endif /* TARGET_REG_BITS */
} else
/* Patch in opcode to load taint from tempidx */
tcg_gen_ld_i32(arg0, cpu_env, offsetof(OurCPUState,tempidx));
} else
/* Patch in opcode to load taint from tempidx */
tcg_gen_ld_i32(arg0, cpu_env, offsetof(OurCPUState,tempidx));
}
break;
case INDEX_op_qemu_ld64:
#if 1 // AWH - FIXME: 64-bit memory ops may cause corruption
DUMMY_TAINT(nb_oargs, nb_args);
#else
// TARGET_REG_BITS = 32, TARGET_LONG_BITS = 32
if ((nb_oargs == 2) && (nb_iargs == 1)) {
arg0 = find_shadow_arg(gen_opparam_ptr[-4]); // Taint of low DWORD
arg1 = find_shadow_arg(gen_opparam_ptr[-3]); // Taint of hi DWORD
if (arg0 || arg1) {
gen_opc_ptr[-1] += (INDEX_op_taint_qemu_ld8u - INDEX_op_qemu_ld8u);
if (taint_load_pointers_enabled) {
arg2 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg2) {
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
t3 = tcg_temp_new_i32();
/* Load taint from tempidx */
tcg_gen_ld_i32(t2, cpu_env, offsetof(OurCPUState,tempidx));
tcg_gen_ld_i32(t3, cpu_env, offsetof(OurCPUState, tempidx2));
/* Check for pointer taint */
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t1, arg2, t_zero);
tcg_gen_neg_i32(t0, t1);
/* Combine pointer and tempidx taint */
if (arg0)
tcg_gen_or_i32(arg0, t0, t2);
if (arg1)
tcg_gen_or_i32(arg1, t0, t3);
} else {
/* Patch in opcode to load taint from tempidx */
if (arg0)
tcg_gen_ld_i32(arg0, cpu_env, offsetof(OurCPUState,tempidx));
if (arg1)
tcg_gen_ld_i32(arg1, cpu_env, offsetof(OurCPUState,tempidx2));
}
} /* taint_pointers_enabled */
else {
/* Patch in opcode to load taint from tempidx */
if (arg0)
tcg_gen_ld32u_tl(arg0, cpu_env, offsetof(OurCPUState,tempidx));
if (arg1)
tcg_gen_ld32u_tl(arg1, cpu_env, offsetof(OurCPUState,tempidx2));
} /* taint_pointers_enabled */
}
// TARGET_REG_BITS = 64, TARGET_LONG_BITS = 64
} else if ((nb_oargs ==1) && (nb_iargs == 1)) {
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
gen_opc_ptr[-1] += (INDEX_op_taint_qemu_ld8u - INDEX_op_qemu_ld8u);
if (taint_load_pointers_enabled) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg1) {
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
t3 = tcg_temp_new_i64();
/* Load taint from tempidx */
tcg_gen_ld_i64(t3, cpu_env, offsetof(OurCPUState,tempidx));
/* Check for pointer taint */
t_zero = tcg_temp_new_i64();
tcg_gen_movi_i64(t_zero, 0);
tcg_gen_setcond_i64(TCG_COND_NE, t2, arg1, t_zero);
tcg_gen_neg_i64(t0, t2);
/* Combine pointer and tempidx taint */
tcg_gen_or_i64(arg0, t0, t3);
} else
/* Patch in opcode to load taint from tempidx */
tcg_gen_ld_i64(arg0, cpu_env, offsetof(OurCPUState,tempidx));
} else
/* Patch in opcode to load taint from tempidx */
tcg_gen_ld_i64(arg0, cpu_env, offsetof(OurCPUState,tempidx));
}
// TARGET_REG_BITS = 64, TARGET_LONG_BITS = 32
} else
tcg_abort();
#endif // FIXME
break;
#if 1 // AWH - DEBUG
case INDEX_op_qemu_st32:
//DUMMY_TAINT(nb_oargs, nb_args);
//break;
case INDEX_op_qemu_st8:
case INDEX_op_qemu_st16:
#else
case INDEX_op_qemu_st8:
case INDEX_op_qemu_st16:
case INDEX_op_qemu_st32:
#endif // AWH
// TARGET_REG_BITS = 64 OR (TARGET_REG_BITS = 32, TARGET_LONG_BITS = 32)
if (nb_iargs == 2) {
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
/* Save the qemu_st* parameters */
int mem_index = gen_opparam_ptr[-1];
int addr = gen_opparam_ptr[-2];
int ret = gen_opparam_ptr[-3];
int ir = gen_opc_ptr[-1];
/* Back up to insert a new IR on top of the qemu_st* */
gen_opc_ptr--;
gen_opparam_ptr -= 3;
if (taint_store_pointers_enabled) {
if (arg1) {
#if (TCG_TARGET_REG_BITS == 64)
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
/* Check for pointer taint */
t_zero = tcg_temp_new_i64();
tcg_gen_movi_i64(t_zero, 0);
tcg_gen_setcond_i64(TCG_COND_NE, t2, arg1, t_zero);
tcg_gen_neg_i64(t0, t2);
/* Combine pointer and data taint */
tcg_gen_or_i64(t1, t0, arg0);
/* Store combined taint to tempidx */
tcg_gen_st32_tl(t1, cpu_env, offsetof(OurCPUState,tempidx));
#else
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
/* Check for pointer taint */
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t2, arg1, t_zero);
tcg_gen_neg_i32(t0, t2);
/* Combine pointer and data taint */
tcg_gen_or_i32(t1, t0, arg0);
/* Store combined taint to tempidx */
tcg_gen_st32_tl(t1, cpu_env, offsetof(OurCPUState,tempidx));
#endif /* TARGET_REG_BITS */
} else
tcg_gen_st32_tl(arg0, cpu_env, offsetof(OurCPUState,tempidx));
} else
tcg_gen_st32_tl(arg0, cpu_env, offsetof(OurCPUState,tempidx));
/* Insert the taint_qemu_st* IR */
gen_opc_ptr++;
gen_opparam_ptr += 3;
gen_opc_ptr[-1] = ir + (INDEX_op_taint_qemu_ld8u - INDEX_op_qemu_ld8u);
gen_opparam_ptr[-1] = mem_index;
gen_opparam_ptr[-2] = addr;
gen_opparam_ptr[-3] = ret;
}
} else
tcg_abort();
break;
case INDEX_op_qemu_st64:
#if 0 // AWH - FIXME: 64-bit memory ops may cause corruption
/* TARGET_REG_BITS == 64 */
if (nb_iargs == 2) {
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
/* Save the qemu_st64 parameters */
int mem_index = gen_opparam_ptr[-1];
int addr = gen_opparam_ptr[-2];
int ret = gen_opparam_ptr[-3];
/* Back up to insert a new IR on top of the qemu_st64 */
gen_opc_ptr--;
gen_opparam_ptr -= 3;
if (taint_store_pointers_enabled) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg1) {
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
/* Check for pointer taint */
tcg_gen_movi_i64(t1, 0);
tcg_gen_setcond_i64(TCG_COND_NE, t2, arg1, t1);
tcg_gen_neg_i64(t0, t2);
/* Combine pointer and data taint */
tcg_gen_or_i64(t1, t0, arg0);
/* Store combined taint to tempidx */
tcg_gen_st_tl(t1, cpu_env, offsetof(OurCPUState,tempidx));
//tcg_temp_free_i64(t0);
//tcg_temp_free_i64(t1);
//tcg_temp_free_i64(t2);
} else
tcg_gen_st_tl(arg0, cpu_env, offsetof(OurCPUState,tempidx));
} else
tcg_gen_st_tl(arg0, cpu_env, offsetof(OurCPUState,tempidx));
/* Insert the taint_qemu_st* IR */
gen_opc_ptr++;
gen_opparam_ptr += 3;
gen_opc_ptr[-1] = INDEX_op_taint_qemu_st64;
gen_opparam_ptr[-1] = mem_index;
gen_opparam_ptr[-2] = addr;
gen_opparam_ptr[-3] = ret;
}
// TARGET_REG_BITS = 32, TARGET_LONG_BITS = 32
} else if (nb_iargs == 3) {
arg0 = find_shadow_arg(gen_opparam_ptr[-4]); // Taint of low DWORD
arg1 = find_shadow_arg(gen_opparam_ptr[-3]); // Taint of high DWORD
if (arg0 || arg1) {
int ret_lo = gen_opparam_ptr[-4]; // Low DWORD of data
int ret_hi = gen_opparam_ptr[-3]; // High DWORD of Data
int addr = gen_opparam_ptr[-2]; // Addr
int mem_index = gen_opparam_ptr[-1]; // MMU index
/* Back up to insert two new store IRs on top of the qemu_st64 */
gen_opc_ptr--;
gen_opparam_ptr -= 4;
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
if (taint_store_pointers_enabled) {
arg2 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg2) {
/* Check for pointer taint */
tcg_gen_movi_i32(t1, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t2, arg1, t1);
tcg_gen_neg_i32(t0, t2);
/* Combine pointer and data taint */
if (!arg0)
tcg_gen_st_tl(t0, cpu_env, offsetof(OurCPUState,tempidx));
else {
tcg_gen_or_i32(t1, t0, arg0);
tcg_gen_st_tl(t1, cpu_env, offsetof(OurCPUState,tempidx));
}
if (!arg1)
tcg_gen_st_tl(t0, cpu_env, offsetof(OurCPUState,tempidx2));
else {
tcg_gen_or_i32(t1, t0, arg1);
tcg_gen_st_tl(t1, cpu_env, offsetof(OurCPUState,tempidx2));
}
} else {
/* If there is no shadow data for either one of the 32-bit chunks
that make up this 64-bit store, then use a zeroed-out temp reg
to indicate there is no taint for that 32-bit chunk. */
if (!arg0) {
tcg_gen_movi_i32(t0, 0);
tcg_gen_st_tl(t0, cpu_env, offsetof(OurCPUState,tempidx));
} else
tcg_gen_st_tl(arg0, cpu_env, offsetof(OurCPUState,tempidx));
if (!arg1) {
tcg_gen_movi_i32(t1, 0);
tcg_gen_st_tl(t1, cpu_env, offsetof(OurCPUState,tempidx2));
} else
tcg_gen_st_tl(arg1, cpu_env, offsetof(OurCPUState,tempidx2));
}
//tcg_temp_free_i32(t0);
//tcg_temp_free_i32(t1);
//tcg_temp_free_i32(t2);
} else {
/* If there is no shadow data for either one of the 32-bit chunks
that make up this 64-bit store, then use a zeroed-out temp reg
to indicate there is no taint for that 32-bit chunk. */
if (!arg0) {
t0 = tcg_temp_new_i32();
tcg_gen_movi_i32(t0, 0);
tcg_gen_st_tl(t0, cpu_env, offsetof(OurCPUState,tempidx));
//tcg_temp_free_i32(t0);
} else
tcg_gen_st_tl(arg0, cpu_env, offsetof(OurCPUState,tempidx));
if (!arg1) {
t0 = tcg_temp_new_i32();
tcg_gen_movi_i32(t0, 0);
tcg_gen_st_tl(t0, cpu_env, offsetof(OurCPUState,tempidx2));
//tcg_temp_free_i32(t0);
} else
tcg_gen_st_tl(arg1, cpu_env, offsetof(OurCPUState,tempidx2));
}
/* Insert the taint_qemu_st* IR */
gen_opc_ptr++;
gen_opparam_ptr += 4;
gen_opc_ptr[-1] = INDEX_op_taint_qemu_st64;
gen_opparam_ptr[-1] = mem_index;
gen_opparam_ptr[-2] = addr;
gen_opparam_ptr[-3] = ret_hi;
gen_opparam_ptr[-4] = ret_lo;
}
// TARGET_REG_BITS = 32, TARGET_LONG_BITS = 64
} else /*if (nb_iargs == 4)*/ {
tcg_abort();
}
#endif // FIXME
break;
/* Arithmethic/shift/rotate operations (32 bit). */
case INDEX_op_setcond_i32: // All-Around: UifU32() (mkLazy())
arg0 = find_shadow_arg(gen_opparam_ptr[-4]); // Output
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-3]); // Input1
arg2 = find_shadow_arg(gen_opparam_ptr[-2]); // Input2
/* Store opcode and parms and back up */
orig0 = gen_opparam_ptr[-4];
orig1 = gen_opparam_ptr[-3];
orig2 = gen_opparam_ptr[-2];
orig3 = gen_opparam_ptr[-1];
/* Rewind instruction stream */
gen_opparam_ptr -= 4;
gen_opc_ptr--;
if (arg1 && arg2) {
t0 = tcg_temp_new_i32();
tcg_gen_or_i32(t0, arg1, arg2);
} else if (arg1) {
t0 = tcg_temp_new_i32();
tcg_gen_mov_i32(t0, arg1);
} else if (arg2) {
t0 = tcg_temp_new_i32();
tcg_gen_mov_i32(t0, arg2);
} else {
tcg_gen_mov_i32(arg0, 0);
/* Reinsert original opcode */
tcg_gen_setcond_i32(orig0, orig1, orig2, orig3);
break;
}
// Determine if there is any taint
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t2, t0, t_zero);
tcg_gen_neg_i32(arg0, t2);
/* Reinsert original opcode */
tcg_gen_setcond_i32(orig0, orig1, orig2, orig3);
}
break;
/* IN MEMCHECK (VALGRIND), LOOK AT: memcheck/mc_translate.c
expr2vbits_Binop(), expr2vbits_Unop() */
case INDEX_op_shl_i32: // Special - scalarShift()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
/* Store opcode parms */
orig0 = gen_opparam_ptr[-3];
orig1 = gen_opparam_ptr[-2];
orig2 = gen_opparam_ptr[-1];
/* Rewind instruction stream */
gen_opparam_ptr -= 3;
gen_opc_ptr--;
/* Insert taint IR */
if (!arg1 && !arg2) {
tcg_gen_movi_i32(arg0, 0);
/* Reinsert original opcode */
tcg_gen_shl_i32(orig0, orig1, orig2);
break;
}
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
if (arg2) {
// Check if the shift amount (arg2) is tainted. If so, the
// entire result will be tainted.
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t1, t_zero, arg2);
tcg_gen_neg_i32(t2, t1);
} else
tcg_gen_movi_i32(t2, 0);
if (arg1) {
// Perform the SHL on arg1
tcg_gen_shl_i32(t0, arg1, orig2);//tcg_gen_shl_i32(t0, arg1, gen_opparam_ptr[-1]);
// OR together the taint of shifted arg1 (t0) and arg2 (t2)
tcg_gen_or_i32(arg0, t0, t2);
} else
tcg_gen_mov_i32(arg0, t2);
/* Reinsert original opcode */
tcg_gen_shl_i32(orig0, orig1, orig2);
}
break;
case INDEX_op_shr_i32: // Special - scalarShift()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
/* Store opcode parms */
orig0 = gen_opparam_ptr[-3];
orig1 = gen_opparam_ptr[-2];
orig2 = gen_opparam_ptr[-1];
/* Rewind instruction stream */
gen_opparam_ptr -= 3;
gen_opc_ptr--;
/* Insert taint IR */
if (!arg1 && !arg2) {
tcg_gen_movi_i32(arg0, 0);
/* Reinsert original opcode */
tcg_gen_shr_i32(orig0, orig1, orig2);
break;
}
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
if (arg2) {
// Check if the shift amount (arg2) is tainted. If so, the
// entire result will be tainted.
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t1, t_zero, arg2);
tcg_gen_neg_i32(t2, t1);
} else
tcg_gen_movi_i32(t2, 0);
if (arg1) {
// Perform the SHR on arg1
tcg_gen_shr_i32(t0, arg1, orig2);
// OR together the taint of shifted arg1 (t0) and arg2 (t2)
tcg_gen_or_i32(arg0, t0, t2);
} else
tcg_gen_mov_i32(arg0, t2);
/* Reinsert original opcode */
tcg_gen_shr_i32(orig0, orig1, orig2);
}
break;
case INDEX_op_sar_i32: // Special - scalarShift()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
/* Store opcode parms */
orig0 = gen_opparam_ptr[-3];
orig1 = gen_opparam_ptr[-2];
orig2 = gen_opparam_ptr[-1];
/* Rewind the instruction stream */
gen_opparam_ptr -= 3;
gen_opc_ptr--;
/* Insert taint IR */
if (!arg1 && !arg2) {
tcg_gen_movi_i32(arg0, 0);
/* Reinsert original opcode */
tcg_gen_sar_i32(orig0, orig1, orig2);
break;
}
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
if (arg2) {
// Check if the shift amount (arg2) is tainted. If so, the
// entire result will be tainted.
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t1, t_zero, arg2);
tcg_gen_neg_i32(t2, t1);
} else
tcg_gen_movi_i32(t2, 0);
if (arg1) {
// Perform the SAR on arg1
tcg_gen_sar_i32(t0, arg1, orig2);
// OR together the taint of shifted arg1 (t0) and arg2 (t2)
tcg_gen_or_i32(arg0, t0, t2);
} else
tcg_gen_mov_i32(arg0, t2);
/* Reinsert original opcode */
tcg_gen_sar_i32(orig0, orig1, orig2);
}
break;
#if TCG_TARGET_HAS_rot_i32
case INDEX_op_rotl_i32: // Special - MemCheck does lazy, but we shift
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
/* Store opcode and parms and back up */
orig0 = gen_opparam_ptr[-3];
orig1 = gen_opparam_ptr[-2];
orig2 = gen_opparam_ptr[-1];
/* Rewind the instruction stream */
gen_opparam_ptr -= 3;
gen_opc_ptr--;
/* Insert tainting IR */
if (!arg1 && !arg2) {
tcg_gen_movi_i32(arg0, 0);
/* Reinsert original opcode */
tcg_gen_rotl_i32(orig0, orig1, orig2);
break;
}
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
if (arg2) {
// Check if the shift amount (arg2) is tainted. If so, the
// entire result will be tainted.
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t1, t_zero, arg2);
tcg_gen_neg_i32(t2, t1);
} else
tcg_gen_movi_i32(t2, 0);
if (arg1) {
// Perform the ROTL on arg1
tcg_gen_rotl_i32(t0, arg1, orig2);
// OR together the taint of shifted arg1 (t0) and arg2 (t2)
tcg_gen_or_i32(arg0, t0, t2);
} else
tcg_gen_mov_i32(arg0, t2);
/* Reinsert original opcode */
tcg_gen_rotl_i32(orig0, orig1, orig2);
}
break;
case INDEX_op_rotr_i32: // Special - MemCheck does lazy, but we shift
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
/* Store opcode and parms and back up */
orig0 = gen_opparam_ptr[-3];
orig1 = gen_opparam_ptr[-2];
orig2 = gen_opparam_ptr[-1];
/* Rewind instruction stream */
gen_opparam_ptr -= 3;
gen_opc_ptr--;
/* Insert tainting IR */
if (!arg1 && !arg2) {
tcg_gen_movi_i32(arg0, 0);
/* Reinsert original opcode */
tcg_gen_rotr_i32(orig0, orig1, orig2);
break;
}
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
if (arg2) {
// Check if the shift amount (arg2) is tainted. If so, the
// entire result will be tainted.
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t1, t_zero, arg2);
tcg_gen_neg_i32(t2, t1);
} else
tcg_gen_movi_i32(t2, 0);
if (arg1) {
// Perform the ROTR on arg1
tcg_gen_rotr_i32(t0, arg1, orig2);
// OR together the taint of shifted arg1 (t0) and arg2 (t2)
tcg_gen_or_i32(arg0, t0, t2);
} else
tcg_gen_mov_i32(arg0, t2);
/* Reinsert original opcode */
tcg_gen_rotr_i32(orig0, orig1, orig2);
}
break;
#endif /* TCG_TARGET_HAS_rot_i32 */
#ifdef TCG_BITWISE_TAINT
#ifdef TAINT_EXPENSIVE_ADDSUB
// AWH - expensiveAddSub() for add_i32/or_i32 are buggy, use cheap one
/* T0 = (T1 | T2) | ((V1_min + V2_min) ^ (V1_max + V2_max)) */
case INDEX_op_add_i32: // Special - expensiveAddSub()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
//LOK: Changed the names of orig0 and orig 1 to orig1 and 2
// so I don't get confused
// Basically arg is vxx and orig is x
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
//make sure we have a copy of the values first
orig0 = gen_opparam_ptr[-3];
orig1 = gen_opparam_ptr[-2];
orig2 = gen_opparam_ptr[-1];
//delete the original operation
gen_opparam_ptr -= 3;
gen_opc_ptr--;
//LOK: Declared the new temporary variables that we need
t0 = tcg_temp_new_i32(); //scratch
t1 = tcg_temp_new_i32(); //a_min
t2 = tcg_temp_new_i32(); //b_min
t3 = tcg_temp_new_i32(); //a_max
t4 = tcg_temp_new_i32(); //b_max
/* Per the expensiveAddSub() logic:
qaa = T1 = arg1
qbb = T2 = arg2
aa = V1 = orig1
bb = V2 = orig2 */
//LOK: First lets calculate a_min = aa & ~qaa
tcg_gen_not_i32(t0, arg1); // ~qaa
tcg_gen_and_i32(t1, orig1, t0);//t1 = aa & ~qaa
//LOK: Then calculate b_min
tcg_gen_not_i32(t0, arg2); // ~qbb
tcg_gen_and_i32(t2, orig2, t0);//t2 = bb & ~qbb
//LOK: Then calculate a_max = aa | qaa
tcg_gen_or_i32(t3, orig1, arg1);//t3 = aa | qaa
tcg_gen_or_i32(t4, orig2, arg2);//t4 = bb | qbb
//LOK: Now that we have the mins and maxes, we need to sum them
tcg_gen_add_i32(t0, t3, t4); // t0 = a_max + b_max
//LOK: Note that t3 is being reused in this case
tcg_gen_add_i32(t3, t1, t2); // t3 = a_min + b_min
tcg_gen_xor_i32(t1, t0, t3); // t1 = ((a_min + b_min)^(a_max + b_max))
tcg_gen_or_i32(t0, arg1, arg2); // t0 = qa | qb
tcg_gen_or_i32(arg0, t0, t1); // arg0 = (qa | qb) | ( (a_min + b_min) ^ (a_max + b_max)
//put the original operation back
tcg_gen_add_i32(orig0, orig1, orig2);
}
break;
/* T0 = (T1 | T2) | ((V1_min - V2_max) ^ (V1_max - V2_min)) */
case INDEX_op_sub_i32: // Special - expensiveAddSub()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
//NOTE: It is important that we get the order of the operands correct
// Right now, the assumption is
// arg0 = arg1 - arg2
// If there are errors - this could be the culprit
//LOK: Changed the names of orig0 and orig 1 to orig1 and 2
// so I don't get confused
// Basically arg is vxx and orig is x
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
//make sure we have a copy of the values first
orig0 = gen_opparam_ptr[-3];
orig1 = gen_opparam_ptr[-2];
orig2 = gen_opparam_ptr[-1];
//delete the original operation
gen_opparam_ptr -= 3;
gen_opc_ptr--;
//LOK: Declared the new temporary variables that we need
t0 = tcg_temp_new_i32(); //scratch
t1 = tcg_temp_new_i32(); //a_min
t2 = tcg_temp_new_i32(); //b_min
t3 = tcg_temp_new_i32(); //a_max
t4 = tcg_temp_new_i32(); //b_max
/* Per the expensiveAddSub() logic:
qaa = T1 = arg1
qbb = T2 = arg2
aa = V1 = orig1
bb = V2 = orig2 */
//LOK: First lets calculate a_min = aa & ~qaa
tcg_gen_not_i32(t0, arg1); // ~qaa
tcg_gen_and_i32(t1, orig1, t0);//t1 = aa & ~qaa
//LOK: Then calculate b_min
tcg_gen_not_i32(t0, arg2); // ~qbb
tcg_gen_and_i32(t2, orig2, t0);//t2 = bb & ~qbb
//LOK: Then calculate a_max = aa | qaa
tcg_gen_or_i32(t3, orig1, arg1);//t3 = aa | qaa
tcg_gen_or_i32(t4, orig2, arg2);//t4 = bb | qbb
//LOK: Now that we have the mins and maxes, we need to find the differences
//NOTE: This is why the order of the operands is important
tcg_gen_sub_i32(t0, t1, t4); // t0 = a_min - b_max
//LOK: Note that t3 is being reused in this case
tcg_gen_sub_i32(t4, t3, t2); // t4 = a_max - b_min
tcg_gen_xor_i32(t1, t0, t4); // t1 = ((a_min - b_max)^(a_max - b_min))
tcg_gen_or_i32(t0, arg1, arg2); // t0 = qa | qb
tcg_gen_or_i32(arg0, t0, t1); // arg0 = (qa | qb) | ( (a_min - b_max) ^ (a_max - b_min)
//put the original operation back
tcg_gen_sub_i32(orig0, orig1, orig2);
}
break;
// AWH
#else
case INDEX_op_add_i32: // Up - cheap_AddSub32
case INDEX_op_sub_i32: // Up - cheap_AddSub32
#endif
case INDEX_op_mul_i32: // Up - mkUifU32(), mkLeft32(), mkPCastTo()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
/* Store opcode and parms and back up */
orig0 = gen_opparam_ptr[-3];
orig1 = gen_opparam_ptr[-2];
orig2 = gen_opparam_ptr[-1];
/* Rewind instruction stream */
gen_opparam_ptr -= 3;
gen_opc_ptr--;
if (!arg1 && !arg2) {
tcg_gen_movi_i32(arg0, 0);
/* Reinsert original opcode */
tcg_gen_mul_i32(orig0, orig1, orig2);
break;
}
t0 = tcg_temp_new_i32();
if (arg1 && arg2)
// mkUifU32(arg1, arg2)
tcg_gen_or_i32(t0, arg1, arg2);
else if (arg1)
tcg_gen_movi_i32(t0, arg1);
else if (arg2)
tcg_gen_movi_i32(t0, arg2);
// mkLeft32(t0)
t1 = tcg_temp_new_i32();
tcg_gen_neg_i32(t1, t0); // (-s32)
tcg_gen_or_i32(arg0, t0, t1); // (s32 | (-s32)) -> vLo32
/* Reinsert original opcode */
tcg_gen_mul_i32(orig0, orig1, orig2);
}
break;
/* Bitwise AND rules:
Taint1 Value1 Op Taint2 Value2 ResultingTaint
0 1 AND 1 X 1
1 X AND 0 1 1
1 X AND 1 X 1
... otherwise, ResultingTaint = 0
AND: ((NOT T1) * V1 * T2) + (T1 * (NOT T2) * V2) + (T1 * T2)
*/
case INDEX_op_and_i32: // Special - and_or_ty()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
/* Store opcode parms */
orig0 = gen_opparam_ptr[-1];//V1
orig1 = gen_opparam_ptr[-2];//V2
orig2 = gen_opparam_ptr[-3];
/* Rewind instruction stream */
gen_opparam_ptr -= 3;
gen_opc_ptr--;
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
t3 = tcg_temp_new_i32();
/* T1 -> arg1
V1 -> gen_opparam_ptr[-2]
T2 -> arg2
V2 -> gen_opparam_ptr[-1] */
if (arg1)
tcg_gen_not_i32(t0, arg1); // NOT T1
else
tcg_gen_movi_i32(t0, -1);
if (arg2)
tcg_gen_and_i32(t1,orig1,arg2);//tcg_gen_and_i32(t1, gen_opparam_ptr[-2], arg2); // V1 * T2
else
tcg_gen_movi_i32(t1, 0);
tcg_gen_and_i32(t2, t0, t1); // (NOT T1) * V1 * T2
if (arg2)
tcg_gen_not_i32(t0, arg2); // NOT T2
else
tcg_gen_movi_i32(t0, -1);
if (arg1)
tcg_gen_and_i32(t1,arg1,orig0);//tcg_gen_and_i32(t1, arg1, gen_opparam_ptr[-1]); // T1 * V2
else
tcg_gen_movi_i32(t1, 0);
tcg_gen_and_i32(t3, t0, t1); // (T1 * (NOT T2) * V2)
if (arg1 && arg2)
tcg_gen_and_i32(t0, arg1, arg2); // T1 * T2
else
tcg_gen_movi_i32(t0, 0);
// OR it all together
tcg_gen_or_i32(t1, t2, t3);
tcg_gen_or_i32(arg0, t0, t1);
/* Reinsert original opcode */
tcg_gen_and_i32(orig2, orig1, orig0);
}
break;
/* Bitwise OR rules:
Taint1 Value1 Op Taint2 Value2 ResultingTaint
0 0 OR 1 X 1
1 X OR 0 0 1
1 X OR 1 X 1
... otherwise, ResultingTaint = 0
OR: ((NOT T1) * (NOT V1) * T2) + (T1 * (NOT T2) * (NOT V2)) + (T1 * T2)
*/
case INDEX_op_or_i32: // Special - and_or_ty()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-1];//V1
orig1 = gen_opparam_ptr[-2];//V2
orig2 = gen_opparam_ptr[-3];
/* Rewind instruction stream */
gen_opparam_ptr -= 3;
gen_opc_ptr--;
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
t3 = tcg_temp_new_i32();
/* T1 -> arg1
V1 -> gen_opparam_ptr[-2]
T2 -> arg2
V2 -> gen_opparam_ptr[-1] */
if (arg1)
tcg_gen_not_i32(t0, arg1); // NOT T1
else
tcg_gen_movi_i32(t0, -1);
tcg_gen_not_i32(t1, orig1);//tcg_gen_not_i32(t1, gen_opparam_ptr[-2]); // NOT V1
tcg_gen_and_i32(t2, t0, t1); // (NOT T1) * (NOT V1)
if (arg2)
tcg_gen_and_i32(t0, t2, arg2); // (NOT T1) * (NOT V1) * T2
else
tcg_gen_movi_i32(t0, 0);
if (arg2)
tcg_gen_not_i32(t1, arg2); // NOT T2
else
tcg_gen_movi_i32(t1, -1);
tcg_gen_not_i32(t2, orig0);//tcg_gen_not_i32(t2, gen_opparam_ptr[-1]); // NOT V2
tcg_gen_and_i32(t3, t1, t2); // (NOT T2) * (NOT V2)
if (arg1)
tcg_gen_and_i32(t1, t3, arg1); // (NOT T2) * (NOT V2) * T1
else
tcg_gen_movi_i32(t1, 0);
if (arg1 && arg2)
tcg_gen_and_i32(t2, arg1, arg2); // T1 * T2
else if (arg1)
tcg_gen_mov_i32(t2, arg1);
else if (arg2)
tcg_gen_mov_i32(t2, arg2);
// OR it all together
tcg_gen_or_i32(t3, t0, t1);
tcg_gen_or_i32(arg0, t2, t3);
/* Reinsert original opcode */
tcg_gen_or_i32(orig2, orig1, orig0);
}
break;
#else
/* Bytewise taint for arithmethic/shift/rotate operations (32 bit). */
/* These all use the following pattern of shadow registers: */
/* arg0 = arg1 op arg2. To bitwise taint this pattern in shadow */
/* registers, we use the following steps:
Step 1: temp0 = arg1 or arg2
Step 2: temp1 = 0
Step 3: temp2 = (temp0 != temp1)
Step 4: arg0 = ~temp2
MemCheck: mkLazy2() for all of these */
case INDEX_op_add_i32:
case INDEX_op_sub_i32:
case INDEX_op_mul_i32:
case INDEX_op_and_i32:
case INDEX_op_or_i32:
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
/* Determine which args are shadowed */
if (arg1 && arg2) {
t0 = tcg_temp_new_i32();
tcg_gen_or_i32(t0, arg1, arg2);
} else if (arg1) {
t0 = tcg_temp_new_i32();
tcg_gen_mov_i32(t0, arg1);
} else if (arg2) {
t0 = tcg_temp_new_i32();
tcg_gen_mov_i32(t0, arg2);
} else {
tcg_gen_movi_i32(arg0, 0);
break;
}
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t2, t_zero, t0);
tcg_gen_neg_i32(arg0, t2);
}
break;
#endif /* TCG_BITWISE_TAINT */
case INDEX_op_mulu2_i32: // Bytewise, mkLazyN()
arg0 = find_shadow_arg(gen_opparam_ptr[-4]);
arg1 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0 && arg1) {
arg2 = find_shadow_arg(gen_opparam_ptr[-2]);
arg3 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-4];
orig1 = gen_opparam_ptr[-3];
orig2 = gen_opparam_ptr[-2];
orig3 = gen_opparam_ptr[-1];
if (arg2 && arg3) {
t0 = tcg_temp_new_i32();
tcg_gen_or_i32(t0, arg2, arg3);
} else if (arg2) {
t0 = tcg_temp_new_i32();
tcg_gen_mov_i32(t0, arg2);
} else if (arg3) {
t0 = tcg_temp_new_i32();
tcg_gen_mov_i32(t0, arg3);
} else {
tcg_gen_movi_i32(arg0, 0);
tcg_gen_movi_i32(arg1, 0);
break; //LOK: this is a bug - need to break it
}
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t2, t0, t_zero);
tcg_gen_neg_i32(arg0, t2);
tcg_gen_neg_i32(arg1, t2);
}
break;
case INDEX_op_add2_i32: // Bytewise, mkLazyN()
case INDEX_op_sub2_i32: // Bytewise, mkLazyN()
arg0 = find_shadow_arg(gen_opparam_ptr[-6]); // Output low
arg1 = find_shadow_arg(gen_opparam_ptr[-5]); // Output high
if (arg0 && arg1) {
arg2 = find_shadow_arg(gen_opparam_ptr[-4]); // Input1 low
arg3 = find_shadow_arg(gen_opparam_ptr[-3]); // Input1 high
arg4 = find_shadow_arg(gen_opparam_ptr[-2]); // Input2 low
arg5 = find_shadow_arg(gen_opparam_ptr[-1]); // Input2 high
orig0 = gen_opparam_ptr[-6];
orig1 = gen_opparam_ptr[-5];
orig2 = gen_opparam_ptr[-4];
orig3 = gen_opparam_ptr[-3];
orig4 = gen_opparam_ptr[-2];
orig5 = gen_opparam_ptr[-1];
if (!(arg2 || arg3 || arg4 || arg5)) {
tcg_gen_movi_i32(arg0, 0);
tcg_gen_movi_i32(arg1, 0);
break;
}
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
t3 = tcg_temp_new_i32();
// Combine high/low taint of Input 1 into t2
if (arg2 && arg3)
tcg_gen_or_i32(t2, arg2, arg3);
else if (arg2)
tcg_gen_mov_i32(t2, arg2);
else if (arg3)
tcg_gen_mov_i32(t2, arg3);
else
tcg_gen_movi_i32(t2, 0);
// Combine high/low taint of Input 2 into t3
if (arg4 && arg5)
tcg_gen_or_i32(t3, arg4, arg5);
else if (arg4)
tcg_gen_mov_i32(t3, arg4);
else if (arg5)
tcg_gen_mov_i32(t3, arg5);
else
tcg_gen_movi_i32(t3, 0);
// Determine if there is any taint
tcg_gen_or_i32(t0, t2, t3);
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t2, t0, t_zero); // Reuse t2
tcg_gen_neg_i32(arg0, t2);
tcg_gen_neg_i32(arg1, t2);
}
break;
case INDEX_op_xor_i32: // In-Place - mkUifU32
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-3];
orig1 = gen_opparam_ptr[-2];
orig2 = gen_opparam_ptr[-1];
/* Perform an OR an arg1 and arg2 to find taint */
if (arg1 && arg2)
tcg_gen_or_i32(arg0, arg1, arg2);
else if (arg1)
tcg_gen_mov_i32(arg0, arg1);
else if (arg2)
tcg_gen_mov_i32(arg0, arg2);
else
tcg_gen_movi_i32(arg0, 0);
}
break;
#if TCG_TARGET_HAS_div_i32
case INDEX_op_div_i32: // All-around: mkLazy2()
case INDEX_op_divu_i32: // All-around: mkLazy2()
case INDEX_op_rem_i32: // All-around: mkLazy2()
case INDEX_op_remu_i32: // All-around: mkLazy2()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-3];
orig1 = gen_opparam_ptr[-2];
orig2 = gen_opparam_ptr[-1];
if (arg1 && arg2) {
t0 = tcg_temp_new_i32();
tcg_gen_or_i32(t0, arg1, arg2);
} else if (arg1) {
t0 = tcg_temp_new_i32();
tcg_gen_mov_i32(t0, arg1);
} else if (arg2) {
t0 = tcg_temp_new_i32();
tcg_gen_mov_i32(t0, arg2);
} else {
tcg_gen_movi_i32(arg0, 0);
}
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t2, t0, t_zero);
tcg_gen_neg_i32(arg0, t2);
}
break;
#elif TCG_TARGET_HAS_div2_i32
case INDEX_op_div2_i32: // All-around: mkLazy3()
case INDEX_op_divu2_i32: // All-around: mkLazy3()
arg0 = find_shadow_arg(gen_opparam_ptr[-5]);
arg1 = find_shadow_arg(gen_opparam_ptr[-4]);
if (arg0 && arg1) {
arg2 = find_shadow_arg(gen_opparam_ptr[-3]);
arg3 = find_shadow_arg(gen_opparam_ptr[-2]);
arg4 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-5];
orig1 = gen_opparam_ptr[-4];
orig2 = gen_opparam_ptr[-3];
orig3 = gen_opparam_ptr[-2];
orig4 = gen_opparam_ptr[-1];
/* No shadows for any inputs */
if (!(arg2 || arg3 || arg4))
{
tcg_gen_movi_i32(arg0, 0);
tcg_gen_movi_i32(arg1, 0);
break;
}
t0 = tcg_temp_new_i32();
t1 = tcg_temp_new_i32();
t2 = tcg_temp_new_i32();
/* Check for shadows on arg2 and arg3 */
if (arg2 && arg3)
tcg_gen_or_i32(t0, arg2, arg3);
else if (arg2)
tcg_gen_mov_i32(t0, arg2);
else if (arg3)
tcg_gen_mov_i32(t0, arg3);
else
tcg_gen_movi_i32(t0, 0);
/* Check for shadow on arg4 */
if (arg4)
tcg_gen_or_i32(t2, t0, arg4);
else
tcg_gen_mov_i32(t2, t0);
t_zero = tcg_temp_new_i32();
tcg_gen_movi_i32(t_zero, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t0, t2, t_zero);
tcg_gen_neg_i32(arg0, t0);
tcg_gen_neg_i32(arg1, t0);
}
break;
#endif /* TCG_TARGET_HAS_div*_i32 */
#if TCG_TARGET_HAS_ext8s_i32
case INDEX_op_ext8s_i32: // MemCheck: VgT_SWiden14
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-2];
orig1 = gen_opparam_ptr[-1];
if (arg1)
tcg_gen_ext8s_i32(arg0, arg1);
else
tcg_gen_movi_i32(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_ext8s_i32 */
#if TCG_TARGET_HAS_ext16s_i32
case INDEX_op_ext16s_i32: // MemCheck: VgT_SWiden24
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-2];
orig1 = gen_opparam_ptr[-1];
if (arg1)
tcg_gen_ext16s_i32(arg0, arg1);
else
tcg_gen_movi_i32(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_ext16s_i32 */
#if TCG_TARGET_HAS_ext8u_i32
case INDEX_op_ext8u_i32: // MemCheck: VgT_ZWiden14
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-2];
orig1 = gen_opparam_ptr[-1];
if (arg1)
tcg_gen_ext8u_i32(arg0, arg1);
else
tcg_gen_movi_i32(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_ext8u_i32 */
#if TCG_TARGET_HAS_ext16u_i32
case INDEX_op_ext16u_i32: // MemCheck: VgT_ZWiden24
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-2];
orig1 = gen_opparam_ptr[-1];
if (arg1)
tcg_gen_ext16u_i32(arg0, arg1);
else
tcg_gen_movi_i32(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_ext16u_i32 */
#if TCG_TARGET_HAS_bswap16_i32
case INDEX_op_bswap16_i32: // MemCheck: UifU2
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-2];
orig1 = gen_opparam_ptr[-1];
if (arg1)
tcg_gen_bswap16_i32(arg0, arg1);
else
tcg_gen_movi_i32(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_bswap16_i32 */
#if TCG_TARGET_HAS_bswap32_i32
case INDEX_op_bswap32_i32: // MemCheck: UifU4
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-2];
orig1 = gen_opparam_ptr[-1];
if (arg1)
tcg_gen_bswap32_i32(arg0, arg1);
else
tcg_gen_movi_i32(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_bswap32_i32 */
#if TCG_TARGET_HAS_not_i32
case INDEX_op_not_i32: // MemCheck: Nothing! (Returns orig atom)
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-2];
orig1 = gen_opparam_ptr[-1];
if (arg1)
tcg_gen_mov_i32(arg0, arg1);
else
tcg_gen_movi_i32(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_not_i32 */
#if TCG_TARGET_HAS_neg_i32
case INDEX_op_neg_i32:
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-2];
orig1 = gen_opparam_ptr[-1];
if (arg1)
tcg_gen_mov_i32(arg0, arg1);
else
tcg_gen_movi_i32(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_neg_i32 */
case INDEX_op_movi_i64:
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
#ifdef TARGET_I386
#define HELPER_SECTION_TWO
#include "helper_i386_check.h"
#if 0 // AWH
/* Check if the constant is a helper function for IN* opcodes */
if ( (gen_opparam_ptr[-1] == (tcg_target_ulong)helper_inb) ||
(gen_opparam_ptr[-1] == (tcg_target_ulong)helper_inw) ||
(gen_opparam_ptr[-1] == (tcg_target_ulong)helper_inl) )
in_helper_func = 1;
/* Check if the constant is a helper function for OUT* opcodes */
else if ( (gen_opparam_ptr[-1] == (tcg_target_ulong)helper_outb) ||
(gen_opparam_ptr[-1] == (tcg_target_ulong)helper_outw) ||
(gen_opparam_ptr[-1] == (tcg_target_ulong)helper_outl) )
out_helper_func = 1;
/* Check if the constant is the helper function for CMPXCHG */
else if (gen_opparam_ptr[-1] == (tcg_target_ulong)helper_DECAF_taint_cmpxchg)
cmpxchg_helper_func = 1;
#endif // AWH
#endif /* TARGET_I386 */
tcg_gen_movi_i64(arg0, 0);
}
break;
case INDEX_op_mov_i64:
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg0) {
if (arg1)
tcg_gen_mov_i64(arg0, arg1);
else
tcg_gen_movi_i64(arg0, 0);
}
break;
/* Arithmethic/shift/rotate operations (64 bit). */
case INDEX_op_setcond_i64: // All-Around: UifU64() (mkLazy())
arg0 = find_shadow_arg(gen_opparam_ptr[-4]); // Output
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-3]); // Input1
arg2 = find_shadow_arg(gen_opparam_ptr[-2]); // Input2
if (arg1 && arg2) {
t0 = tcg_temp_new_i64();
tcg_gen_or_i64(t0, arg1, arg2);
} else if (arg1) {
t0 = tcg_temp_new_i64();
tcg_gen_mov_i64(t0, arg1);
} else if (arg2) {
t0 = tcg_temp_new_i64();
tcg_gen_mov_i64(t0, arg2);
} else {
tcg_gen_mov_i64(arg0, 0);
break;
}
// Determine if there is any taint
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
tcg_gen_movi_i64(t1, 0);
tcg_gen_setcond_i64(TCG_COND_NE, t2, t0, t1);
tcg_gen_neg_i64(arg0, t2);
}
break;
#ifdef TCG_BITWISE_TAINT
case INDEX_op_shl_i64: // Special - scalarShift()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-1];
if (!arg1 && !arg2) {
tcg_gen_movi_i64(arg0, 0);
break;
}
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
if (arg2) {
// Check if the shift amount (arg2) is tainted. If so, the
// entire result will be tainted.
tcg_gen_movi_i64(t0, 0);
tcg_gen_setcond_i64(TCG_COND_NE, t1, t0, arg2);
tcg_gen_neg_i64(t2, t1);
} else
tcg_gen_movi_i64(t2, 0);
if (arg1) {
// Perform the SHL on arg1
tcg_gen_shl_i64(t0, arg1, orig0);// tcg_gen_shl_i64(t0, arg1, gen_opparam_ptr[-1]);
// OR together the taint of shifted arg1 (t0) and arg2 (t2)
tcg_gen_or_i64(arg0, t0, t2);
} else
tcg_gen_mov_i64(arg0, t2);
}
break;
case INDEX_op_shr_i64: // Special - scalarShift()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-1];
if (!arg1 && !arg2) {
tcg_gen_movi_i64(arg0, 0);
break;
}
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
if (arg2) {
// Check if the shift amount (arg2) is tainted. If so, the
// entire result will be tainted.
tcg_gen_movi_i64(t0, 0);
tcg_gen_setcond_i64(TCG_COND_NE, t1, t0, arg2);
tcg_gen_neg_i64(t2, t1);
} else
tcg_gen_movi_i64(t2, 0);
if (arg1) {
// Perform the SHR on arg1
tcg_gen_shr_i64(t0, arg1, orig0);//tcg_gen_shr_i64(t0, arg1, gen_opparam_ptr[-1]);
// OR together the taint of shifted arg1 (t0) and arg2 (t2)
tcg_gen_or_i64(arg0, t0, t2);
} else
tcg_gen_mov_i64(arg0, t2);
}
break;
case INDEX_op_sar_i64: // Special - scalarShift()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-1];
if (!arg1 && !arg2) {
tcg_gen_movi_i64(arg0, 0);
break;
}
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
if (arg2) {
// Check if the shift amount (arg2) is tainted. If so, the
// entire result will be tainted.
tcg_gen_movi_i64(t0, 0);
tcg_gen_setcond_i64(TCG_COND_NE, t1, t0, arg2);
tcg_gen_neg_i64(t2, t1);
} else
tcg_gen_movi_i64(t2, 0);
if (arg1) {
// Perform the SAR on arg1
tcg_gen_sar_i64(t0, arg1, orig0);//tcg_gen_sar_i64(t0, arg1, gen_opparam_ptr[-1]);
// OR together the taint of shifted arg1 (t0) and arg2 (t2)
tcg_gen_or_i64(arg0, t0, t2);
} else
tcg_gen_mov_i64(arg0, t2);
}
break;
#if TCG_TARGET_HAS_rot_i64
case INDEX_op_rotl_i64: // Special - MemCheck does lazy, but we shift
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-1];
if (!arg1 && !arg2) {
tcg_gen_movi_i64(arg0, 0);
break;
}
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
if (arg2) {
// Check if the shift amount (arg2) is tainted. If so, the
// entire result will be tainted.
tcg_gen_movi_i64(t0, 0);
tcg_gen_setcond_i64(TCG_COND_NE, t1, t0, arg2);
tcg_gen_neg_i64(t2, t1);
} else
tcg_gen_movi_i64(t2, 0);
if (arg1) {
// Perform the ROTL on arg1
tcg_gen_rotl_i64(t0, arg1, orig0);//tcg_gen_rotl_i64(t0, arg1, gen_opparam_ptr[-1]);
// OR together the taint of shifted arg1 (t0) and arg2 (t2)
tcg_gen_or_i64(arg0, t0, t2);
} else
tcg_gen_mov_i64(arg0, t2);
}
break;
case INDEX_op_rotr_i64: // Special - MemCheck does lazy, but we shift
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-1];
if (!arg1 && !arg2) {
tcg_gen_movi_i64(arg0, 0);
break;
}
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
if (arg2) {
// Check if the shift amount (arg2) is tainted. If so, the
// entire result will be tainted.
tcg_gen_movi_i64(t0, 0);
tcg_gen_setcond_i64(TCG_COND_NE, t1, t0, arg2);
tcg_gen_neg_i64(t2, t1);
} else
tcg_gen_movi_i64(t2, 0);
if (arg1) {
// Perform the ROTL on arg1
tcg_gen_rotr_i64(t0, arg1, orig0);//tcg_gen_rotr_i64(t0, arg1, gen_opparam_ptr[-1]);
// OR together the taint of shifted arg1 (t0) and arg2 (t2)
tcg_gen_or_i64(arg0, t0, t2);
} else
tcg_gen_mov_i64(arg0, t2);
}
break;
#endif /* TCG_TARGET_HAS_rot_i64 */
// AWH - expensiveAddSub() for add_i64/or_i64 are buggy, use cheap one
/* T0 = (T1 | T2) | ((V1_min + V2_min) ^ (V1_max + V2_max)) */
case INDEX_op_add_i64: // Special - expensiveAddSub()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
//LOK: Changed the names of orig0 and orig 1 to orig1 and 2
// so I don't get confused
// Basically arg is vxx and orig is x
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
//make sure we have a copy of the values first
orig0 = gen_opparam_ptr[-3];
orig1 = gen_opparam_ptr[-2];
orig2 = gen_opparam_ptr[-1];
//delete the original operation
gen_opparam_ptr -= 3;
gen_opc_ptr--;
//LOK: Declared the new temporary variables that we need
t0 = tcg_temp_new_i64(); //scratch
t1 = tcg_temp_new_i64(); //a_min
t2 = tcg_temp_new_i64(); //b_min
t3 = tcg_temp_new_i64(); //a_max
t4 = tcg_temp_new_i64(); //b_max
/* Per the expensiveAddSub() logic:
qaa = T1 = arg1
qbb = T2 = arg2
aa = V1 = orig1
bb = V2 = orig2 */
//LOK: First lets calculate a_min = aa & ~qaa
tcg_gen_not_i64(t0, arg1); // ~qaa
tcg_gen_and_i64(t1, orig1, t0);//t1 = aa & ~qaa
//LOK: Then calculate b_min
tcg_gen_not_i64(t0, arg2); // ~qbb
tcg_gen_and_i64(t2, orig2, t0);//t2 = bb & ~qbb
//LOK: Then calculate a_max = aa | qaa
tcg_gen_or_i64(t3, orig1, arg1);//t3 = aa | qaa
tcg_gen_or_i64(t4, orig2, arg2);//t4 = bb | qbb
//LOK: Now that we have the mins and maxes, we need to sum them
tcg_gen_add_i64(t0, t3, t4); // t0 = a_max + b_max
//LOK: Note that t3 is being reused in this case
tcg_gen_add_i64(t3, t1, t2); // t3 = a_min + b_min
tcg_gen_xor_i64(t1, t0, t3); // t1 = ((a_min + b_min)^(a_max + b_max))
tcg_gen_or_i64(t0, arg1, arg2); // t0 = qa | qb
tcg_gen_or_i64(arg0, t0, t1); // arg0 = (qa | qb) | ( (a_min + b_min) ^ (a_max + b_max)
//put the original back
tcg_gen_add_i64(orig0, orig1, orig2);
}
break;
/* T0 = (T1 | T2) | ((V1_min - V2_max) ^ (V1_max - V2_min)) */
case INDEX_op_sub_i64: // Special - expensiveAddSub()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
//NOTE: It is important that we get the order of the operands correct
// Right now, the assumption is
// arg0 = arg1 - arg2
// If there are errors - this could be the culprit
//LOK: Changed the names of orig0 and orig 1 to orig1 and 2
// so I don't get confused
// Basically arg is vxx and orig is x
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
//make sure we have a copy of the values first
orig0 = gen_opparam_ptr[-3];
orig1 = gen_opparam_ptr[-2];
orig2 = gen_opparam_ptr[-1];
//delete the original operation
gen_opparam_ptr -= 3;
gen_opc_ptr--;
//LOK: Declared the new temporary variables that we need
t0 = tcg_temp_new_i64(); //scratch
t1 = tcg_temp_new_i64(); //a_min
t2 = tcg_temp_new_i64(); //b_min
t3 = tcg_temp_new_i64(); //a_max
t4 = tcg_temp_new_i64(); //b_max
/* Per the expensiveAddSub() logic:
qaa = T1 = arg1
qbb = T2 = arg2
aa = V1 = orig1
bb = V2 = orig2 */
//LOK: First lets calculate a_min = aa & ~qaa
tcg_gen_not_i64(t0, arg1); // ~qaa
tcg_gen_and_i64(t1, orig1, t0);//t1 = aa & ~qaa
//LOK: Then calculate b_min
tcg_gen_not_i64(t0, arg2); // ~qbb
tcg_gen_and_i64(t2, orig2, t0);//t2 = bb & ~qbb
//LOK: Then calculate a_max = aa | qaa
tcg_gen_or_i64(t3, orig1, arg1);//t3 = aa | qaa
tcg_gen_or_i64(t4, orig2, arg2);//t4 = bb | qbb
//LOK: Now that we have the mins and maxes, we need to find the differences
//NOTE: This is why the order of the operands is important
tcg_gen_sub_i64(t0, t1, t4); // t0 = a_min - b_max
//LOK: Note that t3 is being reused in this case
tcg_gen_sub_i64(t4, t3, t2); // t4 = a_max - b_min
tcg_gen_xor_i64(t1, t0, t4); // t1 = ((a_min - b_max)^(a_max - b_min))
tcg_gen_or_i64(t0, arg1, arg2); // t0 = qa | qb
tcg_gen_or_i64(arg0, t0, t1); // arg0 = (qa | qb) | ( (a_min - b_max) ^ (a_max - b_min)
//put the original back
tcg_gen_sub_i64(orig0, orig1, orig2);
}
break;
#if 0
case INDEX_op_add_i64: // Up - cheap_AddSub64
case INDEX_op_sub_i64: // Up - cheap_AddSub64
#endif
case INDEX_op_mul_i64: // Up - mkUifU64(), mkLeft64(), mkPCastTo()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
if (!arg1 && !arg2) {
tcg_gen_movi_i64(arg0, 0);
break;
}
t0 = tcg_temp_new_i64();
if (arg1 && arg2)
// mkUifU64(arg1, arg2)
tcg_gen_or_i64(t0, arg1, arg2);
else if (arg1)
tcg_gen_movi_i64(t0, arg1);
else if (arg2)
tcg_gen_movi_i64(t0, arg2);
// mkLeft64(t0)
t1 = tcg_temp_new_i64();
tcg_gen_neg_i64(t1, t0); // (-s64)
tcg_gen_or_i64(arg0, t0, t1); // (s64 | (-s64)) -> vLo64
}
break;
#if TCG_TARGET_HAS_nand_i64
case INDEX_op_nand_i64: // Special - and_or_ty()
#endif /* TCG_TARGET_HAS_nand_i64 */
case INDEX_op_and_i64: // Special - and_or_ty()
#if TCG_TARGET_HAS_andc_i64
case INDEX_op_andc_i64: // Special - and_or_ty()
#endif /* TCG_TARGET_HAS_andc_i64 */
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-1];
orig1 = gen_opparam_ptr[-2];
if (!arg1 && !arg2) {
tcg_gen_movi_i64(arg0, 0);
break;
}
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
t3 = tcg_temp_new_i64();
/* T1 -> arg1
V1 -> gen_opparam_ptr[-2]
T2 -> arg2
V2 -> gen_opparam_ptr[-1] */
if (arg1)
tcg_gen_not_i64(t0, arg1); // NOT T1
else
tcg_gen_movi_i64(t0, -1);
if (arg2)
tcg_gen_and_i64(t1, orig1, arg2);//tcg_gen_and_i64(t1, gen_opparam_ptr[-2], arg2); // V1 * T2
else
tcg_gen_movi_i64(t1, 0);
tcg_gen_and_i64(t2, t0, t1); // (NOT T1) * V1 * T2
if (arg2)
tcg_gen_not_i64(t0, arg2); // NOT T2
else
tcg_gen_movi_i64(t0, -1);
if (arg1)
tcg_gen_and_i64(t1, arg1, orig0);//tcg_gen_and_i64(t1, arg1, gen_opparam_ptr[-1]); // T1 * V2
else
tcg_gen_movi_i64(t1, 0);
tcg_gen_and_i64(t3, t0, t1); // (T1 * (NOT T2) * V2)
if (arg1 && arg2)
tcg_gen_and_i64(t0, arg1, arg2); // T1 * T2
else
tcg_gen_movi_i64(t0, 0);
// OR it all together
tcg_gen_or_i64(t1, t2, t3);
tcg_gen_or_i64(arg0, t0, t1);
}
break;
#if TCG_TARGET_HAS_nor_i64
case INDEX_op_nor_i64: // Special - and_or_ty()
#endif /* TCG_TARGET_HAS_nor_i64 */
case INDEX_op_or_i64: // Special - and_or_ty()
#if TCG_TARGET_HAS_orc_i64
case INDEX_op_orc_i64: // Special - and_or_ty()
#endif /* TCG_TARGET_HAS_orc_i64 */
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
orig0 = gen_opparam_ptr[-1];
orig1 = gen_opparam_ptr[-2];
if (!arg1 && !arg2) {
tcg_gen_movi_i64(arg0, 0);
break;
}
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
t3 = tcg_temp_new_i64();
/* T1 -> arg1
V1 -> gen_opparam_ptr[-2]
T2 -> arg2
V2 -> gen_opparam_ptr[-1] */
if (arg1)
tcg_gen_not_i64(t0, arg1); // NOT T1
else
tcg_gen_movi_i64(t0, -1);
tcg_gen_not_i64(t1, orig1);//tcg_gen_not_i64(t1, gen_opparam_ptr[-2]); // NOT V1
tcg_gen_and_i64(t2, t0, t1); // (NOT T1) * (NOT V1)
if (arg2)
tcg_gen_and_i64(t0, t2, arg2); // (NOT T1) * (NOT V1) * T2
else
tcg_gen_movi_i64(t0, 0);
if (arg2)
tcg_gen_not_i64(t1, arg2); // NOT T2
else
tcg_gen_movi_i64(t1, -1);
tcg_gen_not_i64(t2, orig0);//tcg_gen_not_i64(t2, gen_opparam_ptr[-1]); // NOT V2
tcg_gen_and_i64(t3, t1, t2); // (NOT T2) * (NOT V2)
if (arg1)
tcg_gen_and_i64(t1, t3, arg1); // (NOT T2) * (NOT V2) * T1
else
tcg_gen_movi_i64(t1, 0);
if (arg1 && arg2)
tcg_gen_and_i64(t2, arg1, arg2); // T1 * T2
else if (arg1)
tcg_gen_mov_i64(t2, arg1);
else if (arg2)
tcg_gen_mov_i64(t2, arg2);
// OR it all together
tcg_gen_or_i64(t3, t0, t1);
tcg_gen_or_i64(arg0, t2, t3);
}
break;
#else
/* These all use the following pattern of shadow registers: */
/* arg0 = arg1 op arg2. To bitwise taint this pattern in shadow */
/* registers, we use the following steps:
Step 1: temp0 = arg1 or arg2
Step 2: temp1 = 0
Step 3: temp2 = (temp0 != temp1)
Step 4: arg0 = ~temp2 */
case INDEX_op_shl_i64:
case INDEX_op_shr_i64:
case INDEX_op_sar_i64:
#if TCG_TARGET_HAS_rot_i64
case INDEX_op_rotl_i64:
case INDEX_op_rotr_i64:
#endif /* TCG_TARGET_HAS_rot_i64 */
case INDEX_op_add_i64:
case INDEX_op_sub_i64:
case INDEX_op_mul_i64:
case INDEX_op_and_i64:
case INDEX_op_or_i64:
#if TCG_TARGET_HAS_andc_i64
case INDEX_op_andc_i64:
#endif /* TCG_TARGET_HAS_andc_i64 */
#if TCG_TARGET_HAS_orc_i64
case INDEX_op_orc_i64:
#endif /* TCG_TARGET_HAS_orc_i64 */
#if TCG_TARGET_HAS_nand_i64
case INDEX_op_nand_i64:
#endif /* TCG_TARGET_HAS_nand_i64 */
#if TCG_TARGET_HAS_nor_i64
case INDEX_op_nor_i64:
#endif /* TCG_TARGET_HAS_nor_i64 */
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
if (!arg1 && !arg2) {
tcg_gen_movi_i32(arg0, 0);
break;
}
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
if (arg1)
tcg_gen_mov_i64(t0, arg1);
else if (arg2)
tcg_gen_mov_i64(t0, arg2);
else
tcg_gen_or_i64(t0, arg1, arg2);
tcg_gen_movi_i64(t1, 0);
tcg_gen_setcond_i64(TCG_COND_NE, t2, t0, t1);
tcg_gen_neg_i64(arg0, t2);
}
break;
#endif /* TCG_BITWISE_TAINT */
#if TCG_TARGET_HAS_eqv_i64
case INDEX_op_eqv_i64: // In-Place - mkUifU64
#endif /* TCG_TARGET_HAS_eqv_i64 */
case INDEX_op_xor_i64: // In-Place - mkUifU64
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg1 && arg2)
// Perform an OR on arg1 and arg2 to find taint
tcg_gen_or_i64(arg0, arg1, arg2);
else if (arg1)
tcg_gen_mov_i64(arg0, arg1);
else if (arg2)
tcg_gen_mov_i64(arg0, arg2);
else
tcg_gen_movi_i64(arg0, 0);
}
break;
#if TCG_TARGET_HAS_div_i64
case INDEX_op_div_i64: // All-around: mkLazy2()
case INDEX_op_divu_i64: // All-around: mkLazy2()
case INDEX_op_rem_i64: // All-around: mkLazy2()
case INDEX_op_remu_i64: // All-around: mkLazy2()
arg0 = find_shadow_arg(gen_opparam_ptr[-3]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-2]);
arg2 = find_shadow_arg(gen_opparam_ptr[-1]);
if (!arg1 && !arg2) {
tcg_gen_movi_i64(arg0, 0);
break;
}
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
if (arg1)
tcg_gen_mov_i64(t0, arg1);
else if (arg2)
tcg_gen_mov_i64(t0, arg2);
else
tcg_gen_or_i64(t0, arg1, arg2);
tcg_gen_movi_i64(t1, 0);
tcg_gen_setcond_i64(TCG_COND_NE, t2, t0, t1);
tcg_gen_neg_i64(arg0, t2);
}
break;
#endif /* TCG_TARGET_HAS_div_i64 */
#if TCG_TARGET_HAS_div2_i64
case INDEX_op_div2_i64: // All-around: mkLazy3()
case INDEX_op_divu2_i64: // All-around: mkLazy3()
arg0 = find_shadow_arg(gen_opparam_ptr[-5]);
arg1 = find_shadow_arg(gen_opparam_ptr[-4]);
if (arg0 && arg1) {
arg2 = find_shadow_arg(gen_opparam_ptr[-3]);
arg3 = find_shadow_arg(gen_opparam_ptr[-2]);
arg4 = find_shadow_arg(gen_opparam_ptr[-1]);
t0 = tcg_temp_new_i64();
t1 = tcg_temp_new_i64();
t2 = tcg_temp_new_i64();
if (!arg2 && !arg3) {
if (!arg4) {
tcg_gen_movi_i64(arg0, 0);
tcg_gen_movi_i64(arg1, 0);
break;
}
tcg_gen_movi_i64(t0, 0);
} else
tcg_gen_or_i32(t0, arg2, arg3);
if (arg4)
tcg_gen_or_i32(t2, t0, arg4);
else
tcg_gen_mov_i32(t2, t0);
tcg_gen_movi_i32(t1, 0);
tcg_gen_setcond_i32(TCG_COND_NE, t0, t2, t1);
tcg_gen_neg_i32(arg0, t0);
tcg_gen_neg_i32(arg1, t0);
}
break;
#endif /* TCG_TARGET_HAS_div2_i64 */
#if TCG_TARGET_HAS_deposit_i64
case INDEX_op_deposit_i64: // Always bitwise taint
arg0 = find_shadow_arg(gen_opparam_ptr[-5]); // Output
if (arg0) {
int pos, len; // Constant parameters
arg1 = find_shadow_arg(gen_opparam_ptr[-4]); // Input1
arg2 = find_shadow_arg(gen_opparam_ptr[-3]); // Input2
// Pull out the two constant parameters
pos = gen_opparam_ptr[-2]; // Position of mask
len = gen_opparam_ptr[-1]; // Length of mask
// Handle special 64-bit transfer case (copy arg2 taint)
if (len == 64) {
if (arg2)
tcg_gen_mov_i64(arg0, arg2);
else
tcg_gen_movi_i64(arg0, 0);
// Handle special 0-bit transfer case (copy arg1 taint)
} else if (len == 0) {
if (arg1)
tcg_gen_mov_i64(arg0, arg1);
else
tcg_gen_movi_i64(arg0, 0);
// Handle general case
} else {
if (arg1 && arg2)
tcg_gen_deposit_tl(arg0, arg1, arg2, pos, len);
else if (arg1) {
t0 = tcg_temp_new_i64();
tcg_gen_movi_i64(t0, 0);
tcg_gen_deposit_tl(arg0, arg1, t0, pos, len);
} else if (arg2) {
t0 = tcg_temp_new_i64();
tcg_gen_movi_i64(t0, 0);
tcg_gen_deposit_tl(arg0, t0, arg2, pos, len);
}
}
}
break;
#endif /* TCG_TARGET_HAS_deposit_i64 */
#if TCG_TARGET_HAS_ext8s_i64
case INDEX_op_ext8s_i64: // MemCheck: VgT_SWiden18
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg1)
tcg_gen_ext8s_i64(arg0, arg1);
else
tcg_gen_movi_i64(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_ext8s_i64 */
#if TCG_TARGET_HAS_ext16s_i64
case INDEX_op_ext16s_i64: // MemCheck: VgT_SWiden28
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg1)
tcg_gen_ext16s_i64(arg0, arg1);
else
tcg_gen_movi_i64(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_ext16s_i64 */
#if TCG_TARGET_HAS_ext32s_i64
case INDEX_op_ext32s_i64: // MemCheck: VgT_SWiden48
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg1)
tcg_gen_ext32s_i64(arg0, arg1);
else
tcg_gen_movi_i64(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_ext32s_i64 */
#if TCG_TARGET_HAS_ext8u_i64
case INDEX_op_ext8u_i64: // MemCheck: VgT_ZWiden18
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg1)
tcg_gen_ext8u_i64(arg0, arg1);
else
tcg_gen_movi_i64(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_ext8u_i64 */
#if TCG_TARGET_HAS_ext16u_i64
case INDEX_op_ext16u_i64: // MemCheck: VgT_ZWiden28
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg1)
tcg_gen_ext16u_i64(arg0, arg1);
else
tcg_gen_movi_i64(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_ext16u_i64 */
#if TCG_TARGET_HAS_ext32u_i64
case INDEX_op_ext32u_i64: // MemCheck: VgT_ZWiden48
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg1)
tcg_gen_ext32u_i64(arg0, arg1);
else
tcg_gen_movi_i64(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_ext32u_i64 */
#if TCG_TARGET_HAS_bswap16_i64
case INDEX_op_bswap16_i64: // MemCheck: UifU2
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg1)
tcg_gen_bswap16_i64(arg0, arg1);
else
tcg_gen_movi_i64(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_bswap16_i64 */
#if TCG_TARGET_HAS_bswap32_i64
case INDEX_op_bswap32_i64: // MemCheck: UifU4
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg1)
tcg_gen_bswap32_i64(arg0, arg1);
else
tcg_gen_movi_i64(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_bswap32_i64 */
#if TCG_TARGET_HAS_bswap64_i64
case INDEX_op_bswap64_i64: // MemCheck: UifU8
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg1)
tcg_gen_bswap64_i64(arg0, arg1);
else
tcg_gen_movi_i64(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_bswap64_i64 */
#if TCG_TARGET_HAS_not_i64
case INDEX_op_not_i64: // MemCheck: nothing! Returns orig atom
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg1)
tcg_gen_mov_i64(arg0, arg1);
else
tcg_gen_movi_i64(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_not_i64 */
#if TCG_TARGET_HAS_neg_i64
case INDEX_op_neg_i64:
arg0 = find_shadow_arg(gen_opparam_ptr[-2]);
if (arg0) {
arg1 = find_shadow_arg(gen_opparam_ptr[-1]);
if (arg1)
tcg_gen_mov_i64(arg0, arg1);
else
tcg_gen_movi_i64(arg0, 0);
}
break;
#endif /* TCG_TARGET_HAS_neg_i64 */
/* QEMU-specific operations. */
case INDEX_op_ld8u_i32:
case INDEX_op_ld8s_i32:
case INDEX_op_ld16u_i32:
case INDEX_op_ld16s_i32:
case INDEX_op_ld_i32:
case INDEX_op_st8_i32:
case INDEX_op_st16_i32:
case INDEX_op_st_i32:
case INDEX_op_ld8u_i64:
case INDEX_op_ld8s_i64:
case INDEX_op_ld16u_i64:
case INDEX_op_ld16s_i64:
case INDEX_op_ld32u_i64:
case INDEX_op_ld32s_i64:
case INDEX_op_ld_i64:
case INDEX_op_st8_i64:
case INDEX_op_st16_i64:
case INDEX_op_st32_i64:
case INDEX_op_st_i64:
DUMMY_TAINT(nb_oargs, nb_args);
break; /* No taint info propagated (register liveness gets these) */
case INDEX_op_DECAF_checkeip:
if (DECAF_is_callback_needed(DECAF_EIP_CHECK_CB)){
arg0 = gen_opparam_ptr[-1];//target eip
arg1 = gen_opparam_ptr[-2];//source eip
TCGv shadow = shadow_arg[arg0];
if (shadow != 0) {
set_con_i32(0, arg1);
set_con_i32(1, arg0);
set_con_i32(2, shadow);
tcg_gen_helperN(helper_DECAF_invoke_eip_check_callback, 0,
0, TCG_CALL_DUMMY_ARG, 3, helper_arg_array);
}
}
break;
default:
fprintf(stderr, "gen_taintcheck_insn() -> UNKNOWN %d (%s)\n", opc, tcg_op_defs[opc].name);
fprintf(stderr, "(%s)\n", (tcg_op_defs[opc]).name);
assert(1==0);
break;
} /* End switch */
} /* End taint while loop */
return return_lj;
#else
return 0;
#endif /* CONFIG_TCG_TAINT */
}
int optimize_taint(int search_pc) {
int retVal;
#ifdef USE_TCG_OPTIMIZATIONS
if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP_OPT))) {
qemu_log("OP partial buffer before optimization:\n");
tcg_dump_ops(&tcg_ctx, logfile);
qemu_log("\n");
}
gen_opparam_ptr =
tcg_optimize(&tcg_ctx, gen_opc_ptr, gen_opparam_buf, tcg_op_defs);
#if 0 // AWH - Causes phantom taint in tempidx, so remove for now
build_liveness_metadata(&tcg_ctx);
#endif // AWH
#endif
block_count++;
if (unlikely(qemu_loglevel_mask(
CPU_LOG_TB_OUT_ASM | CPU_LOG_TB_IN_ASM |
CPU_LOG_TB_OP | CPU_LOG_TB_OP_OPT)) )
{
qemu_log("------------ BEGIN BLOCK %u ---------------------\n", block_count);
}
if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP_OPT))) {
qemu_log("OP partial buffer before taint instrumentation\n");
tcg_dump_ops(&tcg_ctx, logfile);
qemu_log("\n");
}
retVal = gen_taintcheck_insn(search_pc);
if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP))) {
qemu_log("OP after taint instrumentation\n");
tcg_dump_ops(&tcg_ctx, logfile);
qemu_log("\n");
}
return(retVal);
}
#if 0 //defined(USE_TCG_OPTIMIZATIONS)
static void build_liveness_metadata(TCGContext *s)
{
int i, op_index, nb_args, nb_iargs, nb_oargs, arg, nb_ops;
TCGOpcode op;
TCGArg *args;
const TCGOpDef *def;
uint8_t *dead_temps;
unsigned int dead_args;
nb_ops = gen_opc_ptr - gen_opc_buf;
dead_temps = tcg_malloc(s->nb_temps);
memset(dead_temps, 1, s->nb_temps);
args = gen_opparam_ptr;
op_index = nb_ops - 1;
while (op_index >= 0) {
//fprintf(stderr, "op_index: %d\n", op_index);
/* Liveness metadata (alive by default) */
gen_old_liveness_metadata[op_index] = 1;
op = gen_opc_buf[op_index];
def = &tcg_op_defs[op];
switch(op) {
case INDEX_op_call:
{
int call_flags;
nb_args = args[-1];
args -= nb_args;
nb_iargs = args[0] & 0xffff;
nb_oargs = args[0] >> 16;
args++;
call_flags = args[nb_oargs + nb_iargs];
/* pure functions can be removed if their result is not
used */
if (call_flags & TCG_CALL_PURE) {
for(i = 0; i < nb_oargs; i++) {
arg = args[i];
if (!dead_temps[arg])
goto do_not_remove_call;
}
/* Mark the liveness metadata that this will be
eliminated during liveness checks */
gen_old_liveness_metadata[op_index] = 0;
//fprintf(stderr, "Setting opc index: %d as dead\n", op_index);
//tcg_set_nop(s, gen_opc_buf + op_index,args - 1, nb_args);
} else {
do_not_remove_call:
/* output args are dead */
dead_args = 0;
for(i = 0; i < nb_oargs; i++) {
arg = args[i];
if (dead_temps[arg]) {
dead_args |= (1 << i);
}
dead_temps[arg] = 1;
}
if (!(call_flags & TCG_CALL_CONST)) {
/* globals are live (they may be used by the call) */
memset(dead_temps, 0, s->nb_globals);
}
/* input args are live */
for(i = nb_oargs; i < nb_iargs + nb_oargs; i++) {
arg = args[i];
if (arg != TCG_CALL_DUMMY_ARG) {
if (dead_temps[arg]) {
dead_args |= (1 << i);
}
dead_temps[arg] = 0;
}
}
}
args--;
}
break;
case INDEX_op_set_label:
args--;
/* mark end of basic block */
// AWH tcg_la_bb_end(s, dead_temps);
break;
case INDEX_op_debug_insn_start:
args -= def->nb_args;
break;
case INDEX_op_nopn:
nb_args = args[-1];
args -= nb_args;
break;
case INDEX_op_discard:
args--;
/* mark the temporary as dead */
dead_temps[args[0]] = 1;
break;
case INDEX_op_end:
break;
/* XXX: optimize by hardcoding common cases (e.g. triadic ops) */
default:
args -= def->nb_args;
nb_iargs = def->nb_iargs;
nb_oargs = def->nb_oargs;
/* Test if the operation can be removed because all
its outputs are dead. We assume that nb_oargs == 0
implies side effects */
if (!(def->flags & TCG_OPF_SIDE_EFFECTS) && nb_oargs != 0) {
for(i = 0; i < nb_oargs; i++) {
arg = args[i];
if (!dead_temps[arg])
goto do_not_remove;
}
/* Mark the liveness metadata that this will be
eliminated during liveness checks */
gen_old_liveness_metadata[op_index] = 0;
//fprintf(stderr, "Setting opc index: %d as dead\n", op_index);
//tcg_set_nop(s, gen_opc_buf + op_index, args, def->nb_args);
#ifdef CONFIG_PROFILER
// s->del_op_count++;
#endif
} else {
do_not_remove:
/* output args are dead */
dead_args = 0;
for(i = 0; i < nb_oargs; i++) {
arg = args[i];
if (dead_temps[arg]) {
dead_args |= (1 << i);
}
dead_temps[arg] = 1;
}
/* if end of basic block, update */
if (def->flags & TCG_OPF_BB_END) {
// AWH tcg_la_bb_end(s, dead_temps);
} else if (def->flags & TCG_OPF_CALL_CLOBBER) {
/* globals are live */
memset(dead_temps, 0, s->nb_globals);
}
/* input args are live */
for(i = nb_oargs; i < nb_oargs + nb_iargs; i++) {
arg = args[i];
if (dead_temps[arg]) {
dead_args |= (1 << i);
}
dead_temps[arg] = 0;
}
}
break;
}
op_index--;
}
if (args != gen_opparam_buf)
tcg_abort();
}
#endif /* USE_TCG_OPTIMIZATIONS */
|
KernelAnalysisPlatform/KlareDbg
|
tracers/qemu/decaf/shared/tainting/tcg_taint.c
|
C
|
gpl-3.0
| 113,817
|
package service;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import modelo.Menu;
@Stateless
public class MenuService extends GenericService<Menu>{
public MenuService() {
super(Menu.class);
}
public List<Menu> obtemMenuComMenuItens(){
final CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
final CriteriaQuery<Menu> cQuery = cb.createQuery(Menu.class);
cQuery.select(cQuery.from(Menu.class));
List<Menu> menu = getEntityManager().createQuery(cQuery).getResultList();
for (Menu m : menu) {
m.getItens().size();
}
return menu;
}
}
|
kashm1r/photoiff
|
src/service/MenuService.java
|
Java
|
gpl-3.0
| 699
|
.clearfix:after {
content: " ";
display: table;
clear: both;
}
.st-panel {
border: 1px solid #f00;
padding: 10px;
}
.st-panel .st-choise {
width: 45%;
float: left;
padding: 10px;
}
.st-panel img {
width: 100%;
}
.st-selected {
border: 2px solid green;
}
|
sergehog/subjective-test-framework
|
styles/main.css
|
CSS
|
gpl-3.0
| 300
|
/*
* Copyright (C) 2015 Information Retrieval Group at Universidad Autonoma
* de Madrid, http://ir.ii.uam.es
*
* 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 es.uam.eps.ir.ranksys.core.util.topn;
import it.unimi.dsi.fastutil.objects.AbstractObject2DoubleMap.BasicEntry;
import it.unimi.dsi.fastutil.objects.Object2DoubleMap.Entry;
/**
* Bounded min-heap to keep just the top-n greatest object-double pairs according to the value of the double.
*
* @author Saúl Vargas (saul.vargas@uam.es)
*
* @param <T> type of the object
*/
public class ObjectDoubleTopN<T> extends AbstractTopN<Entry<T>> {
private final T[] keys;
private final double[] values;
/**
* Constructor.
*
* @param capacity maximum capacity of the heap
*/
@SuppressWarnings("unchecked")
public ObjectDoubleTopN(int capacity) {
super(capacity);
keys = (T[]) new Object[capacity];
values = new double[capacity];
}
/**
* Tries to add an object-double pair to the heap.
*
* @param object object to be added
* @param value double to be added
* @return true if the pair was added to the heap, false otherwise
*/
public boolean add(T object, double value) {
return add(new BasicEntry<>(object, value));
}
@Override
protected Entry<T> get(int i) {
return new BasicEntry<>(keys[i], values[i]);
}
@Override
protected void set(int i, Entry<T> e) {
keys[i] = e.getKey();
values[i] = e.getDoubleValue();
}
@SuppressWarnings("unchecked")
@Override
protected int compare(int i, Entry<T> e) {
double v = e.getDoubleValue();
int c = Double.compare(values[i], v);
if (c != 0) {
return c;
} else {
c = ((Comparable<T>) keys[i]).compareTo(e.getKey());
return c;
}
}
@SuppressWarnings("unchecked")
@Override
protected int compare(int i, int j) {
int c = Double.compare(values[i], values[j]);
if (c != 0) {
return c;
} else {
c = ((Comparable<T>) keys[i]).compareTo(keys[j]);
return c;
}
}
@Override
protected void swap(int i, int j) {
T k = keys[i];
keys[i] = keys[j];
keys[j] = k;
double v = values[i];
values[i] = values[j];
values[j] = v;
}
}
|
OlafLee/RankSys
|
RankSys-core/src/main/java/es/uam/eps/ir/ranksys/core/util/topn/ObjectDoubleTopN.java
|
Java
|
gpl-3.0
| 3,023
|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.11.24 at 09:50:34 AM AEDT
//
package org.isotc211._2005.gco;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for TypeName_PropertyType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="TypeName_PropertyType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence minOccurs="0">
* <element ref="{http://www.isotc211.org/2005/gco}TypeName"/>
* </sequence>
* <attGroup ref="{http://www.isotc211.org/2005/gco}ObjectReference"/>
* <attribute ref="{http://www.isotc211.org/2005/gco}nilReason"/>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TypeName_PropertyType", propOrder = {
"typeName"
})
public class TypeNamePropertyType {
@XmlElement(name = "TypeName")
protected TypeNameType typeName;
@XmlAttribute(name = "nilReason", namespace = "http://www.isotc211.org/2005/gco")
protected List<String> nilReason;
@XmlAttribute(name = "uuidref")
protected String uuidref;
@XmlAttribute(name = "type", namespace = "http://www.w3.org/1999/xlink")
protected String type;
@XmlAttribute(name = "href", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anyURI")
protected String href;
@XmlAttribute(name = "role", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anyURI")
protected String role;
@XmlAttribute(name = "arcrole", namespace = "http://www.w3.org/1999/xlink")
@XmlSchemaType(name = "anyURI")
protected String arcrole;
@XmlAttribute(name = "title", namespace = "http://www.w3.org/1999/xlink")
protected String title;
@XmlAttribute(name = "show", namespace = "http://www.w3.org/1999/xlink")
protected String show;
@XmlAttribute(name = "actuate", namespace = "http://www.w3.org/1999/xlink")
protected String actuate;
/**
* Gets the value of the typeName property.
*
* @return
* possible object is
* {@link TypeNameType }
*
*/
public TypeNameType getTypeName() {
return typeName;
}
/**
* Sets the value of the typeName property.
*
* @param value
* allowed object is
* {@link TypeNameType }
*
*/
public void setTypeName(TypeNameType value) {
this.typeName = value;
}
/**
* Gets the value of the nilReason property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the nilReason property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNilReason().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getNilReason() {
if (nilReason == null) {
nilReason = new ArrayList<String>();
}
return this.nilReason;
}
/**
* Gets the value of the uuidref property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUuidref() {
return uuidref;
}
/**
* Sets the value of the uuidref property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUuidref(String value) {
this.uuidref = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
if (type == null) {
return "simple";
} else {
return type;
}
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the href property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHref() {
return href;
}
/**
* Sets the value of the href property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHref(String value) {
this.href = value;
}
/**
* Gets the value of the role property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRole() {
return role;
}
/**
* Sets the value of the role property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRole(String value) {
this.role = value;
}
/**
* Gets the value of the arcrole property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getArcrole() {
return arcrole;
}
/**
* Sets the value of the arcrole property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setArcrole(String value) {
this.arcrole = value;
}
/**
* Gets the value of the title property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTitle() {
return title;
}
/**
* Sets the value of the title property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitle(String value) {
this.title = value;
}
/**
* Gets the value of the show property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getShow() {
return show;
}
/**
* Sets the value of the show property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setShow(String value) {
this.show = value;
}
/**
* Gets the value of the actuate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getActuate() {
return actuate;
}
/**
* Sets the value of the actuate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setActuate(String value) {
this.actuate = value;
}
}
|
anu-doi/anudc
|
DataCommons/src/main/java/org/isotc211/_2005/gco/TypeNamePropertyType.java
|
Java
|
gpl-3.0
| 7,642
|
package de.jdellert.iwsa.tokenize;
/**
* Models a configuration for an IPATokenizer, essentially just a combination of
* binary flags, with the default configuration tuned towards NorthEuraLex.
*
*/
public class IPATokenizerConfiguration {
public final boolean SEPARATE_EJECTIVITY;
public final boolean SEPARATE_ASPIRATION;
public final boolean SEPARATE_NASAL_RELEASE;
public final boolean SEPARATE_LATERAL_RELEASE;
public final boolean SEPARATE_LABIALIZATION;
public final boolean SEPARATE_PALATALIZATION;
public final boolean SEPARATE_VELARIZATION;
public final boolean SEPARATE_NASALIZATION;
public final boolean SEPARATE_GLOTTALIZATION;
public final boolean SEPARATE_PHARYNGEALIZATION;
public final boolean SINGLE_SEGMENT_AFFRICATES;
public final boolean SINGLE_SEGMENT_DIPHTHONGS;
public final boolean SINGLE_SEGMENT_LONG_VOWELS;
public final boolean SINGLE_SEGMENT_GEMINATES;
public final boolean IGNORE_TONES;
public final boolean IGNORE_STRESS;
public final boolean IGNORE_SYLLABICITY;
public final boolean IGNORE_PHONATION_DIACRITICS;
public final boolean IGNORE_ARTICULATION_DIACRITICS;
public final boolean IGNORE_UNKNOWN_SYMBOLS;
// default tokenization: as in my dissertation (Dellert 2017)
public IPATokenizerConfiguration() {
SEPARATE_EJECTIVITY = true;
SEPARATE_ASPIRATION = true;
SEPARATE_NASAL_RELEASE = true;
SEPARATE_LATERAL_RELEASE = true;
SEPARATE_LABIALIZATION = true;
SEPARATE_PALATALIZATION = true;
SEPARATE_VELARIZATION = true;
SEPARATE_NASALIZATION = true;
SEPARATE_GLOTTALIZATION = true;
SEPARATE_PHARYNGEALIZATION = true;
SINGLE_SEGMENT_AFFRICATES = true;
SINGLE_SEGMENT_DIPHTHONGS = false;
SINGLE_SEGMENT_LONG_VOWELS = false;
SINGLE_SEGMENT_GEMINATES = false;
IGNORE_TONES = true;
IGNORE_STRESS = true;
IGNORE_SYLLABICITY = true;
IGNORE_PHONATION_DIACRITICS = true;
IGNORE_ARTICULATION_DIACRITICS = true;
IGNORE_UNKNOWN_SYMBOLS = true;
}
public IPATokenizerConfiguration(boolean SEPARATE_EJECTIVITY, boolean SEPARATE_ASPIRATION,
boolean SEPARATE_NASAL_RELEASE, boolean SEPARATE_LATERAL_RELEASE, boolean SEPARATE_LABIALIZATION,
boolean SEPARATE_PALATALIZATION, boolean SEPARATE_VELARIZATION, boolean SEPARATE_NASALIZATION,
boolean SEPARATE_GLOTTALIZATION, boolean SEPARATE_PHARYNGEALIZATION, boolean SINGLE_SEGMENT_AFFRICATES,
boolean SINGLE_SEGMENT_DIPHTHONGS, boolean SINGLE_SEGMENT_LONG_VOWELS, boolean SINGLE_SEGMENT_GEMINATES,
boolean IGNORE_TONES, boolean IGNORE_STRESS, boolean IGNORE_SYLLABICITY,
boolean IGNORE_PHONATION_DIACRITICS, boolean IGNORE_ARTICULATION_DIACRITICS,
boolean IGNORE_UNKNOWN_SYMBOLS) {
this.SEPARATE_EJECTIVITY = SEPARATE_EJECTIVITY;
this.SEPARATE_ASPIRATION = SEPARATE_ASPIRATION;
this.SEPARATE_NASAL_RELEASE = SEPARATE_NASAL_RELEASE;
this.SEPARATE_LATERAL_RELEASE = SEPARATE_LATERAL_RELEASE;
this.SEPARATE_LABIALIZATION = SEPARATE_LABIALIZATION;
this.SEPARATE_PALATALIZATION = SEPARATE_PALATALIZATION;
this.SEPARATE_VELARIZATION = SEPARATE_VELARIZATION;
this.SEPARATE_NASALIZATION = SEPARATE_NASALIZATION;
this.SEPARATE_GLOTTALIZATION = SEPARATE_GLOTTALIZATION;
this.SEPARATE_PHARYNGEALIZATION = SEPARATE_PHARYNGEALIZATION;
this.SINGLE_SEGMENT_AFFRICATES = SINGLE_SEGMENT_AFFRICATES;
this.SINGLE_SEGMENT_DIPHTHONGS = SINGLE_SEGMENT_DIPHTHONGS;
this.SINGLE_SEGMENT_LONG_VOWELS = SINGLE_SEGMENT_LONG_VOWELS;
this.SINGLE_SEGMENT_GEMINATES = SINGLE_SEGMENT_GEMINATES;
this.IGNORE_TONES = IGNORE_TONES;
this.IGNORE_STRESS = IGNORE_STRESS;
this.IGNORE_SYLLABICITY = IGNORE_SYLLABICITY;
this.IGNORE_PHONATION_DIACRITICS = IGNORE_PHONATION_DIACRITICS;
this.IGNORE_ARTICULATION_DIACRITICS = IGNORE_ARTICULATION_DIACRITICS;
this.IGNORE_UNKNOWN_SYMBOLS = IGNORE_UNKNOWN_SYMBOLS;
}
}
|
jdellert/iwsa
|
src/de/jdellert/iwsa/tokenize/IPATokenizerConfiguration.java
|
Java
|
gpl-3.0
| 3,782
|
package jeql.workbench.ui.geomview.style;
import java.util.*;
import java.awt.Graphics2D;
import jeql.workbench.ui.geomview.Viewport;
import org.locationtech.jts.geom.Geometry;
/**
* Contains a list of styles and allows Geometrys
* to be rendered using those styles.
*
* @author mbdavis
*
*/
public class StyleList implements Style
{
private List styleList = new ArrayList();
public void paint(Geometry geom, Viewport viewport, Graphics2D g)
throws Exception
{
for (Iterator i = styleList.iterator(); i.hasNext(); ) {
StyleEntry styleEntry = (StyleEntry) i.next();
if (styleEntry.isFullyEnabled())
styleEntry.getStyle().paint(geom, viewport, g);
}
}
public void add(Style style)
{
add(style, null);
}
public void add(Style style, StyleFilter filter)
{
styleList.add(new StyleEntry(style, filter));
}
public void setEnabled(Style style, boolean isEnabled)
{
StyleEntry entry = getEntry(style);
if (entry == null)
return;
entry.setEnabled(isEnabled);
}
private StyleEntry getEntry(Style style)
{
int index = getEntryIndex(style);
if (index < 0) return null;
return (StyleEntry) styleList.get(index);
}
private int getEntryIndex(Style style)
{
for (int i = 0; i < styleList.size(); i++) {
StyleEntry entry = (StyleEntry) styleList.get(i);
if (entry.getStyle() == style)
return i;
}
return -1;
}
public interface StyleFilter {
boolean isFiltered(Style style);
}
}
class StyleEntry
{
private Style style;
private boolean isEnabled = true;
private StyleList.StyleFilter filter = null;
public StyleEntry(Style style)
{
this.style = style;
}
public StyleEntry(Style style, StyleList.StyleFilter filter)
{
this.style = style;
this.filter = filter;
}
public void setEnabled(boolean isEnabled)
{
this.isEnabled = isEnabled;
}
public boolean isEnabled() { return isEnabled; }
public boolean isFiltered() {
if (filter == null)
return false;
return filter.isFiltered(style);
}
public boolean isFullyEnabled()
{
return isEnabled() && ! isFiltered();
}
public Style getStyle() { return style; }
}
|
dr-jts/jeql
|
modules/jeqlw/src/main/java/jeql/workbench/ui/geomview/style/StyleList.java
|
Java
|
gpl-3.0
| 2,177
|
package com.drexel.septaplanner;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLoadedCallback;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.LatLngBounds.Builder;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MyMapFrag extends FragmentActivity {
String tag = "mymapfrag";
LatLngBounds bounds;
public GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_fragment);
// get arraylist passed into intent
Intent i = getIntent();
ArrayList<septaTrain> trains = i.getParcelableArrayListExtra("trains");
// make map object
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
// set markers on map
ArrayList<Marker> markers = new ArrayList<Marker>();
LatLng l;
Builder bBounds = new LatLngBounds.Builder();
//get bounds for the group of trains and also the add markers on
//map for those trains
for (int k = 0; k < trains.size(); k++) {
l = trains.get(k).getLatlong();
if (l.latitude != 0 && l.longitude != 0) {
bBounds.include(l);
markers.add(mMap.addMarker(new MarkerOptions().position(l)
.title("#" + trains.get(k).getTrainNum())));
}
}
if (markers.size() == 0){
//create bounds for philadelphia septa area
bBounds.include(new LatLng(39.863371,-75.411728));
bBounds.include(new LatLng(40.295894,-74.681652));
Toast.makeText(
MyMapFrag.this,
"There are no trains with gps coordinates on this route",
Toast.LENGTH_LONG).show();
}
bounds = bBounds.build();
mMap.setOnMapLoadedCallback(new OnMapLoadedCallback() {
@Override
public void onMapLoaded() {
mMap.animateCamera(
CameraUpdateFactory.newLatLngBounds(bounds, 100), 1500,
null);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
}
|
JamesBarnes88/SeptaPlanner
|
src/com/drexel/septaplanner/MyMapFrag.java
|
Java
|
gpl-3.0
| 2,520
|
package net.qrab.watchit.stages;
import com.badlogic.gdx.scenes.scene2d.Stage;
public class HudStage extends Stage {
public HudStage() {
}
}
|
jkleininger/BaggageClimb
|
core/src/net/qrab/watchit/stages/HudStage.java
|
Java
|
gpl-3.0
| 148
|
<!DOCTYPE html>
<html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-GB">
<title>Ross Gammon’s Family Tree - Events</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">Ross Gammon’s Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li class = "CurrentSection"><a href="../../../events.html" title="Events">Events</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="EventDetail">
<h3>Birth</h3>
<table class="infolist eventlist">
<tbody>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnGRAMPSID">E3701</td>
</tr>
<tr>
<td class="ColumnAttribute">Date</td>
<td class="ColumnColumnDate">
1742
</td>
</tr>
<tr>
<td class="ColumnAttribute">Place</td>
<td class="ColumnColumnPlace">
<a href="../../../plc/2/2/d15f5fe17274355d899e941ca22.html" title="">
</a>
</td>
</tr>
</tbody>
</table>
<div class="subsection" id="references">
<h4>References</h4>
<ol class="Col1" role="Volume-n-Page"type = 1>
<li>
<a href="../../../ppl/d/9/d15f5fe28ec5cecb9f12c6c8e9d.html">
CHUGG, Elizabeth
<span class="grampsid"> [I3321]</span>
</a>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:54:14<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
|
RossGammon/the-gammons.net
|
RossFamilyTree/evt/3/4/d15f5fe28ef48fb96c6893a0443.html
|
HTML
|
gpl-3.0
| 2,906
|
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!!
# This file is machine-generated by lib/unicore/mktables from the Unicode
# database, Version 13.0.0. Any changes made here will be lost!
# !!!!!!! INTERNAL PERL USE ONLY !!!!!!!
# This file is for internal use by core Perl only. The format and even the
# name or existence of this file are subject to change without notice. Don't
# use it directly. Use Unicode::UCD to access the Unicode character data
# base.
return <<'END';
V40
173
174
1536
1542
1564
1565
1757
1758
1807
1808
2274
2275
6158
6159
8203
8204
8206
8208
8234
8239
8288
8293
8294
8304
65279
65280
65529
65532
69821
69822
69837
69838
78896
78905
113824
113828
119155
119163
917505
917506
END
|
Ascoware/get-iplayer-automator
|
Binaries/get_iplayer/perl/lib/5.32.0/unicore/lib/SB/FO.pl
|
Perl
|
gpl-3.0
| 711
|
'use strict';
/**
* Module dependencies
*/
var path = require('path'),
config = require(path.resolve('./config/config'));
/**
* Quiz module init function.
*/
module.exports = function (app, db) {
};
|
AnnaGenev/pokeapp-meanjs
|
modules/quiz/server/config/quiz.server.config.js
|
JavaScript
|
gpl-3.0
| 208
|
/*
* Copyright (C) 2014 Robert Stark
*
* 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 de.rs.scrumit.entity;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.hibernate.annotations.OrderBy;
import org.hibernate.envers.Audited;
@Entity
@Table(name="release")
public class ReleaseModel extends BaseEntityAuditModel {
private static final long serialVersionUID = 1L;
@Audited(withModifiedFlag=true)
private String description;
@ManyToOne(optional=false)
private ReleasePlanModel releasePlan;
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable=false)
@Audited(withModifiedFlag=true)
private Date releaseDate;
@OneToMany(mappedBy="release", targetEntity=SprintModel.class, fetch=FetchType.LAZY)
@OrderBy(clause="startdate")
private List<SprintModel> sprints;
public ReleaseModel(){}
public ReleaseModel(String code, Date releaseDate) {
super(code);
this.releaseDate = releaseDate;
}
public ReleaseModel(String code, ReleasePlanModel releasePlan, Date releaseDate) {
super(code);
this.releasePlan = releasePlan;
this.releaseDate = releaseDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ReleasePlanModel getReleasePlan() {
return releasePlan;
}
public void setReleasePlan(ReleasePlanModel releasePlan) {
this.releasePlan = releasePlan;
}
public Date getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(Date releaseDate) {
this.releaseDate = releaseDate;
}
public List<SprintModel> getSprints() {
return sprints;
}
public void setSprints(List<SprintModel> sprints) {
this.sprints = sprints;
}
}
|
StarkoMania/scrum-it
|
src/main/java/de/rs/scrumit/entity/ReleaseModel.java
|
Java
|
gpl-3.0
| 2,590
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ancienttiles;
import ancienttiles.griddisplay.TileDisplay;
import ancienttiles.tiles.ai.TimedObject;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.Timer;
import javax.swing.event.MouseInputAdapter;
/**
*
* @author krr428
*/
public abstract class AbstractGameManager
{
private AbstractMapManager mapManager = null;
private HumIntManager humanIntelligenceManager = null;
private AbstractAIManager aiManager = null;
private ViewManager viewManager = null;
private AbstractTimingManager timingManager = null;
private AbstractInputManager inputManager = null;
//<editor-fold defaultstate="collapsed" desc="Field Gets/Sets">
public AbstractMapManager getMapManager()
{
return mapManager;
}
protected void setMapManager(AbstractMapManager mapManager)
{
this.mapManager = mapManager;
}
public HumIntManager getHIManager()
{
return humanIntelligenceManager;
}
protected void setHIManager(HumIntManager humanIntelligenceManager)
{
this.humanIntelligenceManager = humanIntelligenceManager;
}
public AbstractAIManager getAIManager()
{
return aiManager;
}
protected void setAIManager(AbstractAIManager aiManager)
{
this.aiManager = aiManager;
}
public ViewManager getViewManager()
{
return viewManager;
}
protected void setViewManager(ViewManager viewManager)
{
this.viewManager = viewManager;
}
public AbstractTimingManager getTimingManager()
{
return timingManager;
}
protected void setTimingManager(AbstractTimingManager timingManager)
{
this.timingManager = timingManager;
}
public AbstractInputManager getInputManager()
{
return inputManager;
}
protected void setInputManager(AbstractInputManager inputManager)
{
this.inputManager = inputManager;
}
//</editor-fold>
// This method provided for convenience and compatibility.
public LayerStack getCurrentMap()
{
return getMapManager().getCurrent();
}
public interface MapChangedListener
{
public void mapChanged();
}
public abstract class AbstractMapManager
{
//<editor-fold defaultstate="collapsed" desc="MapChangedEvent">
private Set<MapChangedListener> mapChangedListeners = null;
public AbstractMapManager()
{
mapChangedListeners = new HashSet<MapChangedListener>();
}
public void addMapChangedListener(MapChangedListener mcl)
{
mapChangedListeners.add(mcl);
}
public void removeMapChangedListener(MapChangedListener mcl)
{
mapChangedListeners.remove(mcl);
}
public void fireMapChanged()
{
for (MapChangedListener mcl: mapChangedListeners)
{
mcl.mapChanged();
}
getViewManager().setUpdateOn();
}
//</editor-fold>
public abstract LayerStack getCurrent();
public abstract LayerStack getMap(String name);
public abstract void addMap(String name, LayerStack map);
public abstract void setCurrentMap(String name);
public abstract void setCurrentMap(LayerStack ls);
public abstract Collection<Tile> getCurTiles(int x, int y);
public abstract void resetCurrent();
public abstract void loadMap(URL location, int width, int height);
public abstract void loadMap(URL location);
public abstract void loadParent();
// @Deprecated
// public void initTimedObjects()
// {
// getAIManager().initTimedObjects();
// }
}
public class HumIntManager
{
private HumanIntelligence humanIntelligence = null;
public HumanIntelligence getHI()
{
return humanIntelligence;
}
void setHI(HumanIntelligence hi)
{
this.humanIntelligence = hi;
this.humanIntelligence.setManager(AbstractGameManager.this);
}
}
public abstract class AbstractAIManager
{
public abstract void killTimedObjects();
public abstract void initTimedObjects();
}
public abstract class AbstractInputManager
{
protected InputMap inputMap = null;
protected ActionMap actionMap = null;
public AbstractInputManager()
{
}
public AbstractInputManager(InputMap im, ActionMap am)
{
setActionMap(am);
setInputMap(im);
}
public AbstractInputManager(AbstractInputManager formerManager)
{
this(formerManager.getInputMap(), formerManager.getActionMap());
}
public InputMap getInputMap()
{
return inputMap;
}
public final void setInputMap(InputMap inputMap)
{
this.inputMap = inputMap;
}
public ActionMap getActionMap()
{
return actionMap;
}
public final void setActionMap(ActionMap actionMap)
{
this.actionMap = actionMap;
}
public abstract void init(); //Called when the
//public abstract void bindKeys();
public abstract MouseInputAdapter getMouseInputAdapter();
}
public class ViewManager implements ActionListener
{
private TileDisplay view = null;
private Timer paintTimer = null;
private boolean updateViewFlag = true;
public ViewManager(TileDisplay td)
{
this.setDisplay(td);
//Set to 1000ms / 40 frames per second.
paintTimer = new Timer(1000/60, this);
paintTimer.start();
}
public void setUpdateOn()
{
updateViewFlag = true;
}
public TileDisplay getView()
{
return view;
}
public final void setDisplay(TileDisplay td)
{
view = td;
}
@Override
public void actionPerformed(ActionEvent e)
{
if (view != null && updateViewFlag)
{
view.repaint();
updateViewFlag = false;
}
}
}
public abstract class AbstractTimingManager
{
public abstract void addListener(String timer, TimedObject t);
public abstract void removeListener(String timer, TimedObject t);
public abstract void createTimer(String name, int interval);
public abstract void pauseTimer(String name);
public abstract void removeTimer(String name);
public abstract boolean containsTimer(String name);
}
}
|
krrg/ancient-tiles-java
|
src/ancienttiles/AbstractGameManager.java
|
Java
|
gpl-3.0
| 7,396
|
<?php
/**
* Extensions list template
*
* @package notification
*/
$premium_extensions = (array) $this->get_var( 'premium_extensions' );
?>
<div class="wrap notification-extensions">
<h1><?php esc_html_e( 'Extensions', 'notification' ); ?></h1>
<?php if ( ! empty( $premium_extensions ) ) : ?>
<h2><?php esc_html_e( 'Premium extensions', 'notification' ); ?></h2>
<div id="the-list">
<?php foreach ( $premium_extensions as $extension ) : ?>
<?php
$this->set_var( 'extension', $extension, true );
$this->get_view( 'extension/extension-box-premium' );
?>
<?php endforeach; ?>
</div>
<div class="clear"></div>
<?php endif ?>
<?php if ( ! empty( $premium_extensions ) ) : ?>
<h2><?php esc_html_e( 'Available extensions', 'notification' ); ?></h2>
<?php endif ?>
<div id="the-list">
<?php foreach ( (array) $this->get_var( 'extensions' ) as $extension ) : ?>
<?php
$this->set_var( 'extension', $extension, true );
$this->get_view( 'extension/extension-box' );
?>
<?php endforeach; ?>
<?php $this->get_view( 'extension/promo-box' ); ?>
</div>
</div>
|
Kubitomakita/Notification
|
views/extension/page.php
|
PHP
|
gpl-3.0
| 1,120
|
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "jobs" collection of methods.
* Typical usage is:
* <code>
* $dataprocService = new Google_Service_Dataproc(...);
* $jobs = $dataprocService->jobs;
* </code>
*/
class Google_Service_Dataproc_Resource_ProjectsRegionsJobs extends Google_Service_Resource
{
/**
* Starts a job cancellation request. To access the job resource after
* cancellation, call regions/{region}/jobs.list or regions/{region}/jobs.get.
* (jobs.cancel)
*
* @param string $projectId Required. The ID of the Google Cloud Platform
* project that the job belongs to.
* @param string $region Required. The Cloud Dataproc region in which to handle
* the request.
* @param string $jobId Required. The job ID.
* @param Google_Service_Dataproc_CancelJobRequest $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_Dataproc_Job
*/
public function cancel($projectId, $region, $jobId, Google_Service_Dataproc_CancelJobRequest $postBody, $optParams = array())
{
$params = array('projectId' => $projectId, 'region' => $region, 'jobId' => $jobId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('cancel', array($params), "Google_Service_Dataproc_Job");
}
/**
* Deletes the job from the project. If the job is active, the delete fails, and
* the response returns FAILED_PRECONDITION. (jobs.delete)
*
* @param string $projectId Required. The ID of the Google Cloud Platform
* project that the job belongs to.
* @param string $region Required. The Cloud Dataproc region in which to handle
* the request.
* @param string $jobId Required. The job ID.
* @param array $optParams Optional parameters.
* @return Google_Service_Dataproc_DataprocEmpty
*/
public function delete($projectId, $region, $jobId, $optParams = array())
{
$params = array('projectId' => $projectId, 'region' => $region, 'jobId' => $jobId);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params), "Google_Service_Dataproc_DataprocEmpty");
}
/**
* Gets the resource representation for a job in a project. (jobs.get)
*
* @param string $projectId Required. The ID of the Google Cloud Platform
* project that the job belongs to.
* @param string $region Required. The Cloud Dataproc region in which to handle
* the request.
* @param string $jobId Required. The job ID.
* @param array $optParams Optional parameters.
* @return Google_Service_Dataproc_Job
*/
public function get($projectId, $region, $jobId, $optParams = array())
{
$params = array('projectId' => $projectId, 'region' => $region, 'jobId' => $jobId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Dataproc_Job");
}
/**
* Lists regions/{region}/jobs in a project. (jobs.listProjectsRegionsJobs)
*
* @param string $projectId Required. The ID of the Google Cloud Platform
* project that the job belongs to.
* @param string $region Required. The Cloud Dataproc region in which to handle
* the request.
* @param array $optParams Optional parameters.
*
* @opt_param string filter Optional. A filter constraining the jobs to list.
* Filters are case-sensitive and have the following syntax:field = value AND
* field = value ...where field is status.state or labels.[KEY], and [KEY] is a
* label key. value can be * to match all values. status.state can be either
* ACTIVE or INACTIVE. Only the logical AND operator is supported; space-
* separated items are treated as having an implicit AND operator.Example
* filter:status.state = ACTIVE AND labels.env = staging AND labels.starred = *
* @opt_param string jobStateMatcher Optional. Specifies enumerated categories
* of jobs to list (default = match ALL jobs).
* @opt_param string pageToken Optional. The page token, returned by a previous
* call, to request the next page of results.
* @opt_param int pageSize Optional. The number of results to return in each
* response.
* @opt_param string clusterName Optional. If set, the returned jobs list
* includes only jobs that were submitted to the named cluster.
* @return Google_Service_Dataproc_ListJobsResponse
*/
public function listProjectsRegionsJobs($projectId, $region, $optParams = array())
{
$params = array('projectId' => $projectId, 'region' => $region);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_Dataproc_ListJobsResponse");
}
/**
* Updates a job in a project. (jobs.patch)
*
* @param string $projectId Required. The ID of the Google Cloud Platform
* project that the job belongs to.
* @param string $region Required. The Cloud Dataproc region in which to handle
* the request.
* @param string $jobId Required. The job ID.
* @param Google_Service_Dataproc_Job $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string updateMask Required. Specifies the path, relative to Job,
* of the field to update. For example, to update the labels of a Job the
* update_mask parameter would be specified as labels, and the PATCH request
* body would specify the new value. Note: Currently, labels is the only field
* that can be updated.
* @return Google_Service_Dataproc_Job
*/
public function patch($projectId, $region, $jobId, Google_Service_Dataproc_Job $postBody, $optParams = array())
{
$params = array('projectId' => $projectId, 'region' => $region, 'jobId' => $jobId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('patch', array($params), "Google_Service_Dataproc_Job");
}
/**
* Submits a job to a cluster. (jobs.submit)
*
* @param string $projectId Required. The ID of the Google Cloud Platform
* project that the job belongs to.
* @param string $region Required. The Cloud Dataproc region in which to handle
* the request.
* @param Google_Service_Dataproc_SubmitJobRequest $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_Dataproc_Job
*/
public function submit($projectId, $region, Google_Service_Dataproc_SubmitJobRequest $postBody, $optParams = array())
{
$params = array('projectId' => $projectId, 'region' => $region, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('submit', array($params), "Google_Service_Dataproc_Job");
}
}
|
dannydes/ecologie
|
vendor/google/apiclient-services/src/Google/Service/Dataproc/Resource/ProjectsRegionsJobs.php
|
PHP
|
gpl-3.0
| 7,165
|
Module mdmWaveDb
Public Declare Function waveInOpen Lib "winmm.dll" Alias "waveInOpen" (lphWaveIn As Integer, ByVal uDeviceID As Integer, lpFormat As WAVEFORMAT, ByVal dwCallback As Integer, ByVal dwInstance As Integer, ByVal dwFlags As Integer) As Integer
Public Declare Function CreateEvent Lib "kernel32" Alias "CreateEventA" (lpEventAttributes As SECURITY_ATTRIBUTES, ByVal bManualReset As Integer, ByVal bInitialState As Integer, ByVal lpName As String) As Integer
Public Declare Function waveInPrepareHeader Lib "winmm.dll" Alias "waveInPrepareHeader" (ByVal hWaveIn As Integer, lpWaveInHdr As WAVEHDR, ByVal uSize As Integer) As Integer
Public Declare Function waveInAddBuffer Lib "winmm.dll" Alias "waveInAddBuffer" (ByVal hWaveIn As Integer, lpWaveInHdr As WAVEHDR, ByVal uSize As Integer) As Integer
Public Declare Function waveInStart Lib "winmm.dll" Alias "waveInStart" (ByVal hWaveIn As Integer) As Integer
Public Declare Function waveInReset Lib "winmm.dll" Alias "waveInReset" (ByVal hWaveIn As Integer) As Integer
Public Const WAVE_MAPPER = -1&
Public Const CALLBACK_FUNCTION = &H30000 ' dwCallback is a FARPROC
Public Const WAVE_FORMAT_PCM = &H1
Private Function fnByteToInt16(ByVal Buffer0 As Byte, ByVal Buffer1 As Byte) As Int16
Dim B1 As Integer = Buffer1
Dim B0 As Integer = Buffer0
If B1 <= 127 Then
fnByteToInt16 = B1 * 256 + B0
Else
fnByteToInt16 = B1 * 256 + B0 - 65536
End If
End Function
Public Structure WAVEFORMATEX
Dim wFormatTag As Int16
Dim nChannels As Int16
Dim nSamplesPerSec As Int32
Dim nAvgBytesPerSec As Int32
Dim nBlockAlign As Int16
Dim wBitsPerSample As Int16
Dim cbSize As Int16
End Structure
Public Structure WAVEFORMAT
Dim wFormatTag As Int16
Dim nChannels As Int16
Dim nSamplesPerSec As Int32
Dim nAvgBytesPerSec As Int32
Dim nBlockAlign As Int16
End Structure
Public Structure SECURITY_ATTRIBUTES
Dim nLength As Int32
Dim lpSecurityDescriptor As Int32
Dim bInheritHandle As Int32
End Structure
Public Structure WAVEHDR
Dim lpData As String
Dim dwBufferLength As Int32
Dim dwBytesRecorded As Int32
Dim dwUser As Int32
Dim dwFlags As Int32
Dim dwLoops As Int32
Dim lpNext As Int32
Dim Reserved As Int32
End Structure
Public Function fngetPcmDB(ByRef pcmdata() As Byte, ByVal size As Integer) As Integer
Dim db As Int32 = 0
Dim value As Int16 = 0
Dim sum As Double = 0
For i As Integer = 0 To size - 1 Step 2
value = fnByteToInt16(pcmdata(i), pcmdata(i + 1))
'CopyMemory(value, pcmdata + i, 2) '获取2个字节的大小(值)
sum += System.Math.Abs(value) ' 绝对值求和
Next
sum = sum / (size / 2) ' //求平均值(2个字节表示一个振幅,所以振幅个数为:size/ 2个)
If sum > 0 Then
db = Int(20.0 * System.Math.Log(sum))
End If
Return db
End Function
End Module
|
moummn/MMN
|
mWaveDb/mWaveDb/mdmWaveDb.vb
|
Visual Basic
|
gpl-3.0
| 3,205
|
#ifndef Hector_Utils_String_h
#define Hector_Utils_String_h
#include <string>
namespace hector {
/// Format a string using a printf style format descriptor.
std::string format(const std::string fmt, ...);
/// Remove leading and trailing whitespaces to a string
std::string trim(const std::string& str);
/// Get the lowercase version of a string
std::string lowercase(const std::string& str);
/// Enumeration of possible TTY colours
enum class Colour {
reset = -1,
black = 30,
red = 31,
green = 32,
yellow = 33,
blue = 34,
magenta = 35,
cyan = 36,
white = 37
};
/// TTY-type enumeration of text styles
enum class Modifier { reset = -1, bold = 1, dimmed = 2, italic = 3, underline = 4, blink = 5, reverse = 7 };
/// Set the TTY colour and font style for a string
std::string colourise(const std::string& str, Colour col, Modifier mod);
/// Current human-readable date and time
std::string now();
} // namespace hector
#endif
|
hectorhep/hector2
|
Hector/Utils/String.h
|
C
|
gpl-3.0
| 993
|
/*
Copyright (c) 2009 Andrew Caudwell (acaudwell@gmail.com)
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. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#include "seeklog.h"
long gSeekLogMaxBufferSize = 104857600;
//StreamLog
StreamLog::StreamLog() {
this->stream = &std::cin;
fcntl_fail = false;
#ifdef _WIN32
stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
#else
int ret = fcntl(STDIN_FILENO, F_GETFL, 0);
if (fcntl (STDIN_FILENO, F_SETFL, ret | O_NONBLOCK) < 0) {
debugLog("fcntl(stdin) failed\n");
fcntl_fail = true;
}
#endif
}
StreamLog::~StreamLog() {
}
bool StreamLog::getNextLine(std::string& line) {
//try and fix the stream
if(isFinished()) stream->clear();
#ifdef _WIN32
DWORD available_bytes;
if (!PeekNamedPipe(stdin_handle, 0, 0, 0,
&available_bytes, 0)) return false;
if(available_bytes==0) return false;
#endif
std::getline(*stream, line);
//remove carriage returns
if (line.size() > 0 && line[line.size()-1] == '\r') {
line.resize(line.size() - 1);
}
if(isFinished()) {
return false;
}
return true;
}
bool StreamLog::isFinished() {
if(fcntl_fail || stream->fail() || stream->eof()) {
return true;
}
return false;
}
// SeekLog
SeekLog::SeekLog(std::string logfile) {
this->logfile = logfile;
this->stream = 0;
if(!readFully()) {
throw SeekLogException(logfile);
}
}
bool SeekLog::readFully() {
if(stream!=0) delete stream;
std::ifstream* file = new std::ifstream(logfile.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
file_size = file->tellg();
if(!file->is_open()) return false;
file->seekg (0, std::ios::beg);
//dont load into memory if larger than
if(file_size > gSeekLogMaxBufferSize) {
stream = file;
return true;
}
//buffer entire file into memory
char* filebuffer = new char[file_size+1];
if(!file->read(filebuffer, file_size)) {
file->close();
delete file;
return false;
}
filebuffer[file_size] = '\0';
file->close();
delete file;
stream = new std::istringstream(std::string(filebuffer));
delete[] filebuffer;
return true;
}
SeekLog::~SeekLog() {
if(stream!=0) delete stream;
}
float SeekLog::getPercent() {
return current_percent;
}
void SeekLog::setPointer(std::streampos pointer) {
stream->seekg(pointer);
}
std::streampos SeekLog::getPointer() {
return stream->tellg();
}
void SeekLog::seekTo(float percent) {
if(isFinished()) stream->clear();
std::streampos mem_offset = (std::streampos) (percent * file_size);
setPointer(mem_offset);
//throw away end of line
if(mem_offset != (std::streampos)0) {
std::string eol;
getNextLine(eol);
}
}
bool SeekLog::getNextLine(std::string& line) {
//try and fix the stream
if(isFinished()) stream->clear();
std::getline(*stream, line);
//remove carriage returns
if (line.size() > 0 && line[line.size()-1] == '\r') {
line.resize(line.size() - 1);
}
if(stream->fail()) {
return false;
}
current_percent = (float) stream->tellg() / file_size;
//debugLog("current_percent = %.2f\n", current_percent);
return true;
}
// temporarily move the file pointer to get a line somewhere else in the file
bool SeekLog::getNextLineAt(std::string& line, float percent) {
stream->clear();
std::streampos currpointer = getPointer();
seekTo(percent);
bool success = getNextLine(line);
stream->clear();
//set the pointer back
setPointer(currpointer);
return success;
}
bool SeekLog::isFinished() {
bool finished = false;
if(stream->fail() || stream->eof()) {
debugLog("stream is finished\n");
finished=true;
}
return finished;
}
|
dos1/Logstalgia
|
src/core/seeklog.cpp
|
C++
|
gpl-3.0
| 5,269
|
namespace InsuranceSystem.BLL.Services.Catalogs
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using DTO.Catalogs;
using Interfaces;
using Interfaces.Catalogs;
using Library.Models.Catalogs;
using UnitOfWork;
using UnitOfWork.Catalogs;
using static Validation.CheckValues;
using InsuranceSystem.BLL.Infrastructure;
public class BankAccountService : IBankAccountService
{
readonly AutoMapperConfig autoMapperConfig;
readonly IUnitOfWork<BankAccount> bankAccountUnit;
public BankAccountService()
{
autoMapperConfig = AutoMapperConfig.Instance;
bankAccountUnit = new BankAccountUnit();
}
public int Delete(BankAccountDTO entity)
{
CheckForNull(entity);
bankAccountUnit.Repository.Delete(entity.Id);
return bankAccountUnit.Commit();
}
public int Delete(int? id)
{
CheckForNull(id);
bankAccountUnit.Repository.Delete((int)id);
return bankAccountUnit.Commit();
}
public async Task<int> DeleteAsync(BankAccountDTO entity)
{
CheckForNull(entity);
bankAccountUnit.Repository.Delete(entity.Id);
return await bankAccountUnit.CommitAsync();
}
public async Task<int> DeleteAsync(int? id)
{
CheckForNull(id);
bankAccountUnit.Repository.Delete((int)id);
return await bankAccountUnit.CommitAsync();
}
public void Dispose()
{
bankAccountUnit.Dispose();
}
public IEnumerable<BankAccountDTO> GetAll()
{
return Mapper.Map<IEnumerable<BankAccount>, IEnumerable<BankAccountDTO>>(
bankAccountUnit.Repository.GetAll());
}
public async Task<List<BankAccountDTO>> GetAllAsync()
{
return Mapper.Map<List<BankAccount>, List<BankAccountDTO>>(await
bankAccountUnit.Repository.GetAllAsync());
}
public async Task<List<BankAccountDTO>> GetByAccountNumberAsync(string number)
{
return Mapper.Map<List<BankAccount>, List<BankAccountDTO>>(await
bankAccountUnit.Repository.GetManyAsync(p =>
p.AccountNumber.Trim() == number));
}
public async Task<List<BankAccountDTO>> GetByBankIdAsync(int? id)
{
CheckForNull(id);
return Mapper.Map<List<BankAccount>, List<BankAccountDTO>>(await
bankAccountUnit.Repository.GetManyAsync(p => p.BankId == (int)id));
}
public async Task<List<BankAccountDTO>> GetByCloseDate(DateTime date)
{
CheckForNull(date);
return Mapper.Map<List<BankAccount>, List<BankAccountDTO>>(await
bankAccountUnit.Repository.GetManyAsync(p => p.CloseDate == date));
}
public async Task<List<BankAccountDTO>> GetByCurrencyIdAsync(int? id)
{
CheckForNull(id);
return Mapper.Map<List<BankAccount>, List<BankAccountDTO>>(await
bankAccountUnit.Repository.GetManyAsync(p => p.CurrencyId == (int)id));
}
public BankAccountDTO GetById(int? id)
{
CheckForNull(id);
return Mapper.Map<BankAccount, BankAccountDTO>(
bankAccountUnit.Repository.GetById((int)id));
}
public async Task<BankAccountDTO> GetByIdAsync(int? id)
{
CheckForNull(id);
return Mapper.Map<BankAccount, BankAccountDTO>(await
bankAccountUnit.Repository.GetAsync(p => p.Id == id));
}
public async Task<List<BankAccountDTO>> GetByOpenDate(DateTime date)
{
CheckForNull(date);
return Mapper.Map<List<BankAccount>, List<BankAccountDTO>>(await
bankAccountUnit.Repository.GetManyAsync(p => p.OpenDate == date));
}
public int Insert(BankAccountDTO entity)
{
CheckForNull(entity);
bankAccountUnit.Repository.Insert(Mapper
.Map<BankAccountDTO, BankAccount>(entity));
return bankAccountUnit.Commit();
}
public async Task<int> InsertAsync(BankAccountDTO entity)
{
CheckForNull(entity);
bankAccountUnit.Repository.Insert(Mapper
.Map<BankAccountDTO, BankAccount>(entity));
return await bankAccountUnit.CommitAsync();
}
public int Update(BankAccountDTO entity)
{
CheckForNull(entity);
BankAccount item = FillBankAccount(entity);
bankAccountUnit.Repository.Insert(item);
return bankAccountUnit.Commit();
}
private BankAccount FillBankAccount(BankAccountDTO entity)
{
var item = bankAccountUnit.Repository.GetById(entity.Id);
item.ModifiedDate = DateTime.Now;
item.AccountNumber = entity.AccountNumber;
item.BankId = entity.BankId;
item.CloseDate = entity.CloseDate;
item.CurrencyId = entity.CurrencyId;
item.IsDelete = entity.IsDelete;
item.IsGroup = entity.IsGroup;
item.Name = entity.Name;
item.OpenDate = entity.OpenDate;
item.ParentId = entity.ParentId;
item.PurposeOfPayment = entity.PurposeOfPayment;
return item;
}
public async Task<int> UpdateAsync(BankAccountDTO entity)
{
CheckForNull(entity);
BankAccount item = FillBankAccount(entity);
bankAccountUnit.Repository.Insert(item);
return await bankAccountUnit.CommitAsync();
}
public async Task<List<BankAccountDTO>> GetByNameAsync(string name)
{
return Mapper.Map<List<BankAccount>, List<BankAccountDTO>>(
await bankAccountUnit.Repository
.GetManyAsync(p => p.Name.ToUpper().Contains(name.ToUpper())));
}
}
}
|
mishakos/InsuranceSystem.Library
|
InsuranceSystem.BLL/Services/Catalogs/BankAccountService.cs
|
C#
|
gpl-3.0
| 6,165
|
{-# LANGUAGE UnicodeSyntax #-}
--
-- Utility functions to run the program.
--
module Program where
import Prelude.Unicode
import System.Environment
import System.Exit
runAction ∷ IO Bool → IO ()
runAction action = do
isSuccess ← action
exitWith $ exitStatus isSuccess
where
exitStatus True = ExitSuccess
exitStatus False = ExitFailure (0-1)
|
c0c0n3/hAppYard
|
inkscape-util/src/shared/Program.hs
|
Haskell
|
gpl-3.0
| 399
|
// circular_automaton, Copyright 2013 Vicente Oscar Mier Vela <vomv1988@gmail.com>
// This file is part of circular_automaton.
// circular_automaton 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.
// circular_automaton 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 circular_automaton. If not, see <http://www.gnu.org/licenses/>.
/* Save comparison between circle and cells in compare */
int imgcompare(int **compare, int **circle, int **cells, int x, int y);
/* One iteration of cellular automata. Requires buffer image */
int imgcelliter(int **img, int **buffer, int x, int y);
/* Draw circle of radius r with center on (cx,cy) on img */
int imgdrawcircle(int **img, int cx, int cy, int r);
/* Allocate memory to image matrix */
int **imgalloc(int x, int y);
/* Free image matrix memory */
int imgfree(int **img, int x, int y);
/* Assign zeros to all pixels in image matrix */
int imgclear(int **img, int x, int y);
/* Copy (0,0) to (x,y) submatrix from ori image to dest image */
int imgcopy(int **dest, int **ori, int x, int y);
/* Print image matrix in PPM format to stdout */
int printppm(int **img, int x, int y);
/* Set a pixel in img matrix to 1 */
int imgseed(int **img, int x, int y);
/* Save image matrix in PPM format */
void saveppm(char *fname, int **img, int x, int y);
|
vomv1988/circular_automaton
|
cellauto.h
|
C
|
gpl-3.0
| 1,752
|
<?php $this->load->view('global/validasi_form'); ?>
<div class='modal-body'>
<div class="row">
<div class="col-sm-12">
<div class="box box-danger">
<div class="box-body">
<table class="table table-bordered table-striped table-hover" >
<tbody>
<tr>
<td style="padding-top : 10px;padding-bottom : 10px; width:40%;" ><?= $judul_terdata_nama?></td>
<td> : <?= $terdata_nama?></td>
</tr>
<tr>
<td style="padding-top : 10px;padding-bottom : 10px; width:40%;" ><?= $judul_terdata_info?></td>
<td> : <?= $terdata_info?></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-sm-12">
<div class="box box-danger">
<div class="box-body">
<form id="validasi" action="<?= $form_action?>" method="POST" enctype="multipart/form-data" class="form-horizontal">
<?php include("donjo-app/views/covid19/form_isian_pemudik.php"); ?>
</form>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-social btn-flat btn-danger btn-sm" data-dismiss="modal"><i class='fa fa-sign-out'></i> Tutup</button>
<button type="submit" class="btn btn-social btn-flat btn-info btn-sm" onclick="$('#'+'validasi').submit();"><i class="fa fa-check"></i> Simpan</button>
</div>
</div>
|
OpenSID/OpenSID
|
donjo-app/views/covid19/edit_pemudik.php
|
PHP
|
gpl-3.0
| 1,333
|
# Questions
Polar questions in Malayalam are formed by adding the interrogative clitic ഓ to the predicate of an affirmative clause.
::: rule
To get the question form for present and future tense verbs, replace ുക at the end with ുമോ
:::
::: example
* വരുക ⇒ വരും ⇒ വരുമോ?
* ഓടുക ⇒ ഓടും ⇒ ഓടുമോ?
* പറയുക ⇒ പറയും ⇒ പറയുമോ
:::
::: rule
To get the question form for past tense verbs, replace ു at the end of past tense form with ോ or ുവോ. Replace ി at the end of past tense form with ിയോ
:::
::: example
* വരുക ⇒ വന്നു ⇒ വന്നോ? വന്നുവോ?
* പറയുക ⇒ പറഞ്ഞു ⇒ പറഞ്ഞോ?, പറഞ്ഞുവോ?
* ഓടുക ⇒ ഓടി ⇒ ഓടിയോ?
* കരയുക ⇒ കരഞ്ഞു ⇒ കരഞ്ഞുവോ?
* കിടക്കുക ⇒ കിടന്നു ⇒ കിടന്നുവോ?
:::
Some of these forms can be confusing with permissive mood if analysed without context. For example, പറഞ്ഞോ can be a question or a permission to tell(variant of പറഞ്ഞോളു)
::: warning TODO
Add note about negation handling വന്നില്ലയോ, വന്നില്ലേ, പറഞ്ഞില്ലേ
:::
|
santhoshtr/mlmorph
|
docs/vinfl/questions.md
|
Markdown
|
gpl-3.0
| 1,364
|