repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
shamrath/Axis2-Samples | web-services/jaxws/jaxws-client/src/main/java/org/apache/axis2/sample/jaxws/client/TestJAXWSService.java | 2061 | /*
* Copyright 2004,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.axis2.sample.jaxws.client;
import org.apache.axis2.sample.jaxws.JAXWSServiceService;
import org.apache.axis2.sample.jaxws.JAXWSService;
import org.apache.axis2.sample.jaxws.Project;
import org.apache.axis2.sample.jaxws.Employee;
public class TestJAXWSService {
public static void main(String[] args) {
JAXWSServiceService service = new JAXWSServiceService();
JAXWSService jaxwsService = service.getJAXWSServicePort();
String result = jaxwsService.echoString("hello");
System.out.println("Result ==> " + result);
Project project = new Project();
project.setName("axis2");
Employee manager = new Employee();
manager.setAge(40);
manager.setEmpID("E1");
manager.setName("AAAA");
manager.setSalary(345.78);
project.setManager(manager);
Employee[] develpers = new Employee[2];
develpers[0] = new Employee();
develpers[0].setAge(34);
develpers[0].setEmpID("E2");
develpers[0].setName("BBBB");
develpers[0].setSalary(3451.78);
develpers[1] = new Employee();
develpers[1].setAge(34);
develpers[1].setEmpID("E3");
develpers[1].setName("CCCC");
develpers[1].setSalary(3452.78);
project.getDevelopers().add(develpers[0]);
project.getDevelopers().add(develpers[1]);
jaxwsService.echoProject(project);
}
}
| apache-2.0 |
destiny1020/hranalyzer | src/main/java/com/destiny1020/hranalyzer/domain/org/OrganizationBase.java | 1419 | package com.destiny1020.hranalyzer.domain.org;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import org.apache.commons.lang3.builder.ToStringBuilder;
import com.destiny1020.hranalyzer.domain.Term;
@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class OrganizationBase {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "PK", updatable = false)
protected Long id;
@Column(name = "NAME", nullable = false)
protected String name;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "REGISTER_TERM_ID")
protected Term beginTerm;
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Term getBeginTerm() {
return beginTerm;
}
public void setBeginTerm(Term beginTerm) {
this.beginTerm = beginTerm;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
| apache-2.0 |
nesfit/NetfoxDetective | Common/Core/BaseTypes/Views/CollectionUserControlBase.cs | 3166 | // Copyright (c) 2017 Jan Pluskal
//
//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.
using System;
using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Threading;
using GalaSoft.MvvmLight.Command;
namespace Netfox.Core.BaseTypes.Views
{
public class CollectionUserControlBase : UserControl
{
public static readonly DependencyProperty ItemSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(CollectionUserControlBase), new FrameworkPropertyMetadata
{
BindsTwoWayByDefault = false,
DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
});
public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof(object), typeof(CollectionUserControlBase), new FrameworkPropertyMetadata
{
BindsTwoWayByDefault = true,
DefaultUpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
});
public static readonly DependencyProperty CSelectItemProperty = DependencyProperty.Register("CSelectedItemItem", typeof(RelayCommand<object>), typeof(CollectionUserControlBase));
public static readonly DependencyProperty CSelectDoubleClikedItemProperty = DependencyProperty.Register("CSelectedDoubleCliked", typeof(RelayCommand<object>), typeof(CollectionUserControlBase));
public CollectionUserControlBase()
{
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(this.SetDataContext));
}
public IEnumerable ItemsSource
{
get { return (IEnumerable) this.GetValue(ItemSourceProperty); }
set { this.SetValue(ItemSourceProperty, value); }
}
public object SelectedItem
{
get { return this.GetValue(SelectedItemProperty); }
set { this.SetValue(SelectedItemProperty, value); }
}
public RelayCommand<object> CSelectItem
{
get { return (RelayCommand<object>)this.GetValue(CSelectItemProperty); }
set { this.SetValue(CSelectItemProperty, value); }
}
public RelayCommand<object> CSelectDoubleClikedItem
{
get { return (RelayCommand<object>)this.GetValue(CSelectDoubleClikedItemProperty); }
set { this.SetValue(CSelectDoubleClikedItemProperty, value); }
}
public void SetDataContext()
{
var frameworkElement = this.Content as FrameworkElement;
if(frameworkElement != null) { frameworkElement.DataContext = this; }
}
}
} | apache-2.0 |
angry-tony/Portus-20170827 | app/assets/javascripts/modules/namespaces/index.js | 314 | import './pages/index';
import NamespacesShowPage from './pages/show';
const NAMESPACES_SHOW_ROUTE = 'namespaces/show';
$(() => {
const $body = $('body');
const route = $body.data('route');
if (route === NAMESPACES_SHOW_ROUTE) {
// eslint-disable-next-line
new NamespacesShowPage($body);
}
});
| apache-2.0 |
s1-platform/s1 | s1-mongodb/src/java/org/s1/mongodb/log/MongoDBLogStorage.java | 2550 | /*
* Copyright 2014 Grigory Pykhov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.s1.mongodb.log;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import org.s1.log.LogStorage;
import org.s1.misc.Closure;
import org.s1.mongodb.MongoDBConnectionHelper;
import org.s1.objects.ObjectIterator;
import org.s1.objects.Objects;
import org.s1.options.Options;
import java.util.List;
import java.util.Map;
/**
* MongoDB log storage impl
*/
public class MongoDBLogStorage extends LogStorage{
public static DBCollection getCollection(){
String d = "log4j";
String c = Options.getStorage().get("MongoDB","connections.log4j.collection","log4j");
return MongoDBConnectionHelper.getConnection(d).getCollection(c);
}
@Override
public long list(List<Map<String, Object>> list, Map<String, Object> search, int skip, int max) {
//return super.list(list, search, skip, max);
DBCollection coll = getCollection();
DBObject s = new BasicDBObject();
if(search!=null){
//remove $where
search = Objects.iterate(search,new Closure<ObjectIterator.IterateBean, Object>() {
@Override
public Object call(ObjectIterator.IterateBean input) {
if(input.getValue() instanceof Map){
if(((Map) input.getValue()).containsKey("$where"))
((Map) input.getValue()).remove("$where");
}
return input.getValue();
}
});
s = new BasicDBObject(search);
}
DBCursor cur = coll
.find(s).sort(new BasicDBObject("date",-1))
.limit(max).skip(skip);
while(cur.hasNext()){
Map<String,Object> m = cur.next().toMap();
m.remove("_id");
list.add(m);
}
return coll.count(s);
}
}
| apache-2.0 |
eSDK/esdk_uc_plugin_ucservice | source/UCService/UCRegManager.cpp | 17569 | #include "StdAfx.h"
#include "UCRegManager.h"
#include "UCConfigMgr.h"
#include "UCContactMgr.h"
//lint -e1762
//lint -e1788
ClientSignInNotifyCB UCRegManager::OnClientSignInNotifyCB = NULL;
StatusChangedCB UCRegManager::OnStatusChangedCB = NULL;
UCRegManager::UCRegManager(void):m_pUCClient(NULL),m_pSelf(NULL),m_pSubscribeMgr(NULL)
{
}
UCRegManager::~UCRegManager(void)
{
m_pUCClient = NULL;
m_pSelf = NULL;
m_pSubscribeMgr = NULL;
}
void UCRegManager::Init(void)
{
ctk::Mutex::Lock lck(m_RegMutex);
m_pUCClient = UCClient::GetClient();
if(NULL == m_pUCClient)
{
ERROR_LOG() << "m_pUCClient is NULL";
return;
}
(void)m_pUCClient->Init();
m_pSelf = m_pUCClient->Self;
m_pSubscribeMgr = m_pUCClient->ContactSubManager;
OnClientSignInNotifyCB = NULL;
OnStatusChangedCB = NULL;
}
void UCRegManager::Uninit(void)
{
ctk::Mutex::Lock lck(m_RegMutex);
m_pSelf = NULL;
m_pSubscribeMgr = NULL;
if(NULL != m_pUCClient)
{
(void)m_pUCClient->UnInit();
UCClient::ReleaseClient();
m_pUCClient = NULL;
}
OnClientSignInNotifyCB = NULL;
OnStatusChangedCB = NULL;
}
void UCRegManager::InitSubscribe(void)
{
if(NULL == m_pSubscribeMgr)
{
ERROR_LOG() << "m_pSubscribeMgr is NULL.";
return;
}
m_pSubscribeMgr->Init();
m_pSubscribeMgr->InitSubContactlist();
}
void UCRegManager::UnInitSubscribe(void)
{
if(NULL == m_pSubscribeMgr)
{
ERROR_LOG() << "m_pSubscribeMgr is NULL.";
return;
}
m_pSubscribeMgr->ClearSubList();
m_pSubscribeMgr->Uninit();
}
int UCRegManager::SignInByPWD(const std::string& _account,const std::string& _pwd,const std::string& _serverUrl,const std::string& _langID)
{
if(NULL == m_pUCClient)
{
ERROR_LOG() << "m_pUCClient is NULL.";
return UC_SDK_NotInit;
}
m_pUCClient->SignConfig.account = _account; //µÇ¼Õ˺Å
m_pUCClient->SignConfig.pwd = _pwd; //µÇ¼ÃÜÂë
m_pUCClient->SignConfig.internalurl = _serverUrl; //µÇ¼URL£¬¸ñʽΪIP:Port
m_pUCClient->SignConfig.externalsurl = _serverUrl;
m_pUCClient->SignConfig.lang = _langID; //ÓïÑÔ
//ÆäËû²ÎÊý²ÉÓÃĬÈÏ
m_pUCClient->SignConfig.ver = "v2.1.3.35"; //°æ±¾
m_pUCClient->SignConfig.signinmode = AccountAndPwd; //µÇ¼ģʽĬÈÏΪÕË»§+ÃÜÂë
m_pUCClient->SignConfig.initStatus = Online;
m_pUCClient->SignConfig.siteID = Server1;
//not use svn
m_pUCClient->SignConfig.svntunnel = false;
m_pUCClient->SignConfig.svnServerIp = "";
m_pUCClient->SignConfig.svnServerIpPort = "";
m_pUCClient->SignConfig.svnacc = "";
m_pUCClient->SignConfig.svnpwd = "";
m_pUCClient->SignConfig.svnLoginDlgHwnd = NULL;
//not use https
m_pUCClient->SignConfig.aaTunnelType = uc::model::AA_CONNECTION_HTTP;
//GetUpdateAddress
std::string ip;
int port;
eSDKTool::GetIPPort(_serverUrl,ip,port);
if(!m_pUCClient->GetUpdateAddress(ip,port,_account))
{
WARN_LOG() << "GetUpdateAddress failed.";
}
//login
if (!m_pUCClient->SignIn())
{
ERROR_LOG() << "SignIn failed.";
return UC_SDK_Failed;
}
return UC_SDK_Success;
}
int UCRegManager::SignOut()
{
if(NULL == m_pUCClient)
{
return UC_SDK_NotInit;
}
//¶Ï¿ªÐźÅÁ¬½Ó
UCConfigMgr::Instance().DisConectPhoneJointSignal();
if(!m_pUCClient->SignOut())
{
WARN_LOG() << "SignOut Failed.";
return UC_SDK_Failed;
}
return UC_SDK_Success;
}
int UCRegManager::SetLoginEventCB(ClientSignInNotifyCB _loginEventCB)
{
if(NULL == m_pUCClient)
{
return UC_SDK_NotInit;
}
//Á¬½ÓµÇ½ÐźÅ
m_pUCClient->SignInNotify_.disconnect_all();
m_pUCClient->SignInNotify_.connect(&m_RegEvent, &RegEvent::OnSignInNotify);
m_pUCClient->SipOkNotify_.disconnect_all();
m_pUCClient->SipOkNotify_.connect(&m_RegEvent,&RegEvent::OnSipRegNotify);
UCRegManager::OnClientSignInNotifyCB = _loginEventCB;
return UC_SDK_Success;
}
int UCRegManager::SetStatusEventCB(StatusChangedCB _statusEventCB)
{
if(NULL == m_pUCClient)
{
return UC_SDK_NotInit;
}
if (NULL == m_pSubscribeMgr)
{
return UC_SDK_NotInit;
}
//Á¬½Ó״̬ÐźÅ
m_pSubscribeMgr->UserAvailabilityChanged_.disconnect_all();
m_pSubscribeMgr->UserAvailabilityChanged_.connect(&m_RegEvent, &RegEvent::OnStatusChanged);
UCRegManager::OnStatusChangedCB = _statusEventCB;
return UC_SDK_Success;
}
//¸öÈËæµ״̬ÃèÊö
const std::string USER_STATUS_DESC_CONST_CALLING = "1";
const std::string USER_STATUS_DESC_CONST_INMEETING = "2";
int UCRegManager::PubSelfStatus(ContactAvailability _state,const::string& _desc)
{
DEBUG_LOG() << "--- ENTER";
if(NULL == m_pUCClient )
{
ERROR_LOG() << "m_pUCClient is NULL";
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_NotInit;
}
if(NULL == m_pUCClient->ConvManager)
{
ERROR_LOG() << "ConvManager is NULL";
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_NotInit;
}
if(NULL == m_pSelf)
{
ERROR_LOG() << "m_pSelf is NULL";
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_NotInit;
}
INFO_PARAM2(_state,_desc);
if(_state == m_pSelf->selfStatus)
{
WARN_LOG() << "state is already published.";
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_Success;
}
std::map<UCSelf::PubContactInfoType, std::string> infomap_;
std::ostringstream os;
os << _state;
infomap_[UCSelf::Availability] = os.str();
if(0 < m_pUCClient->ConvManager->GetAVSessionConvCount())
{
if(m_pUCClient->ConvManager->HasConfAVSessionConv())
{
infomap_[UCSelf::CustomStatusDesc] = USER_STATUS_DESC_CONST_INMEETING;
}
else
{
infomap_[UCSelf::CustomStatusDesc] = USER_STATUS_DESC_CONST_CALLING;
}
}
else
{
infomap_[UCSelf::CustomStatusDesc] = _desc;
}
m_pSelf->PublishSelfInformation(infomap_);
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_Success;
}
int UCRegManager::DisSubscribeStatus(const std::string& strUri)
{
DEBUG_LOG() << "--- ENTER";
if(NULL == m_pUCClient )
{
ERROR_LOG() << "m_pUCClient is NULL";
return UC_SDK_NotInit;
}
if(NULL == m_pSelf)
{
ERROR_LOG() << "Self is NULL";
return UC_SDK_NotInit;
}
if(strUri == m_pSelf->selfInfo.uri_)
{
WARN_LOG() << "Cannot DisSubscribe Self";
return UC_SDK_Failed;
}
if(!eSDKTool::IsValidUri(strUri))
{
INFO_LOG() << "Not need to DisSubscribe contact [" << strUri << "] .";
return UC_SDK_Failed;
}
if(NULL == m_pSubscribeMgr)
{
ERROR_LOG() << "ContactSubManager is NULL";
return UC_SDK_NotInit;
}
if(m_pSubscribeMgr->HasSubContact(strUri))
{
m_pSubscribeMgr->RemoveSubContact(strUri);
INFO_LOG() << "DisSubscribe contact [ "<< strUri <<" ] Success.";
return UC_SDK_Success;
}
else
{
INFO_LOG() << "Not Subscribe contact [ "<< strUri <<" ].";
}
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_Success;
}
int UCRegManager::SubscribeStatus(const std::string& strUri)
{
DEBUG_LOG() << "--- ENTER";
if(NULL == m_pUCClient )
{
ERROR_LOG() << "m_pUCClient is NULL";
return UC_SDK_NotInit;
}
if(NULL == m_pSelf)
{
ERROR_LOG() << "Self is NULL";
return UC_SDK_NotInit;
}
//if(strUri == m_pSelf->selfInfo.uri_)
//{
// WARN_LOG() << "Cannot Subscribe Self";
// return UC_SDK_Failed;
//}
if(!eSDKTool::IsValidUri(strUri))
{
INFO_LOG() << "Not need to subscribe contact [" << strUri << "] .";
return UC_SDK_Failed;
}
if(NULL == m_pSubscribeMgr)
{
ERROR_LOG() << "ContactSubManager is NULL";
return UC_SDK_NotInit;
}
if(m_pSubscribeMgr->HasSubContact(strUri))
{
//INFO_LOG() << "has already Subscribed contact ["<< strUri <<"] .";
return UC_SDK_Success;
}
if(m_pSubscribeMgr->AddSubContact(strUri))
{
//INFO_LOG() << "Subscribe contact ["<< strUri <<"] Success.";
}
else
{
WARN_LOG() << "Subscribe contact ["<< strUri <<"] Failed.";
}
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_Success;
}
int UCRegManager::NotifyStatus(const Contact& _contact,ContactAvailability _state,const std::string& _desc)
{
if (NULL == UCRegManager::OnStatusChangedCB)
{
return UC_SDK_Failed;
}
STContact st = {0};
(void)strcpy_s(st.location_,_contact.location_.c_str());
(void)strcpy_s(st.webSite_,_contact.webSite_.c_str());
(void)strcpy_s(st.ipphone1_,_contact.ipphone1_.c_str());
(void)strcpy_s(st.deptName_,_contact.deptName_.c_str());
(void)strcpy_s(st.email_,_contact.email_.c_str());
(void)strcpy_s(st.mobile_,_contact.mobile_.c_str());
(void)strcpy_s(st.officePhone2_,_contact.officePhone2_.c_str());
(void)strcpy_s(st.officePhone_,_contact.officePhone_.c_str());
(void)strcpy_s(st.homePhone_,_contact.homePhone_.c_str());
(void)strcpy_s(st.nickName_,_contact.nickName_.c_str());
(void)strcpy_s(st.name_,_contact.name_.c_str());
(void)strcpy_s(st.staffNo_,_contact.staffNo_.c_str());
(void)strcpy_s(st.ucAcc_,_contact.ucAcc_.c_str());
(void)strcpy_s(st.uri_,_contact.uri_.c_str());
(void)strcpy_s(st.id_,_contact.id_.c_str());
INFO_PARAM3(_contact.ucAcc_,_state,_desc);
DEBUG_LOG() << "--- OnStatusChangedCB ENTER";
UCRegManager::OnStatusChangedCB((int)_state, st);
DEBUG_LOG() << "--- OnStatusChangedCB LEAVE";
return UC_SDK_Success;
}
int UCRegManager::CheckSignStatus(void)
{
DEBUG_LOG() << "--- ENTER";
if(NULL == m_pUCClient )
{
WARN_LOG() << "m_pUCClient is NULL";
return UC_SDK_NotInit;
}
if(NULL == m_pSelf)
{
WARN_LOG() << "Self is NULL";
return UC_SDK_NotInit;
}
if(Offline == m_pSelf->selfStatus)
{
WARN_LOG() << "client is Offline";
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_NotLogin;
}
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_Success;
}
int UCRegManager::GetContactStatus(const std::string& _account,int& _status)
{
DEBUG_LOG() << "--- ENTER";
if(NULL == m_pUCClient )
{
ERROR_LOG() << "m_pUCClient is NULL";
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_NotInit;
}
if(NULL == m_pSubscribeMgr)
{
ERROR_LOG() << "ContactSubManager is NULL";
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_NotInit;
}
Contact uccontact;
if(UC_SDK_Success != UCContactMgr::Instance().getContactByAccount(_account,uccontact))
{
_status = Offline;
WARN_LOG() << " " << _account << " is Offline.";
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_Failed;
}
_status = (ContactAvailability)m_pSubscribeMgr->GetContactStatus(uccontact.uri_);
INFO_LOG() << "[" << _account << "] status is " << _status;
//IPT2.2Òì²½»ñȡ״̬
std::list<std::string> listContact;
listContact.push_back(_account);
m_pUCClient->EntAddrbookManager_.GetEntStaffStatus(listContact);
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_Success;
}
int UCRegManager::GetContactInfo(const std::string& _account,STContact& _Contact)
{
DEBUG_LOG() << "--- ENTER";
if(NULL == m_pUCClient )
{
ERROR_LOG() << "m_pUCClient is NULL";
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_NotInit;
}
Contact ucContact;
if(UC_SDK_Success != UCContactMgr::Instance().getContactByAccount(_account,ucContact))
{
WARN_LOG() << " getContactByAccount failed";
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_Failed;
}
//IPT2.2Òì²½»ñȡ״̬
std::list<std::string> listContact;
listContact.push_back(_account);
m_pUCClient->EntAddrbookManager_.GetEntStaffStatus(listContact);
ctk::MemSet(_Contact.address_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.address_,ucContact.address_.c_str(),(ucContact.address_.size()<(STRING_LENGTH)) ? (ucContact.address_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.avtool_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.avtool_,ucContact.avtool_.c_str(),(ucContact.avtool_.size()<(STRING_LENGTH)) ? (ucContact.avtool_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.corpName_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.corpName_,ucContact.corpName_.c_str(),(ucContact.corpName_.size()<(STRING_LENGTH)) ? (ucContact.corpName_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.deptName_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.deptName_,ucContact.deptName_.c_str(),(ucContact.deptName_.size()<(STRING_LENGTH)) ? (ucContact.deptName_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.desc_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.desc_,ucContact.desc_.c_str(),(ucContact.desc_.size()<(STRING_LENGTH)) ? (ucContact.desc_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.device_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.device_,ucContact.device_.c_str(),(ucContact.device_.size()<(STRING_LENGTH)) ? (ucContact.device_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.duty_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.duty_,ucContact.duty_.c_str(),(ucContact.duty_.size()<(STRING_LENGTH)) ? (ucContact.duty_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.email_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.email_,ucContact.email_.c_str(),(ucContact.email_.size()<(STRING_LENGTH)) ? (ucContact.email_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.fax_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.fax_,ucContact.fax_.c_str(),(ucContact.fax_.size()<(STRING_LENGTH)) ? (ucContact.fax_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.fullUri_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.fullUri_,ucContact.fullUri_.c_str(),(ucContact.fullUri_.size()<(STRING_LENGTH)) ? (ucContact.fullUri_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.homePhone_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.homePhone_,ucContact.homePhone_.c_str(),(ucContact.homePhone_.size()<(STRING_LENGTH)) ? (ucContact.homePhone_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.ipphone1_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.ipphone1_,ucContact.ipphone1_.c_str(),(ucContact.ipphone1_.size()<(STRING_LENGTH)) ? (ucContact.ipphone1_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.ipphone2_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.ipphone2_,ucContact.ipphone2_.c_str(),(ucContact.ipphone2_.size()<(STRING_LENGTH)) ? (ucContact.ipphone2_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.mobile_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.mobile_,ucContact.mobile_.c_str(),(ucContact.mobile_.size()<(STRING_LENGTH)) ? (ucContact.mobile_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.officePhone2_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.officePhone2_,ucContact.officePhone2_.c_str(),(ucContact.officePhone2_.size()<(STRING_LENGTH)) ? (ucContact.officePhone2_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.officePhone_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.officePhone_,ucContact.officePhone_.c_str(),(ucContact.officePhone_.size()<(STRING_LENGTH)) ? (ucContact.officePhone_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.otherPhone2_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.otherPhone2_,ucContact.otherPhone2_.c_str(),(ucContact.otherPhone2_.size()<(STRING_LENGTH)) ? (ucContact.otherPhone2_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.otherPhone_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.otherPhone_,ucContact.otherPhone_.c_str(),(ucContact.otherPhone_.size()<(STRING_LENGTH)) ? (ucContact.otherPhone_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.staffNo_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.staffNo_,ucContact.staffNo_.c_str(),(ucContact.staffNo_.size()<(STRING_LENGTH)) ? (ucContact.staffNo_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.uri_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.uri_,ucContact.uri_.c_str(),(ucContact.uri_.size()<(STRING_LENGTH)) ? (ucContact.uri_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.zip_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.zip_,ucContact.zip_.c_str(),(ucContact.zip_.size()<(STRING_LENGTH)) ? (ucContact.zip_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.ucAcc_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.ucAcc_,ucContact.ucAcc_.c_str(),(ucContact.ucAcc_.size()<(STRING_LENGTH)) ? (ucContact.ucAcc_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.gender_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.gender_,ucContact.gender_.c_str(),(ucContact.gender_.size()<(STRING_LENGTH)) ? (ucContact.gender_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.id_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.id_,ucContact.ucAcc_.c_str(),(ucContact.id_.size()<(STRING_LENGTH)) ? (ucContact.id_.size()) : (STRING_LENGTH-1));
ctk::MemSet(_Contact.name_,0,STRING_LENGTH);
ctk::MemCopy(_Contact.name_,ucContact.name_.c_str(),(ucContact.name_.size()<(STRING_LENGTH)) ? (ucContact.name_.size()) : (STRING_LENGTH-1));
DEBUG_LOG() << "--- LEAVE";
return UC_SDK_Success;
}
int UCRegManager::GetSigninErrorDesc(const std::string _reason,std::string& _errordesc)
{
string::size_type pos = _reason.find("AAresult");
string errorcode;
int remaintries = -1;
if (pos == string::npos)
{
_errordesc = _reason;
return UC_SDK_Failed;
}
ctk::xml::XMLInStream xis(_reason);
int AAretrytimes = -1;
int AAmaxretrytimes = -1;
xis["AAresult"] >> errorcode;
xis["retrytimes"] >> AAretrytimes; //×¢Ò⣺ÊäÈë´íÎó´ÎÊý´ïµ½ÏÞÖÆÊ±£¬´ËʱAA·µ»ØµÄ¸ÃֵΪ0
xis["maxretrytimes"] >> AAmaxretrytimes;
if(AAmaxretrytimes > 0 && AAretrytimes >= 0 )
{
if( 0 == AAretrytimes)
{
remaintries = 0;
}
else if(AAmaxretrytimes >= AAretrytimes)
{
remaintries = AAmaxretrytimes - AAretrytimes;
}
else
{
remaintries = 0;
}
}
long lErrorCode = atol(errorcode.c_str());
switch (lErrorCode)
{
case LOGIN_PASSWORD_ERROR:
{
_errordesc = ERROR_PWD;
break;
}
case LOGIN_ACCOUNT_DONOT_EXIST:
{
_errordesc = ACC_NOT_EXISTED;
break;
}
case LOGIN_ACCOUNT_LOCK:
{
_errordesc = ACC_LOCKED;
break;
}
case LOGIN_ACCOUNT_ERROR:
{
_errordesc = ACC_ERROR;
break;
}
case LOGIN_NEED_CHANGE_PASSWORD:
{
_errordesc = NEED_CHANGEPWD;
break;
}
case LOGIN_TIMEOUT:
{
_errordesc = TIME_OUT;
break;
}
case LOGIN_NEED_NEWVERSION:
{
_errordesc = NEED_NEW_VERSION;
break;
}
case LOGIN_NEED_ACTIVE:
{
_errordesc = NEED_ACTIVE;
break;
}
default:
{
_errordesc = NORMAL_ERROR;
}
}
INFO_PARAM2(_errordesc,remaintries);
return UC_SDK_Success;
}
| apache-2.0 |
Minecor/Java-homework | homework/top/mineor/three/MainClass.java | 1443 | package top.mineor.three;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
/**
* Created by mineor on 2016/12/20.
*/
public class MainClass {
public static void main(String[] args){
//Scanner input = new Scanner(System.in);
String urlAddress = "http://www.infoq.com/cn/news/2016/11/Micro-service-java-EE?utm_source=news_about_java&utm_medium=link&utm_campaign=java";
try{
URL url = new URL(urlAddress);
System.out.println("该URL信息如下:");
printInfo("协议",url.getProtocol());
printInfo("主机名",url.getHost());
printInfo("端口号",url.getPort()+"");
printInfo("文件路径",url.getPath());
URLConnection connection = url.openConnection();//关于输入输出和乱码问题一直是个人比较头痛的,这里只能读utf-8编码的网页,待完善
InputStreamReader input = new InputStreamReader(connection.getInputStream(),"utf-8");
BufferedReader reader = new BufferedReader(input);
String line = null;
while((line = reader.readLine()) != null){
System.out.println(line);
}
}
catch (Exception e){
e.printStackTrace();
}
}
public static void printInfo(String message,String param){
System.out.println(message+"-->"+param);
}
}
| apache-2.0 |
chef/chef-server | oc-chef-pedant/spec/api/knife/data_bag/create_spec.rb | 1771 | # Copyright: Copyright (c) Chef Software, Inc.
# License: Apache License, Version 2.0
#
# 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.
require 'pedant/rspec/knife_util'
describe 'knife', :knife do
context 'data bag' do
context 'create' do
include Pedant::RSpec::KnifeUtil
include Pedant::RSpec::KnifeUtil::DataBag
let(:command) { "knife data bag create #{bag_name} -c #{knife_config}" }
after(:each) { knife "data bag delete #{bag_name} -c #{knife_config} --yes" }
context 'without existing data bag of the same name' do
context 'as an admin' do
let(:requestor) { knife_admin }
it 'should succeed' do
should have_outcome :status => 0, :stderr => /Created data_bag\[#{bag_name}\]/
end
end
end
context 'with an existing data bag of the same name' do
context 'as an admin' do
let(:requestor) { knife_admin }
it 'should fail' do
# Create a data bag with the same name
knife "data bag create #{bag_name} -c #{knife_config}"
# Run knife a second time
should have_outcome :status => 0, :stderr => /Data bag #{bag_name} already exists/
end
end
end
end
end
end
| apache-2.0 |
howepeng/isis | core/metamodel/src/main/java/org/apache/isis/core/metamodel/spec/ObjectSpecification.java | 13311 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.isis.core.metamodel.spec;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.google.common.base.Function;
import org.apache.isis.applib.annotation.ObjectType;
import org.apache.isis.applib.profiles.Localization;
import org.apache.isis.core.commons.authentication.AuthenticationSession;
import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.consent.Consent;
import org.apache.isis.core.metamodel.consent.InteractionInitiatedBy;
import org.apache.isis.core.metamodel.consent.InteractionResult;
import org.apache.isis.core.metamodel.facets.collections.modify.CollectionFacet;
import org.apache.isis.core.metamodel.facets.all.describedas.DescribedAsFacet;
import org.apache.isis.core.metamodel.facets.all.help.HelpFacet;
import org.apache.isis.core.metamodel.facets.all.hide.HiddenFacet;
import org.apache.isis.core.metamodel.facets.all.named.NamedFacet;
import org.apache.isis.core.metamodel.facets.object.parented.ParentedCollectionFacet;
import org.apache.isis.core.metamodel.facets.object.encodeable.EncodableFacet;
import org.apache.isis.core.metamodel.facets.object.icon.IconFacet;
import org.apache.isis.core.metamodel.facets.object.immutable.ImmutableFacet;
import org.apache.isis.core.metamodel.facets.object.objectspecid.ObjectSpecIdFacet;
import org.apache.isis.core.metamodel.facets.object.parseable.ParseableFacet;
import org.apache.isis.core.metamodel.facets.object.plural.PluralFacet;
import org.apache.isis.core.metamodel.facets.object.title.TitleFacet;
import org.apache.isis.core.metamodel.facets.object.value.ValueFacet;
import org.apache.isis.core.metamodel.interactions.InteractionContext;
import org.apache.isis.core.metamodel.interactions.ObjectTitleContext;
import org.apache.isis.core.metamodel.interactions.ObjectValidityContext;
import org.apache.isis.core.metamodel.spec.feature.ObjectActionContainer;
import org.apache.isis.core.metamodel.spec.feature.ObjectAssociationContainer;
import org.apache.isis.core.metamodel.specloader.classsubstitutor.ClassSubstitutor;
/**
* Represents an entity or value (cf {@link java.lang.Class}) within the
* metamodel.
*
* <p>
* As specifications are cyclic (specifically a class will reference its
* subclasses, which in turn reference their superclass) they need be created
* first, and then later work out its internals. Hence we create
* {@link ObjectSpecification}s as we need them, and then introspect them later.
*/
public interface ObjectSpecification extends Specification, ObjectActionContainer, ObjectAssociationContainer, Hierarchical, DefaultProvider {
public final static List<ObjectSpecification> EMPTY_LIST = Collections.emptyList();
public final static Function<ObjectSpecification, String> FUNCTION_FULLY_QUALIFIED_CLASS_NAME = new Function<ObjectSpecification, String>() {
@Override
public String apply(final ObjectSpecification from) {
return from.getFullIdentifier();
}
};
public final static Comparator<ObjectSpecification> COMPARATOR_FULLY_QUALIFIED_CLASS_NAME = new Comparator<ObjectSpecification>() {
@Override
public int compare(final ObjectSpecification o1, final ObjectSpecification o2) {
return o1.getFullIdentifier().compareTo(o2.getFullIdentifier());
}
};
public final static Comparator<ObjectSpecification> COMPARATOR_SHORT_IDENTIFIER_IGNORE_CASE = new Comparator<ObjectSpecification>() {
@Override
public int compare(final ObjectSpecification s1, final ObjectSpecification s2) {
return s1.getShortIdentifier().compareToIgnoreCase(s2.getShortIdentifier());
}
};
/**
* @return
*/
Class<?> getCorrespondingClass();
/**
* Returns the (unique) spec Id, as per the {@link ObjectSpecIdFacet}.
*
* <p>
* This will typically be the value of the {@link ObjectType} annotation (or equivalent);
* if non has been specified then will default to the fully qualified class name (with
* {@link ClassSubstitutor class name substituted} if necessary to allow for runtime bytecode enhancement.
*
* <p>
* The {@link ObjectSpecification} can be retrieved using {@link SpecificationLoader#lookupBySpecId(ObjectSpecId)}.
*/
ObjectSpecId getSpecId();
/**
* Returns an (immutable) "full" identifier for this specification.
*
* <p>
* This will be the fully qualified name of the Class object that this
* object represents (i.e. it includes the package name).
*/
String getFullIdentifier();
/**
* Returns an (immutable) "short" identifier for this specification.
*
* <p>
* This will be the class name without the package; any text up to and
* including the last period is removed.
*/
String getShortIdentifier();
/**
* Returns the (singular) name for objects of this specification.
*
* <p>
* Corresponds to the {@link NamedFacet#value()} of {@link NamedFacet}; is
* not necessarily immutable.
*/
String getSingularName();
/**
* Returns the plural name for objects of this specification.
*
* <p>
* Corresponds to the {@link PluralFacet#value() value} of
* {@link PluralFacet}; is not necessarily immutable.
*/
String getPluralName();
/**
* Returns the description, if any, of the specification.
*
* <p>
* Corresponds to the {@link DescribedAsFacet#value()) value} of
* {@link DescribedAsFacet}; is not necessarily immutable.
*/
@Override
String getDescription();
/**
* Returns a help string or lookup reference, if any, of the specification.
*
* <p>
* Corresponds to the {@link HelpFacet#value()) value} of {@link HelpFacet};
* is not necessarily immutable.
*/
String getHelp();
/**
* Returns the title string for the specified object.
*
* <p>
* Corresponds to the {@link TitleFacet#value()) value} of
* {@link TitleFacet}; is not necessarily immutable.
*
* @deprecated use {@link #getTitle(ObjectAdapter, ObjectAdapter, Localization)}
*/
@Deprecated
String getTitle(ObjectAdapter adapter, Localization localization);
/**
* Returns the title to display of target adapter, rendered within the context
* of some other adapter (if any).
*
* <p>
* @see TitleFacet#title(ObjectAdapter, ObjectAdapter, org.apache.isis.applib.profiles.Localization)
*/
String getTitle(ObjectAdapter contextAdapterIfAny, ObjectAdapter targetAdapter, Localization localization);
/**
* Returns the name of an icon to use for the specified object.
*
* <p>
* Corresponds to the {@link IconFacet#iconName(ObjectAdapter)) icon name}
* returned by the {@link IconFacet}; is not necessarily immutable.
*/
String getIconName(ObjectAdapter object);
/**
*
* @deprecated - use {@link #getCssClass(org.apache.isis.core.metamodel.adapter.ObjectAdapter)}.
*/
@Deprecated
String getCssClass();
/**
* Returns the CSS class name to use for the specified object.
*
* <p>
* Corresponds to the {@link org.apache.isis.core.metamodel.facets.members.cssclass.CssClassFacet#cssClass(org.apache.isis.core.metamodel.adapter.ObjectAdapter)} value}
* returned by the {@link org.apache.isis.core.metamodel.facets.members.cssclass.CssClassFacet}.
*
* @param objectAdapter - to evaluate (may be <tt>null</tt> if called by deprecated {@link #getCssClass}).
*/
String getCssClass(ObjectAdapter objectAdapter);
boolean isAbstract();
// //////////////////////////////////////////////////////////////
// TitleContext
// //////////////////////////////////////////////////////////////
/**
* Create an {@link InteractionContext} representing an attempt to read the
* object's title.
*/
ObjectTitleContext createTitleInteractionContext(AuthenticationSession session, InteractionInitiatedBy invocationMethod, ObjectAdapter targetObjectAdapter);
// //////////////////////////////////////////////////////////////
// ValidityContext, Validity
// //////////////////////////////////////////////////////////////
// internal API
ObjectValidityContext createValidityInteractionContext(
final ObjectAdapter targetAdapter,
final InteractionInitiatedBy interactionInitiatedBy);
/**
* Determines whether the specified object is in a valid state (for example,
* so can be persisted); represented as a {@link Consent}.
*/
Consent isValid(
final ObjectAdapter targetAdapter,
final InteractionInitiatedBy interactionInitiatedBy);
/**
* Determines whether the specified object is in a valid state (for example,
* so can be persisted); represented as a {@link InteractionResult}.
*/
InteractionResult isValidResult(
final ObjectAdapter targetAdapter,
final InteractionInitiatedBy interactionInitiatedBy);
// //////////////////////////////////////////////////////////////
// Facets
// //////////////////////////////////////////////////////////////
/**
* Determines if objects of this specification can be persisted or not. If
* it can be persisted (i.e. it return something other than
* {@link Persistability}.TRANSIENT ObjectAdapter.isPersistent() will
* indicated whether the object is persistent or not. If they cannot be
* persisted then {@link ObjectAdapter}. {@link #persistability()} should be
* ignored.
*/
Persistability persistability();
/**
* Determines if the object represents an value or object.
*
* <p>
* In effect, means that it doesn't have the {@link CollectionFacet}, and
* therefore will return NOT {@link #isParentedOrFreeCollection()}
*
* @see #isCollection().
*/
boolean isNotCollection();
/**
* Determines if objects of this type are a parented (internal) or free-standing (external) collection.
*
* <p>
* In effect, means has got {@link CollectionFacet}, and therefore will
* return NOT {@link #isNotCollection()}.
*
* @see #isNotCollection()
*/
boolean isParentedOrFreeCollection();
/**
* Determines if objects of this type are values.
*
* <p>
* In effect, means has got {@link ValueFacet}.
*/
boolean isValue();
/**
* Determines if objects of this type are parented (a parented collection, or an aggregated entity).
*
* <p>
* In effect, means has got {@link ParentedCollectionFacet}.
*/
boolean isParented();
/**
* Determines if objects of this type are either values or aggregated.
*
* @see #isValue()
* @see #isParented()
*/
boolean isValueOrIsParented();
/**
* Determines if objects of this type can be set up from a text entry
* string.
*
* <p>
* In effect, means has got a {@link ParseableFacet}.
*/
boolean isParseable();
/**
* Determines if objects of this type can be converted to a data-stream.
*
* <p>
* In effect, means has got {@link EncodableFacet}.
*/
boolean isEncodeable();
/**
* Whether has the {@link ImmutableFacet}.
*/
boolean isImmutable();
/**
* Whether has the {@link HiddenFacet}
*/
boolean isHidden();
// //////////////////////////////////////////////////////////////
// Service
// //////////////////////////////////////////////////////////////
/**
* Whether or not this specification represents a domain service (as opposed
* to a domain entity or a value etc).
*
* <p>
* <b>WARNING</b>: this only returns <tt>true</tt> once the metamodel has been
* fully built, and a <tt>PersistenceSession</tt> has been opened. This should
* probably be improved upon; for now, beware...
*/
boolean isService();
public void markAsService();
// //////////////////////////////////////////////////////////////
// view models and wizards
// //////////////////////////////////////////////////////////////
boolean isViewModel();
boolean isViewModelCloneable(ObjectAdapter targetAdapter);
boolean isWizard();
}
| apache-2.0 |
mtransitapps/ca-maritime-bus-parser | src/main/java/org/mtransit/parser/ca_maritime_bus/MaritimeBusAgencyTools.java | 8875 | package org.mtransit.parser.ca_maritime_bus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.mtransit.parser.CleanUtils;
import org.mtransit.parser.DefaultAgencyTools;
import org.mtransit.parser.Pair;
import org.mtransit.parser.SplitUtils;
import org.mtransit.parser.SplitUtils.RouteTripSpec;
import org.mtransit.parser.Utils;
import org.mtransit.parser.gtfs.data.GCalendar;
import org.mtransit.parser.gtfs.data.GCalendarDate;
import org.mtransit.parser.gtfs.data.GRoute;
import org.mtransit.parser.gtfs.data.GSpec;
import org.mtransit.parser.gtfs.data.GStop;
import org.mtransit.parser.gtfs.data.GTrip;
import org.mtransit.parser.gtfs.data.GTripStop;
import org.mtransit.parser.mt.data.MAgency;
import org.mtransit.parser.mt.data.MRoute;
import org.mtransit.parser.mt.data.MTrip;
import org.mtransit.parser.mt.data.MTripStop;
// https://tdstickets.com/gtfs/
// https://webstore.maritimebus.com/gtfs/maritime.zip
public class MaritimeBusAgencyTools extends DefaultAgencyTools {
public static void main(String[] args) {
if (args == null || args.length == 0) {
args = new String[3];
args[0] = "input/gtfs.zip";
args[1] = "../../mtransitapps/ca-maritime-bus-android/res/raw/";
args[2] = ""; // files-prefix
}
new MaritimeBusAgencyTools().start(args);
}
private HashSet<String> serviceIds;
@Override
public void start(String[] args) {
System.out.printf("\nGenerating Maritime bus data...");
long start = System.currentTimeMillis();
this.serviceIds = extractUsefulServiceIds(args, this);
super.start(args);
System.out.printf("\nGenerating Maritime bus data... DONE in %s.\n", Utils.getPrettyDuration(System.currentTimeMillis() - start));
}
@Override
public boolean excludingAll() {
return this.serviceIds != null && this.serviceIds.isEmpty();
}
@Override
public boolean excludeCalendar(GCalendar gCalendar) {
if (this.serviceIds != null) {
return excludeUselessCalendar(gCalendar, this.serviceIds);
}
return super.excludeCalendar(gCalendar);
}
@Override
public boolean excludeCalendarDate(GCalendarDate gCalendarDates) {
if (this.serviceIds != null) {
return excludeUselessCalendarDate(gCalendarDates, this.serviceIds);
}
return super.excludeCalendarDate(gCalendarDates);
}
@Override
public boolean excludeTrip(GTrip gTrip) {
if (this.serviceIds != null) {
return excludeUselessTrip(gTrip, this.serviceIds);
}
return super.excludeTrip(gTrip);
}
@Override
public Integer getAgencyRouteType() {
return MAgency.ROUTE_TYPE_BUS;
}
private static final Pattern DIGITS = Pattern.compile("[\\d]+");
@Override
public long getRouteId(GRoute gRoute) {
if (!Utils.isDigitsOnly(gRoute.getRouteShortName())) {
Matcher matcher = DIGITS.matcher(gRoute.getRouteShortName());
if (matcher.find()) {
return Long.parseLong(matcher.group());
}
System.out.printf("\nUnexpected route ID %s.\n", gRoute);
}
return Long.parseLong(gRoute.getRouteShortName()); // use route short name as route ID
}
@Override
public String getRouteShortName(GRoute gRoute) {
if (!Utils.isDigitsOnly(gRoute.getRouteShortName())) {
Matcher matcher = DIGITS.matcher(gRoute.getRouteShortName());
if (matcher.find()) {
return matcher.group();
}
System.out.printf("\nUnexpected route short name %s.\n", gRoute);
}
return super.getRouteShortName(gRoute);
}
private static final Pattern RLN_TO_RLN = Pattern.compile("((^|\\W){1}(to)(\\W|$){1})", Pattern.CASE_INSENSITIVE);
private static final String RLN_TO_RLN_REPLACEMENT = "$2 - $4";
@Override
public String getRouteLongName(GRoute gRoute) {
String routeLongName = gRoute.getRouteLongName();
routeLongName = RLN_TO_RLN.matcher(routeLongName).replaceAll(RLN_TO_RLN_REPLACEMENT);
routeLongName = CleanUtils.SAINT.matcher(routeLongName).replaceAll(CleanUtils.SAINT_REPLACEMENT);
return CleanUtils.cleanLabel(routeLongName);
}
private static final String AGENCY_COLOR_BLUE = "065E9B"; // BLUE (from web site CSS)
private static final String AGENCY_COLOR_GREEN = "40B449"; // GREEN (from web site CSS)
private static final String AGENCY_COLOR = AGENCY_COLOR_GREEN;
@Override
public String getAgencyColor() {
return AGENCY_COLOR;
}
@Override
public String getRouteColor(GRoute gRoute) {
if (StringUtils.isEmpty(gRoute.getRouteColor())) {
return AGENCY_COLOR_BLUE;
}
return super.getRouteColor(gRoute);
}
private static HashMap<Long, RouteTripSpec> ALL_ROUTE_TRIPS2;
static {
HashMap<Long, RouteTripSpec> map2 = new HashMap<Long, RouteTripSpec>();
ALL_ROUTE_TRIPS2 = map2;
}
@Override
public int compareEarly(long routeId, List<MTripStop> list1, List<MTripStop> list2, MTripStop ts1, MTripStop ts2, GStop ts1GStop, GStop ts2GStop) {
if (ALL_ROUTE_TRIPS2.containsKey(routeId)) {
return ALL_ROUTE_TRIPS2.get(routeId).compare(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop, this);
}
return super.compareEarly(routeId, list1, list2, ts1, ts2, ts1GStop, ts2GStop);
}
@Override
public ArrayList<MTrip> splitTrip(MRoute mRoute, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return ALL_ROUTE_TRIPS2.get(mRoute.getId()).getAllTrips();
}
return super.splitTrip(mRoute, gTrip, gtfs);
}
@Override
public Pair<Long[], Integer[]> splitTripStop(MRoute mRoute, GTrip gTrip, GTripStop gTripStop, ArrayList<MTrip> splitTrips, GSpec routeGTFS) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return SplitUtils.splitTripStop(mRoute, gTrip, gTripStop, routeGTFS, ALL_ROUTE_TRIPS2.get(mRoute.getId()), this);
}
return super.splitTripStop(mRoute, gTrip, gTripStop, splitTrips, routeGTFS);
}
@Override
public void setTripHeadsign(MRoute mRoute, MTrip mTrip, GTrip gTrip, GSpec gtfs) {
if (ALL_ROUTE_TRIPS2.containsKey(mRoute.getId())) {
return; // split
}
String tripHeadsign = gTrip.getTripHeadsign();
if (StringUtils.isEmpty(tripHeadsign)) {
tripHeadsign = mRoute.getLongName();
}
int directionId = gTrip.getDirectionId() == null ? 0 : gTrip.getDirectionId();
mTrip.setHeadsignString(cleanTripHeadsign(tripHeadsign), directionId);
}
private static final Pattern STARTS_WITH_TO = Pattern.compile("(^to )", Pattern.CASE_INSENSITIVE);
private static final Pattern ENDS_WITH_STATE = Pattern.compile("(\\, (PE|QC|NB|NS)$)", Pattern.CASE_INSENSITIVE);
private static final Pattern GREATER_INTERNATIONAL_AIRPORT = Pattern.compile("((^|\\W){1}(greater[\\s]*international airport)(\\W|$){1})",
Pattern.CASE_INSENSITIVE);
private static final String GREATER_INTERNATIONAL_AIRPORT_REPLACEMENT = "$2Airport$4";
private static final Pattern INTERNATIONAL = Pattern.compile("((^|\\W){1}(international)(\\W|$){1})", Pattern.CASE_INSENSITIVE);
private static final String INTERNATIONAL_REPLACEMENT = "$2Int$4";
private static final Pattern UNIVERSITY = Pattern.compile("((^|\\W){1}(university)(\\W|$){1})", Pattern.CASE_INSENSITIVE);
private static final String UNIVERSITY_REPLACEMENT = "$2U$4";
@Override
public String cleanTripHeadsign(String tripHeadsign) {
tripHeadsign = STARTS_WITH_TO.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = ENDS_WITH_STATE.matcher(tripHeadsign).replaceAll(StringUtils.EMPTY);
tripHeadsign = GREATER_INTERNATIONAL_AIRPORT.matcher(tripHeadsign).replaceAll(GREATER_INTERNATIONAL_AIRPORT_REPLACEMENT);
tripHeadsign = CleanUtils.SAINT.matcher(tripHeadsign).replaceAll(CleanUtils.SAINT_REPLACEMENT);
tripHeadsign = UNIVERSITY.matcher(tripHeadsign).replaceAll(UNIVERSITY_REPLACEMENT);
tripHeadsign = CleanUtils.removePoints(tripHeadsign);
tripHeadsign = CleanUtils.cleanNumbers(tripHeadsign);
tripHeadsign = CleanUtils.cleanStreetTypes(tripHeadsign);
tripHeadsign = CleanUtils.cleanStreetTypesFRCA(tripHeadsign);
return CleanUtils.cleanLabel(tripHeadsign);
}
@Override
public String cleanStopName(String gStopName) {
gStopName = CleanUtils.SAINT.matcher(gStopName).replaceAll(CleanUtils.SAINT_REPLACEMENT);
gStopName = INTERNATIONAL.matcher(gStopName).replaceAll(INTERNATIONAL_REPLACEMENT);
gStopName = UNIVERSITY.matcher(gStopName).replaceAll(UNIVERSITY_REPLACEMENT);
gStopName = CleanUtils.removePoints(gStopName);
gStopName = CleanUtils.cleanNumbers(gStopName);
gStopName = CleanUtils.cleanStreetTypes(gStopName);
gStopName = CleanUtils.cleanStreetTypesFRCA(gStopName);
return CleanUtils.cleanLabel(gStopName);
}
@Override
public String getStopCode(GStop gStop) {
if (!StringUtils.isEmpty(gStop.getStopCode()) && Utils.isLettersOnly(gStop.getStopCode())) {
System.out.printf("\nIgnore stop code '%s' for %s.", gStop.getStopCode(), gStop);
return null; // ignore stop code without numbers
}
return super.getStopCode(gStop);
}
}
| apache-2.0 |
appbakers/automon_example | jamonapi/jamon/src/test/java/com/jamonapi/MonitorCompositeTest.java | 8045 | package com.jamonapi;
import com.jamonapi.utils.Misc;
import com.jamonapi.utils.SerializationUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.Collection;
import static org.assertj.core.api.Assertions.assertThat;
//import org.apache.commons.lang3.SerializationUtils;
public class MonitorCompositeTest {
private static final int BUFFER_SIZE = 50;
private static final String EXCEPTION_METHOD = "mymethodexception";
private static final String EXCEPTION_NAME = "My Exception";
@Before
public void setUp() throws Exception {
MonitorFactory.reset();
JAMonListenerFactory.reset();
Object[][] possibleListeners = JAMonListenerFactory.getData();
// Add every possible listener type to ensure that they are all serialized/deserialized
Monitor mon = MonitorFactory.getMonitor(EXCEPTION_METHOD, "ms.");
for (Object[] listenerType : possibleListeners) {
JAMonListener listener = JAMonListenerFactory.get(listenerType[0].toString());
mon.addListener("value", listener);
}
// Add data that we can use to test serialization/deserialization.
// This includes different types of monitors behind the scenes like TimeMon, and TimeNano.
// A stacktraces is also put in the details of the key so it can be checked to see if it was properly
// deserialized too.
for (int i=0; i < BUFFER_SIZE; i++) {
methodWithException(i);
MonitorFactory.add("mylabel", "count", 1);
MonitorFactory.add("mylabel" + i, "count", 1);
Monitor mon0 = MonitorFactory.startNano("mynanotimer"+i);
Monitor mon1 = MonitorFactory.startPrimary("mytimer"+i);
mon1.stop();
mon0.stop();
}
}
@After
public void tearDown() throws Exception {
// Reset JAMon after each test method. The Monitors are static and so would otherwise stick around
MonitorFactory.reset();
JAMonListenerFactory.reset();
}
@Test
public void testSerialization() throws Throwable {
// serialize and deserialize monitors
MonitorComposite original = MonitorFactory.getRootMonitor();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
SerializationUtils.serialize(original, outputStream);
MonitorComposite deserialized = SerializationUtils.deserialize(new ByteArrayInputStream(outputStream.toByteArray()));
deepComparisonAssertions(original, deserialized);
}
@Test
public void testDeepCopy() throws Throwable {
// do a deep copy of the object.
MonitorComposite original = MonitorFactory.getRootMonitor();
MonitorComposite deserialized = original.copy();
deepComparisonAssertions(original, deserialized);
}
@Test
public void testGetMonitorWithUnits() {
MonitorComposite composite = MonitorFactory.getRootMonitor();
assertThat(composite.filterByUnits("AllMonitors").getNumRows()).isEqualTo(composite.getNumRows());
assertThat(composite.filterByUnits("ms.").getNumRows()).isEqualTo(BUFFER_SIZE+1);
assertThat(composite.filterByUnits("ns.").getNumRows()).isEqualTo(BUFFER_SIZE);
assertThat(composite.filterByUnits("count").getNumRows()).isEqualTo(BUFFER_SIZE+1);
assertThat(composite.filterByUnits("no_exist_units").getMonitors()).isNull();
}
@Test
public void testGetDistinctUnits() {
MonitorFactory.start("timelabel1").stop();
MonitorFactory.start("timelabel2").stop();
MonitorFactory.start("timelabel3").stop();
Collection<String> units = MonitorFactory.getRootMonitor().getDistinctUnits();
assertThat(units).containsExactly("Exception", "count", "ms.", "ns.");
}
@Test
public void testMonitorExists() {
MonitorComposite composite = MonitorFactory.getRootMonitor();
assertThat(composite.exists(new MonKeyImp("mylabel", "count" ))).isTrue();
assertThat(composite.exists(new MonKeyImp("I_DO_NOT", "EXIST" ))).isFalse();
}
@Test
public void testGetMonitor() {
MonitorComposite composite = MonitorFactory.getRootMonitor();
assertThat(composite.getMonitor(new MonKeyImp("mylabel", "count" ))).isNotNull();
assertThat(composite.getMonitor(new MonKeyImp("I_DO_NOT", "EXIST" ))).isNull();
}
@Test
public void testGetInstanceName() {
MonitorComposite composite = MonitorFactory.getRootMonitor();
assertThat(composite.getInstanceName()).isEqualTo("local");
assertThat(composite.setInstanceName("newname").getInstanceName()).isEqualTo("newname");
}
@Test
public void testIsLocalInstance() {
MonitorComposite composite = MonitorFactory.getRootMonitor();
assertThat(composite.isLocalInstance()).isTrue();
assertThat(composite.setInstanceName("newname").isLocalInstance()).isFalse();
}
@Test
public void shouldReturnInstanceNameInData() {
MonitorComposite composite = MonitorFactory.getRootMonitor();
int NUM_COLUMNS = 17;
assertThat(composite.getBasicHeader().length).isEqualTo(NUM_COLUMNS);
Object data = composite.getBasicData();
assertThat(composite.getBasicData()[0].length).isEqualTo(NUM_COLUMNS);
}
private Monitor getMonitorWithListeners(MonitorComposite monitorComposite) {
MonKey key = new MonKeyImp(EXCEPTION_METHOD, "ms.");
for (Monitor mon : monitorComposite.getMonitors()) {
if (mon.hasListeners() && mon.getMonKey().equals(key)) {
return mon;
}
}
return null;
}
private void methodWithException(int i) {
Exception exception = new RuntimeException(EXCEPTION_NAME +i);
MonKey key = new MonKeyImp(EXCEPTION_METHOD, Misc.getExceptionTrace(exception), "ms.");
MonitorFactory.add(key, i).start().stop();
}
private void deepComparisonAssertions(MonitorComposite original, MonitorComposite copy) {
// Do a deep comparison to see if the arrays are equal.
// Note getData flattens the data to return any ranges also. It doesn't however return
// Listener buffer data. A following check looks at that.
assertThat(Arrays.deepEquals(original.getData(), copy.getData())).isTrue();
assertThat(original.getReport()).isEqualTo(copy.getReport());
// One of the monitors was given all current listener types. Each of them should have 50 rows of data
Monitor mon = getMonitorWithListeners(copy);
CompositeListener compositeListener = (CompositeListener) mon.getListenerType("value").getListener();
// due to shared buffers being created the number of listeners and the composite uses them (_Shared...)
// but does not contain the actual factory instance (Shared...) the factory will have more elements (1
// for each shard listener) than the composite.
assertThat(compositeListener.getRowCount()).isLessThanOrEqualTo(JAMonListenerFactory.getData().length);
for (Object[] listenerType : compositeListener.getData()) {
JAMonBufferListener bufferListener = (JAMonBufferListener) mon.getListenerType("value").getListener(listenerType[0].toString());
// each should have 50 rows of data.
assertThat(bufferListener.getRowCount()).isEqualTo(BUFFER_SIZE);
Object[][] data = bufferListener.getDetailData().getData();
// each row should have a stacktrace in it. We look for "My ExceptionN"
// and RuntimeException
for (int i=0; i < data.length; i++) {
String stackTrace = data[i][0].toString();
assertThat(stackTrace).contains(EXCEPTION_NAME + i);
assertThat(stackTrace).contains("RuntimeException");
}
}
}
}
| apache-2.0 |
ajaykiet2/htdocs | application/views/website/includes/widgets/custom_menu.php | 564 | <div class="widget">
<div class="widget-title">
<h2>Custom Menu</h2>
</div><!-- /.widget-title -->
<div class="widget-content">
<ul class="menu">
<li><a href="#">Properties</a></li>
<li><a href="#">Features</a></li>
<li><a href="#">Agents</a></li>
<li><a href="#">Blog</a></li>
<li><a href="#">Agencies</a></li>
<li><a href="#">Pricing</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div><!-- /.widget-content -->
</div><!-- /.widget --> | apache-2.0 |
LordAkkarin/netty-msgpack | src/main/java/org/evilco/netty/msgpack/registry/AbstractMessageRegistry.java | 2639 | /*
* Copyright 2014 Johannes Donath <johannesd@evil-co.com>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.evilco.netty.msgpack.registry;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import lombok.NonNull;
import org.evilco.netty.msgpack.error.MessageRegistryException;
import org.evilco.netty.msgpack.error.UnknownMessageException;
/**
* Provides a basic packet registry implementation.
* @author Johannes Donath <johannesd@evil-co.com>
* @copyright Copyright (C) 2014 Evil-Co <http://www.evil-co.com>
*/
public abstract class AbstractMessageRegistry implements IMessageRegistry {
/**
* Stores the registry.
*/
private BiMap<Short, Class<?>> registry = HashBiMap.create ();
/**
* {@inheritDoc}
*/
@Override
public short getMessageID (@NonNull Class<?> messageType) throws MessageRegistryException {
// verify existence
if (!this.registry.inverse ().containsKey (messageType)) throw new UnknownMessageException ("Could not find registration for type " + messageType.getName ());
// get registered identifier
return this.registry.inverse ().get (messageType);
}
/**
* {@inheritDoc}
*/
@Override
public Class<?> getMessageType (short messageID) throws MessageRegistryException {
// verify existence
if (!this.registry.containsKey (messageID)) throw new UnknownMessageException ("Could not find registration for identifier " + messageID);
// get registered type
return this.registry.get (messageID);
}
/**
* Registers a message type.
* @param messageID The message identifier.
* @param messageType The message type.
*/
protected void registerMessage (short messageID, @NonNull Class<?> messageType) {
this.registry.put (messageID, messageType);
}
/**
* Alias for {@link org.evilco.netty.msgpack.registry.AbstractMessageRegistry#registerMessage(short, Class)}
* @see {@link org.evilco.netty.msgpack.registry.AbstractMessageRegistry#registerMessage(short, Class)}
*/
protected void registerMessage (int messageID, @NonNull Class<?> messageType) {
this.registerMessage (((short) messageID), messageType);
}
}
| apache-2.0 |
masoud-bahrami/Chakad.Pipeline4Monolith | Chakad/Pipeline/Core/Query/ChakadListQueryResult.cs | 792 | using Chakad.Pipeline.Core.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Chakad.Pipeline.Core.Query
{
public class ChakadQueryResult<T> : QueryResult, IBusinessQueryResult
{
public ChakadQueryResult()
{
CorrelationId = CorrelationIdConstants.Query;
}
private int _totalCount = -1;
public ICollection<T> Entities { get; set; }
public long ElapsedTime { get; set; }
#region IChakadListQueryResult Members
public IEnumerable GetItems()
{
return Entities;
}
public int TotalCount
{
get { return _totalCount; }
set { _totalCount = value; }
}
#endregion
}
} | apache-2.0 |
JuniorChristian/IDEA2.0 | Resources/Help.js | 2418 | function HelpWindow(title) {
var win = Ti.UI.createWindow({
backgroundColor: 'white',
title:'Help'
});
function addRow(obj) {
var row = Ti.UI.createTableViewRow({
height:Ti.UI.SIZE,
layout: 'horizontal',
});
var view = Ti.UI.createView({
bottom: 10,
height: Ti.UI.SIZE,
layout: 'vertical',
top: 20
});
row.add(view);
var titleLabel = Ti.UI.createLabel({
text: obj.title || '',
font: {fontSize: 16, fontWeight: 'bold'},
height: Ti.UI.SIZE,
left: 10,
right: 10,
textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER
});
view.add(titleLabel);
if(obj.text){
var textLabel = Ti.UI.createLabel({
text: obj.text || '',
height: Ti.UI.SIZE,
left: 10,
right: 10,
textAlign: Ti.UI.TEXT_ALIGNMENT_LEFT
});
view.add(textLabel);
}
return row;
}
var data = [
{
title: 'Welcome to Interactive Discovery and Environmental Assistance app. version 2.0'
},
{
title: 'TO BEGIN WITH...',
text: 'The term "POI" means "Point Of Interest".\n'
+ ' - POI LIST: is the list of our "POI" e.g a bathroom, an office or some other place.\n'
},
{
title: 'QR CODES DISPOSITION',
text: 'QR Codes are placed at about the height of your head, giving your back to the door you find the Qrcodes on your left side when starting from a POI and when arriving to a POI you still find them on your left side'
+ '. We use QRcode only as a checkpoint i.e to check where you are and if you arrive at the destination specified'
},
{
title: 'HOW TO SCAN?',
text: 'To scan, go to "QR Scan" Tab, click on "Scan Code" and face the phone towards the wall, at your head\'s height. When a QR code is found, the app will automatically display the text.'
},
{
title: 'NAVIGATION',
text: 'You search manually for the destination and starting point, just go on "Nav Tab", search for the Point of Interest you desire and then choose where you want to go.'
}
];
var rows = [], intRow = 0, intRows = data.length;
for (intRow = 0; intRow < intRows; intRow = intRow + 1) {
rows.push(addRow({
title: data[intRow].title,
text: data[intRow].text
}));
}
var tableview = Ti.UI.createTableView({
data: rows,
height: Ti.UI.FILL,
minRowHeight: 40,
width: Ti.UI.FILL
});
win.add(tableview);
return win;
};
module.exports = HelpWindow; | apache-2.0 |
serilog/serilog-sinks-email | test/Serilog.Sinks.Email.Tests/UseCultureAttribute.cs | 3747 | using System;
using System.Globalization;
using System.Reflection;
using System.Threading;
using Xunit.Sdk;
namespace Serilog.Sinks.Email.Tests
{
// This class courtesy of the xUnit samples at https://github.com/xunit/samples.xunit/blob/main/UseCulture/UseCultureAttribute.cs
/// <summary>
/// Apply this attribute to your test method to replace the
/// <see cref="Thread.CurrentThread" /> <see cref="CultureInfo.CurrentCulture" /> and
/// <see cref="CultureInfo.CurrentUICulture" /> with another culture.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
class UseCultureAttribute : BeforeAfterTestAttribute
{
readonly Lazy<CultureInfo> _culture;
readonly Lazy<CultureInfo> _uiCulture;
CultureInfo _originalCulture;
CultureInfo _originalUiCulture;
/// <summary>
/// Replaces the culture and UI culture of the current thread with
/// <paramref name="culture" />
/// </summary>
/// <param name="culture">The name of the culture.</param>
/// <remarks>
/// <para>
/// This constructor overload uses <paramref name="culture" /> for both
/// <see cref="Culture" /> and <see cref="UICulture" />.
/// </para>
/// </remarks>
public UseCultureAttribute(string culture)
: this(culture, culture) { }
/// <summary>
/// Replaces the culture and UI culture of the current thread with
/// <paramref name="culture" /> and <paramref name="uiCulture" />
/// </summary>
/// <param name="culture">The name of the culture.</param>
/// <param name="uiCulture">The name of the UI culture.</param>
public UseCultureAttribute(string culture, string uiCulture)
{
_culture = new Lazy<CultureInfo>(() => new CultureInfo(culture, false));
_uiCulture = new Lazy<CultureInfo>(() => new CultureInfo(uiCulture, false));
}
/// <summary>
/// Gets the culture.
/// </summary>
public CultureInfo Culture => _culture.Value;
/// <summary>
/// Gets the UI culture.
/// </summary>
public CultureInfo UICulture => _uiCulture.Value;
/// <summary>
/// Stores the current <see cref="Thread.CurrentPrincipal" />
/// <see cref="CultureInfo.CurrentCulture" /> and <see cref="CultureInfo.CurrentUICulture" />
/// and replaces them with the new cultures defined in the constructor.
/// </summary>
/// <param name="methodUnderTest">The method under test</param>
public override void Before(MethodInfo methodUnderTest)
{
_originalCulture = Thread.CurrentThread.CurrentCulture;
_originalUiCulture = Thread.CurrentThread.CurrentUICulture;
Thread.CurrentThread.CurrentCulture = Culture;
Thread.CurrentThread.CurrentUICulture = UICulture;
CultureInfo.CurrentCulture.ClearCachedData();
CultureInfo.CurrentUICulture.ClearCachedData();
}
/// <summary>
/// Restores the original <see cref="CultureInfo.CurrentCulture" /> and
/// <see cref="CultureInfo.CurrentUICulture" /> to <see cref="Thread.CurrentPrincipal" />
/// </summary>
/// <param name="methodUnderTest">The method under test</param>
public override void After(MethodInfo methodUnderTest)
{
Thread.CurrentThread.CurrentCulture = _originalCulture;
Thread.CurrentThread.CurrentUICulture = _originalUiCulture;
CultureInfo.CurrentCulture.ClearCachedData();
CultureInfo.CurrentUICulture.ClearCachedData();
}
}
}
| apache-2.0 |
aftenkap/jutility-math | src/main/java/org/jutility/math/geometry/Rectangle4.java | 7542 | package org.jutility.math.geometry;
//@formatter:off
/*
* #%L
* * jutility-math
* *
* %%
* Copyright (C) 2013 - 2014 jutility.org
* *
* %%
* 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.
* #L%
*/
//@formatter:on
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.jutility.math.vectoralgebra.IPoint4;
import org.jutility.math.vectoralgebra.Point4;
/**
* The generic {@code Rectangle4} class provides a reference implementation of
* the {@link IRectangle4} interface.
*
* @param <T>
* the {@link Number} type of the {@code Rectangle4}.
*
* @author Peter J. Radics
* @version 0.1.2
* @since 0.1.0
*/
@XmlRootElement(name = "Rectangle4")
@XmlType(name = "Rectangle4")
public class Rectangle4<T extends Number>
implements IRectangle4<T>, Serializable {
/**
* Serial Version UID.
*/
private static final long serialVersionUID = -5650871897919038389L;
@XmlAttribute
private final Class<? extends T> type;
@XmlElement(name = "TopLeftCorner", type = Point4.class)
private final IPoint4<T> topLeftCorner;
@XmlElement(name = "BottomLeftCorner", type = Point4.class)
private final IPoint4<T> bottomLeftCorner;
@XmlElement(name = "TopRightCorner", type = Point4.class)
private final IPoint4<T> topRightCorner;
@XmlElement(name = "BottomRightCorner", type = Point4.class)
private final IPoint4<T> bottomRightCorner;
@Override
public Class<? extends T> getType() {
return this.type;
}
@Override
public IPoint4<T> getBottomLeftCorner() {
return this.bottomLeftCorner;
}
@Override
public IPoint4<T> getBottomRightCorner() {
return this.bottomRightCorner;
}
@Override
public IPoint4<T> getTopLeftCorner() {
return this.topLeftCorner;
}
@Override
public IPoint4<T> getTopRightCorner() {
return this.topRightCorner;
}
/**
* Creates a new instance of the {@code Rectangle4} class. (Serialization
* Constructor)
*/
protected Rectangle4() {
this(null, null, null, true);
}
/**
* Creates a new instance of the {@code Rectangle4} class with the provided
* type and parameters.
*
* @param bottomLeftCorner
* the bottom-left corner.
* @param topRightCorner
* the top-right corner.
* @param type
* the type.
*/
public Rectangle4(final IPoint4<? extends Number> bottomLeftCorner,
final IPoint4<? extends Number> topRightCorner,
final Class<? extends T> type) {
this(bottomLeftCorner, topRightCorner, type, false);
}
/**
* Creates a new instance of the {@code Rectangle4} class with the provided
* type and parameters.
*
* @param bottomLeftCorner
* the bottom-left corner.
* @param topRightCorner
* the top-right corner.
* @param type
* the type.
* @param serialization
* whether or not the constructor is invoked during
* serialization.
*/
public Rectangle4(final IPoint4<? extends Number> bottomLeftCorner,
final IPoint4<? extends Number> topRightCorner,
final Class<? extends T> type, final boolean serialization) {
if (bottomLeftCorner == null && !serialization) {
throw new IllegalArgumentException(
"Cannot create a line without a bottom-left corner!");
}
if (topRightCorner == null && !serialization) {
throw new IllegalArgumentException(
"Cannot create a line without a top-right corner!");
}
if (type == null && !serialization) {
throw new IllegalArgumentException(
"Cannot create a line without a type!");
}
if (bottomLeftCorner != null && topRightCorner != null && type != null) {
this.bottomLeftCorner = new Point4<>(bottomLeftCorner, type);
this.topRightCorner = new Point4<>(topRightCorner, type);
this.topLeftCorner = new Point4<>(bottomLeftCorner.getX(),
topRightCorner.getY(), bottomLeftCorner.getZ(), type);
this.bottomRightCorner = new Point4<>(topRightCorner.getX(),
bottomLeftCorner.getY(), topRightCorner.getZ(), type);
}
else {
this.bottomLeftCorner = null;
this.bottomRightCorner = null;
this.topLeftCorner = null;
this.topRightCorner = null;
}
this.type = type;
}
/**
* Copy Constructor.
*
* @param rectangleToCopy
* the rectangle to copy.
*/
public Rectangle4(final IRectangle4<T> rectangleToCopy) {
this(rectangleToCopy, rectangleToCopy.getType());
}
/**
* Copy Constructor.
*
* @param rectangleToCopy
* the rectangle to cop
* @param type
* the desired type of the rectangle to copy.
*/
public Rectangle4(final IRectangle4<? extends Number> rectangleToCopy,
final Class<? extends T> type) {
this(rectangleToCopy.getBottomLeftCorner(), rectangleToCopy
.getTopRightCorner(), type);
}
@Override
public String toString() {
return "Rectangle [ Top Left: " + this.getTopLeftCorner()
+ ", Top Right: " + this.getTopRightCorner()
+ ", Bottom Left: " + this.getBottomLeftCorner()
+ ", Bottom Right: " + this.getBottomRightCorner() + " ]";
}
@Override
public boolean equals(final Object obj) {
if (obj != null && obj instanceof IRectangle4<?>) {
IRectangle4<?> other = (IRectangle4<?>) obj;
boolean sameTopLeftCorner = this.getTopLeftCorner().equals(
other.getTopLeftCorner());
boolean sameBottomLeftCorner = this.getBottomLeftCorner().equals(
other.getBottomLeftCorner());
boolean sameTopRightCorner = this.getTopRightCorner().equals(
other.getTopRightCorner());
boolean sameBottomRightCorner = this.getBottomRightCorner().equals(
other.getBottomRightCorner());
return sameTopLeftCorner && sameBottomLeftCorner
&& sameTopRightCorner && sameBottomRightCorner;
}
return false;
}
@Override
public int hashCode() {
int hash = 7;
hash += 7 * this.getTopLeftCorner().hashCode();
hash += 11 * this.getBottomLeftCorner().hashCode();
hash += 13 * this.getTopRightCorner().hashCode();
hash += 17 * this.getBottomRightCorner().hashCode();
return hash;
}
}
| apache-2.0 |
celigo/netsuite-service-manager-dotnet | ServiceManager/SuiteTalk/CouponCodeSearch.cs | 873 | //~ Generated by SearchRecordTemplate.tt
#pragma warning disable 1591
using System;
namespace com.celigo.net.ServiceManager.SuiteTalk
{
public partial class CouponCodeSearchBasic : ISearchBasic
{ }
public partial class CouponCodeSearch : ISearchRecord
{
/// <summary>
/// Gets the basic search criteria.
/// </summary>
/// <returns>The basic search criteria</returns>
public ISearchBasic GetSearchBasic()
{
return this.basic;
}
/// <summary>
/// Gets the basic search criteria.
/// </summary>
/// <param name="create">if set to <c>true</c> creates the basic criteria if null.</param>
/// <returns>The basic search criteria</returns>
public ISearchBasic GetSearchBasic(bool create)
{
if (create && this.basic == null)
this.basic = new CouponCodeSearchBasic();
return this.basic;
}
}
}
| apache-2.0 |
davidzchen/bazel | src/test/java/com/google/devtools/build/lib/skyframe/packages/AbstractPackageLoaderTest.java | 11477 | // Copyright 2017 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.skyframe.packages;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.testutil.MoreAsserts.assertContainsEvent;
import static com.google.devtools.build.lib.testutil.MoreAsserts.assertNoEvents;
import static org.junit.Assert.assertThrows;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.eventbus.EventBus;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.events.Reporter;
import com.google.devtools.build.lib.events.StoredEventHandler;
import com.google.devtools.build.lib.packages.NoSuchPackageException;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.skyframe.ExternalFilesHelper.ExternalFileAction;
import com.google.devtools.build.lib.vfs.DigestHashFunction;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.Root;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
import java.util.concurrent.ForkJoinPool;
import org.junit.Before;
import org.junit.Test;
/** Abstract base class of a unit test for a {@link AbstractPackageLoader} implementation. */
public abstract class AbstractPackageLoaderTest {
protected Path workspaceDir;
protected StoredEventHandler handler;
protected FileSystem fs;
protected Root root;
private Reporter reporter;
@Before
public final void init() throws Exception {
fs = new InMemoryFileSystem(DigestHashFunction.SHA256);
workspaceDir = fs.getPath("/workspace/");
workspaceDir.createDirectoryAndParents();
root = Root.fromPath(workspaceDir);
reporter = new Reporter(new EventBus());
handler = new StoredEventHandler();
reporter.addHandler(handler);
}
protected abstract AbstractPackageLoader.Builder newPackageLoaderBuilder(Root workspaceDir);
protected abstract ForkJoinPool extractLegacyGlobbingForkJoinPool(PackageLoader packageLoader);
protected AbstractPackageLoader.Builder newPackageLoaderBuilder() {
return newPackageLoaderBuilder(root).useDefaultStarlarkSemantics().setCommonReporter(reporter);
}
protected PackageLoader newPackageLoader() {
return newPackageLoaderBuilder().build();
}
@Test
public void simpleNoPackage() {
PackageIdentifier pkgId = PackageIdentifier.createInMainRepo(PathFragment.create("nope"));
NoSuchPackageException expected;
try (PackageLoader pkgLoader = newPackageLoader()) {
expected = assertThrows(NoSuchPackageException.class, () -> pkgLoader.loadPackage(pkgId));
}
assertThat(expected)
.hasMessageThat()
.startsWith("no such package 'nope': BUILD file not found");
assertNoEvents(handler.getEvents());
}
@Test
public void simpleBadPackage() throws Exception {
file("bad/BUILD", "invalidBUILDsyntax");
PackageIdentifier pkgId = PackageIdentifier.createInMainRepo(PathFragment.create("bad"));
Package badPkg;
try (PackageLoader pkgLoader = newPackageLoader()) {
badPkg = pkgLoader.loadPackage(pkgId);
}
assertThat(badPkg.containsErrors()).isTrue();
assertContainsEvent(handler.getEvents(), "invalidBUILDsyntax");
}
@Test
public void simpleGoodPackage() throws Exception {
file("good/BUILD", "sh_library(name = 'good')");
PackageIdentifier pkgId = PackageIdentifier.createInMainRepo(PathFragment.create("good"));
Package goodPkg;
try (PackageLoader pkgLoader = newPackageLoader()) {
goodPkg = pkgLoader.loadPackage(pkgId);
}
assertThat(goodPkg.containsErrors()).isFalse();
assertThat(goodPkg.getTarget("good").getAssociatedRule().getRuleClass())
.isEqualTo("sh_library");
assertNoEvents(handler.getEvents());
}
@Test
public void simpleMultipleGoodPackage() throws Exception {
file("good1/BUILD", "sh_library(name = 'good1')");
file("good2/BUILD", "sh_library(name = 'good2')");
PackageIdentifier pkgId1 = PackageIdentifier.createInMainRepo(PathFragment.create("good1"));
PackageIdentifier pkgId2 = PackageIdentifier.createInMainRepo(PathFragment.create("good2"));
PackageLoader.Result result;
try (PackageLoader pkgLoader = newPackageLoader()) {
result = pkgLoader.loadPackages(ImmutableList.of(pkgId1, pkgId2));
}
ImmutableMap<PackageIdentifier, PackageLoader.PackageOrException> pkgs =
result.getLoadedPackages();
assertThat(pkgs.get(pkgId1).get().containsErrors()).isFalse();
assertThat(pkgs.get(pkgId2).get().containsErrors()).isFalse();
assertThat(pkgs.get(pkgId1).get().getTarget("good1").getAssociatedRule().getRuleClass())
.isEqualTo("sh_library");
assertThat(pkgs.get(pkgId2).get().getTarget("good2").getAssociatedRule().getRuleClass())
.isEqualTo("sh_library");
assertNoEvents(result.getEvents());
assertNoEvents(handler.getEvents());
}
@Test
public void testGoodAndBadAndMissingPackages() throws Exception {
file("bad/BUILD", "invalidBUILDsyntax");
PackageIdentifier badPkgId = PackageIdentifier.createInMainRepo(PathFragment.create("bad"));
file("good/BUILD", "sh_library(name = 'good')");
PackageIdentifier goodPkgId = PackageIdentifier.createInMainRepo(PathFragment.create("good"));
PackageIdentifier missingPkgId = PackageIdentifier.createInMainRepo("missing");
PackageLoader.Result result;
try (PackageLoader pkgLoader = newPackageLoader()) {
result = pkgLoader.loadPackages(ImmutableList.of(badPkgId, goodPkgId, missingPkgId));
}
Package goodPkg = result.getLoadedPackages().get(goodPkgId).get();
assertThat(goodPkg.containsErrors()).isFalse();
Package badPkg = result.getLoadedPackages().get(badPkgId).get();
assertThat(badPkg.containsErrors()).isTrue();
assertThrows(
NoSuchPackageException.class, () -> result.getLoadedPackages().get(missingPkgId).get());
assertContainsEvent(result.getEvents(), "invalidBUILDsyntax");
assertContainsEvent(handler.getEvents(), "invalidBUILDsyntax");
}
@Test
public void loadPackagesToleratesDuplicates() throws Exception {
file("good1/BUILD", "sh_library(name = 'good1')");
PackageIdentifier pkgId = PackageIdentifier.createInMainRepo(PathFragment.create("good1"));
PackageLoader.Result result;
try (PackageLoader pkgLoader = newPackageLoader()) {
result = pkgLoader.loadPackages(ImmutableList.of(pkgId, pkgId));
}
ImmutableMap<PackageIdentifier, PackageLoader.PackageOrException> pkgs =
result.getLoadedPackages();
assertThat(pkgs.get(pkgId).get().containsErrors()).isFalse();
assertThat(pkgs.get(pkgId).get().getTarget("good1").getAssociatedRule().getRuleClass())
.isEqualTo("sh_library");
assertNoEvents(result.getEvents());
assertNoEvents(handler.getEvents());
}
@Test
public void simpleGoodPackage_Starlark() throws Exception {
file("good/good.bzl", "def f(x):", " native.sh_library(name = x)");
file("good/BUILD", "load('//good:good.bzl', 'f')", "f('good')");
PackageIdentifier pkgId = PackageIdentifier.createInMainRepo(PathFragment.create("good"));
Package goodPkg;
try (PackageLoader pkgLoader = newPackageLoader()) {
goodPkg = pkgLoader.loadPackage(pkgId);
}
assertThat(goodPkg.containsErrors()).isFalse();
assertThat(goodPkg.getTarget("good").getAssociatedRule().getRuleClass())
.isEqualTo("sh_library");
assertNoEvents(handler.getEvents());
}
@Test
public void externalFile_SupportedByDefault() throws Exception {
Path externalPath = file(absolutePath("/external/BUILD"), "sh_library(name = 'foo')");
symlink("foo/BUILD", externalPath);
PackageIdentifier pkgId = PackageIdentifier.createInMainRepo(PathFragment.create("foo"));
Package fooPkg;
try (PackageLoader pkgLoader = newPackageLoader()) {
fooPkg = pkgLoader.loadPackage(pkgId);
}
assertThat(fooPkg.containsErrors()).isFalse();
assertThat(fooPkg.getTarget("foo").getTargetKind()).isEqualTo("sh_library rule");
assertNoEvents(handler.getEvents());
}
@Test
public void externalFile_AssumeNonExistentAndImmutable() throws Exception {
Path externalPath = file(absolutePath("/external/BUILD"), "sh_library(name = 'foo')");
symlink("foo/BUILD", externalPath);
PackageIdentifier pkgId = PackageIdentifier.createInMainRepo(PathFragment.create("foo"));
NoSuchPackageException expected;
try (PackageLoader pkgLoader =
newPackageLoaderBuilder()
.setExternalFileAction(
ExternalFileAction.ASSUME_NON_EXISTENT_AND_IMMUTABLE_FOR_EXTERNAL_PATHS)
.build()) {
expected = assertThrows(NoSuchPackageException.class, () -> pkgLoader.loadPackage(pkgId));
}
assertThat(expected).hasMessageThat().contains("no such package 'foo': BUILD file not found");
}
@Test
public void testNonPackageEventsReported() throws Exception {
path("foo").createDirectoryAndParents();
symlink("foo/infinitesymlinkpkg", path("foo/infinitesymlinkpkg/subdir"));
PackageIdentifier pkgId = PackageIdentifier.createInMainRepo("foo/infinitesymlinkpkg");
PackageLoader.Result result;
try (PackageLoader pkgLoader = newPackageLoader()) {
result = pkgLoader.loadPackages(ImmutableList.of(pkgId));
}
assertThrows(NoSuchPackageException.class, () -> result.getLoadedPackages().get(pkgId).get());
assertContainsEvent(result.getEvents(), "infinite symlink expansion detected");
}
@Test
public void testClosesForkJoinPool() throws Exception {
PackageLoader pkgLoader = newPackageLoader();
ForkJoinPool forkJoinPool = extractLegacyGlobbingForkJoinPool(pkgLoader);
assertThat(forkJoinPool.isShutdown()).isFalse();
pkgLoader.close();
assertThat(forkJoinPool.isShutdown()).isTrue();
}
protected Path path(String rootRelativePath) {
return workspaceDir.getRelative(PathFragment.create(rootRelativePath));
}
protected Path absolutePath(String absolutePath) {
return fs.getPath(absolutePath);
}
protected Path file(String fileName, String... contents) throws Exception {
return file(path(fileName), contents);
}
protected Path file(Path path, String... contents) throws Exception {
path.getParentDirectory().createDirectoryAndParents();
FileSystemUtils.writeContentAsLatin1(path, Joiner.on("\n").join(contents));
return path;
}
protected Path symlink(String linkPathString, Path linkTargetPath) throws Exception {
Path path = path(linkPathString);
FileSystemUtils.ensureSymbolicLink(path, linkTargetPath);
return path;
}
}
| apache-2.0 |
qudh1/focusture | frame/src/main/java/cn/hybris/util/ListUtil.java | 770 | package cn.hybris.util;
import java.util.ArrayList;
import java.util.List;
/**
* 根据指定长度分割list
*/
public class ListUtil
{
public static <T> List<List<T>> splitList(List<T> list, int pageSize)
{
int listSize = list.size();
int page = (listSize + (pageSize - 1)) / pageSize;
List<List<T>> listArray = new ArrayList<List<T>>();
for (int i = 0; i < page; i++)
{
List<T> subList = new ArrayList<T>();
for (int j = 0; j < listSize; j++)
{
int pageIndex = ((j + 1) + (pageSize - 1)) / pageSize;
if (pageIndex == (i + 1))
{
subList.add(list.get(j));
}
if ((j + 1) == ((j + 1) * pageSize))
{
break;
}
}
listArray.add(subList);
}
return listArray;
}
}
| apache-2.0 |
firejack-open/Firejack-Platform | core/src/main/java/net/firejack/platform/core/model/registry/IUrlPathContainer.java | 1082 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package net.firejack.platform.core.model.registry;
public interface IUrlPathContainer {
/**
* @return
*/
public String getUrlPath();
/**
* @param urlPath
*/
public void setUrlPath(String urlPath);
} | apache-2.0 |
aam-at/tensorflow | tensorflow/compiler/mlir/hlo/lib/Dialect/mhlo/transforms/legalize_to_linalg.cc | 41163 | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
// This file implements logic for lowering HLO/LHLO dialect to Linalg dialect.
#include <numeric>
#include "llvm/ADT/STLExtras.h"
#include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
#include "mlir-hlo/Dialect/mhlo/IR/lhlo_ops.h"
#include "mlir-hlo/Dialect/mhlo/transforms/map_lmhlo_to_scalar_op.h"
#include "mlir-hlo/Dialect/mhlo/transforms/rewriters.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Linalg/IR/LinalgOps.h"
#include "mlir/Dialect/Linalg/IR/LinalgTypes.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/IR/AffineExpr.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Function.h"
#include "mlir/IR/Location.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/OperationSupport.h"
#include "mlir/IR/PatternMatch.h"
#include "mlir/IR/StandardTypes.h"
#include "mlir/IR/TypeUtilities.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
namespace mlir {
namespace {
SmallVector<StringRef, 3> GetNParallelLoopsAttrs(unsigned nParallelLoops) {
static constexpr StringRef kParallelIterType = "parallel";
return SmallVector<StringRef, 3>(nParallelLoops, kParallelIterType);
}
template <bool isLHLO = true>
Value getResultValue(Operation* op) {
return isLHLO ? op->getOperand(op->getNumOperands() - 1) : op->getResult(0);
}
template <bool isLHLO = true>
ShapedType getHloOpResultType(Operation* op) {
return getResultValue<isLHLO>(op).getType().template cast<ShapedType>();
}
template <bool isLHLO = true>
bool verifyHloOpBufferOrTensorSemantics(Operation* op) {
auto verify_type = [&](Value val) -> bool {
return (isLHLO && val.getType().isa<MemRefType>()) ||
(!isLHLO && val.getType().isa<RankedTensorType>());
};
if (!llvm::all_of(op->getOperands(), verify_type)) return false;
return isLHLO ? op->getResults().empty()
: llvm::all_of(op->getResults(), verify_type);
}
template <typename OpTy, bool isLHLO = true>
class PointwiseToLinalgConverter : public OpConversionPattern<OpTy> {
public:
using OpConversionPattern<OpTy>::OpConversionPattern;
LogicalResult matchAndRewrite(
OpTy op, ArrayRef<Value> args,
ConversionPatternRewriter& rewriter) const final {
auto loc = op.getLoc();
ShapedType t0 = args[0].getType().template dyn_cast<ShapedType>();
if (!t0) return failure();
unsigned nloops = t0.getRank();
auto fail = [&](ShapedType t) {
return !t || !t.hasRank() || t.getRank() != nloops ||
!(t.getElementType().isSignlessIntOrFloat() ||
t.getElementType().isa<ComplexType>());
};
if (llvm::any_of(args,
[&](Value v) {
return fail(v.getType().dyn_cast<ShapedType>());
}) ||
llvm::any_of(op.getOperation()->getResultTypes(),
[&](Type t) { return fail(t.dyn_cast<ShapedType>()); }))
return emitError(loc,
"lhlo to linalg conversion expects ranked args of "
"signless int, float or complex element type with ")
<< nloops << " parallel iterators: " << *(op.getOperation());
// Construct the indexing maps needed for linalg.generic ops.
SmallVector<Type, 4> body_arg_types, body_result_types, op_result_types;
// This doesnt account for implicit broadcast, but the working assumption
// in HLO/LHLO is that are broadcasts are made explicit.
if (isLHLO && !nloops) return failure();
int num_inputs = (isLHLO ? args.size() - 1 : args.size());
ValueRange inputs(args.take_front(num_inputs));
for (Value in : inputs)
body_arg_types.emplace_back(getElementTypeOrSelf(in.getType()));
ValueRange output_buffers(args.take_back(args.size() - num_inputs));
for (Value out : output_buffers)
body_result_types.emplace_back(getElementTypeOrSelf(out.getType()));
if (!isLHLO) {
// HLO operations have return as tensor types.
assert(body_result_types.empty() &&
"When lowering HLO ops result can't be part of arguments");
Value result = op.getOperation()->getResult(0);
body_result_types.push_back(getElementTypeOrSelf(result));
op_result_types.push_back(result.getType());
}
AffineMap common_indexing_map =
nloops ? rewriter.getMultiDimIdentityMap(nloops)
: AffineMap::get(nloops, 0, rewriter.getContext());
SmallVector<AffineMap, 2> indexing_maps(args.size() + (isLHLO ? 0 : 1),
common_indexing_map);
auto linalg_op = rewriter.create<linalg::GenericOp>(
loc, op_result_types, inputs, output_buffers,
/*initTensors=*/ValueRange{}, indexing_maps,
GetNParallelLoopsAttrs(nloops),
[&](OpBuilder& nested_builder, Location nested_loc, ValueRange args) {
// TODO(ravishankarm) : For now use the method in lmhlo namespace.
// That method needs to be moved out of there.
Value op_result = lmhlo::HloOpToStdScalarOp::map<OpTy>(
op, body_result_types,
llvm::to_vector<2>(args.take_front(inputs.size())), &rewriter);
nested_builder.create<linalg::YieldOp>(loc, op_result);
});
rewriter.replaceOp(op, linalg_op.getOperation()->getResults());
return success();
}
};
template <typename LhloOp>
class ScalarPointwiseToStandardConverter : public OpConversionPattern<LhloOp> {
public:
using OpConversionPattern<LhloOp>::OpConversionPattern;
LogicalResult matchAndRewrite(
LhloOp lhlo_op, ArrayRef<Value> args,
ConversionPatternRewriter& rewriter) const final {
auto loc = lhlo_op.getLoc();
auto arg_type =
lhlo_op.getOperand(0).getType().template dyn_cast<ShapedType>();
if (!arg_type || !arg_type.getElementType().isSignlessIntOrFloat() ||
(arg_type.getRank() != 0)) {
return failure();
}
// Create two loads from the input.
auto lhs = rewriter.create<LoadOp>(loc, lhlo_op.lhs());
auto rhs = rewriter.create<LoadOp>(loc, lhlo_op.rhs());
// TODO(ravishankarm) : Move this method out of lmhlo namespace.
Value op_result = lmhlo::HloOpToStdScalarOp::map<LhloOp>(
lhlo_op, arg_type.getElementType(), llvm::ArrayRef<Value>{lhs, rhs},
&rewriter);
rewriter.create<StoreOp>(loc, op_result, lhlo_op.out());
rewriter.eraseOp(lhlo_op);
return success();
}
};
//===----------------------------------------------------------------------===//
// lmhlo.convolution conversion pattern.
//===----------------------------------------------------------------------===//
/// Converts lmhlo.convolution operation to a linalg.conv op.
struct ConvToLinalgConverter : public OpConversionPattern<lmhlo::ConvOp> {
public:
using OpConversionPattern<lmhlo::ConvOp>::OpConversionPattern;
// This code has been adapted from IREE's
// (https://github.com/google/iree/) mhlo -> linalg conversion.
LogicalResult matchAndRewrite(
lmhlo::ConvOp op, ArrayRef<Value> args,
ConversionPatternRewriter& rewriter) const final {
// Check validity of dimension information.
if (const mhlo::ConvDimensionNumbers& dimension_numbers =
op.dimension_numbers()) {
const int input_spatial_rank =
llvm::size(dimension_numbers.input_spatial_dimensions());
// The dimensions for input should follow the order of
// batch_count, spatial_dims..., input_feature_count.
if (dimension_numbers.input_batch_dimension().getInt() != 0 ||
dimension_numbers.input_feature_dimension().getInt() !=
(input_spatial_rank + 1))
return failure();
const int kernel_spatial_rank =
llvm::size(dimension_numbers.kernel_spatial_dimensions());
// The dimensions for filter should follow the order of
// spatial_dims..., input_feature_count, num_output_feature_count.
if (dimension_numbers.kernel_input_feature_dimension().getInt() !=
kernel_spatial_rank ||
dimension_numbers.kernel_output_feature_dimension().getInt() !=
(kernel_spatial_rank + 1))
return failure();
const int output_spatial_rank =
llvm::size(dimension_numbers.output_spatial_dimensions());
// The dimensions for output should follow the order of
// batch_count, spatial_dims.., output_feature_count.
if (dimension_numbers.output_batch_dimension().getInt() != 0 ||
dimension_numbers.output_feature_dimension().getInt() !=
(output_spatial_rank + 1))
return failure();
if (input_spatial_rank != output_spatial_rank ||
input_spatial_rank != kernel_spatial_rank)
return failure();
auto input_spatial_dim =
dimension_numbers.input_spatial_dimensions().begin();
auto kernel_spatial_dim =
dimension_numbers.kernel_spatial_dimensions().begin();
auto output_spatial_dim =
dimension_numbers.output_spatial_dimensions().begin();
// Check if spatial dims are ordered correctly.
for (int i = 0; i < input_spatial_rank; ++i) {
const int dim = i + 1;
if ((*input_spatial_dim++).getZExtValue() != dim ||
(*output_spatial_dim++).getZExtValue() != dim ||
(*kernel_spatial_dim++).getZExtValue() != i)
return failure();
}
}
// TODO: LHS dilation for deconvolution not supported yet.
if (op.lhs_dilation()) {
return failure();
}
llvm::SmallVector<Attribute, 4> strides;
if (auto window_strides = op.window_strides()) {
auto range = window_strides->getAttributeValues();
strides.assign(range.begin(), range.end());
}
auto strides_arg = ArrayAttr::get(strides, op.getContext());
llvm::SmallVector<Attribute, 2> dilation;
if (auto rhs_dilation = op.rhs_dilation()) {
auto range = rhs_dilation->getAttributeValues();
dilation.assign(range.begin(), range.end());
} else {
// Default dilation of 1.
dilation.resize(2, IntegerAttr::get(rewriter.getIntegerType(64), 1));
}
auto dilation_arg = ArrayAttr::get(dilation, op.getContext());
// Set padding only if it is non-zero.
DenseIntElementsAttr padding = op.paddingAttr();
if (!padding ||
!llvm::any_of(padding.getValues<APInt>(),
[](APInt int_val) { return !int_val.isNullValue(); })) {
padding = nullptr;
}
// The order of input and filter are switched with linalg.conv.
rewriter.replaceOpWithNewOp<linalg::ConvOp>(
op, args[1], args[0], args[2], strides_arg, dilation_arg, padding);
return success();
}
};
/// Base class for lowering HLO operations that have one operand and one result,
/// and are semantically equivalent to a copy of the input to the output (like
/// transpose, some reshape, etc.). The derived classes need to provide a method
/// `getIndexingMaps` that returns AffineMaps for the index maps of the input
/// and the output.
template <typename Derived, typename OpTy, bool isLHLO = true>
class DataMovementOpConverter : public OpConversionPattern<OpTy> {
public:
using OpConversionPattern<OpTy>::OpConversionPattern;
LogicalResult matchAndRewrite(
OpTy op, ArrayRef<Value> args,
ConversionPatternRewriter& rewriter) const final {
if (!verifyHloOpBufferOrTensorSemantics<isLHLO>(op)) return failure();
auto result_type = getHloOpResultType<isLHLO>(op);
SmallVector<AffineMap, 2> indexing_maps =
Derived::getIndexingMaps(op, &rewriter);
if (indexing_maps.empty()) return failure();
auto nloops = result_type.getRank();
auto loc = op.getLoc();
auto linalg_op = rewriter.create<linalg::GenericOp>(
loc,
/*resultTensorTypes=*/isLHLO ? ArrayRef<Type>{} : result_type,
/*inputs=*/args.front(),
/*outputBuffers=*/isLHLO ? ValueRange{args.back()} : ValueRange{},
/*initTensor=*/ValueRange{}, indexing_maps,
GetNParallelLoopsAttrs(nloops),
[&](OpBuilder& nested_builder, Location nested_loc, ValueRange args) {
nested_builder.create<linalg::YieldOp>(loc, *args.begin());
});
rewriter.replaceOp(op, linalg_op.getOperation()->getResults());
return success();
}
};
/// Pattern to convert BroadcastOp to Linalg ops.
template <typename OpTy, bool isLHLO = true>
class BroadcastConverter
: public DataMovementOpConverter<BroadcastConverter<OpTy, isLHLO>, OpTy,
isLHLO> {
public:
using DataMovementOpConverter<BroadcastConverter, OpTy,
isLHLO>::DataMovementOpConverter;
static SmallVector<AffineMap, 2> getIndexingMaps(OpTy broadcast_op,
Builder* b) {
ShapedType input_type =
broadcast_op.operand().getType().template cast<ShapedType>();
unsigned input_rank = input_type.getRank();
unsigned nloops = getHloOpResultType<isLHLO>(broadcast_op).getRank();
// BroadcastOp prepends the dimensions in the `broadcast_sizes` attribute to
// the input's dimensions.
unsigned num_prepended_dims = llvm::size(broadcast_op.broadcast_sizes());
SmallVector<AffineExpr, 4> input_dim_exprs;
input_dim_exprs.reserve(input_rank);
for (int i = 0; i < input_rank; ++i) {
input_dim_exprs.push_back(b->getAffineDimExpr(num_prepended_dims + i));
}
AffineMap input_map;
MLIRContext* context = b->getContext();
if (input_dim_exprs.empty()) {
// The input is a scalar, i.e. this is a scalar broadcast op.
input_map = AffineMap::get(nloops, /*symbolCount=*/0, context);
} else {
input_map =
AffineMap::get(nloops, /*symbolCount=*/0, input_dim_exprs, context);
}
return {input_map, b->getMultiDimIdentityMap(nloops)};
}
};
class HloBroadcastInDimConverter
: public DataMovementOpConverter<HloBroadcastInDimConverter,
mhlo::BroadcastInDimOp, false> {
public:
using DataMovementOpConverter<HloBroadcastInDimConverter,
mhlo::BroadcastInDimOp,
false>::DataMovementOpConverter;
static SmallVector<AffineMap, 2> getIndexingMaps(
mhlo::BroadcastInDimOp broadcast_op, Builder* b) {
auto result_type = getHloOpResultType<false>(broadcast_op);
auto operand_type =
broadcast_op.operand().getType().template cast<ShapedType>();
unsigned nloops = result_type.getRank();
// The input is a scalar, i.e. this is a scalar broadcast op.
if (operand_type.getRank() == 0) {
return {AffineMap::get(nloops, /*symbolCount=*/0, b->getContext()),
b->getMultiDimIdentityMap(nloops)};
}
auto operand_shape = operand_type.getShape();
SmallVector<AffineExpr, 4> dim_exprs;
dim_exprs.reserve(nloops);
if (broadcast_op.broadcast_dimensions()) {
for (const auto& broadcastDim :
enumerate(broadcast_op.broadcast_dimensions().getIntValues())) {
int size = broadcastDim.value().getSExtValue();
bool expansion_needed = operand_shape[broadcastDim.index()] == 1 &&
result_type.getShape()[size] != 1;
dim_exprs.push_back(expansion_needed ? b->getAffineConstantExpr(0)
: b->getAffineDimExpr(size));
}
}
return {
AffineMap::get(nloops, /*symbolCount=*/0, dim_exprs, b->getContext()),
b->getMultiDimIdentityMap(nloops)};
}
};
class LhloBroadcastInDimConverter
: public OpConversionPattern<lmhlo::BroadcastInDimOp> {
public:
using OpConversionPattern<lmhlo::BroadcastInDimOp>::OpConversionPattern;
LogicalResult matchAndRewrite(
lmhlo::BroadcastInDimOp op, ArrayRef<Value> args,
ConversionPatternRewriter& rewriter) const final {
lmhlo::BroadcastInDimOp::Adaptor operand_adaptor(args);
auto result_type = operand_adaptor.output().getType().cast<MemRefType>();
auto result_shape = result_type.getShape();
auto operand_and_dims = InsertReshapeIfNecessary(op, args, rewriter);
Value operand = std::get<0>(operand_and_dims);
auto broadcast_dims = std::get<1>(operand_and_dims);
auto loc = op.getLoc();
auto nloops = result_type.getRank();
auto operand_type = operand.getType().cast<MemRefType>();
// For a degenerate case, i.e. broadcasting with expansion of
// memref<1xELEMENT_TYPE>, the operand is not passed to `linalg.generic`.
// Instead the value is loaded and used directly in `linalg.yield`.
if (operand_type.getRank() == 1 &&
operand_type.getDimSize(0) <
result_type.getDimSize(broadcast_dims.front())) {
Value zero = rewriter.create<ConstantIndexOp>(loc, 0);
Value val =
rewriter.create<LoadOp>(loc, operand, llvm::makeArrayRef({zero}));
rewriter.create<linalg::GenericOp>(
loc, /*inputs=*/ValueRange{},
/*outputBuffers=*/ValueRange{operand_adaptor.output()},
llvm::makeArrayRef(rewriter.getMultiDimIdentityMap(nloops)),
GetNParallelLoopsAttrs(nloops),
[&](OpBuilder& nested_builder, Location nested_loc, ValueRange args) {
nested_builder.create<linalg::YieldOp>(loc, val);
});
} else {
auto indexing_maps = getIndexingMaps(op, broadcast_dims, result_shape,
operand_type, &rewriter);
rewriter.create<linalg::GenericOp>(
loc, /*inputs=*/ValueRange{operand},
/*outputBuffers=*/ValueRange{operand_adaptor.output()}, indexing_maps,
GetNParallelLoopsAttrs(nloops),
[&](OpBuilder& nested_builder, Location nested_loc, ValueRange args) {
nested_builder.create<linalg::YieldOp>(loc, *args.begin());
});
}
rewriter.replaceOp(op, llvm::None);
return success();
}
// Inserts 'linalg.reshape' if there is a size-1 dim expansion.
std::pair<Value, SmallVector<int64_t, 2>> InsertReshapeIfNecessary(
lmhlo::BroadcastInDimOp op, ArrayRef<Value> args,
ConversionPatternRewriter& rewriter) const {
lmhlo::BroadcastInDimOp::Adaptor operand_adaptor(args);
Value operand = operand_adaptor.operand();
auto operand_type = operand_adaptor.operand().getType().cast<MemRefType>();
auto operand_shape = operand_type.getShape();
Value result = operand_adaptor.output();
auto result_type = result.getType().cast<MemRefType>();
auto result_shape = result_type.getShape();
SmallVector<int64_t, 2> operand_strides;
int64_t operand_offset;
if (failed(getStridesAndOffset(operand_type, operand_strides,
operand_offset))) {
op.emitOpError() << "Failed to get offset and strides.";
}
SmallVector<int64_t, 2> new_shape, new_strides, broadcast_dims;
SmallVector<linalg::ReassociationIndices, 4> collapsed_dims_list;
linalg::ReassociationIndices collapsed_dims;
for (const auto& item :
enumerate(op.broadcast_dimensions().getIntValues())) {
size_t index = item.index();
int dim = item.value().getSExtValue();
collapsed_dims.push_back(index);
bool expansion_needed =
operand_shape[index] == 1 && result_shape[dim] != 1;
if (expansion_needed) {
continue;
}
new_shape.push_back(operand_shape[index]);
new_strides.push_back(operand_strides[index]);
broadcast_dims.push_back(dim);
collapsed_dims_list.push_back(collapsed_dims);
collapsed_dims.clear();
}
// If `collapsed_dims_list` is empty, then the memref has shape [1, ..., 1]
// and all dimensions need expansion. Such memref will be reshaped to a 1D
// memref with a single element. New shape and strides needs to be updated
// accordingly.
if (collapsed_dims_list.empty()) {
collapsed_dims_list.push_back({});
new_shape.push_back(1);
new_strides.push_back(1);
broadcast_dims.push_back(0);
}
for (const auto& dims : collapsed_dims) {
collapsed_dims_list.back().push_back(dims);
}
// `linalg.reshape` is inserted only if necessary, i.e. when the rank can be
// reduced.
if (new_shape.size() < operand_shape.size()) {
auto new_memref_type = MemRefType::get(
new_shape, operand_type.getElementType(),
makeStridedLinearLayoutMap(new_strides, operand_offset,
rewriter.getContext()));
operand = rewriter.create<linalg::ReshapeOp>(op.getLoc(), new_memref_type,
operand_adaptor.operand(),
collapsed_dims_list);
}
return std::make_pair(operand, broadcast_dims);
}
SmallVector<AffineMap, 2> getIndexingMaps(lmhlo::BroadcastInDimOp op,
ArrayRef<int64_t> broadcast_dims,
ArrayRef<int64_t> result_shape,
MemRefType operand_type,
Builder* b) const {
unsigned nloops = result_shape.size();
// The input is a scalar, i.e. this is a scalar broadcast op.
if (operand_type.getRank() == 0) {
return {AffineMap::get(nloops, /*symbolCount=*/0, b->getContext()),
b->getMultiDimIdentityMap(nloops)};
}
auto operand_shape = operand_type.getShape();
SmallVector<AffineExpr, 4> dim_exprs;
dim_exprs.reserve(nloops);
for (const auto& broadcast_dim : llvm::enumerate(broadcast_dims)) {
int size = broadcast_dim.value();
bool expansion_needed =
operand_shape[broadcast_dim.index()] == 1 && result_shape[size] != 1;
if (expansion_needed) {
op.emitOpError(
"BroadcastInDimOp lowering to Linalg does not support size-1 "
"dimensions expansion.");
}
dim_exprs.push_back(b->getAffineDimExpr(size));
}
return {
AffineMap::get(nloops, /*symbolCount=*/0, dim_exprs, b->getContext()),
b->getMultiDimIdentityMap(nloops)};
}
};
template <typename OpTy, bool isLHLO = true>
class TransposeConverter
: public DataMovementOpConverter<TransposeConverter<OpTy, isLHLO>, OpTy,
isLHLO> {
public:
using DataMovementOpConverter<TransposeConverter<OpTy, isLHLO>, OpTy,
isLHLO>::DataMovementOpConverter;
static SmallVector<AffineMap, 2> getIndexingMaps(OpTy op, Builder* b) {
auto result_type =
getHloOpResultType<isLHLO>(op).template cast<ShapedType>();
auto nloops = result_type.getRank();
SmallVector<AffineExpr, 2> input_exprs;
input_exprs.resize(result_type.getRank());
for (auto permutation : llvm::enumerate(op.permutation())) {
input_exprs[permutation.value().getZExtValue()] =
b->getAffineDimExpr(permutation.index());
}
return {
AffineMap::get(nloops, /*symbolCount=*/0, input_exprs, b->getContext()),
b->getMultiDimIdentityMap(nloops)};
}
};
// Converts reshape ops that can be proven to be either a collapse of dimensions
// or expansion of dimensions of the operand.
template <typename OpTy, bool isLHLO = true>
class ReshapeOpConverter : public OpConversionPattern<OpTy> {
public:
using OpConversionPattern<OpTy>::OpConversionPattern;
LogicalResult matchAndRewrite(
OpTy reshape_op, ArrayRef<Value> args,
ConversionPatternRewriter& rewriter) const final {
if (!verifyHloOpBufferOrTensorSemantics<isLHLO>(reshape_op))
return failure();
ShapedType operand_type =
reshape_op.operand().getType().template cast<ShapedType>();
ShapedType result_type = getHloOpResultType<isLHLO>(reshape_op);
if (!operand_type.hasStaticShape() || !result_type.hasStaticShape())
return failure();
// Compute the reassociation maps for the linalg operation.
ArrayRef<int64_t> src_shape =
(operand_type.getRank() > result_type.getRank()
? operand_type.getShape()
: result_type.getShape());
ArrayRef<int64_t> dst_shape =
(operand_type.getRank() > result_type.getRank()
? result_type.getShape()
: operand_type.getShape());
unsigned curr_src_dim = 0, curr_dst_dim = 0;
SmallVector<linalg::ReassociationExprs, 4> reassociation_map(
dst_shape.size());
bool is_expanding_or_collapsing = true;
while (curr_src_dim < src_shape.size() && curr_dst_dim < dst_shape.size()) {
int64_t dst_size = dst_shape[curr_dst_dim];
int64_t src_size = src_shape[curr_src_dim];
while (src_size < dst_size && curr_src_dim < src_shape.size()) {
reassociation_map[curr_dst_dim].push_back(
rewriter.getAffineDimExpr(curr_src_dim++));
src_size *= src_shape[curr_src_dim];
}
if (src_size == dst_size) {
reassociation_map[curr_dst_dim].push_back(
rewriter.getAffineDimExpr(curr_src_dim++));
// If the next dim in dst_shape is not 1, treat subsequent dims in
// src_shape which are 1 to be collapsed.
if (curr_dst_dim == dst_shape.size() - 1 ||
dst_shape[curr_dst_dim + 1] != 1) {
while (curr_src_dim < src_shape.size() &&
src_shape[curr_src_dim] == 1) {
reassociation_map[curr_dst_dim].push_back(
rewriter.getAffineDimExpr(curr_src_dim++));
}
}
} else {
is_expanding_or_collapsing = false;
break;
}
curr_dst_dim++;
}
if (curr_src_dim != src_shape.size() || curr_dst_dim != dst_shape.size())
is_expanding_or_collapsing = false;
if (!is_expanding_or_collapsing) {
auto get_identity_exprs = [&rewriter](int n) {
SmallVector<AffineExpr, 4> exprs;
for (int i = 0; i < n; ++i)
exprs.push_back(rewriter.getAffineDimExpr(i));
return exprs;
};
Location loc = reshape_op.getLoc();
int64_t total_elems = std::accumulate(src_shape.begin(), src_shape.end(),
1, std::multiplies<int64_t>());
auto elem_type = operand_type.getElementType();
SmallVector<linalg::ReassociationExprs, 4> collapsing_map = {
get_identity_exprs(dst_shape.size())};
SmallVector<linalg::ReassociationExprs, 4> expanding_map = {
get_identity_exprs(src_shape.size())};
if (isLHLO) {
auto collapsed_type = MemRefType::get({total_elems}, elem_type);
Value collapsed_op = rewriter.create<linalg::ReshapeOp>(
loc, collapsed_type, args[0], collapsing_map);
Value reshape_buffer = rewriter.create<linalg::ReshapeOp>(
loc, result_type, collapsed_op, expanding_map);
rewriter.replaceOpWithNewOp<linalg::CopyOp>(
reshape_op, reshape_buffer, args[1], /*inputPermutation =*/nullptr,
/*outputPermutation =*/nullptr);
} else {
auto collapsed_type = RankedTensorType::get({total_elems}, elem_type);
Value collapsed_op = rewriter.create<linalg::TensorReshapeOp>(
loc, collapsed_type, args[0], collapsing_map);
rewriter.replaceOpWithNewOp<linalg::TensorReshapeOp>(
reshape_op, result_type, collapsed_op, expanding_map);
}
return success();
}
if (isLHLO) {
Value reshape_buffer = rewriter.create<linalg::ReshapeOp>(
reshape_op.getLoc(), result_type, args[0], reassociation_map);
rewriter.replaceOpWithNewOp<linalg::CopyOp>(
reshape_op, reshape_buffer, args[1], /*inputPermutation =*/nullptr,
/*outputPermutation =*/nullptr);
} else {
rewriter.replaceOpWithNewOp<linalg::TensorReshapeOp>(
reshape_op, result_type, args[0], reassociation_map);
}
return success();
}
};
template <typename OpTy, bool isLHLO = true>
class IotaConverter : public OpConversionPattern<OpTy> {
public:
using OpConversionPattern<OpTy>::OpConversionPattern;
LogicalResult matchAndRewrite(
OpTy iota_op, ArrayRef<Value> args,
ConversionPatternRewriter& rewriter) const final {
ShapedType result_shaped_type = getHloOpResultType<isLHLO>(iota_op);
if (!result_shaped_type) return failure();
auto result_element_type = result_shaped_type.getElementType();
if (!result_element_type.isSignlessIntOrFloat()) return failure();
// Construct the indexing maps needed for linalg.generic ops.
unsigned nloops = result_shaped_type.getRank();
auto linalg_op = rewriter.create<linalg::IndexedGenericOp>(
iota_op.getLoc(),
/*resultTensorTypes=*/
isLHLO ? ArrayRef<Type>{} : ArrayRef<Type>{result_shaped_type},
/*inputs=*/ValueRange{},
/*outputBuffers=*/isLHLO ? ValueRange{args} : ValueRange{},
/*initTensors=*/ValueRange{},
llvm::makeArrayRef(rewriter.getMultiDimIdentityMap(nloops)),
GetNParallelLoopsAttrs(nloops),
[&](OpBuilder& nested_builder, Location nested_loc, ValueRange ivs,
ValueRange args) {
Value cast_op = nested_builder.create<IndexCastOp>(
nested_loc, ivs[iota_op.iota_dimension()],
nested_builder.getIntegerType(
result_element_type.getIntOrFloatBitWidth()));
if (result_element_type.template isa<FloatType>()) {
cast_op = nested_builder.create<SIToFPOp>(nested_loc, cast_op,
result_element_type);
}
nested_builder.create<linalg::YieldOp>(nested_loc, cast_op);
});
if (isLHLO)
rewriter.replaceOp(iota_op, llvm::None);
else
rewriter.replaceOp(iota_op, linalg_op.result_tensors());
return success();
}
};
class ConstConverter : public OpConversionPattern<lmhlo::ConstOp> {
public:
using OpConversionPattern<lmhlo::ConstOp>::OpConversionPattern;
LogicalResult matchAndRewrite(
lmhlo::ConstOp const_op, ArrayRef<Value> args,
ConversionPatternRewriter& rewriter) const final {
auto loc = const_op.getLoc();
auto value_attr = const_op.value().cast<DenseElementsAttr>();
if (value_attr.getType().getRank() != 0) return failure();
auto std_const_op =
rewriter.create<mlir::ConstantOp>(loc, value_attr.getValue({}));
rewriter.create<mlir::AffineStoreOp>(loc, std_const_op,
const_op.getOperand(), ValueRange());
rewriter.eraseOp(const_op);
return success();
}
};
// TODO(b/156787842): Support the lowering for dynamic shapes.
template <typename OpTy, bool isLHLO = true>
class ReverseConverter
: public DataMovementOpConverter<ReverseConverter<OpTy, isLHLO>, OpTy,
isLHLO> {
public:
using DataMovementOpConverter<ReverseConverter<OpTy, isLHLO>, OpTy,
isLHLO>::DataMovementOpConverter;
static SmallVector<AffineMap, 2> getIndexingMaps(OpTy op, Builder* b) {
auto result_type =
getHloOpResultType<isLHLO>(op).template cast<ShapedType>();
auto nloops = result_type.getRank();
SmallVector<AffineExpr, 2> input_exprs;
input_exprs.reserve(nloops);
for (int i = 0; i < nloops; ++i)
input_exprs.push_back(b->getAffineDimExpr(i));
for (auto dim : op.dimensions()) {
int i = dim.getZExtValue();
if (result_type.isDynamicDim(i)) return {};
int n = result_type.getShape()[i];
input_exprs[i] = b->getAffineConstantExpr(n - 1) - input_exprs[i];
}
return {
AffineMap::get(nloops, /*symbolCount=*/0, input_exprs, b->getContext()),
b->getMultiDimIdentityMap(nloops)};
}
};
class SliceConverter : public OpConversionPattern<lmhlo::SliceOp> {
public:
using OpConversionPattern<lmhlo::SliceOp>::OpConversionPattern;
LogicalResult matchAndRewrite(
lmhlo::SliceOp slice_op, ArrayRef<Value> args,
ConversionPatternRewriter& rewriter) const final {
auto loc = slice_op.getLoc();
auto arg_type =
slice_op.getOperand(0).getType().template dyn_cast<ShapedType>();
if (!arg_type || !arg_type.hasRank()) {
emitError(loc, "lhlo to linalg conversion expects known-rank args");
return failure();
}
SmallVector<Value, 3> ranges;
for (int i = 0, e = arg_type.getRank(); i < e; ++i) {
Value start_index = rewriter.create<ConstantIndexOp>(
loc, slice_op.start_indices().getValue<int64_t>(i));
Value limit_index = rewriter.create<ConstantIndexOp>(
loc, slice_op.limit_indices().getValue<int64_t>(i));
Value stride = rewriter.create<ConstantIndexOp>(
loc, slice_op.strides().getValue<int64_t>(i));
ranges.push_back(rewriter.create<linalg::RangeOp>(loc, start_index,
limit_index, stride));
}
auto linalg_slice =
rewriter.create<linalg::SliceOp>(loc, slice_op.getOperand(0), ranges);
rewriter.create<linalg::CopyOp>(loc, linalg_slice, slice_op.getOperand(1));
rewriter.eraseOp(slice_op);
return success();
}
};
void populateLHLOToLinalgConversionPattern(MLIRContext* context,
OwningRewritePatternList* patterns) {
// clang-format off
patterns->insert<BroadcastConverter<lmhlo::BroadcastOp>,
ConstConverter,
ConvToLinalgConverter,
IotaConverter<lmhlo::IotaOp>,
LhloBroadcastInDimConverter,
PointwiseToLinalgConverter<lmhlo::AbsOp>,
PointwiseToLinalgConverter<lmhlo::AddOp>,
PointwiseToLinalgConverter<lmhlo::AndOp>,
PointwiseToLinalgConverter<lmhlo::Atan2Op>,
PointwiseToLinalgConverter<lmhlo::CeilOp>,
PointwiseToLinalgConverter<lmhlo::CompareOp>,
PointwiseToLinalgConverter<lmhlo::ComplexOp>,
PointwiseToLinalgConverter<lmhlo::ConvertOp>,
// TODO(ataei): Remove this pattern, CopyOp is folded away.
PointwiseToLinalgConverter<lmhlo::CopyOp>,
PointwiseToLinalgConverter<lmhlo::CosOp>,
PointwiseToLinalgConverter<lmhlo::DivOp>,
PointwiseToLinalgConverter<lmhlo::ExpOp>,
PointwiseToLinalgConverter<lmhlo::FloorOp>,
PointwiseToLinalgConverter<lmhlo::ImagOp>,
PointwiseToLinalgConverter<lmhlo::LogOp>,
PointwiseToLinalgConverter<lmhlo::MaxOp>,
PointwiseToLinalgConverter<lmhlo::MinOp>,
PointwiseToLinalgConverter<lmhlo::MulOp>,
PointwiseToLinalgConverter<lmhlo::NegOp>,
PointwiseToLinalgConverter<lmhlo::NotOp>,
PointwiseToLinalgConverter<lmhlo::RealOp>,
PointwiseToLinalgConverter<lmhlo::RemOp>,
PointwiseToLinalgConverter<lmhlo::RsqrtOp>,
PointwiseToLinalgConverter<lmhlo::SelectOp>,
PointwiseToLinalgConverter<lmhlo::SignOp>,
PointwiseToLinalgConverter<lmhlo::SinOp>,
PointwiseToLinalgConverter<lmhlo::SqrtOp>,
PointwiseToLinalgConverter<lmhlo::SubOp>,
PointwiseToLinalgConverter<lmhlo::TanhOp>,
PointwiseToLinalgConverter<lmhlo::IsFiniteOp>,
ReshapeOpConverter<lmhlo::ReshapeOp>,
ReverseConverter<lmhlo::ReverseOp>,
ScalarPointwiseToStandardConverter<lmhlo::AddOp>,
SliceConverter,
TransposeConverter<lmhlo::TransposeOp>
>(context);
// clang-format on
}
// Converts LHLO ops to Linalg generic.
// Sample result for lmhlo::AddOp.
//
// "lmhlo.add"(%arg1, %arg2, %out) :
// (memref<2x2xf32>, memref<2x2xf32>, memref<2x2xf32>) -> ()
//
// will be converted to
//
// #map0 = (d0, d1) -> (d0, d1)
// "linalg.generic"(%arg1, %arg2, %out) ( {
// ^bb0(%arg4: f32, %arg5: f32):
// %0 = addf %arg4, %arg5 : f32
// "linalg.yield"(%0) : (f32) -> ()
// }) {
// indexing_maps = [#map0, #map0, #map0],
// iterator_types = ["parallel", "parallel"],
// } : (memref<2x2xf32>, memref<2x2xf32>, memref<2x2xf32>) -> ()
struct LhloLegalizeToLinalgPass
: public PassWrapper<LhloLegalizeToLinalgPass, FunctionPass> {
void getDependentDialects(DialectRegistry& registry) const override {
registry.insert<AffineDialect, linalg::LinalgDialect>();
}
void runOnFunction() override {
OwningRewritePatternList patterns;
ConversionTarget target(getContext());
target.addLegalDialect<linalg::LinalgDialect, StandardOpsDialect,
AffineDialect>();
auto func = getFunction();
populateLHLOToLinalgConversionPattern(func.getContext(), &patterns);
if (failed(applyPartialConversion(func, target, std::move(patterns)))) {
signalPassFailure();
}
}
};
struct HloLegalizeToLinalgPass
: public PassWrapper<HloLegalizeToLinalgPass, FunctionPass> {
void getDependentDialects(DialectRegistry& registry) const override {
registry.insert<linalg::LinalgDialect>();
}
void runOnFunction() override {
OwningRewritePatternList patterns;
ConversionTarget target(getContext());
target.addLegalDialect<linalg::LinalgDialect, StandardOpsDialect>();
auto func = getFunction();
mhlo::populateHLOToLinalgConversionPattern(func.getContext(), &patterns);
if (failed(applyPartialConversion(func, target, std::move(patterns)))) {
signalPassFailure();
}
}
};
} // namespace
namespace lmhlo {
std::unique_ptr<OperationPass<FuncOp>> createLegalizeLhloToLinalgPass() {
return std::make_unique<LhloLegalizeToLinalgPass>();
}
} // namespace lmhlo
namespace mhlo {
void populateHLOToLinalgConversionPattern(MLIRContext* context,
OwningRewritePatternList* patterns) {
patterns
->insert<BroadcastConverter<mhlo::BroadcastOp, false>,
HloBroadcastInDimConverter, IotaConverter<mhlo::IotaOp, false>,
PointwiseToLinalgConverter<mhlo::AbsOp, false>,
PointwiseToLinalgConverter<mhlo::AddOp, false>,
PointwiseToLinalgConverter<mhlo::AndOp, false>,
PointwiseToLinalgConverter<mhlo::Atan2Op, false>,
PointwiseToLinalgConverter<mhlo::CeilOp, false>,
PointwiseToLinalgConverter<mhlo::CompareOp, false>,
PointwiseToLinalgConverter<mhlo::ComplexOp, false>,
PointwiseToLinalgConverter<mhlo::ConvertOp, false>,
PointwiseToLinalgConverter<mhlo::CopyOp, false>,
PointwiseToLinalgConverter<mhlo::CosOp, false>,
PointwiseToLinalgConverter<mhlo::DivOp, false>,
PointwiseToLinalgConverter<mhlo::ExpOp, false>,
PointwiseToLinalgConverter<mhlo::FloorOp, false>,
PointwiseToLinalgConverter<mhlo::ImagOp, false>,
PointwiseToLinalgConverter<mhlo::LogOp, false>,
PointwiseToLinalgConverter<mhlo::MaxOp, false>,
PointwiseToLinalgConverter<mhlo::MinOp, false>,
PointwiseToLinalgConverter<mhlo::MulOp, false>,
PointwiseToLinalgConverter<mhlo::NegOp, false>,
PointwiseToLinalgConverter<mhlo::NotOp, false>,
PointwiseToLinalgConverter<mhlo::RealOp, false>,
PointwiseToLinalgConverter<mhlo::RemOp, false>,
PointwiseToLinalgConverter<mhlo::RsqrtOp, false>,
PointwiseToLinalgConverter<mhlo::SelectOp, false>,
PointwiseToLinalgConverter<mhlo::SinOp, false>,
PointwiseToLinalgConverter<mhlo::SqrtOp, false>,
PointwiseToLinalgConverter<mhlo::SubOp, false>,
PointwiseToLinalgConverter<mhlo::TanhOp, false>,
PointwiseToLinalgConverter<mhlo::IsFiniteOp, false>,
ReshapeOpConverter<mhlo::ReshapeOp, false>,
ReverseConverter<mhlo::ReverseOp, false>,
TransposeConverter<mhlo::TransposeOp, false>>(context);
}
std::unique_ptr<OperationPass<FuncOp>> createLegalizeHloToLinalgPass() {
return std::make_unique<HloLegalizeToLinalgPass>();
}
} // namespace mhlo
} // namespace mlir
| apache-2.0 |
sinlov/JavaFactory | TestForm/src/main/java/com/sinlov/my/test/collection/datestringset/DescendingDateString.java | 686 | package com.sinlov.my.test.collection.datestringset;
import java.util.Comparator;
/**
* <pre>
* sinlov
*
* /\__/\
* /` '\
* ≈≈≈ 0 0 ≈≈≈ Hello world!
* \ -- /
* / \
* / \
* | |
* \ || || /
* \_oo__oo_/≡≡≡≡≡≡≡≡o
*
* </pre>
* Created by sinlov on 17/12/27.
*/
public class DescendingDateString<D extends DateLineString> implements Comparator<D> {
@Override
public int compare(D o1, D o2) {
int res = -(o1.getTime().compareTo(o2.getTime()));
if (res == 0) {
res = -(o1.getContent().compareTo(o2.getContent()));
}
return res;
}
}
| apache-2.0 |
Datenheld/Bulldog | bulldog.board.raspberrypi/src/main/java/org/bulldog/raspberrypi/gpio/PwmFrequencyCalculator.java | 875 | package org.bulldog.raspberrypi.gpio;
public class PwmFrequencyCalculator {
private static final double CLOCK_FREQUENCY = 19200000.0;
public static int calculateDivisorRegister(double targetFrequency) {
int minDivF = 1024;
int currentDivreg = 0;
for (int i = 1; i < 4096; i++) {
boolean error = false;
double frequency = targetFrequency * i;
double divisor = CLOCK_FREQUENCY / frequency;
int DIVI = (int) Math.floor(divisor);
int DIVF = (int) Math.floor((divisor - DIVI) * 1024);
int divreg = (0x5a << 24) | ((int) DIVI << 12) | (DIVF);
if (Double.isNaN(DIVF) || Double.isInfinite(DIVI) || DIVI < 1 || DIVI > 4095) {
error = true;
}
if(DIVF < minDivF && error == false) {
currentDivreg = divreg;
minDivF = DIVF;
}
if (DIVF == 0 && error == false) {
return divreg;
}
}
return currentDivreg;
}
}
| apache-2.0 |
firejack-open/Firejack-Platform | platform/src/main/webapp/js/net/firejack/platform/console/documentation/manager/DocumentationTreePanel.js | 6653 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
Ext.define('OPF.console.documentation.manager.DocumentationTreePanel', {
extend: 'Ext.tree.Panel',
alias: 'widget.documentation-tree',
width: 200,
autoHeight: true,
useArrows: true,
autoScroll: true,
animate: true,
collapsible: false,
split: true,
rootVisible: false,
border: false,
isFirstLoad: true,
/**
*
*/
initComponent: function() {
var me = this;
this.initializeChildNodes = function(model) {
if (isEmpty(model.childNodes) || (model.childNodes.length == 0)) {
var children = model.get('children');
if (isNotEmpty(children) && Ext.isArray(children)) {
var i, nodes = [];
for (i = 0; i < children.length; i++) {
var childModel = Ext.create('OPF.core.model.RegistryNodeTreeModel', children[i]);
var node = Ext.data.NodeInterface.decorate(childModel);
nodes.push(node);
}
model.appendChild(nodes);
}
}
if (isNotEmpty(model.childNodes)) {
for (i = 0; i < model.childNodes.length; i++) {
this.initializeChildNodes(model.childNodes[i]);
}
}
};
this.store = Ext.create('Ext.data.TreeStore', {
model: 'OPF.core.model.RegistryNodeTreeModel',
proxy: {
type: 'ajax',
url: this.getLoadNodeUrl(0),
reader: {
type: 'json',
root: 'data'
}
},
root: {
text: 'root',
id: OPF.core.utils.RegistryNodeType.REGISTRY.generateId(0),
rendered: false,
expanded: true,
normalizedName: 'root'
},
folderSort: true,
sorters: this.SORTER,
clearOnLoad: false,
listeners: {
beforeload: function(store, operation, eOpts) {
var nodeId = SqGetIdFromTreeEntityId(operation.node.get('id'));
if (isEmpty(nodeId)) {
nodeId = 0;
}
store.proxy.url = me.getLoadNodeUrl(nodeId);
},
load: function(store, node, models, successful, eOpts ) {
if (me.isFirstLoad) {
me.isFirstLoad = false;
if (isNotEmpty(models) && Ext.isArray(models)) {
for (var i = 0; i < models.length; i++) {
me.initializeChildNodes(models[i]);
}
}
var type = OPF.core.utils.RegistryNodeType.findRegistryNodeByType(OPF.DCfg.REGISTRY_NODE_TYPE);
var nodeId = type.generateId(OPF.DCfg.REGISTRY_NODE_ID);
me.selectedNode = store.getNodeById(nodeId);
if (isNotEmpty(me.selectedNode)) {
try {
me.selectedNode.bubble(function(node){
node.expand();
});
var selectedNodeLookup = me.selectedNode.get('lookup');
var pathParts = selectedNodeLookup.split('.');
var selectPath = '.root.';
if (pathParts.length > 1) {
selectPath += pathParts[0];
selectPath += pathParts[1];
for (var j = 2; j < pathParts.length; j++) {
selectPath += '.';
selectPath += pathParts[j];
}
}
me.selectPath(selectPath, 'normalizedName', '.');
} catch(e){
Ext.Msg.alert('Error', e);
}
}
// me.managerLayout.openEditor(editEntity, me.selectedNode);
}
},
append: function(node, newChildNode, index, eOpts) {
if (!newChildNode.isRoot()) {
var normalizedName;
if (newChildNode.get('type') == 'ROOT_DOMAIN') {
normalizedName = newChildNode.get('lookup').replace(/\./g, '');
} else {
var lookup = newChildNode.get('lookup');
normalizedName = lookup.substring(lookup.lastIndexOf('.') + 1);
}
newChildNode.set('normalizedName', normalizedName);
var href = newChildNode.get('lookup').replace(/\./g, '/');
newChildNode.set('href', OPF.DCfg.DOC_URL + '/' + OPF.DCfg.COUNTRY + '/' + href);
}
}
}
});
this.callParent(arguments);
},
listeners: {
itemclick: function(tree, record) {
document.location = record.get('href');
}
},
getLoadNodeUrl: function(nodeId) {
var url = OPF.core.utils.RegistryNodeType.REGISTRY.generateUrl('/children/' + nodeId + '?pageType=' + OPF.Cfg.PAGE_TYPE);
if (this.isFirstLoad) {
url = OPF.core.utils.RegistryNodeType.REGISTRY.generateUrl('/children/expanded-by-id/' + OPF.DCfg.REGISTRY_NODE_ID + '?pageType=' + OPF.Cfg.PAGE_TYPE);
}
return url;
}
}); | apache-2.0 |
shiver-me-timbers/smt-retrying-parent | smt-retrying-test/smt-retrying-aspect-integration/smt-retrying-aspect-test-executions/src/main/java/shiver/me/timbers/retrying/factory/MapLookupFactory.java | 1430 | /*
* Copyright 2016 Karl Bennett
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package shiver.me.timbers.retrying.factory;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static java.util.Arrays.asList;
public class MapLookupFactory<T> implements LookupFactory<T> {
private final Map<Object, T> map;
public MapLookupFactory() {
this(new ConcurrentHashMap<Object, T>());
}
public MapLookupFactory(Map<Object, T> map) {
this.map = map;
}
@Override
public T find(Object... args) {
final T result = map.get(asList(args));
if (result != null) {
return result;
}
throw new IllegalArgumentException("No object found for args " + Arrays.toString(args));
}
@Override
public void add(T object, Object... args) {
map.put(asList(args), object);
}
}
| apache-2.0 |
Snadde/infotainment | apps/headunit/src/se/chalmers/pd/headunit/Action.java | 757 | package se.chalmers.pd.headunit;
/**
* This class contains the available actions that can be performed and sent
* by the application. They are;
*
* <b>action</b>
* Not a specific action itself. Used to populate the action key.
*
* <b>exists</b>
* Used when a device asks the head unit if an application is
* installed or not.
*
* <b>install</b>
* Used when a device wants to install an application.
*
* <b>uninstall</b>
* Used when a device wants to uninstall an application.
*
* <b>start</b>
* Used to start the hosted web application.
*
* <b>stop</b>
* Used to stop the hosted web application.
*
* <b>NONE</b>
* Not used.
*/
public enum Action {
action,
exist,
install,
uninstall,
start,
stop,
NONE
}
| apache-2.0 |
marek-kulon/hangman-game | src/test/java/hangman/util/AccessMonitorExecuteTimeoutTest.java | 3524 | package hangman.util;
import edu.umd.cs.mtc.MultithreadedTestCase;
import edu.umd.cs.mtc.TestFramework;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeoutException;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* Test {@link AccessMonitor#execute(java.lang.Object, java.util.function.Supplier)} blocks access for the same key
* and throws {@link TimeoutException} on entering monitor
* Scenario:
* - thread 1 enters monitor and executes long-running job (where job time > monitor acquiring timeout),
* - thread 2 tries to enter monitor and execute its job
* Expected results:
* - thread 1 executes fine
* - thread 2 receives {@link TimeoutException}
*
* Instead of {@link Thread#sleep(long)} or {@link java.util.concurrent.CountDownLatch} implementation uses MultithreadedTC for ordering threads
*/
public class AccessMonitorExecuteTimeoutTest extends MultithreadedTestCase {
private static final Logger log = LoggerFactory.getLogger(AccessMonitorExecuteTimeoutTest.class);
private static final String KEY = "key";
private static final int MONITOR_TIME = 100;
private AccessMonitor<String, String> monitor;
@Override
public void initialize() {
monitor = new AccessMonitor<>(1, MONITOR_TIME, MILLISECONDS);
}
/**
* thread 1 successfully enters monitor and executes its job
*/
public void thread1() {
waitForTick(1);
String res = "NOK";
try {
log.info("thread 1 about to enter monitor");
res = monitor.execute(KEY, () -> {
log.info("thread 1 entered the monitor");
waitForTick(3);
freezeClock(); // disable clock thread -> make sure thread 1 isn't captured
trySleep(500);
unfreezeClock();
log.info("thread 1 about to exit the monitor");
return "OK";
});
} catch (InterruptedException e) {
fail("IE occurred");
} catch (TimeoutException e) {
fail("TE occurred");
}
assertEquals("OK", res);
log.info("thread 1 finished");
}
/**
* thread 2 can't enter monitor and times out
*/
public void thread2() {
final long start = System.currentTimeMillis();
try {
waitForTick(2);
log.info("thread 2 about to enter monitor");
monitor.execute(KEY, () -> {
log.error("thread 2 entered the monitor");
fail();
return null;
});
} catch (InterruptedException e) {
fail("IE occurred");
} catch (TimeoutException e) {
long acquiringTime = System.currentTimeMillis() - start;
log.info("thread 2 timeout occurred, acquiring time: {}", acquiringTime);
assertTrue("Monitor tried to acquire lock for minimum provided time", acquiringTime >= MONITOR_TIME);
log.info("thread 2 finished");
return;
}
fail();
}
@Test // no need for timeout here - framework provides it
public void executeThrowsMonitorExceptionTest() throws Throwable {
TestFramework.runOnce(new AccessMonitorExecuteTimeoutTest());
}
private void trySleep(int timeInMills) {
try {
MILLISECONDS.sleep(timeInMills);
} catch (InterruptedException e) {
fail("IE occurred");
}
}
}
| apache-2.0 |
imAArtist/simIr | Data/singleFile/code_85.cpp | 510 | int hIndex(vector<int>& citations) {
if (citations.empty())
return 0;
vector<int> count(citations.size()+1, 0); // record 0-size
for (int i = 0; i < citations.size(); ++i)
{
count[citations[i] < count.size() ? citations[i] : count.size() - 1]++;
}
int sum = 0;
for (int j = count.size() - 1; j >= 0; --j)
{
sum += count[j];
if (j <= sum)
return j;
}
return 0;
}
| artistic-2.0 |
midniteio/npm | lib/run-script.js | 5399 | module.exports = runScript
var lifecycle = require('./utils/lifecycle.js')
var npm = require('./npm.js')
var path = require('path')
var readJson = require('read-package-json')
var log = require('npmlog')
var chain = require('slide').chain
runScript.usage = 'npm run-script <command> [-- <args>...]' +
'\n\nalias: npm run'
runScript.completion = function (opts, cb) {
// see if there's already a package specified.
var argv = opts.conf.argv.remain
if (argv.length >= 4) return cb()
if (argv.length === 3) {
// either specified a script locally, in which case, done,
// or a package, in which case, complete against its scripts
var json = path.join(npm.localPrefix, 'package.json')
return readJson(json, function (er, d) {
if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
if (er) d = {}
var scripts = Object.keys(d.scripts || {})
console.error('local scripts', scripts)
if (scripts.indexOf(argv[2]) !== -1) return cb()
// ok, try to find out which package it was, then
var pref = npm.config.get('global') ? npm.config.get('prefix')
: npm.localPrefix
var pkgDir = path.resolve(pref, 'node_modules', argv[2], 'package.json')
readJson(pkgDir, function (er, d) {
if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
if (er) d = {}
var scripts = Object.keys(d.scripts || {})
return cb(null, scripts)
})
})
}
readJson(path.join(npm.localPrefix, 'package.json'), function (er, d) {
if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
d = d || {}
cb(null, Object.keys(d.scripts || {}))
})
}
function runScript (args, cb) {
if (!args.length) return list(cb)
var pkgdir = npm.localPrefix
var cmd = args.shift()
readJson(path.resolve(pkgdir, 'package.json'), function (er, d) {
if (er) return cb(er)
run(d, pkgdir, cmd, args, cb)
})
}
function list (cb) {
var json = path.join(npm.localPrefix, 'package.json')
var cmdList = [
'publish',
'install',
'uninstall',
'test',
'stop',
'start',
'restart',
'version'
].reduce(function (l, p) {
return l.concat(['pre' + p, p, 'post' + p])
}, [])
return readJson(json, function (er, d) {
if (er && er.code !== 'ENOENT' && er.code !== 'ENOTDIR') return cb(er)
if (er) d = {}
var allScripts = Object.keys(d.scripts || {})
var scripts = []
var runScripts = []
allScripts.forEach(function (script) {
if (cmdList.indexOf(script) !== -1) scripts.push(script)
else runScripts.push(script)
})
if (log.level === 'silent') {
return cb(null, allScripts)
}
if (npm.config.get('json')) {
console.log(JSON.stringify(d.scripts || {}, null, 2))
return cb(null, allScripts)
}
if (npm.config.get('parseable')) {
allScripts.forEach(function (script) {
console.log(script + ':' + d.scripts[script])
})
return cb(null, allScripts)
}
var s = '\n '
var prefix = ' '
if (scripts.length) {
console.log('Lifecycle scripts included in %s:', d.name)
}
scripts.forEach(function (script) {
console.log(prefix + script + s + d.scripts[script])
})
if (!scripts.length && runScripts.length) {
console.log('Scripts available in %s via `npm run-script`:', d.name)
} else if (runScripts.length) {
console.log('\navailable via `npm run-script`:')
}
runScripts.forEach(function (script) {
console.log(prefix + script + s + d.scripts[script])
})
return cb(null, allScripts)
})
}
function run (pkg, wd, cmd, args, cb) {
if (!pkg.scripts) pkg.scripts = {}
var cmds
if (cmd === 'restart' && !pkg.scripts.restart) {
cmds = [
'prestop', 'stop', 'poststop',
'restart',
'prestart', 'start', 'poststart'
]
} else {
if (!pkg.scripts[cmd]) {
if (cmd === 'test') {
pkg.scripts.test = 'echo \'Error: no test specified\''
} else if (cmd === 'env') {
if (process.platform === 'win32') {
log.verbose('run-script using default platform env: SET (Windows)')
pkg.scripts[cmd] = 'SET'
} else {
log.verbose('run-script using default platform env: env (Unix)')
pkg.scripts[cmd] = 'env'
}
} else if (npm.config.get('if-present')) {
return cb(null)
} else {
return cb(new Error('missing script: ' + cmd))
}
}
cmds = [cmd]
}
if (!cmd.match(/^(pre|post)/)) {
cmds = ['pre' + cmd].concat(cmds).concat('post' + cmd)
}
log.verbose('run-script', cmds)
chain(cmds.map(function (c) {
// pass cli arguments after -- to script.
if (pkg.scripts[c] && c === cmd) {
pkg.scripts[c] = pkg.scripts[c] + joinArgs(args)
}
// when running scripts explicitly, assume that they're trusted.
return [lifecycle, pkg, c, wd, true]
}), cb)
}
// join arguments after '--' and pass them to script,
// handle special characters such as ', ", ' '.
// if arg ends in trailing backlash, ensure it is escaped
function joinArgs (args) {
var joinedArgs = ''
args.forEach(function (arg) {
if (arg.slice(-1) === '\\' && arg.slice(-2) !== '\\') {
arg += '\\'
}
joinedArgs += ' "' + arg.replace(/"/g, '\\"') + '"'
})
return joinedArgs
}
| artistic-2.0 |
muggy8/Music-Matrix-Composer | mmc/services/getPublicSongById.php | 1276 | <?php
//$uName = addcslashes($_POST["name"], "W");
//$sessionID = addcslashes($_POST["sessionID"], "W");
$DBID = addcslashes($_POST["inDBSongID"], "W");
$returnStuff = "{";
include "../../configs/sqlConnect.php";
/*$sql="select username, userID, sessionID from users where username = '$uName' and sessionID = '$sessionID'";
$results = mysqli_query($conn, $sql);
$rowCount = mysqli_num_rows($results);
if ($rowCount === 1){
$userID=-1;
$row=mysqli_fetch_row($results);
$userID = $row[1];
*/
$sql="select name, songID, public, nps, duration from songs where public = 1 and songID = $DBID";
$results = mysqli_query($conn, $sql);
$count = 0;
while($row = mysqli_fetch_assoc($results)) {
if ($count > 0){
$returnStuff = $returnStuff . ", ";
}
$returnStuff = $returnStuff . "\"song$count\" : {\"songName\": \"" . $row["name"] . "\" , \"songID\": " . $row["songID"] . " , \"public\": " . $row["public"] . ", \"nps\":" . $row["nps"] . ", \"length\":" . $row["duration"] . "}";
$count = $count +1;
}
//}
$returnStuff = $returnStuff . "}";
echo $returnStuff;
$conn->close();
?> | artistic-2.0 |
douhao4648/Test | src/concurrency/chapter7_customization/recipe3_thread_factory/task/MyTask.java | 507 | package concurrency.chapter7_customization.recipe3_thread_factory.task;
import java.util.concurrent.TimeUnit;
/**
* Task to be executed in the MyThread threads
*/
public class MyTask implements Runnable {
/**
* Main method of the Thread. Sleeps the thread during two seconds
*/
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| artistic-2.0 |
toulezu/play | Dubbo/testConsumer/src/test/java/com/test/service/consumer/AppTest.java | 653 | package com.test.service.consumer;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| artistic-2.0 |
Xparcel/Xparcel-Project | php/gplus_lib/vendor/google/apiclient/src/Google/Service/Classroom.php | 52961 | <?php
/*
* 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.
*/
/**
* Service definition for Classroom (v1).
*
* <p>
* Google Classroom API</p>
*
* <p>
* For more information about this service, see the API
* <a href="https://developers.google.com/classroom/" target="_blank">Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class Google_Service_Classroom extends Google_Service
{
/** Manage your Google Classroom classes. */
const CLASSROOM_COURSES =
"https://www.googleapis.com/auth/classroom.courses";
/** View your Google Classroom classes. */
const CLASSROOM_COURSES_READONLY =
"https://www.googleapis.com/auth/classroom.courses.readonly";
/** View the email addresses of people in your classes. */
const CLASSROOM_PROFILE_EMAILS =
"https://www.googleapis.com/auth/classroom.profile.emails";
/** View the profile photos of people in your classes. */
const CLASSROOM_PROFILE_PHOTOS =
"https://www.googleapis.com/auth/classroom.profile.photos";
/** Manage your Google Classroom class rosters. */
const CLASSROOM_ROSTERS =
"https://www.googleapis.com/auth/classroom.rosters";
/** View your Google Classroom class rosters. */
const CLASSROOM_ROSTERS_READONLY =
"https://www.googleapis.com/auth/classroom.rosters.readonly";
public $courses;
public $courses_aliases;
public $courses_students;
public $courses_teachers;
public $invitations;
public $userProfiles;
/**
* Constructs the internal representation of the Classroom service.
*
* @param Google_Client $client
*/
public function __construct(Google_Client $client)
{
parent::__construct($client);
$this->rootUrl = 'https://classroom.googleapis.com/';
$this->servicePath = '';
$this->version = 'v1';
$this->serviceName = 'classroom';
$this->courses = new Google_Service_Classroom_Courses_Resource(
$this,
$this->serviceName,
'courses',
array(
'methods' => array(
'create' => array(
'path' => 'v1/courses',
'httpMethod' => 'POST',
'parameters' => array(),
),'delete' => array(
'path' => 'v1/courses/{id}',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'get' => array(
'path' => 'v1/courses/{id}',
'httpMethod' => 'GET',
'parameters' => array(
'id' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'list' => array(
'path' => 'v1/courses',
'httpMethod' => 'GET',
'parameters' => array(
'studentId' => array(
'location' => 'query',
'type' => 'string',
),
'teacherId' => array(
'location' => 'query',
'type' => 'string',
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),'patch' => array(
'path' => 'v1/courses/{id}',
'httpMethod' => 'PATCH',
'parameters' => array(
'id' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'updateMask' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'v1/courses/{id}',
'httpMethod' => 'PUT',
'parameters' => array(
'id' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),
)
)
);
$this->courses_aliases = new Google_Service_Classroom_CoursesAliases_Resource(
$this,
$this->serviceName,
'aliases',
array(
'methods' => array(
'create' => array(
'path' => 'v1/courses/{courseId}/aliases',
'httpMethod' => 'POST',
'parameters' => array(
'courseId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'delete' => array(
'path' => 'v1/courses/{courseId}/aliases/{alias}',
'httpMethod' => 'DELETE',
'parameters' => array(
'courseId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'alias' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'list' => array(
'path' => 'v1/courses/{courseId}/aliases',
'httpMethod' => 'GET',
'parameters' => array(
'courseId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->courses_students = new Google_Service_Classroom_CoursesStudents_Resource(
$this,
$this->serviceName,
'students',
array(
'methods' => array(
'create' => array(
'path' => 'v1/courses/{courseId}/students',
'httpMethod' => 'POST',
'parameters' => array(
'courseId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'enrollmentCode' => array(
'location' => 'query',
'type' => 'string',
),
),
),'delete' => array(
'path' => 'v1/courses/{courseId}/students/{userId}',
'httpMethod' => 'DELETE',
'parameters' => array(
'courseId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'userId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'get' => array(
'path' => 'v1/courses/{courseId}/students/{userId}',
'httpMethod' => 'GET',
'parameters' => array(
'courseId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'userId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'list' => array(
'path' => 'v1/courses/{courseId}/students',
'httpMethod' => 'GET',
'parameters' => array(
'courseId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->courses_teachers = new Google_Service_Classroom_CoursesTeachers_Resource(
$this,
$this->serviceName,
'teachers',
array(
'methods' => array(
'create' => array(
'path' => 'v1/courses/{courseId}/teachers',
'httpMethod' => 'POST',
'parameters' => array(
'courseId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'delete' => array(
'path' => 'v1/courses/{courseId}/teachers/{userId}',
'httpMethod' => 'DELETE',
'parameters' => array(
'courseId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'userId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'get' => array(
'path' => 'v1/courses/{courseId}/teachers/{userId}',
'httpMethod' => 'GET',
'parameters' => array(
'courseId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'userId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'list' => array(
'path' => 'v1/courses/{courseId}/teachers',
'httpMethod' => 'GET',
'parameters' => array(
'courseId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->invitations = new Google_Service_Classroom_Invitations_Resource(
$this,
$this->serviceName,
'invitations',
array(
'methods' => array(
'accept' => array(
'path' => 'v1/invitations/{id}:accept',
'httpMethod' => 'POST',
'parameters' => array(
'id' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'create' => array(
'path' => 'v1/invitations',
'httpMethod' => 'POST',
'parameters' => array(),
),'delete' => array(
'path' => 'v1/invitations/{id}',
'httpMethod' => 'DELETE',
'parameters' => array(
'id' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'get' => array(
'path' => 'v1/invitations/{id}',
'httpMethod' => 'GET',
'parameters' => array(
'id' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'list' => array(
'path' => 'v1/invitations',
'httpMethod' => 'GET',
'parameters' => array(
'userId' => array(
'location' => 'query',
'type' => 'string',
),
'courseId' => array(
'location' => 'query',
'type' => 'string',
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->userProfiles = new Google_Service_Classroom_UserProfiles_Resource(
$this,
$this->serviceName,
'userProfiles',
array(
'methods' => array(
'get' => array(
'path' => 'v1/userProfiles/{userId}',
'httpMethod' => 'GET',
'parameters' => array(
'userId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),
)
)
);
}
}
/**
* The "courses" collection of methods.
* Typical usage is:
* <code>
* $classroomService = new Google_Service_Classroom(...);
* $courses = $classroomService->courses;
* </code>
*/
class Google_Service_Classroom_Courses_Resource extends Google_Service_Resource
{
/**
* Creates a course. The user specified in `ownerId` is the owner of the created
* course and added as a teacher. This method returns the following error codes:
* * `PERMISSION_DENIED` if the requesting user is not permitted to create
* courses or for access errors. * `NOT_FOUND` if the primary teacher is not a
* valid user. * `FAILED_PRECONDITION` if the course owner's account is disabled
* or for the following request errors: * UserGroupsMembershipLimitReached *
* `ALREADY_EXISTS` if an alias was specified in the `id` and already exists.
* (courses.create)
*
* @param Google_Course $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_Course
*/
public function create(Google_Service_Classroom_Course $postBody, $optParams = array())
{
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "Google_Service_Classroom_Course");
}
/**
* Deletes a course. This method returns the following error codes: *
* `PERMISSION_DENIED` if the requesting user is not permitted to delete the
* requested course or for access errors. * `NOT_FOUND` if no course exists with
* the requested ID. (courses.delete)
*
* @param string $id Identifier of the course to delete. This identifier can be
* either the Classroom-assigned identifier or an alias.
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_Empty
*/
public function delete($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params), "Google_Service_Classroom_Empty");
}
/**
* Returns a course. This method returns the following error codes: *
* `PERMISSION_DENIED` if the requesting user is not permitted to access the
* requested course or for access errors. * `NOT_FOUND` if no course exists with
* the requested ID. (courses.get)
*
* @param string $id Identifier of the course to return. This identifier can be
* either the Classroom-assigned identifier or an alias.
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_Course
*/
public function get($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Classroom_Course");
}
/**
* Returns a list of courses that the requesting user is permitted to view,
* restricted to those that match the request. This method returns the following
* error codes: * `PERMISSION_DENIED` for access errors. * `INVALID_ARGUMENT` if
* the query argument is malformed. * `NOT_FOUND` if any users specified in the
* query arguments do not exist. (courses.listCourses)
*
* @param array $optParams Optional parameters.
*
* @opt_param string studentId Restricts returned courses to those having a
* student with the specified identifier. The identifier can be one of the
* following: * the numeric identifier for the user * the email address of the
* user * the string literal `"me"`, indicating the requesting user
* @opt_param string teacherId Restricts returned courses to those having a
* teacher with the specified identifier. The identifier can be one of the
* following: * the numeric identifier for the user * the email address of the
* user * the string literal `"me"`, indicating the requesting user
* @opt_param int pageSize Maximum number of items to return. Zero or
* unspecified indicates that the server may assign a maximum. The server may
* return fewer than the specified number of results.
* @opt_param string pageToken nextPageToken value returned from a previous list
* call, indicating that the subsequent page of results should be returned. The
* list request must be otherwise identical to the one that resulted in this
* token.
* @return Google_Service_Classroom_ListCoursesResponse
*/
public function listCourses($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_Classroom_ListCoursesResponse");
}
/**
* Updates one or more fields in a course. This method returns the following
* error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to
* modify the requested course or for access errors. * `NOT_FOUND` if no course
* exists with the requested ID. * `INVALID_ARGUMENT` if invalid fields are
* specified in the update mask or if no update mask is supplied. *
* `FAILED_PRECONDITION` for the following request errors: * CourseNotModifiable
* (courses.patch)
*
* @param string $id Identifier of the course to update. This identifier can be
* either the Classroom-assigned identifier or an alias.
* @param Google_Course $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string updateMask Mask that identifies which fields on the course
* to update. This field is required to do an update. The update will fail if
* invalid fields are specified. The following fields are valid: * `name` *
* `section` * `descriptionHeading` * `description` * `room` * `courseState`
* When set in a query parameter, this field should be specified as
* `updateMask=,,...`
* @return Google_Service_Classroom_Course
*/
public function patch($id, Google_Service_Classroom_Course $postBody, $optParams = array())
{
$params = array('id' => $id, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('patch', array($params), "Google_Service_Classroom_Course");
}
/**
* Updates a course. This method returns the following error codes: *
* `PERMISSION_DENIED` if the requesting user is not permitted to modify the
* requested course or for access errors. * `NOT_FOUND` if no course exists with
* the requested ID. * `FAILED_PRECONDITION` for the following request errors: *
* CourseNotModifiable (courses.update)
*
* @param string $id Identifier of the course to update. This identifier can be
* either the Classroom-assigned identifier or an alias.
* @param Google_Course $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_Course
*/
public function update($id, Google_Service_Classroom_Course $postBody, $optParams = array())
{
$params = array('id' => $id, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "Google_Service_Classroom_Course");
}
}
/**
* The "aliases" collection of methods.
* Typical usage is:
* <code>
* $classroomService = new Google_Service_Classroom(...);
* $aliases = $classroomService->aliases;
* </code>
*/
class Google_Service_Classroom_CoursesAliases_Resource extends Google_Service_Resource
{
/**
* Creates an alias for a course. This method returns the following error codes:
* * `PERMISSION_DENIED` if the requesting user is not permitted to create the
* alias or for access errors. * `NOT_FOUND` if the course does not exist. *
* `ALREADY_EXISTS` if the alias already exists. (aliases.create)
*
* @param string $courseId Identifier of the course to alias. This identifier
* can be either the Classroom-assigned identifier or an alias.
* @param Google_CourseAlias $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_CourseAlias
*/
public function create($courseId, Google_Service_Classroom_CourseAlias $postBody, $optParams = array())
{
$params = array('courseId' => $courseId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "Google_Service_Classroom_CourseAlias");
}
/**
* Deletes an alias of a course. This method returns the following error codes:
* * `PERMISSION_DENIED` if the requesting user is not permitted to remove the
* alias or for access errors. * `NOT_FOUND` if the alias does not exist.
* (aliases.delete)
*
* @param string $courseId Identifier of the course whose alias should be
* deleted. This identifier can be either the Classroom-assigned identifier or
* an alias.
* @param string $alias Alias to delete. This may not be the Classroom-assigned
* identifier.
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_Empty
*/
public function delete($courseId, $alias, $optParams = array())
{
$params = array('courseId' => $courseId, 'alias' => $alias);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params), "Google_Service_Classroom_Empty");
}
/**
* Returns a list of aliases for a course. This method returns the following
* error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to
* access the course or for access errors. * `NOT_FOUND` if the course does not
* exist. (aliases.listCoursesAliases)
*
* @param string $courseId The identifier of the course. This identifier can be
* either the Classroom-assigned identifier or an alias.
* @param array $optParams Optional parameters.
*
* @opt_param int pageSize Maximum number of items to return. Zero or
* unspecified indicates that the server may assign a maximum. The server may
* return fewer than the specified number of results.
* @opt_param string pageToken nextPageToken value returned from a previous list
* call, indicating that the subsequent page of results should be returned. The
* list request must be otherwise identical to the one that resulted in this
* token.
* @return Google_Service_Classroom_ListCourseAliasesResponse
*/
public function listCoursesAliases($courseId, $optParams = array())
{
$params = array('courseId' => $courseId);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_Classroom_ListCourseAliasesResponse");
}
}
/**
* The "students" collection of methods.
* Typical usage is:
* <code>
* $classroomService = new Google_Service_Classroom(...);
* $students = $classroomService->students;
* </code>
*/
class Google_Service_Classroom_CoursesStudents_Resource extends Google_Service_Resource
{
/**
* Adds a user as a student of a course. This method returns the following error
* codes: * `PERMISSION_DENIED` if the requesting user is not permitted to
* create students in this course or for access errors. * `NOT_FOUND` if the
* requested course ID does not exist. * `FAILED_PRECONDITION` if the requested
* user's account is disabled, for the following request errors: *
* CourseMemberLimitReached * CourseNotModifiable *
* UserGroupsMembershipLimitReached * `ALREADY_EXISTS` if the user is already a
* student or teacher in the course. (students.create)
*
* @param string $courseId Identifier of the course to create the student in.
* This identifier can be either the Classroom-assigned identifier or an alias.
* @param Google_Student $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string enrollmentCode Enrollment code of the course to create the
* student in. This code is required if userId corresponds to the requesting
* user; it may be omitted if the requesting user has administrative permissions
* to create students for any user.
* @return Google_Service_Classroom_Student
*/
public function create($courseId, Google_Service_Classroom_Student $postBody, $optParams = array())
{
$params = array('courseId' => $courseId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "Google_Service_Classroom_Student");
}
/**
* Deletes a student of a course. This method returns the following error codes:
* * `PERMISSION_DENIED` if the requesting user is not permitted to delete
* students of this course or for access errors. * `NOT_FOUND` if no student of
* this course has the requested ID or if the course does not exist.
* (students.delete)
*
* @param string $courseId Identifier of the course. This identifier can be
* either the Classroom-assigned identifier or an alias.
* @param string $userId Identifier of the student to delete. The identifier can
* be one of the following: * the numeric identifier for the user * the email
* address of the user * the string literal `"me"`, indicating the requesting
* user
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_Empty
*/
public function delete($courseId, $userId, $optParams = array())
{
$params = array('courseId' => $courseId, 'userId' => $userId);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params), "Google_Service_Classroom_Empty");
}
/**
* Returns a student of a course. This method returns the following error codes:
* * `PERMISSION_DENIED` if the requesting user is not permitted to view
* students of this course or for access errors. * `NOT_FOUND` if no student of
* this course has the requested ID or if the course does not exist.
* (students.get)
*
* @param string $courseId Identifier of the course. This identifier can be
* either the Classroom-assigned identifier or an alias.
* @param string $userId Identifier of the student to return. The identifier can
* be one of the following: * the numeric identifier for the user * the email
* address of the user * the string literal `"me"`, indicating the requesting
* user
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_Student
*/
public function get($courseId, $userId, $optParams = array())
{
$params = array('courseId' => $courseId, 'userId' => $userId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Classroom_Student");
}
/**
* Returns a list of students of this course that the requester is permitted to
* view. This method returns the following error codes: * `NOT_FOUND` if the
* course does not exist. * `PERMISSION_DENIED` for access errors.
* (students.listCoursesStudents)
*
* @param string $courseId Identifier of the course. This identifier can be
* either the Classroom-assigned identifier or an alias.
* @param array $optParams Optional parameters.
*
* @opt_param int pageSize Maximum number of items to return. Zero means no
* maximum. The server may return fewer than the specified number of results.
* @opt_param string pageToken nextPageToken value returned from a previous list
* call, indicating that the subsequent page of results should be returned. The
* list request must be otherwise identical to the one that resulted in this
* token.
* @return Google_Service_Classroom_ListStudentsResponse
*/
public function listCoursesStudents($courseId, $optParams = array())
{
$params = array('courseId' => $courseId);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_Classroom_ListStudentsResponse");
}
}
/**
* The "teachers" collection of methods.
* Typical usage is:
* <code>
* $classroomService = new Google_Service_Classroom(...);
* $teachers = $classroomService->teachers;
* </code>
*/
class Google_Service_Classroom_CoursesTeachers_Resource extends Google_Service_Resource
{
/**
* Creates a teacher of a course. This method returns the following error codes:
* * `PERMISSION_DENIED` if the requesting user is not permitted to create
* teachers in this course or for access errors. * `NOT_FOUND` if the requested
* course ID does not exist. * `FAILED_PRECONDITION` if the requested user's
* account is disabled, for the following request errors: *
* CourseMemberLimitReached * CourseNotModifiable * CourseTeacherLimitReached *
* UserGroupsMembershipLimitReached * `ALREADY_EXISTS` if the user is already a
* teacher or student in the course. (teachers.create)
*
* @param string $courseId Identifier of the course. This identifier can be
* either the Classroom-assigned identifier or an alias.
* @param Google_Teacher $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_Teacher
*/
public function create($courseId, Google_Service_Classroom_Teacher $postBody, $optParams = array())
{
$params = array('courseId' => $courseId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "Google_Service_Classroom_Teacher");
}
/**
* Deletes a teacher of a course. This method returns the following error codes:
* * `PERMISSION_DENIED` if the requesting user is not permitted to delete
* teachers of this course or for access errors. * `NOT_FOUND` if no teacher of
* this course has the requested ID or if the course does not exist. *
* `FAILED_PRECONDITION` if the requested ID belongs to the primary teacher of
* this course. (teachers.delete)
*
* @param string $courseId Identifier of the course. This identifier can be
* either the Classroom-assigned identifier or an alias.
* @param string $userId Identifier of the teacher to delete. The identifier can
* be one of the following: * the numeric identifier for the user * the email
* address of the user * the string literal `"me"`, indicating the requesting
* user
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_Empty
*/
public function delete($courseId, $userId, $optParams = array())
{
$params = array('courseId' => $courseId, 'userId' => $userId);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params), "Google_Service_Classroom_Empty");
}
/**
* Returns a teacher of a course. This method returns the following error codes:
* * `PERMISSION_DENIED` if the requesting user is not permitted to view
* teachers of this course or for access errors. * `NOT_FOUND` if no teacher of
* this course has the requested ID or if the course does not exist.
* (teachers.get)
*
* @param string $courseId Identifier of the course. This identifier can be
* either the Classroom-assigned identifier or an alias.
* @param string $userId Identifier of the teacher to return. The identifier can
* be one of the following: * the numeric identifier for the user * the email
* address of the user * the string literal `"me"`, indicating the requesting
* user
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_Teacher
*/
public function get($courseId, $userId, $optParams = array())
{
$params = array('courseId' => $courseId, 'userId' => $userId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Classroom_Teacher");
}
/**
* Returns a list of teachers of this course that the requester is permitted to
* view. This method returns the following error codes: * `NOT_FOUND` if the
* course does not exist. * `PERMISSION_DENIED` for access errors.
* (teachers.listCoursesTeachers)
*
* @param string $courseId Identifier of the course. This identifier can be
* either the Classroom-assigned identifier or an alias.
* @param array $optParams Optional parameters.
*
* @opt_param int pageSize Maximum number of items to return. Zero means no
* maximum. The server may return fewer than the specified number of results.
* @opt_param string pageToken nextPageToken value returned from a previous list
* call, indicating that the subsequent page of results should be returned. The
* list request must be otherwise identical to the one that resulted in this
* token.
* @return Google_Service_Classroom_ListTeachersResponse
*/
public function listCoursesTeachers($courseId, $optParams = array())
{
$params = array('courseId' => $courseId);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_Classroom_ListTeachersResponse");
}
}
/**
* The "invitations" collection of methods.
* Typical usage is:
* <code>
* $classroomService = new Google_Service_Classroom(...);
* $invitations = $classroomService->invitations;
* </code>
*/
class Google_Service_Classroom_Invitations_Resource extends Google_Service_Resource
{
/**
* Accepts an invitation, removing it and adding the invited user to the
* teachers or students (as appropriate) of the specified course. Only the
* invited user may accept an invitation. This method returns the following
* error codes: * `PERMISSION_DENIED` if the requesting user is not permitted to
* accept the requested invitation or for access errors. * `FAILED_PRECONDITION`
* for the following request errors: * CourseMemberLimitReached *
* CourseNotModifiable * CourseTeacherLimitReached *
* UserGroupsMembershipLimitReached * `NOT_FOUND` if no invitation exists with
* the requested ID. (invitations.accept)
*
* @param string $id Identifier of the invitation to accept.
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_Empty
*/
public function accept($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('accept', array($params), "Google_Service_Classroom_Empty");
}
/**
* Creates an invitation. Only one invitation for a user and course may exist at
* a time. Delete and re-create an invitation to make changes. This method
* returns the following error codes: * `PERMISSION_DENIED` if the requesting
* user is not permitted to create invitations for this course or for access
* errors. * `NOT_FOUND` if the course or the user does not exist. *
* `FAILED_PRECONDITION` if the requested user's account is disabled or if the
* user already has this role or a role with greater permissions. *
* `ALREADY_EXISTS` if an invitation for the specified user and course already
* exists. (invitations.create)
*
* @param Google_Invitation $postBody
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_Invitation
*/
public function create(Google_Service_Classroom_Invitation $postBody, $optParams = array())
{
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "Google_Service_Classroom_Invitation");
}
/**
* Deletes an invitation. This method returns the following error codes: *
* `PERMISSION_DENIED` if the requesting user is not permitted to delete the
* requested invitation or for access errors. * `NOT_FOUND` if no invitation
* exists with the requested ID. (invitations.delete)
*
* @param string $id Identifier of the invitation to delete.
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_Empty
*/
public function delete($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params), "Google_Service_Classroom_Empty");
}
/**
* Returns an invitation. This method returns the following error codes: *
* `PERMISSION_DENIED` if the requesting user is not permitted to view the
* requested invitation or for access errors. * `NOT_FOUND` if no invitation
* exists with the requested ID. (invitations.get)
*
* @param string $id Identifier of the invitation to return.
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_Invitation
*/
public function get($id, $optParams = array())
{
$params = array('id' => $id);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Classroom_Invitation");
}
/**
* Returns a list of invitations that the requesting user is permitted to view,
* restricted to those that match the list request. *Note:* At least one of
* `user_id` or `course_id` must be supplied. Both fields can be supplied. This
* method returns the following error codes: * `PERMISSION_DENIED` for access
* errors. (invitations.listInvitations)
*
* @param array $optParams Optional parameters.
*
* @opt_param string userId Restricts returned invitations to those for a
* specific user. The identifier can be one of the following: * the numeric
* identifier for the user * the email address of the user * the string literal
* `"me"`, indicating the requesting user
* @opt_param string courseId Restricts returned invitations to those for a
* course with the specified identifier.
* @opt_param int pageSize Maximum number of items to return. Zero means no
* maximum. The server may return fewer than the specified number of results.
* @opt_param string pageToken nextPageToken value returned from a previous list
* call, indicating that the subsequent page of results should be returned. The
* list request must be otherwise identical to the one that resulted in this
* token.
* @return Google_Service_Classroom_ListInvitationsResponse
*/
public function listInvitations($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_Classroom_ListInvitationsResponse");
}
}
/**
* The "userProfiles" collection of methods.
* Typical usage is:
* <code>
* $classroomService = new Google_Service_Classroom(...);
* $userProfiles = $classroomService->userProfiles;
* </code>
*/
class Google_Service_Classroom_UserProfiles_Resource extends Google_Service_Resource
{
/**
* Returns a user profile. This method returns the following error codes: *
* `PERMISSION_DENIED` if the requesting user is not permitted to access this
* user profile or if no profile exists with the requested ID or for access
* errors. (userProfiles.get)
*
* @param string $userId Identifier of the profile to return. The identifier can
* be one of the following: * the numeric identifier for the user * the email
* address of the user * the string literal `"me"`, indicating the requesting
* user
* @param array $optParams Optional parameters.
* @return Google_Service_Classroom_UserProfile
*/
public function get($userId, $optParams = array())
{
$params = array('userId' => $userId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Classroom_UserProfile");
}
}
class Google_Service_Classroom_Course extends Google_Model
{
protected $internal_gapi_mappings = array(
);
public $alternateLink;
public $courseState;
public $creationTime;
public $description;
public $descriptionHeading;
public $enrollmentCode;
public $id;
public $name;
public $ownerId;
public $room;
public $section;
public $updateTime;
public function setAlternateLink($alternateLink)
{
$this->alternateLink = $alternateLink;
}
public function getAlternateLink()
{
return $this->alternateLink;
}
public function setCourseState($courseState)
{
$this->courseState = $courseState;
}
public function getCourseState()
{
return $this->courseState;
}
public function setCreationTime($creationTime)
{
$this->creationTime = $creationTime;
}
public function getCreationTime()
{
return $this->creationTime;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setDescriptionHeading($descriptionHeading)
{
$this->descriptionHeading = $descriptionHeading;
}
public function getDescriptionHeading()
{
return $this->descriptionHeading;
}
public function setEnrollmentCode($enrollmentCode)
{
$this->enrollmentCode = $enrollmentCode;
}
public function getEnrollmentCode()
{
return $this->enrollmentCode;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setOwnerId($ownerId)
{
$this->ownerId = $ownerId;
}
public function getOwnerId()
{
return $this->ownerId;
}
public function setRoom($room)
{
$this->room = $room;
}
public function getRoom()
{
return $this->room;
}
public function setSection($section)
{
$this->section = $section;
}
public function getSection()
{
return $this->section;
}
public function setUpdateTime($updateTime)
{
$this->updateTime = $updateTime;
}
public function getUpdateTime()
{
return $this->updateTime;
}
}
class Google_Service_Classroom_CourseAlias extends Google_Model
{
protected $internal_gapi_mappings = array(
);
public $alias;
public function setAlias($alias)
{
$this->alias = $alias;
}
public function getAlias()
{
return $this->alias;
}
}
class Google_Service_Classroom_Empty extends Google_Model
{
}
class Google_Service_Classroom_GlobalPermission extends Google_Model
{
protected $internal_gapi_mappings = array(
);
public $permission;
public function setPermission($permission)
{
$this->permission = $permission;
}
public function getPermission()
{
return $this->permission;
}
}
class Google_Service_Classroom_Invitation extends Google_Model
{
protected $internal_gapi_mappings = array(
);
public $courseId;
public $id;
public $role;
public $userId;
public function setCourseId($courseId)
{
$this->courseId = $courseId;
}
public function getCourseId()
{
return $this->courseId;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setRole($role)
{
$this->role = $role;
}
public function getRole()
{
return $this->role;
}
public function setUserId($userId)
{
$this->userId = $userId;
}
public function getUserId()
{
return $this->userId;
}
}
class Google_Service_Classroom_ListCourseAliasesResponse extends Google_Collection
{
protected $collection_key = 'aliases';
protected $internal_gapi_mappings = array(
);
protected $aliasesType = 'Google_Service_Classroom_CourseAlias';
protected $aliasesDataType = 'array';
public $nextPageToken;
public function setAliases($aliases)
{
$this->aliases = $aliases;
}
public function getAliases()
{
return $this->aliases;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
}
class Google_Service_Classroom_ListCoursesResponse extends Google_Collection
{
protected $collection_key = 'courses';
protected $internal_gapi_mappings = array(
);
protected $coursesType = 'Google_Service_Classroom_Course';
protected $coursesDataType = 'array';
public $nextPageToken;
public function setCourses($courses)
{
$this->courses = $courses;
}
public function getCourses()
{
return $this->courses;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
}
class Google_Service_Classroom_ListInvitationsResponse extends Google_Collection
{
protected $collection_key = 'invitations';
protected $internal_gapi_mappings = array(
);
protected $invitationsType = 'Google_Service_Classroom_Invitation';
protected $invitationsDataType = 'array';
public $nextPageToken;
public function setInvitations($invitations)
{
$this->invitations = $invitations;
}
public function getInvitations()
{
return $this->invitations;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
}
class Google_Service_Classroom_ListStudentsResponse extends Google_Collection
{
protected $collection_key = 'students';
protected $internal_gapi_mappings = array(
);
public $nextPageToken;
protected $studentsType = 'Google_Service_Classroom_Student';
protected $studentsDataType = 'array';
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
public function setStudents($students)
{
$this->students = $students;
}
public function getStudents()
{
return $this->students;
}
}
class Google_Service_Classroom_ListTeachersResponse extends Google_Collection
{
protected $collection_key = 'teachers';
protected $internal_gapi_mappings = array(
);
public $nextPageToken;
protected $teachersType = 'Google_Service_Classroom_Teacher';
protected $teachersDataType = 'array';
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
public function setTeachers($teachers)
{
$this->teachers = $teachers;
}
public function getTeachers()
{
return $this->teachers;
}
}
class Google_Service_Classroom_Name extends Google_Model
{
protected $internal_gapi_mappings = array(
);
public $familyName;
public $fullName;
public $givenName;
public function setFamilyName($familyName)
{
$this->familyName = $familyName;
}
public function getFamilyName()
{
return $this->familyName;
}
public function setFullName($fullName)
{
$this->fullName = $fullName;
}
public function getFullName()
{
return $this->fullName;
}
public function setGivenName($givenName)
{
$this->givenName = $givenName;
}
public function getGivenName()
{
return $this->givenName;
}
}
class Google_Service_Classroom_Student extends Google_Model
{
protected $internal_gapi_mappings = array(
);
public $courseId;
protected $profileType = 'Google_Service_Classroom_UserProfile';
protected $profileDataType = '';
public $userId;
public function setCourseId($courseId)
{
$this->courseId = $courseId;
}
public function getCourseId()
{
return $this->courseId;
}
public function setProfile(Google_Service_Classroom_UserProfile $profile)
{
$this->profile = $profile;
}
public function getProfile()
{
return $this->profile;
}
public function setUserId($userId)
{
$this->userId = $userId;
}
public function getUserId()
{
return $this->userId;
}
}
class Google_Service_Classroom_Teacher extends Google_Model
{
protected $internal_gapi_mappings = array(
);
public $courseId;
protected $profileType = 'Google_Service_Classroom_UserProfile';
protected $profileDataType = '';
public $userId;
public function setCourseId($courseId)
{
$this->courseId = $courseId;
}
public function getCourseId()
{
return $this->courseId;
}
public function setProfile(Google_Service_Classroom_UserProfile $profile)
{
$this->profile = $profile;
}
public function getProfile()
{
return $this->profile;
}
public function setUserId($userId)
{
$this->userId = $userId;
}
public function getUserId()
{
return $this->userId;
}
}
class Google_Service_Classroom_UserProfile extends Google_Collection
{
protected $collection_key = 'permissions';
protected $internal_gapi_mappings = array(
);
public $emailAddress;
public $id;
protected $nameType = 'Google_Service_Classroom_Name';
protected $nameDataType = '';
protected $permissionsType = 'Google_Service_Classroom_GlobalPermission';
protected $permissionsDataType = 'array';
public $photoUrl;
public function setEmailAddress($emailAddress)
{
$this->emailAddress = $emailAddress;
}
public function getEmailAddress()
{
return $this->emailAddress;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setName(Google_Service_Classroom_Name $name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setPermissions($permissions)
{
$this->permissions = $permissions;
}
public function getPermissions()
{
return $this->permissions;
}
public function setPhotoUrl($photoUrl)
{
$this->photoUrl = $photoUrl;
}
public function getPhotoUrl()
{
return $this->photoUrl;
}
}
| artistic-2.0 |
douhao4648/Test | src/concurrency/chapter1_thread_manage/recipe7_daemon/core/Main.java | 1118 | package concurrency.chapter1_thread_manage.recipe7_daemon.core;
import concurrency.chapter1_thread_manage.recipe7_daemon.event.Event;
import concurrency.chapter1_thread_manage.recipe7_daemon.task.CleanerTask;
import concurrency.chapter1_thread_manage.recipe7_daemon.task.WriterTask;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* Main class of the example. Creates three WriterTaks and a CleanerTask
*/
public class Main {
/**
* Main method of the example. Creates three WriterTasks and a CleanerTask
*
* @param args
*/
public static void main(String[] args) {
// Creates the Event data structure
Deque<Event> deque = new ArrayDeque<Event>();
// Creates the three WriterTask and starts them
WriterTask writer = new WriterTask(deque);
for (int i = 0; i < 3; i++) {
Thread thread = new Thread(writer);
thread.start();
}
// Creates a cleaner task and starts them
CleanerTask cleaner = new CleanerTask(deque);
cleaner.start();
}
}
| artistic-2.0 |
WildElf/BeginningCSharp | StringManipulation/StringManipulation/Program.cs | 832 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// read in csv string
Console.Write("Enter name and percent (name,percent): ");
string csvString = Console.ReadLine();
// find comma location
int commaLocation = csvString.IndexOf(',');
// extract name and percent
string name = csvString.Substring(0, commaLocation);
float percent = float.Parse(csvString.Substring(commaLocation + 1));
// print name and percent
Console.WriteLine("Name: " + name);
Console.WriteLine("Percent: " + percent + "%");
Console.WriteLine();
}
}
}
| artistic-2.0 |
WizGeek/SafetyHarborRobotics | TurtleBots/Arduino/Development/ArduBlock/ardublock/src/main/java/com/ardublock/translator/block/dfrobot/lcdkeypad.java | 1121 | package com.ardublock.translator.block.dfrobot;
import com.ardublock.translator.Translator;
import com.ardublock.translator.block.TranslatorBlock;
import com.ardublock.translator.block.exception.SocketNullException;
import com.ardublock.translator.block.exception.SubroutineNotDeclaredException;
public class lcdkeypad extends TranslatorBlock {
public lcdkeypad(Long blockId, Translator translator, String codePrefix, String codeSuffix, String label)
{
super(blockId, translator, codePrefix, codeSuffix, label);
}
//@Override
public String toCode() throws SocketNullException, SubroutineNotDeclaredException
{
// recuperation des parametres du module, ici le message place en rang 0
// on ecrit donc le code A generer
TranslatorBlock translatorBlock = this.getRequiredTranslatorBlockAtSocket(0, "lcd.print( ", " );\n");
// creation du texte de code correspondant
translator.addHeaderFile("LiquidCrystal.h");
translator.addDefinitionCommand("LiquidCrystal lcd(12, 11, 5, 4, 3, 2);");
translator.addSetupCommand("lcd.begin(16, 2);");
String ret = translatorBlock.toCode();
return ret;
}
} | artistic-2.0 |
jahidhsn002/PMS | application/models/md_meta.php | 921 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class md_meta extends CI_Model {
public $id;
public $name;
public $value;
public function __construct(){
parent::__construct();
}
public function INFO(){
$query = $this->db->get('meta');
return $query->result();
}
public function ADD($data){
$this->id = $data['id'];
$this->name = $data['name'];
$this->value = $data['value'];
$this->db->insert('meta', $this);
return $this->uid;
}
public function EDIT($data){
$this->id = $data['id'];
$this->name = $data['name'];
$this->value = $data['value'];
$this->db->where('id', $this->id);
$this->db->update('meta', $this);
return $this->uid;
}
public function TRASH($data){
$this->uid = $data['uid'];
$this->db->where('uid', $this->uid);
$this->db->delete('meta');
}
} | artistic-2.0 |
ASMlover/study | cplusplus/lvmpp/token.cc | 2731 | // Copyright (c) 2019 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <cstdlib>
#include <iomanip>
#include <sstream>
#include <unordered_map>
#include "token.h"
namespace lox {
static constexpr const char* const kTokenNames[] = {
#define TOKDEF(k, s) s,
#include "kind_defs.h"
#undef TOKDEF
nullptr
};
static const std::unordered_map<std::string, TokenKind> kTokenKeywords = {
#define KEYWORD(k, s) {s, TokenKind::KW_##k},
#include "kind_defs.h"
#undef KEYWORD
};
const char* get_token_name(TokenKind kind) {
if (kind < TokenKind::NUM_TOKENS)
return kTokenNames[kind];
return nullptr;
}
bool contains_in_keywords(TokenKind kind) {
return kind >= TokenKind::KW_AND && kind <= TokenKind::KW_WHILE;
}
TokenKind get_keyword_kind(const char* key) {
auto kind_iter = kTokenKeywords.find(key);
if (kind_iter != kTokenKeywords.end())
return kind_iter->second;
return TokenKind::TK_IDENTIFIER;
}
std::string Token::stringify(void) const {
std::stringstream ss;
ss << std::left << std::setw(20) << get_token_name(kind_) << ":"
<< std::right << std::setw(24) << literal_ << "|"
<< std::right << std::setw(4) << lineno_;
return ss.str();
}
double Token::as_numeric(void) const {
return std::atof(literal_.c_str());
}
std::string Token::as_string(void) const {
return literal_;
}
std::ostream& operator<<(std::ostream& out, const Token& tok) {
return out << tok.stringify();
}
}
| bsd-2-clause |
bmatsuo/gonew | templates/templates.go | 2821 | // Copyright 2012, Bryan Matsuo. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The templating system for gonew (v2).
package templates
/* Filename: templates.go
* Author: Bryan Matsuo <bryan.matsuo [at] gmail.com>
* Created: 2012-07-05 23:02:29.719822 -0700 PDT
* Description:
*/
import (
"fmt"
"io"
"os"
"path/filepath"
"text/template"
)
type SourceTemplate struct{ Name, Text string }
type SourceFile string
type SourceDirectory string
type ErrSourceType struct{ v interface{} }
type ErrNoTemplate string
func (err ErrSourceType) Error() string { return fmt.Sprint("not a source: ", err.v) }
func (err ErrNoTemplate) Error() string { return "no template: " + string(err) }
// A set of templates relatively in-line with template.Template.
type Interface interface {
Render(io.Writer, string, interface{}) error // Render a named template.
Source(interface{}) error // Add a template source.
Funcs(template.FuncMap) error // Add a set of functions.
}
// The straight-forward implementation of Interface.
type templates struct {
t *template.Template
ext string
}
// Create a new template set that recognizes ext as a template file extension.
func New(ext string) Interface { return (&templates{ext: ext}).setup() }
func (ts *templates) Render(out io.Writer, name string, environment interface{}) error {
if ts.t == nil {
return ErrNoTemplate(name)
}
return ts.t.ExecuteTemplate(out, name, environment)
}
func (ts *templates) setup() *templates {
if ts.t == nil {
fns := template.FuncMap{"gonew": func() string { return "gonew v2" }}
ts.t = template.Must(template.New("gonew").Funcs(fns).Parse("{{gonew}}"))
}
return ts
}
func (ts *templates) Source(src interface{}) (err error) {
switch src.(type) {
case SourceTemplate:
_, err = ts.setup().t.
New(src.(SourceTemplate).Name).
Parse(src.(SourceTemplate).Text)
case SourceFile:
_, err = ts.setup().t.ParseFiles(string(src.(SourceFile)))
case SourceDirectory:
dir := string(src.(SourceDirectory))
if !isDir(dir) {
return fmt.Errorf("not a directory: %s", dir)
}
var paths []string
filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() && filepath.Ext(path) == ts.ext {
paths = append(paths, path)
}
return nil
})
_, err = ts.setup().t.ParseFiles(paths...)
case *template.Template:
t := src.(*template.Template)
_, err = ts.setup().t.AddParseTree(t.Name(), t.Tree)
default:
err = ErrSourceType{src}
}
return
}
func (ts *templates) Funcs(fns template.FuncMap) error {
ts.setup().t.Funcs(fns)
return nil
}
func isDir(d string) bool { // be careful
info, err := os.Stat(d)
return err == nil && info.IsDir()
}
| bsd-2-clause |
PopCap/GameIdea | Engine/Source/Programs/IOS/DeploymentServer/Properties/AssemblyInfo.cs | 263 | /**
* Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
*/
using System.Reflection;
[assembly: AssemblyTitle("DeploymentServer")]
[assembly: AssemblyDescription("Deploys packaged applications to iOS devices")]
[assembly: AssemblyConfiguration("")]
| bsd-2-clause |
mfikes/homebrew-core | Formula/stella.rb | 1607 | class Stella < Formula
desc "Atari 2600 VCS emulator"
homepage "https://stella-emu.github.io/"
url "https://github.com/stella-emu/stella/releases/download/6.0.2/stella-6.0.2-src.tar.xz"
sha256 "bcbd82294f97d00457fdb727e9b08ff73b685dc7f77704cea1eceb58d8967387"
head "https://github.com/stella-emu/stella.git"
bottle do
cellar :any
sha256 "e8ba8548bb9a0eee1cc7ae25ece7a71ec34b659007fd28ed511785d2426f8bd9" => :catalina
sha256 "9eb712f39ab97788ee8d7290e866a6bbf002ac31ba72f1e926a2c07831158a4a" => :mojave
sha256 "8f9a6e8cfd9c54c78816526fe5050a1d299931ec150af1eead1fed485c1bd0f4" => :high_sierra
end
depends_on :xcode => :build
depends_on "libpng"
depends_on "sdl2"
uses_from_macos "zlib"
def install
sdl2 = Formula["sdl2"]
libpng = Formula["libpng"]
cd "src/macos" do
inreplace "stella.xcodeproj/project.pbxproj" do |s|
s.gsub! %r{(\w{24} \/\* SDL2\.framework)}, '//\1'
s.gsub! %r{(\w{24} \/\* png)}, '//\1'
s.gsub! /(HEADER_SEARCH_PATHS) = \(/,
"\\1 = (#{sdl2.opt_include}/SDL2, #{libpng.opt_include},"
s.gsub! /(LIBRARY_SEARCH_PATHS) = ("\$\(LIBRARY_SEARCH_PATHS\)");/,
"\\1 = (#{sdl2.opt_lib}, #{libpng.opt_lib}, \\2);"
s.gsub! /(OTHER_LDFLAGS) = "((-\w+)*)"/, '\1 = "-lSDL2 -lpng \2"'
end
xcodebuild "SYMROOT=build"
prefix.install "build/Release/Stella.app"
bin.write_exec_script "#{prefix}/Stella.app/Contents/MacOS/Stella"
end
end
test do
assert_match /Stella version #{version}/, shell_output("#{bin}/Stella -help").strip
end
end
| bsd-2-clause |
ChrisRx/cpkt | cpkt/protocols/ip.py | 3821 | from .. import Packet, types, Field
IP_PROTO_IP = 0
IP_PROTO_TCP = 6
IP_PROTO_UDP = 17
IP_PROTO_HOPOPTS = 0
IP_PROTO_ROUTING = 43
IP_PROTO_FRAGMENT = 44
IP_PROTO_AH = 51
IP_PROTO_ESP = 50
IP_PROTO_DSTOPTS = 60
class IP(Packet):
v_hl = Field(types.UnsignedChar, default=(4 << 4) | (20 >> 2))
tos = Field(types.UnsignedChar, default=0)
len = Field(types.UnsignedShort, default=20)
id = Field(types.UnsignedShort, default=0)
off = Field(types.UnsignedShort, default=0)
ttl = Field(types.UnsignedChar, default=64)
p = Field(types.UnsignedChar, default=0)
sum = Field(types.UnsignedShort, default=0)
src = Field(types.String(4), default=types.NULL(4))
dst = Field(types.String(4), default=types.NULL(4))
class IP6(Packet):
v_fc_flow = Field(types.UnsignedInteger, default=0x60000000L)
plen = Field(types.UnsignedShort, default=0)
nxt = Field(types.UnsignedChar, default=0)
hlim = Field(types.UnsignedChar, default=0)
src = Field(types.String(16), default=None)
dst = Field(types.String(16), default=None)
def process(self):
ext_data = self.data[:self.plen]
next_ext = self.nxt
while (next_ext in EXTENSION_HEADERS.keys()):
ext = EXTENSION_HEADERS[next_ext](ext_data)
ext_data = ext_data[ext.length:]
next_ext = ext.nxt
self.p = next_ext
class IP6Extension(Packet):
pass
class IP6Options(IP6Extension):
nxt = Field(types.UnsignedChar, default=0)
len = Field(types.UnsignedChar, default=0)
def process(self):
self.options = []
index = 0
while (index < ((self.len + 1) * 8) - 2):
opt_type = ord(self.data[index])
if opt_type == 0:
index += 1
continue;
opt_length = ord(self.data[index + 1])
if opt_type == 1:
index += opt_length + 2
continue
self.options.append({
'type': opt_type,
'opt_length': opt_length,
'data': self.data[index + 2:index + 2 + opt_length]
})
index += opt_length + 2
class IP6HopOptions(IP6Options): pass
class IP6DstOptions(IP6Options): pass
class IP6Routing(IP6Extension):
nxt = Field(types.UnsignedChar, default=0)
len = Field(types.UnsignedChar, default=0)
type = Field(types.UnsignedChar, default=0)
segs_left = Field(types.UnsignedChar, default=0)
rsvd_sl_bits = Field(types.UnsignedInteger, default=0)
def process(self):
buf = buf[8:8 + self.len / 2 * 16]
self.length = (self.len * 8) + 8
self.addresses = [buf[i * addr_size: i * addr_size + addr_size]
for i in range(self.len / 2)]
self.data = buf
class IP6Fragment(IP6Extension):
nxt = Field(types.UnsignedChar, default=0)
resv = Field(types.UnsignedChar, default=0)
frag_off_resv_m = Field(types.UnsignedShort, default=0)
id = Field(types.UnsignedInteger, default=0)
class IP6AH(IP6Extension):
nxt = Field(types.UnsignedChar, default=0)
len = Field(types.UnsignedChar, default=0)
resv = Field(types.UnsignedShort, default=0)
spi = Field(types.UnsignedInteger, default=0)
seq = Field(types.UnsignedInteger, default=0)
class IP6ESP(IP6Extension):
pass
EXTENSION_HEADERS = {
IP_PROTO_HOPOPTS: IP6HopOptions,
IP_PROTO_ROUTING: IP6Routing,
IP_PROTO_FRAGMENT: IP6Fragment,
IP_PROTO_ESP: IP6ESP,
IP_PROTO_AH: IP6AH,
IP_PROTO_DSTOPTS: IP6DstOptions
}
| bsd-2-clause |
adamaveray/blight | blight/src/Interfaces/Models/Author.php | 1340 | <?php
namespace Blight\Interfaces\Models;
interface Author {
/**
* @param \Blight\Interfaces\Blog $blog
* @param array $data
*
* $data = array(
* 'name' => '', // Required
* 'email' => '',
* 'url' => ''
* )
*
* @throws \InvalidArgumentException The data is missing the name
*/
public function __construct(\Blight\Interfaces\Blog $blog, $data);
/**
* @return string The author's name
*/
public function getName();
/**
* @return string The author's email address
* @throws \RuntimeException The author does not have an email address set
*/
public function getEmail();
/**
* @return string The author's URL
* @throws \RuntimeException The author does not have a URL set
*/
public function getURL();
/**
* @param string $name The name of the attribute to retrieve
* @return mixed The attribute value
* @throws \RuntimeException The author does not have the requested attribute set
*/
public function getAttribute($name);
/**
* @return bool Whether the author has an email address set
*/
public function hasEmail();
/**
* @return bool Whether the author has a URL set
*/
public function hasURL();
/**
* @param string $name The name of the attribute to check for
* @return bool Whether the attribute exists
*/
public function hasAttribute($name);
};
| bsd-2-clause |
ProductLayer/ProductLayer-SDK-for-Android | ply-android-common/src/main/java/com/productlayer/android/common/handler/HasPLYAndroidHolder.java | 1626 | /*
* Copyright (c) 2015, ProductLayer GmbH All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.productlayer.android.common.handler;
/**
* Implemented by classes providing a PLYAndroid holder.
*/
public interface HasPLYAndroidHolder {
/**
* @return the PLYAndroid handler
*/
PLYAndroidHolder getPLYAndroidHolder();
}
| bsd-2-clause |
eslint/espree | tests/fixtures/ecma-version/6/regexUFlag/regex-u-extended-escape.result.js | 5116 | import conditionalRegex from "../../../../lib/conditional-regex-value.js";
export default {
"type": "Program",
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 41
}
},
"range": [
0,
41
],
"body": [
{
"type": "VariableDeclaration",
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 41
}
},
"range": [
0,
41
],
"declarations": [
{
"type": "VariableDeclarator",
"loc": {
"start": {
"line": 1,
"column": 4
},
"end": {
"line": 1,
"column": 40
}
},
"range": [
4,
40
],
"id": {
"type": "Identifier",
"loc": {
"start": {
"line": 1,
"column": 4
},
"end": {
"line": 1,
"column": 5
}
},
"range": [
4,
5
],
"name": "x"
},
"init": conditionalRegex({
"type": "Literal",
"loc": {
"start": {
"line": 1,
"column": 8
},
"end": {
"line": 1,
"column": 40
}
},
"range": [
8,
40
],
"value": null,
"raw": "/[\\u{0000000000000061}-\\u{7A}]/u",
"regex": {
"pattern": "[\\u{0000000000000061}-\\u{7A}]",
"flags": "u"
}
})
}
],
"kind": "var"
}
],
"sourceType": "script",
"tokens": [
{
"type": "Keyword",
"value": "var",
"loc": {
"start": {
"line": 1,
"column": 0
},
"end": {
"line": 1,
"column": 3
}
},
"range": [
0,
3
]
},
{
"type": "Identifier",
"value": "x",
"loc": {
"start": {
"line": 1,
"column": 4
},
"end": {
"line": 1,
"column": 5
}
},
"range": [
4,
5
]
},
{
"type": "Punctuator",
"value": "=",
"loc": {
"start": {
"line": 1,
"column": 6
},
"end": {
"line": 1,
"column": 7
}
},
"range": [
6,
7
]
},
{
"type": "RegularExpression",
"value": "/[\\u{0000000000000061}-\\u{7A}]/u",
"loc": {
"start": {
"line": 1,
"column": 8
},
"end": {
"line": 1,
"column": 40
}
},
"range": [
8,
40
],
"regex": {
"flags": "u",
"pattern": "[\\u{0000000000000061}-\\u{7A}]"
}
},
{
"type": "Punctuator",
"value": ";",
"loc": {
"start": {
"line": 1,
"column": 40
},
"end": {
"line": 1,
"column": 41
}
},
"range": [
40,
41
]
}
]
}; | bsd-2-clause |
ToQoz/goimps | importable_test.go | 5571 | package main
import (
"bytes"
"go/build"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
func TestisBuildable(t *testing.T) {
var bc string
var o string
var a string
// --- Should match ---
o = "darwin"
a = "arm64"
bc = "cgo"
if !isBuildable(o, a, bc) {
t.Errorf("%s should match to GOOS:%s GOARCH:%s", bc, o, a)
}
o = "darwin"
a = "arm64"
bc = "!cgo"
if !isBuildable(o, a, bc) {
t.Errorf("%s should match to GOOS:%s GOARCH:%s", bc, o, a)
}
o = "darwin"
a = "arm64"
bc = "darwin,arm64"
if !isBuildable(o, a, bc) {
t.Errorf("%s should match to GOOS:%s GOARCH:%s", bc, o, a)
}
o = "darwin"
a = "arm64"
bc = "darwin"
if !isBuildable(o, a, bc) {
t.Errorf("%s should match to GOOS:%s GOARCH:%s", bc, o, a)
}
o = "darwin"
a = "arm64"
bc = "!linux,!windows"
if !isBuildable(o, a, bc) {
t.Errorf("%s should match to GOOS:%s GOARCH:%s", bc, o, a)
}
// --- Should not match ---
o = "darwin"
a = "arm64"
bc = "ignore"
if isBuildable(o, a, bc) {
t.Errorf("%s should not match to GOOS:%s GOARCH:%s", bc, o, a)
}
o = "darwin"
a = "arm64"
bc = "!darwin"
if isBuildable(o, a, bc) {
t.Errorf("%s should not match to GOOS:%s GOARCH:%s", bc, o, a)
}
o = "darwin"
a = "arm64"
bc = "darwin,linux,freebsd,plan9" // hahaha...
if isBuildable(o, a, bc) {
t.Errorf("%s should not match to GOOS:%s GOARCH:%s", bc, o, a)
}
}
func TestGetPackageNameFromGoFiles(t *testing.T) {
var err error
var got string
var expected string
got, err = getPackageNameFromGoFiles(stdPkgPath("net/http"))
expected = "http"
if err != nil {
panic(err)
}
if got != expected {
t.Errorf("expected pakcage name is %s, but got %s", expected, got)
}
got, err = getPackageNameFromGoFiles(stdPkgPath("net"))
expected = "net"
if err != nil {
panic(err)
}
if got != expected {
t.Errorf("expected pakcage name is %s, but got %s", expected, got)
}
got, err = getPackageNameFromGoFiles(stdPkgPath("strings"))
expected = "strings"
if err != nil {
panic(err)
}
if got != expected {
t.Errorf("expected pakcage name is %s, but got %s", expected, got)
}
}
func TestCmdImportable(t *testing.T) {
// comment out pkg that has no buildable source
expected := []string{
// "archive",
"archive/tar",
"archive/zip",
"bufio",
"builtin",
"bytes",
// "compress",
"compress/bzip2",
"compress/flate",
"compress/gzip",
"compress/lzw",
"compress/zlib",
// "container",
"container/heap",
"container/list",
"container/ring",
"crypto",
"crypto/aes",
"crypto/cipher",
"crypto/des",
"crypto/dsa",
"crypto/ecdsa",
"crypto/elliptic",
"crypto/hmac",
"crypto/md5",
"crypto/rand",
"crypto/rc4",
"crypto/rsa",
"crypto/sha1",
"crypto/sha256",
"crypto/sha512",
"crypto/subtle",
"crypto/tls",
"crypto/x509",
"crypto/x509/pkix",
// "database",
"database/sql",
"database/sql/driver",
// "debug",
"debug/dwarf",
"debug/elf",
"debug/gosym",
"debug/macho",
"debug/pe",
// "debug/plan9obj",
"encoding",
"encoding/ascii85",
"encoding/asn1",
"encoding/base32",
"encoding/base64",
"encoding/binary",
"encoding/csv",
"encoding/gob",
"encoding/hex",
"encoding/json",
"encoding/pem",
"encoding/xml",
"errors",
"expvar",
"flag",
"fmt",
// "go",
"go/ast",
"go/build",
"go/doc",
"go/format",
"go/parser",
"go/printer",
"go/scanner",
"go/token",
"hash",
"hash/adler32",
"hash/crc32",
"hash/crc64",
"hash/fnv",
"html",
"html/template",
"image",
"image/color",
"image/color/palette",
"image/draw",
"image/gif",
"image/jpeg",
"image/png",
// "index",
"index/suffixarray",
"io",
"io/ioutil",
"log",
"log/syslog",
"math",
"math/big",
"math/cmplx",
"math/rand",
"mime",
"mime/multipart",
"net",
"net/http",
"net/http/cgi",
"net/http/cookiejar",
"net/http/fcgi",
"net/http/httptest",
"net/http/httputil",
"net/http/pprof",
"net/mail",
"net/rpc",
"net/rpc/jsonrpc",
"net/smtp",
"net/textproto",
"net/url",
"os",
"os/exec",
"os/signal",
"os/user",
"path",
"path/filepath",
"reflect",
"regexp",
"regexp/syntax",
"runtime",
"runtime/cgo",
"runtime/debug",
"runtime/pprof",
"runtime/race",
"sort",
"strconv",
"strings",
"sync",
"sync/atomic",
"syscall",
"testing",
"testing/iotest",
"testing/quick",
// "text",
"text/scanner",
"text/tabwriter",
"text/template",
"text/template/parse",
"time",
"unicode",
"unicode/utf16",
"unicode/utf8",
"unsafe",
"foo",
}
build.Default.GOPATH = "./testdata/testgopath"
var w bytes.Buffer
if cmdImportable(&w, os.Stderr) != 0 {
panic("error in cmdImportable")
}
importable := strings.Split(strings.Trim(w.String(), "\n"), "\n")
errFound := false
for _, e := range expected {
if !contains(importable, e) {
errFound = true
t.Errorf("expected %s is listed, but isn't listed", e)
}
}
if len(importable) != len(expected) {
errFound = true
t.Logf("expected importable count is %d, but got %d", len(expected), len(importable))
}
if errFound {
t.Logf("--- diff <importable> <expected> ---\n%s", getArrayDiff(importable, expected))
}
}
func stdPkgPath(name string) string {
name = filepath.Join(strings.Split(name, "/")...)
if isGo14OrLater() {
return filepath.Join(build.Default.GOROOT, "src", name)
}
return filepath.Join(build.Default.GOROOT, "src", "pkg", name)
}
func isGo14OrLater() bool {
vs := strings.TrimPrefix(runtime.Version(), "go")
vs = strings.Replace(vs, ".", "", -1)
return vs[:2] >= "14"
}
| bsd-2-clause |
malob/homebrew-cask | Casks/thetimemachinemechanic.rb | 1215 | cask "thetimemachinemechanic" do
version "1.19,2021.09"
sha256 "aa41043dd8bff576c27173859ed55766fad947d17f28938f10aa8fc764cfb16c"
url "https://eclecticlightdotcom.files.wordpress.com/#{version.csv.second.major}/#{version.csv.second.minor}/t2m2#{version.csv.first.no_dots}.zip",
verified: "eclecticlightdotcom.files.wordpress.com/"
name "The Time Machine Mechanic"
name "T2M2"
desc "Time Machine log viewer & status inspector"
homepage "https://eclecticlight.co/consolation-t2m2-and-log-utilities/"
livecheck do
url "https://raw.githubusercontent.com/hoakleyelc/updates/master/eclecticapps.plist"
strategy :page_match do |page|
match = page.match(%r{/(\d+)/(\d+)/t2m2(\d+)\.zip}i)
next if match.blank?
"#{match[3].split("", 2).join(".")},#{match[1]}.#{match[2]}"
end
end
depends_on macos: ">= :sierra"
app "t2m2#{version.before_comma.major}#{version.before_comma.minor}/TheTimeMachineMechanic.app"
zap trash: [
"~/Library/Caches/co.eclecticlight.TheTimeMachineMechanic",
"~/Library/Preferences/co.eclecticlight.TheTimeMachineMechanic.plist",
"~/Library/Saved Application State/co.eclecticlight.TheTimeMachineMechanic.savedState",
]
end
| bsd-2-clause |
dmilios/U-check | learningFromFormulae/src/priors/GaussianPrior.java | 514 | package priors;
public final class GaussianPrior extends Prior {
final private double mu;
final private double s2;
/** Normal distribution with mean 'mu' and variance 's2' */
public GaussianPrior(double mu, double s2) {
super();
this.mu = mu;
this.s2 = s2;
}
@Override
public double logProbability(final double x) {
return Math.log(1 / Math.sqrt(2 * Math.PI * s2)) - (x - mu) * (x - mu)
/ (2 * s2);
}
@Override
public String toString() {
return "Normal(" + mu + ", " + s2 + ")";
}
}
| bsd-2-clause |
btccom/copernicus | msg/AddressMessage.go | 2863 | package msg
import (
"fmt"
"github.com/btccom/copernicus/network"
"github.com/btccom/copernicus/protocol"
"github.com/btccom/copernicus/utils"
"github.com/pkg/errors"
"io"
)
const (
MaxAddressesCount = 1024
MaxVarIntPayload = 9
MaxUserAgentLen = 256
)
type AddressMessage struct {
Message
AddressList []*network.PeerAddress
}
func (addressMessage *AddressMessage) AddPeerAddress(peerAddress *network.PeerAddress) error {
if len(addressMessage.AddressList) > MaxAddressesCount {
str := fmt.Sprintf("has too many addresses in message ,count is %v ", MaxAddressesCount)
return errors.New(str)
}
addressMessage.AddressList = append(addressMessage.AddressList, peerAddress)
return nil
}
func (addressMessage *AddressMessage) AddPeerAddresses(peerAddresses ...*network.PeerAddress) (err error) {
for _, peerAddress := range peerAddresses {
err = addressMessage.AddPeerAddress(peerAddress)
if err != nil {
return err
}
}
return nil
}
func (addressMessage *AddressMessage) ClearAddresses() {
addressMessage.AddressList = []*network.PeerAddress{}
}
func (addressMessage *AddressMessage) BitcoinParse(reader io.Reader, size uint32) error {
count, err := utils.ReadVarInt(reader, size)
if err != nil {
return err
}
if count > MaxAddressesCount {
str := fmt.Sprintf("too many addresses for message count %v ,max %v", count, MaxAddressesCount)
return errors.New(str)
}
addrList := make([]*network.PeerAddress, count)
addressMessage.AddressList = make([]*network.PeerAddress, 0, count)
for i := uint64(0); i < count; i++ {
peerAddress := addrList[i]
err := network.ReadPeerAddress(reader, size, peerAddress, true)
if err != nil {
return err
}
addressMessage.AddPeerAddress(peerAddress)
}
return nil
}
func (addressMessage *AddressMessage) BitcoinSerialize(w io.Writer, size uint32) error {
count := len(addressMessage.AddressList)
if size < protocol.MultipleAddressVersion && count > 1 {
str := fmt.Sprintf("too many address for message of protocol version %v count %v ", size, count)
return errors.New(str)
}
if count > MaxAddressesCount {
str := fmt.Sprintf("too many addresses for message count %v,max %v", count, MaxAddressesCount)
return errors.New(str)
}
err := utils.WriteVarInt(w, size, uint64(count))
if err != nil {
return err
}
for _, peerAddress := range addressMessage.AddressList {
err := network.WritePeerAddress(w, size, peerAddress, true)
if err != nil {
return err
}
}
return nil
}
func (addressMessage *AddressMessage) MaxPayloadLength(version uint32) uint32 {
if version < protocol.MultipleAddressVersion {
return MaxVarIntPayload + network.MaxPeerAddressPayload(version)
}
return MaxVarIntPayload + (MaxAddressesCount * network.MaxPeerAddressPayload(version))
}
func (addressMessage *AddressMessage) Command() string {
return CommandAddress
}
| bsd-2-clause |
ingydotnet/cdent-py | cdent/emitter/coffee.py | 816 | """\
CoffeeScript code emitter for C'Dent
"""
from __future__ import absolute_import
from cdent.emitter import Emitter as Base
class Emitter(Base):
LANGUAGE_ID = 'coffee'
BLOCK_COMMENT_PREFIX = ''
def emit_includecdent(self, includecdent):
self.writeln('use CDent::Run;')
def emit_class(self, class_):
name = class_.name
self.writeln('class %s' % name)
self.emit(class_.has, indent=True)
def emit_method(self, method):
name = method.name
self.writeln('%s: () ->' % name)
self.emit(method.has, indent=True)
def emit_println(self, println):
self.write('print ', indent=True)
self.emit(println.args)
self.writeln(', "\\n"', indent=False)
def emit_return(self, ret):
self.writeln('return;')
| bsd-2-clause |
manslogic/first | src/main/java/com/ths/first/gzip/GZipServletOutputStream.java | 1293 | package com.ths.first.gzip;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
public class GZipServletOutputStream extends ServletOutputStream {
private GZIPOutputStream gzipOutputStream = null;
public GZipServletOutputStream(OutputStream output)
throws IOException {
super();
this.gzipOutputStream = new GZIPOutputStream(output);
}
@Override
public void close() throws IOException {
this.gzipOutputStream.close();
}
@Override
public void flush() throws IOException {
this.gzipOutputStream.flush();
}
@Override
public void write(byte b[]) throws IOException {
this.gzipOutputStream.write(b);
}
@Override
public void write(byte b[], int off, int len) throws IOException {
this.gzipOutputStream.write(b, off, len);
}
@Override
public void write(int b) throws IOException {
this.gzipOutputStream.write(b);
}
@Override
public boolean isReady() {
// TODO Auto-generated method stub
return true;
}
@Override
public void setWriteListener(WriteListener writeListener) {
// TODO Auto-generated method stub
}
}
| bsd-2-clause |
fraxachun/koala-framework | tests/Kwc/News/PagesModel.php | 475 | <?php
class Kwc_News_PagesModel extends Kwc_Root_Category_GeneratorModel
{
public function __construct()
{
$config['proxyModel'] = new Kwf_Model_FnF(array(
'data' => array(
array('id'=>2100, 'pos'=>1, 'visible'=>true, 'name'=>'NewsBar', 'filename' => 'newsbar1',
'parent_id'=>'root', 'component'=>'news', 'is_home'=>false, 'hide'=>false),
)
));
parent::__construct($config);
}
}
| bsd-2-clause |
Pushjet/Pushjet-Android | gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/src/language-base/org/gradle/language/base/internal/BinaryNamingSchemeBuilder.java | 942 | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.language.base.internal;
public interface BinaryNamingSchemeBuilder {
BinaryNamingSchemeBuilder withComponentName(String name);
BinaryNamingSchemeBuilder withTypeString(String newTypeString);
BinaryNamingSchemeBuilder withVariantDimension(String dimension);
BinaryNamingScheme build();
}
| bsd-2-clause |
khchine5/book | lino_book/projects/crl/fixtures/hs2lino.py | 11938 | # -*- coding: UTF-8 -*-
# Copyright 2011-2013 Luc Saffre
# This file is part of the Lino project.
# Lino 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 of the License, or
# (at your option) any later version.
# Lino 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 Lino ; if not, see <http://www.gnu.org/licenses/>.
"""
"""
import logging
logger = logging.getLogger(__name__)
import os
import sys
import datetime
from dateutil import parser as dateparser
from django.conf import settings
from django.core.management import call_command
from django.db import IntegrityError
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand, CommandError
#~ from lino import lino_site
from lino.utils import dbfreader
from lino.utils import dblogger
#~ from lino import diag
#~ from lino.utils import crl2hex, hex2crl
from lino.utils import join_words
from lino_xl.lib.contacts.utils import name2kw, street2kw
#~ from lino_xl.lib.contacts.models import GENDER_MALE, GENDER_FEMALE
from lino.api import dd, rt
from lino.utils.instantiator import Instantiator
from lino.core.utils import resolve_model, obj2str
import lino
from lino.utils import confirm, iif
from lino.core.utils import app_labels
from lino_book.projects.crl.models import CRL
Country = resolve_model('countries.Country')
Place = resolve_model('countries.Place')
Person = resolve_model("contacts.Person")
Company = resolve_model("contacts.Company")
def parsedate(T):
if not T:
return
T = T.replace('.', '')
try:
if len(T) == 4:
return (datetime.date(int(T), 6, 30), True)
elif len(T) == 6:
return (datetime.date(int(T[:4]), int(T[4:6]), 15), True)
elif len(T) == 8:
return (datetime.date(int(T[:4]), int(T[4:6]), int(T[6:])), False)
except ValueError:
pass
dblogger.warning("Ignored invalid date value %r" % T)
def store(kw, **d):
for k, v in d.items():
if v is not None:
# see `/blog/2011/0711`
#~ if v:
kw[k] = v
#~ def convert_username(name):
#~ return name.lower()
def convert_sex(v):
if v in ('W', 'F'):
return 'F'
if v == 'M':
return 'M'
return None
def isolang(x):
if x == 'K':
return 'et'
if x == 'E':
return 'en'
if x == 'D':
return 'de'
if x == 'F':
return 'fr'
if x == 'N':
return 'nl'
def is_company(data):
# wer eine nationalregisternummer hat ist eine Person, selbst wenn er auch
# eine MWst-Nummer hat.
if data.get('NB2', False):
return False
if data.get('NOTVA', False):
#~ if data.get('NOTVA',False):
return True
return False
def store_date(row, obj, rowattr, objattr):
v = row[rowattr]
if v:
if isinstance(v, basestring):
v = dateparser.parse(v)
setattr(obj, objattr, v)
def ADR_id(cIdAdr):
assert len(cIdAdr) == 3
#~ assert [cIdAdr:-3] == '000'
try:
return 199000 + int(cIdAdr)
except ValueError, e:
return None
def country2kw(row, kw):
# for both PAR and ADR
if row.has_key('PROF'):
activity = row['PROF']
if activity:
try:
activity = int(activity)
except ValueError:
dblogger.debug("Ignored invalid value PROF = %r", activity)
else:
if activity:
try:
activity = Activity.objects.get(pk=activity)
except Activity.DoesNotExist:
activity = Activity(
id=activity, name=str(activity))
activity.save(force_insert=True)
kw.update(activity=activity)
country = row['PAYS']
if country:
try:
country = Country.objects.get(short_code__exact=country)
except Country.DoesNotExist:
country = Country(isocode=country, name=country,
short_code=country)
country.save()
kw.update(country=country)
store(kw,
phone=row['TEL'],
fax=row['FAX'],
email=row['EMAIL'],
)
kw.update(street2kw(join_words(row['RUE'], row['RUENUM'], row['RUEBTE'])))
zip_code = row['CP']
if zip_code:
kw.update(zip_code=zip_code)
try:
city = Place.objects.get(
country=country,
zip_code__exact=zip_code,
)
kw.update(city=city)
except Place.DoesNotExist, e:
city = Place(zip_code=zip_code, name=zip_code, country=country)
city.save()
kw.update(city=city)
#~ logger.warning("%s-%s : %s",row['PAYS'],row['CP'],e)
except Place.MultipleObjectsReturned, e:
dblogger.warning("%s-%s : %s", row['PAYS'], row['CP'], e)
def par2person(row, person):
person.is_active = iif(row['IDPRT'] == 'I', False, True)
if row['IDPRT'] == 'S':
person.is_cpas = True
elif row['IDPRT'] == 'A':
person.is_senior = True
def pxs2person(row, person):
kw = {}
store(kw,
card_number=row['CARDNUMBER'],
card_type=row.get('CARDTYPE', ''), # 20110110
card_issuer=row.get('CARDISSUER', ''), # 20110110
noble_condition=row.get('NOBLEECOND', ''), # 20110110
birth_place=row.get('BIRTHPLACE', ''),
remarks2=row.get('MEMO', ''),
gender=convert_sex(row['SEXE'])
)
for k, v in kw.items():
setattr(person, k, v)
par2person(row, person)
if row['IDMUT']:
try:
person.health_insurance = Company.objects.get(
pk=ADR_id(row['IDMUT']))
except ValueError, e:
dblogger.warning(u"%s : invalid health_insurance %r",
obj2str(person), row['IDMUT'])
except Company.DoesNotExist, e:
dblogger.warning(u"%s : health_insurance %s not found",
obj2str(person), row['IDMUT'])
if row['APOTHEKE']:
try:
person.pharmacy = Company.objects.get(pk=int(row['APOTHEKE']))
except ValueError, e:
dblogger.warning(u"%s : invalid pharmacy %r",
obj2str(person), row['APOTHEKE'])
except Company.DoesNotExist, e:
dblogger.warning(u"%s : pharmacy %s not found",
obj2str(person), row['APOTHEKE'])
nat = row['NATIONALIT']
if nat:
try:
country = Country.objects.get(short_code__exact=nat)
except Country.DoesNotExist:
country = Country(isocode=nat, name=nat, short_code=nat)
country.save()
person.nationality = country
store_date(row, person, 'GEBDAT', 'birth_date')
store_date(row, person, 'VALID1', 'card_valid_from')
store_date(row, person, 'VALID2', 'card_valid_until')
def try_full_clean(i):
while True:
try:
i.full_clean()
except ValidationError, e:
if not hasattr(e, 'message_dict'):
raise
for k in e.message_dict.keys():
fld = i._meta.get_field(k)
v = getattr(i, k)
setattr(i, k, fld.default)
dblogger.warning(
"%s : ignoring value %r for %s : %s", obj2str(i), v, k, e)
return
def load_dbf(tableName, load):
fn = os.path.join(settings.SITE.legacy_data_path, '%s.DBF' % tableName)
f = dbfreader.DBFFile(fn, codepage="cp850")
logger.info("Loading %d records from %s...", len(f), fn)
f.open()
for dbfrow in f:
i = load(dbfrow)
if i is not None:
i = settings.TIM2LINO_LOCAL(tableName, i)
if i is not None:
try_full_clean(i)
yield i
#~ try:
#~ i.save()
#~ except Exception,e:
#~ dblogger.warning("Failed to save %s from %s : %s",obj2str(i),dbfrow,e)
#~ dblogger.exception(e)
f.close()
def load_O_(row):
kw = {}
o = row['O']
if o:
if len(o) == 2:
try:
country = Country.objects.get(pk=o)
if country.name.upper() != row['A'].upper():
logger.warning('Country %s : %r != %r',
o, country.name, row['A'])
except Country.DoesNotExist:
return Country(isocode=o, name=row['A'] + ' <<<<')
elif len(o) == 4:
try:
be = Country.objects.get(pk='BE')
city = Place.objects.get(country=be, zip_code=o)
if city.name.upper() != row['A'].upper():
logger.warning('Place BE-%s : %r != %r',
o, city.name, row['A'])
except Place.MultipleObjectsReturned:
logger.warning(
"O %s (%s) : MultipleObjectsReturned", o, row['A'])
except Place.DoesNotExist:
return Place(country=be, zip_code=o, name=row['A'] + ' <<<<')
else:
logger.warning("O %s (%s) : unknown format", o, row['A'])
def load_P_(row):
kw = {}
#~ kw.update(street2kw(join_words(row['RUE'],row['RUENUM'],row['RUEBTE'])))
store(kw, last_name=row['AN'])
store(kw, first_name=row['AP'])
store(kw, crl=CRL(row['P'].encode('cp437')))
#~ store(kw,crl=crl2hex(row['P']))
OU = row['OU']
if OU:
kw.update(street2kw(OU))
title = row['PQ']
if title:
if title == 'Mme':
kw.update(language='fr', gender=dd.Genders.female)
elif title == 'Mlle':
kw.update(language='fr', gender=dd.Genders.female)
elif title == 'M.':
kw.update(language='fr', gender=dd.Genders.male)
elif title == 'dHr':
kw.update(language='nl', gender=dd.Genders.male)
elif title == 'Mvw':
kw.update(language='nl', gender=dd.Genders.female)
elif title == 'Mr':
kw.update(language='en', gender=dd.Genders.male)
elif title == 'Mrs':
kw.update(language='en', gender=dd.Genders.female)
elif title == 'Hrrn':
kw.update(language='de', gender=dd.Genders.male)
elif title == 'Fr':
kw.update(language='de', gender=dd.Genders.female)
elif title == 'Fr.':
kw.update(language='fr', gender=dd.Genders.male, title=u"Frère")
elif title == 'Frl':
kw.update(language='de', gender=dd.Genders.female)
elif title == 'Bx':
kw.update(gender=dd.Genders.male, title="Bx")
elif title == 'Bse':
kw.update(gender=dd.Genders.female, title="Bse")
elif title == 'St':
kw.update(gender=dd.Genders.male, title="St")
elif title == 'Ste':
kw.update(gender=dd.Genders.female, title="Ste")
else:
dblogger.warning("Ignored PQ value %r" % title)
a = parsedate(row['T'])
if a:
kw.update(birth_date=a[0], birth_date_circa=a[1])
a = parsedate(row['T'])
if a:
kw.update(died_date=a[0])
if a[1]:
logger.warning("Ignored 'circa' flag for died_date")
return Person(**kw)
def objects():
for i in load_dbf('P_', load_P_):
yield i
for i in load_dbf('O_', load_O_):
yield i
| bsd-2-clause |
sebastienros/jint | Jint.Tests.Test262/test/annexB/language/eval-code/indirect/global-if-stmt-else-decl-eval-global-block-scoping.js | 2006 | // This file was procedurally generated from the following sources:
// - src/annex-b-fns/eval-global-block-scoping.case
// - src/annex-b-fns/eval-global/indirect-if-stmt-else-decl.template
/*---
description: A block-scoped binding is created (IfStatement with a declaration in the second statement position in eval code)
esid: sec-functiondeclarations-in-ifstatement-statement-clauses
es6id: B.3.4
flags: [generated, noStrict]
info: |
The following rules for IfStatement augment those in 13.6:
IfStatement[Yield, Return]:
if ( Expression[In, ?Yield] ) FunctionDeclaration[?Yield] else Statement[?Yield, ?Return]
if ( Expression[In, ?Yield] ) Statement[?Yield, ?Return] else FunctionDeclaration[?Yield]
if ( Expression[In, ?Yield] ) FunctionDeclaration[?Yield] else FunctionDeclaration[?Yield]
if ( Expression[In, ?Yield] ) FunctionDeclaration[?Yield]
13.2.14 Runtime Semantics: BlockDeclarationInstantiation
[...]
4. For each element d in declarations do
a. For each element dn of the BoundNames of d do
i. If IsConstantDeclaration of d is true, then
[...]
ii. Else,
2. Perform ! envRec.CreateMutableBinding(dn, false).
b. If d is a GeneratorDeclaration production or a FunctionDeclaration
production, then
i. Let fn be the sole element of the BoundNames of d.
ii. Let fo be the result of performing InstantiateFunctionObject for
d with argument env.
iii. Perform envRec.InitializeBinding(fn, fo).
---*/
var initialBV, currentBV;
(0,eval)(
'if (false) ; else function f() { initialBV = f; f = 123; currentBV = f; return "decl"; }'
);
f();
assert.sameValue(
initialBV(),
'decl',
'Block-scoped binding value is function object at execution time'
);
assert.sameValue(currentBV, 123, 'Block-scoped binding is mutable');
assert.sameValue(
f(),
'decl',
'Block-scoped binding is independent of outer var-scoped binding'
);
| bsd-2-clause |
ninjahoahong/homebrew-cask | Casks/yate.rb | 417 | cask 'yate' do
version '3.16.2.1'
sha256 '461512039ac4f6b09313e089233c7bc4e74cfec983fb9d28bc816ccee4f74def'
url 'https://2manyrobots.com/Updates/Yate/Yate.zip',
using: :post
appcast 'https://2manyrobots.com/Updates/Yate/appcast.xml',
checkpoint: '43c4eba17acc3a5f8bd6150fe7029d6e19fb073b379664b524c8bce64ffbd33b'
name 'Yate'
homepage 'https://2manyrobots.com/yate/'
app 'Yate.app'
end
| bsd-2-clause |
rohitgirdhar-cmu-experimental/caffe-3dnormal_joint_past | tools/test_net_3dnormal_joint_img.cpp | 4057 | // 输出分割的结果
/*#include <cuda_runtime.h>*/
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
/*#include <cv.h>
#include <highgui.h>
#include <cxcore.h>*/
#include <cstring>
#include <cstdlib>
#include <vector>
#include <cmath>
#include <utility>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <leveldb/db.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "caffe/caffe.hpp"
#include "caffe/util/io.hpp"
#include <string>
#include <fstream>
using namespace std;
using namespace cv;
using namespace caffe;
using std::vector;
int CreateDir(const char *sPathName, int beg) {
char DirName[256];
strcpy(DirName, sPathName);
int i, len = strlen(DirName);
if (DirName[len - 1] != '/')
strcat(DirName, "/");
len = strlen(DirName);
for (i = beg; i < len; i++) {
if (DirName[i] == '/') {
DirName[i] = 0;
if (access(DirName, 0) != 0) {
CHECK(mkdir(DirName, 0755) == 0)<< "Failed to create folder "<< sPathName;
}
DirName[i] = '/';
}
}
return 0;
}
char buf[101000];
int main(int argc, char** argv)
{
cudaSetDevice(0);
Caffe::set_phase(Caffe::TEST);
//Caffe::SetDevice(2);
if (argc == 8 && strcmp(argv[7], "CPU") == 0) {
LOG(ERROR) << "Using CPU";
Caffe::set_mode(Caffe::CPU);
} else {
LOG(ERROR) << "Using GPU";
Caffe::set_mode(Caffe::GPU);
}
Caffe::set_mode(Caffe::GPU);
Caffe::SetDevice(0);
//Caffe::set_mode(Caffe::CPU);
NetParameter test_net_param;
ReadProtoFromTextFile(argv[1], &test_net_param);
Net<float> caffe_test_net(test_net_param);
for(int i = 0; i < 3; i ++)
{
NetParameter trained_net_param;
ReadProtoFromBinaryFile(argv[2 + i], &trained_net_param);
caffe_test_net.CopyTrainedLayersFrom(trained_net_param);
}
vector<shared_ptr<Layer<float> > > layers = caffe_test_net.layers();
//const DataLayer<float> *datalayer = dynamic_cast<const DataLayer<float>* >(layers[0].get());
//CHECK(datalayer);
string labelFile(argv[3 + 2]);
int data_counts = 0;
FILE * file = fopen(labelFile.c_str(), "r");
while(fgets(buf,100000,file) > 0)
{
data_counts++;
}
fclose(file);
vector<Blob<float>*> dummy_blob_input_vec;
string rootfolder(argv[4 + 2]);
rootfolder.append("/");
CreateDir(rootfolder.c_str(), rootfolder.size() - 1);
string folder;
string fName;
float output;
int counts = 0;
file = fopen(labelFile.c_str(), "r");
Blob<float>* c1 = (*(caffe_test_net.bottom_vecs().rbegin()))[0];
int c2 = c1->num();
int batchCount = std::ceil(data_counts / (floor)(c2));//(test_net_param.layers(0).layer().batchsize()));// (test_net_param.layers(0).layer().batchsize() ));
string resulttxt = rootfolder; //+ "3dNormalResult.txt";
// FILE * resultfile = fopen(resulttxt.c_str(), "w");
for (int batch_id = 0; batch_id < batchCount; ++batch_id)
{
LOG(INFO)<< "processing batch :" << batch_id+1 << "/" << batchCount <<"...";
const vector<Blob<float>*>& result = caffe_test_net.Forward(dummy_blob_input_vec);
Blob<float>* bboxs = (*(caffe_test_net.bottom_vecs().rbegin()))[0];
int bsize = bboxs->num();
const Blob<float>* labels = (*(caffe_test_net.bottom_vecs().rbegin()))[1];
for (int i = 0; i < bsize && counts < data_counts; i++, counts++)
{
char fname[1010];
fscanf(file, "%s", fname);
//fprintf(resultfile, "%s ", fname);
int channels = bboxs->channels();
int height = bboxs->height();
int width = bboxs->width();
int len = channels * height * width;
Mat imgout(Size(width, height), CV_8UC3);
for (int c = 0; c < channels; c ++)
for(int h = 0; h < height; h ++)
for(int w = 0; w < width; w ++)
{
imgout.at<cv::Vec3b>(h, w)[2 - c] =(uchar)( ((float)(bboxs->data_at(i, c, h, w))) * 128 + 128 );
}
//fprintf(resultfile, "\n");
string outstr = rootfolder;
outstr += fname;
imwrite(outstr, imgout);
}
}
//fclose(resultfile);
fclose(file);
return 0;
}
| bsd-2-clause |
r12f/PSPlus | PSPlus.Windows/Interop/Kernel32/Kernel32APIs.cs | 739 | using System;
using System.Runtime.InteropServices;
namespace PSPlus.Windows.Interop.Kernel32
{
public static unsafe class Kernel32APIs
{
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process([In] IntPtr processHandle, [Out] bool* IsWow64Process);
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ReadProcessMemory([In] IntPtr processHandle, [In] IntPtr baseAddress, [Out] IntPtr buffer, [In] int size, [Out] IntPtr numberOfBytesRead);
}
}
| bsd-2-clause |
Sparkier/inviwo | modules/opencl/src/buffer/bufferclbase.cpp | 1839 | /*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2014-2019 Inviwo Foundation
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/opencl/buffer/bufferclbase.h>
namespace inviwo {} // namespace inviwo
namespace cl {
template <>
cl_int Kernel::setArg(cl_uint index, const inviwo::BufferCLBase& value) {
return setArg(index, value.get());
}
} // namespace cl
| bsd-2-clause |
akehrer/Motome | Motome/config.py | 2330 | # Import the future
from __future__ import unicode_literals
VERSION = '0.2.3'
# Import standard library modules
import logging
import os
import sys
# Import Qt modules
from PySide.QtGui import QColor
PLATFORM = sys.platform
LOG_LEVEL = logging.DEBUG
###################################################
# Motome Configuration Variables #
###################################################
# app directory, determine if application is a script file or frozen exe
# see: http://stackoverflow.com/questions/404744/determining-application-path-in-a-python-exe-generated-by-pyinstaller
if getattr(sys, 'frozen', False):
APP_DIR = os.path.dirname(sys.executable)
elif __file__:
APP_DIR = os.path.dirname(__file__)
# window title prefix
WINDOW_TITLE = 'Motome' # 'Mo\u0305to\u0305me'
# Default notes directory if the user never chooses one, this will be created in their home directory
DEFAULT_NOTES_DIR = "Notes"
# app data directory in note directory
NOTE_DATA_DIR = '.motome'
# file extensions
NOTE_EXTENSION = '.txt'
ZIP_EXTENSION = '.zip'
HTML_EXTENSION = '.html'
# file encoding
ENCODING = 'utf-8'
# note directory sub-folder names
MEDIA_FOLDER = 'media'
HTML_FOLDER = 'html'
HISTORY_FOLDER = 'archive'
# the character prepended to tag values when searching
TAG_QUERY_CHAR = '#'
# unsafe filename characters, being pretty strict
UNSAFE_CHARS = '<>:"/\|?*#'
# the unicode end of text character
# http://www.fileformat.info/info/unicode/char/0003/index.htm
# This signifies where the note content ends and any metadata begins
END_OF_TEXT = '\u0003' # Only applies to pre 0.2 versions
# the YAML bracket that splits the files metadata
YAML_BRACKET = '---'
# colors
MOTOME_BLUE = QColor.fromRgb(38, 87, 127, a=255)
MOTOME_LTBLUE = QColor.fromRgb(145, 177, 203, a=255)
MOTOME_GRYBLUE = QColor.fromRgb(89, 122, 148, a=255)
MOTOME_BRTBLUE = QColor.fromRgb(61, 139, 203, a=255)
HIGHLIGHT_COLOR = QColor.fromRgb(255, 255, 153, a=255)
# diff status template, to show when at current note record
STATUS_TEMPLATE = """
<html>
<body>
<p>
{notename}
</p>
<p>
This is the latest version.
</p>
<p>
Last saved: {timestamp}
</p>
<p>
Last Recorded: {recorded}
</p>
</body>
</html>"""
| bsd-2-clause |
csuft/CnBlogsClient | Network/XmlParser.cpp | 4167 | #include "XmlParser.h"
XmlParser::XmlParser(void)
{
// nothing to do
}
XmlParser::~XmlParser(void)
{
// nothing to do
}
/*
* 1. __EVENTTARGET
* 2. __EVENTARGUMENT
* 3. __VIEWSTATE
* 4. __EVENTVALIDATION
* 模拟登陆时需要上述四个字段构造URL,因此在这里解析出来并返回
*/
map<string, string> XmlParser::getLoginParams(const char* fileName)
{
map<string, string> params;
// 从DOM树中获取两个迭代器,以迭代方式获取DOM元素
tree<HTML::Node> dom = createDom(fileName);
tree<HTML::Node>::iterator itStart = dom.begin();
tree<HTML::Node>::iterator itEnd = dom.end();
int count = 0;
for (; itStart != itEnd; ++itStart)
{
// 检索到input元素,则解析Input元素的属性,获得name和value属性
if (!itStart->tagName().compare("input"))
{
itStart->parseAttributes();
params[itStart->attribute("name").second] = itStart->attribute("value").second;
// 只需要解析完上述4对就满足要求了
if (++count == 4)
{
break;
}
}
}
return params;
}
/*
* 复用打开文件创建DOM的代码
*/
tree<HTML::Node> XmlParser::createDom(const char* fileName)
{
HTML::ParserDom parser;
fstream readFrom;
readFrom.open(fileName, ios::in);
istreambuf_iterator<char> fileBegin(readFrom), fileEnd;
string html(fileBegin, fileEnd);
readFrom.close();
return parser.parseTree(html);
}
/*
* 登陆请求发送给服务器之后,解析服务器的应答数据,确定是否登陆成功
*/
string XmlParser::getLoginResult(const char* fileName)
{
string tempVal;
tree<HTML::Node> dom = createDom(fileName);
tree<HTML::Node>::iterator start = dom.begin();
tree<HTML::Node>::iterator end = dom.end();
for (; start != end; ++start)
{
// 检查返回页面中的span元素,分几种情况:
// 1. 不存在span元素,则说明登录成功
// 2. 存在span元素,说明登录失败,返回错误提示
if (start->isTag() && !start->tagName().compare("span"))
{
start->parseAttributes();
if (!start->attribute("id").second.compare("Message"))
{
// 提取该标签的html内容
tempVal = (++start)->text();
}
}
}
return tempVal;
}
/*
* 本函数为一个转发点,将具体的解析任务委托给对应的函数
*/
void XmlParser::parseArticles(vector<Article>& items, const char* fileName)
{
tree<HTML::Node> dom = createDom(fileName);
parseContents(items, dom);
}
/*
* 该函数出于代码复用独立出来,解析每篇博文的八个字段:
* 1.
*/
void XmlParser::parseContents(vector<Article>& items, tree<HTML::Node>& dom)
{
Article article;
int count, index;
bool flag;
string trimmedStr;
tree<HTML::Node>::iterator start = dom.begin();
tree<HTML::Node>::iterator end = dom.end();
for (; start != end; ++start)
{
if (!start->tagName().compare("div"))
{
start->parseAttributes();
if (!start->attribute("class").second.compare("post_item"))
{
// count的意义在于,我们只需要解析一篇博文的八个字段,又没有找到其他更好的跳出循环的方式
// 于是用count做计数之用。而flag是为了只提取一个url,即博文URL,其他的URL不需要。
count = 0;
flag = false;
// 使用string数组来存储八个字段,inde用来记录索引
index = 0;
for (; start != end; ++start)
{
if (!start->tagName().compare("a") && !flag)
{
start->parseAttributes();
article.postAttr[index++] = start->attribute("href").second;
flag = true;
}
if (!start->isTag())
{
// 原始文件中存在大量的非打印字符,如' ', '\t', '\n', '\r', '\v',在这里全部剔除
trimmedStr = start->text();
trimmedStr.erase(0,trimmedStr.find_first_not_of(" \t\v\r\n"));
trimmedStr.erase(trimmedStr.find_last_not_of(" \t\v\r\n") + 1);
if (!trimmedStr.empty())
{
article.postAttr[index++] = trimmedStr;
++count;
}
}
// 这里确实是7.尽管提取了八个字段,但是有两个字段是同时提取出来的
if (count == 7)
{
items.push_back(article);
break;
}
}
}
}
}
} | bsd-2-clause |
dmather/comp-5590 | Our Project/geneticV1/geneticV1_opencl.cpp | 21985 | // Genetic Algorithm Draft 1
// using
// Core Wars Draft 3
// December 2014
// Charley Hepler
// Changes from Core Wars Draft 3
// Added functions:
// clear_cw
// load_cw
// run_cw -- added a parameter just 'cause I was curious about output
// generate_program -- uniformly at random with a fixed length
// generate_population -- calls generate program
// generate_starts -- for fixed length programs
// select_programs
// clear_survivals
// breed -- too simple: just cross over and one point mutation
// show_part -- just to see that something happens
//
// Changed functions:
// do_one_step: removed debugging print statements
// added check for number of processes to SPT instruction
// added zero check on DIV and MOD
// main: to be the genetic algorithm -- NOT DONE YET
//
// No longer using:
// init_cw
// show_results -- was just for debugging, replaced by show_part
#include "sharedredcode.h"
#include "geneticV1_opencl.h"
#include <iostream>
#include <iomanip>
#include <fstream>
#include <stdlib.h>
#include <string.h>
#include <sstream>
#include <bitset>
#include <CL/cl.h>
#include <ctime>
using namespace std;
ostream& operator<<(ostream& outs, const memory_cell& cell);
istream& operator>>(istream& ins, memory_cell& cell);
int main()
{
int pop[POPULATION_SIZE][MAX_PROGRAM_LENGTH];
int chldrn[POPULATION_SIZE][MAX_PROGRAM_LENGTH];
memory_cell children[POPULATION_SIZE][MAX_PROGRAM_LENGTH];
int survivals[POPULATION_SIZE];
int generation;
int i,j,k;
int max_tournament_length[MAX_GENERATIONS];
// Vars needed for GPU kernel
// OpenCL variables
cl_context context = 0;
cl_command_queue commandQueue = 0;
cl_program program = 0;
cl_device_id device = 0;
cl_kernel kernel = 0;
cl_mem memObjects[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
cl_int errNum;
//srand(1234); // set a specific seed for replicability in debugging
srand(time(NULL)); // Give us a more real random selection
// generate initial population
gen_int_population(pop);
cout << "Before: " << endl;
show_part_int(pop);
// OpenCL host code
context = CreateContext();
if(context == NULL) {
printf("Failed to create OpenCL context.\n");
}
commandQueue = CreateCommandQueue(context, &device);
if(commandQueue == NULL) {
// Cleanup method
return 1;
}
char name[2048] = "";
size_t workItems[3];
size_t paramSize = -1;
// This needs to be adjusted
size_t localWorkSize[1] = { 1 };
errNum = clGetDeviceInfo(device, CL_DEVICE_NAME,
sizeof(name),
&name, ¶mSize);
printf("Requested %lu bytes\n", paramSize);
printf("Device name: %s.\n", name);
if(errNum != CL_SUCCESS) {
printf("Error getting device info: %d\n", errNum);
}
errNum = clGetDeviceInfo(device, CL_DEVICE_MAX_WORK_ITEM_SIZES,
sizeof(workItems),
&workItems, ¶mSize);
printf("Requested %lu bytes\n", paramSize);
printf("Max work items: %lu\n", workItems[0]);
if(errNum != CL_SUCCESS) {
printf("Error getting device info: %d\n", errNum);
}
program = CreateProgram(context, device, "geneticKernel.cl");
if(program == NULL) {
return 1;
}
// End OpenCL host code
for(generation = 0; generation < MAX_GENERATIONS; generation++){
// run tournaments
clear_survivals(survivals);
// Create our Kernel
kernel = clCreateKernel(program, "test", NULL);
if(kernel == NULL) {
printf("Failed to create kernel.\n");
}
// Get the maximum number of work items that is supported with this
// kernel
size_t NUM_TOURNAMENTS;
clGetKernelWorkGroupInfo(kernel, device, CL_KERNEL_WORK_GROUP_SIZE,
sizeof(size_t), &NUM_TOURNAMENTS, NULL);
cout << "Kernel Work Group Size: " << NUM_TOURNAMENTS << endl;
int tournament_lengths[NUM_TOURNAMENTS];
size_t globalWorkSize[1] = { NUM_TOURNAMENTS };
int gpu_starts[NUM_TOURNAMENTS][N_PROGRAMS];
int test[NUM_TOURNAMENTS];
for(i = 0; i < NUM_TOURNAMENTS; i++) {
generate_starts(gpu_starts[i]);
}
// We need random numbers to see the opencl rng so we load an array
// with them
int randSeed[NUM_TOURNAMENTS];
for(i = 0; i < NUM_TOURNAMENTS; i++) {
randSeed[i] = rand();
}
cl_int errNo;
// Load all the objects into OpenCL buffers.
memObjects[0] = clCreateBuffer(context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * (POPULATION_SIZE * MAX_PROGRAM_LENGTH),
pop, &errNo);
cout << "Cl Error: " << errNo << endl;
memObjects[7] = clCreateBuffer(context,
CL_MEM_WRITE_ONLY,
sizeof(int) * NUM_TOURNAMENTS, NULL, &errNo);
cout << "Cl Error: " << errNo << endl;
memObjects[8] = clCreateBuffer(context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * (NUM_TOURNAMENTS * N_PROGRAMS),
gpu_starts, &errNo);
cout << "Cl Error: " << errNo << endl;
memObjects[1] = clCreateBuffer(context,
CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
sizeof(int) * POPULATION_SIZE, survivals, &errNo);
cout << "Cl Error: " << errNo << endl;
memObjects[2] = clCreateBuffer(context,
CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR,
sizeof(int) * NUM_TOURNAMENTS, tournament_lengths, &errNo);
cout << "Cl Error: " << errNo << endl;
memObjects[3] = clCreateBuffer(context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(int) * NUM_TOURNAMENTS, randSeed, &errNo);
cout << "Cl Error: " << errNo << endl;
// Set the kernel arguments for the kernel.
// TODO: Remap the kernel arguments so that they don't occupy random
// indexes of the memObjects array.
errNum = clSetKernelArg(kernel, 0, sizeof(cl_mem), &memObjects[7]);
errNum |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &memObjects[8]);
errNum |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &memObjects[0]);
errNum |= clSetKernelArg(kernel, 3, sizeof(cl_mem), &memObjects[1]);
errNum |= clSetKernelArg(kernel, 4, sizeof(cl_mem), &memObjects[2]);
errNum |= clSetKernelArg(kernel, 5, sizeof(cl_mem), &memObjects[3]);
if(errNum != CL_SUCCESS) {
printf("Error setting kernel arguments. %d\n", errNum);
}
if(checkError(errNum = clEnqueueNDRangeKernel(commandQueue, kernel, 1, NULL,
globalWorkSize, localWorkSize, 0,
NULL, NULL))) {
printf("Error queueing the kernel for execution. %d\n", errNum);
continue;
}
// Wait for the commands to be processed
clFinish(commandQueue);
if(checkError(errNum = clEnqueueReadBuffer(commandQueue,
memObjects[7], CL_TRUE, 0,
sizeof(int) * NUM_TOURNAMENTS,
test, 0, NULL, NULL))) {
cout << "Read Buffer Error: " << errNum << endl;
continue;
}
if(checkError(errNum = clEnqueueReadBuffer(commandQueue, memObjects[1],
CL_TRUE, 0,
sizeof(int) * POPULATION_SIZE,
survivals, 0, NULL, NULL))) {
cout << "Read Buffer Error: " << errNum << endl;
continue;
}
if(checkError(errNum = clEnqueueReadBuffer(commandQueue, memObjects[2], CL_TRUE, 0,
sizeof(int) * NUM_TOURNAMENTS, tournament_lengths, 0, NULL,
NULL))) {
cout << "Read Buffer Error: " << errNum << endl;
continue;
}
for(int i = 0; i < NUM_TOURNAMENTS; i++) {
cout << "Random Number: " << test[i] << endl;
}
for(int i = 0; i < POPULATION_SIZE; i++) {
cout << "Survivals: " << survivals[i] << endl;
}
//cout << "Generation: " << generation << endl;
//cout << "Max Tournament Length: " << max_t_length(tournament_lengths) << endl;
//max_tournament_length[generation] = max_t_length(tournament_lengths);
// variation here??? are the tournaments doing anything?
// if(generation % 10 == 0){
// for(j=0;j<N_TOURNAMENTS;j++){
// cout << tournament_lengths[j] << endl;
// }
// cout << endl;
// }
// breed victors
// the survivals array has a count of how many times each program won
// use that to select which programs get to breed
j = 0;
for(int i = 0; i < POPULATION_SIZE; i++){
// find two parents for child
while(survivals[j] == 0){
j++;
j %= POPULATION_SIZE;
}
k = j + 1;
k %= POPULATION_SIZE;
while(survivals[k] == 0){
k++;
k %= POPULATION_SIZE;
}
//breed(population[j],population[k],children[i]);
breed_int(pop[j],pop[k],chldrn[i]);
j = k + 1;
j %= POPULATION_SIZE;
}
// children becomes next generation
for(int i = 0; i < POPULATION_SIZE; i++){
for(j = 0; j < MAX_PROGRAM_LENGTH; j++){
pop[i][j] = chldrn[i][j];
}
}
// Release Memory Objects (Maybe to save some kernel memory
for(int i = 0; i < 9; i++)
{
clReleaseMemObject(memObjects[i]);
}
clReleaseKernel(kernel);
}
cout << "After: " << endl;
show_part_int(pop);
// for(i = 0; i < 10; i++){
// cout << "Generation " << i << " max run time = " << max_tournament_length[i] << endl;
// }
// cout << "." << endl;
// cout << "." << endl;
// cout << "." << endl;
// for(i = MAX_GENERATIONS - 10; i < MAX_GENERATIONS; i++){
// cout << "Generation " << i << " max run time = " << max_tournament_length[i] << endl;
// }
// Hacky cleanup
clFinish(commandQueue);
// We do this so that the application doesn't close right away on windows
cin.get();
return 0;
}
bool checkError(cl_int errNum)
{
if(errNum == CL_SUCCESS)
return false;
else
return true;
}
cl_context CreateContext(void)
{
cl_int errNum;
cl_uint numPlatforms;
cl_platform_id firstPlatformId;
cl_context context = NULL;
errNum = clGetPlatformIDs(1, &firstPlatformId, &numPlatforms);
if(errNum != CL_SUCCESS || numPlatforms <= 0)
{
printf("Failed to find any OpenCL platforms.\n");
return NULL;
}
cl_context_properties contextProperties[] =
{
CL_CONTEXT_PLATFORM,
(cl_context_properties)firstPlatformId,
0
};
context = clCreateContextFromType(contextProperties, CL_DEVICE_TYPE_GPU,
NULL, NULL, &errNum);
if(errNum != CL_SUCCESS)
{
printf("could not create GPU context, trying CPU...\n");
context = clCreateContextFromType(contextProperties,
CL_DEVICE_TYPE_CPU, NULL, NULL,
&errNum);
if(errNum != CL_SUCCESS)
{
printf("Failed to create an OpenCL GPU or CPU context.\n");
return NULL;
}
}
return context;
}
cl_command_queue CreateCommandQueue(cl_context context, cl_device_id *device)
{
cl_int errNum;
cl_device_id *devices;
cl_command_queue commandQueue = NULL;
size_t deviceBufferSize = -1;
errNum = clGetContextInfo(context, CL_CONTEXT_DEVICES, 0, NULL,
&deviceBufferSize);
if(errNum != CL_SUCCESS) {
printf("Failed called to clGetContextInf(..., CL_CONTEXT_DEVICES, ...)\n");
return NULL;
}
if(deviceBufferSize <= 0) {
printf("No devices available.\n");
return NULL;
}
devices = new cl_device_id[deviceBufferSize/sizeof(cl_device_id)];
errNum = clGetContextInfo(context, CL_CONTEXT_DEVICES, deviceBufferSize,
devices, NULL);
if(errNum != CL_SUCCESS) {
printf("Failed to get device IDs\n");
delete[] devices;
return NULL;
}
commandQueue = clCreateCommandQueue(context, devices[0], 0, NULL);
if(commandQueue == NULL) {
printf("Failed to create command Queue for device 0\n");
return NULL;
}
*device = devices[0];
delete [] devices;
return commandQueue;
}
cl_program CreateProgram(cl_context context, cl_device_id device,
const char* fileName)
{
cl_int errNum;
cl_program program;
ifstream kernelFile(fileName, ios::in);
if(!kernelFile.is_open()) {
printf("Failed to open file for reading: %s\n", fileName);
return NULL;
}
ostringstream oss;
oss << kernelFile.rdbuf();
string srcStdStr = oss.str();
const char *srcStr = srcStdStr.c_str();
program = clCreateProgramWithSource(context, 1, (const char**)&srcStr,
NULL, NULL);
if(program == NULL) {
printf("Failed to create CL program from source.\n");
return NULL;
}
// Fourth argument contains a string for opencl kernel preprocessor
// search directory, this allows us to use includes.
errNum = clBuildProgram(program, 0, NULL, "-I ./", NULL, NULL);
if(errNum != CL_SUCCESS) {
char buildLog[16384];
errNum = clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,
sizeof(buildLog), buildLog, NULL);
cout << "clGetProgramBuildInfo: " << errNum << endl;
cerr << "Error in kernel: " << endl;
cout << buildLog << endl;
clReleaseProgram(program);
return NULL;
}
return program;
}
bool CreateMemObjects(cl_context context,
cl_mem memObjects[9],
int pop[POPULATION_SIZE][MAX_PROGRAM_LENGTH],
int test[N_TOURNAMENTS],
int starts[N_TOURNAMENTS][N_PROGRAMS])
{
cl_int errNo;
// Example buffer objects
memObjects[0] = clCreateBuffer(context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(*pop),
pop, &errNo);
cout << "Cl Error: " << errNo << endl;
memObjects[7] = clCreateBuffer(context,
CL_MEM_WRITE_ONLY,
sizeof(int) * N_TOURNAMENTS, NULL, &errNo);
cout << "Cl Error: " << errNo << endl;
memObjects[8] = clCreateBuffer(context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(*starts),
starts, &errNo);
cout << "Cl Error: " << errNo << endl;
return true;
}
void clear_survivals(int survivals[POPULATION_SIZE])
{
int i;
for(i=0;i<POPULATION_SIZE;i++){
survivals[i] = 0;
}
return;
}
void gen_int_program(int prog[MAX_PROGRAM_LENGTH])
{
int i;
for(i = 0; i<MAX_PROGRAM_LENGTH; i++) {
// There are 13 instruction which fit into 4-bits
// Each variable is temporary so we can bitshift them the
// right direction.
unsigned tInst = (instruction) (rand() % N_OPERATIONS);
unsigned tMode_A = (addressing) (rand() % N_MODES);
int tArg_A = rand() % MEMORY_SIZE;
unsigned tMode_B = (addressing) (rand() % N_MODES);
int tArg_B = rand() % MEMORY_SIZE;
// We bitshift by the according number of bits we've given each
// type 4-bits for instruction, 2-bits for modes, and 12-bits for
// arguments. All numbers are unsigned except arguments which should
// be twos complement and are signed so they need an additional bit.
// e.g in our argument we have 11 data bits and 1 sign bit.
tInst<<=28;
tMode_A<<=26;
tArg_A<<=14;
tMode_B<<=12;
tArg_B<<=0;
prog[i] = tInst | tMode_A | tArg_A | tMode_B | tArg_B;
// We just need to make sure that the data makes sense.
//cout << (bitset<32>) prog[i] << endl;
}
}
// generates a program with random instructions
void generate_program(memory_cell prog[MAX_PROGRAM_LENGTH])
{
int i;
for(i=0;i<MAX_PROGRAM_LENGTH;i++){
prog[i].code = (instruction) (rand() % N_OPERATIONS);
prog[i].arg_A = rand() % MEMORY_SIZE;
prog[i].mode_A = (addressing) (rand() % N_MODES);
prog[i].arg_B = rand() % MEMORY_SIZE;
prog[i].mode_B = (addressing) (rand() % N_MODES);
}
}
// generates an array of programs
void generate_population(memory_cell pop[POPULATION_SIZE][MAX_PROGRAM_LENGTH])
{
int i;
for(i=0;i<POPULATION_SIZE;i++){
generate_program(pop[i]);
}
}
void gen_int_population(int pop[POPULATION_SIZE][MAX_PROGRAM_LENGTH])
{
int i;
for(i = 0; i<POPULATION_SIZE; i++) {
gen_int_program(pop[i]);
}
}
void generate_starts(int starts[N_PROGRAMS])
{
int i;
int programs_to_place;
int space_needed_for_programs;
int start_spaces_available;
int offset;
starts[0] = 0;
for(i=1;i<N_PROGRAMS;i++){
programs_to_place = N_PROGRAMS - i;
space_needed_for_programs = (programs_to_place + 1) * MAX_PROGRAM_LENGTH;
start_spaces_available = MEMORY_SIZE - starts[i-1] - space_needed_for_programs;
if(start_spaces_available != 0){
offset = rand() % start_spaces_available;
} else {
offset = 0;
}
starts[i] = starts[i-1] + MAX_PROGRAM_LENGTH + offset;
}
}
void breed(memory_cell father[MAX_PROGRAM_LENGTH],
memory_cell mother[MAX_PROGRAM_LENGTH],
memory_cell child[MAX_PROGRAM_LENGTH])
{
int cut_location;
int point_mutation;
int i;
cut_location = (rand() % (MAX_PROGRAM_LENGTH - 2)) + 1;
point_mutation = rand() % MAX_PROGRAM_LENGTH;
for(i=0;i<cut_location;i++){
child[i] = father[i];
}
for(i=cut_location;i<MAX_PROGRAM_LENGTH;i++){
child[i] = mother[i];
}
child[point_mutation].code = (instruction) (rand() % N_OPERATIONS);
child[point_mutation].arg_A = rand() % MEMORY_SIZE;
child[point_mutation].mode_A = (addressing) (rand() % N_MODES);
child[point_mutation].arg_B = rand() % MEMORY_SIZE;
child[point_mutation].mode_B = (addressing) (rand() % N_MODES);
return;
}
void breed_int(int father[MAX_PROGRAM_LENGTH],
int mother[MAX_PROGRAM_LENGTH],
int child[MAX_PROGRAM_LENGTH])
{
int cut_location;
int point_mutation;
int i;
unsigned tInst;
unsigned tMode_A;
int tArg_A;
unsigned tMode_B;
int tArg_B;
cut_location = (rand() % (MAX_PROGRAM_LENGTH -2)) + 1;
point_mutation = rand() % MAX_PROGRAM_LENGTH;
for(i = 0; i<cut_location; i++) {
child[i] = father[i];
}
for(i = cut_location; i<MAX_PROGRAM_LENGTH; i++) {
child[i] = mother[i];
}
// Generate our new values
tInst = (instruction) (rand() % N_OPERATIONS);
tMode_A = (addressing) (rand() % N_MODES);
tArg_A = rand() % MEMORY_SIZE;
tMode_B = (addressing) (rand() % N_MODES);
tArg_B = rand() % MEMORY_SIZE;
// Shift to correct locations
tInst<<=28;
tMode_A<<=26;
tArg_A<<=14;
tMode_B<<=12;
tArg_B<<=0;
child[point_mutation] = tInst | tMode_A | tArg_A |
tMode_B | tArg_B;
//cout << (bitset<32>) child[point_mutation] << endl;
}
int max_t_length(int t_lengths[N_TOURNAMENTS])
{
int max = 0;
int i;
for(i=0;i<N_TOURNAMENTS;i++){
if(t_lengths[i] > max){
max = t_lengths[i];
}
}
return max;
}
// really just for debugging
void show_part(memory_cell population[POPULATION_SIZE][MAX_PROGRAM_LENGTH])
{
int i;
for(i=0;i<10;i++){
cout << population[0][i] << endl;
}
return;
}
void show_part_int(int population[POPULATION_SIZE][MAX_PROGRAM_LENGTH])
{
int i;
for(i = 0; i<10; i++) {
int memObj = population[0][i];
unsigned int tInst;
unsigned int tMode_A;
int tArg_A;
unsigned int tMode_B;
int tArg_B;
// Binary and the memObj with a bitmask to get the correct var.
tInst = memObj & 0b11110000000000000000000000000000;
tInst>>=28;
tMode_A = memObj & 0b00001100000000000000000000000000;
tMode_A>>=26;
tArg_A = memObj & 0b00000011111111111100000000000000;
tArg_A>>=14;
tMode_B = memObj & 0b00000000000000000011000000000000;
tMode_B>>=12;
tArg_B = memObj & 0b00000000000000000000111111111111;
tArg_B>>=0;
/*
cout << "Inst: " << tInst;
cout << ", Mode A: " << tMode_A;
cout << ", Arg A: " << tArg_A;
cout << ", Mode B: " << tMode_B;
cout << ", Arg B: " << tArg_B << endl;
*/
switch(tInst) {
case DAT: cout << "DAT"; break;
case MOV: cout << "MOV"; break;
case ADD: cout << "ADD"; break;
case SUB: cout << "SUB"; break;
case MUL: cout << "MUL"; break;
case DIV: cout << "DIV"; break;
case MOD: cout << "MOD"; break;
case JMP: cout << "JMP"; break;
case JMZ: cout << "JMZ"; break;
case DJZ: cout << "DJZ"; break;
case CMP: cout << "CMP"; break;
case SPL: cout << "SPL"; break;
case NOP: cout << "NOP"; break;
default: cout << endl << "*** ERRR: no such instruction: "
<< tInst << " At Index: " << i << endl;
}
cout << " ";
switch(tMode_A) {
case IMM: cout << "#"; break;
case DIR: cout << "$"; break;
case IND: cout << "@"; break;
default: cout << endl << "*** ERROR: no such addressing mode: "
<< tMode_A << " At Index: " << i << endl;
}
cout << tArg_A << " ";
switch(tMode_B) {
case IMM: cout << "#"; break;
case DIR: cout << "$"; break;
case IND: cout << "@"; break;
default: cout << endl << "*** ERROR: no such addressing mode: "
<< tMode_B << " At Index: " << i << endl;
}
cout << tArg_B << " " << endl;
}
}
// Count how many have processes still running
int survivor_count(int n_proc[MAX_PROCESSES]){
int count = 0;
for(int i = 0; i < MAX_PROCESSES; i++){
if(n_proc[i] > 0){
count++;
}
}
return count;
}
ostream& operator<<(ostream& outs, const memory_cell& cell)
{
switch(cell.code){
case DAT: outs << "DAT"; break;
case MOV: outs << "MOV"; break;
case ADD: outs << "ADD"; break;
case SUB: outs << "SUB"; break;
case MUL: outs << "MUL"; break;
case DIV: outs << "DIV"; break;
case MOD: outs << "MOD"; break;
case JMP: outs << "JMP"; break;
case JMZ: outs << "JMZ"; break;
case DJZ: outs << "DJZ"; break;
case CMP: outs << "CMP"; break;
case SPL: outs << "SPL"; break;
case NOP: outs << "NOP"; break;
default: outs << endl << "*** ERROR: no such instruction ***" << endl;
}
outs << " ";
switch(cell.mode_A){
case IMM: outs << "#"; break;
case DIR: outs << "$"; break;
case IND: outs << "@"; break;
default: outs << endl << "*** ERROR: no such addressing mode" << endl;
}
outs << cell.arg_A << " ";
switch(cell.mode_B){
case IMM: outs << "#"; break;
case DIR: outs << "$"; break;
case IND: outs << "@"; break;
default: outs << endl << "*** ERROR: no such addressing mode" << endl;
}
outs << cell.arg_B;
return outs;
}
| bsd-2-clause |
paxswill/evesrp | src/evesrp/views/divisions.py | 14237 | from __future__ import absolute_import
from flask import url_for, render_template, redirect, abort, flash, request,\
Blueprint, current_app
from flask_babel import gettext, lazy_gettext
from flask_login import login_required, fresh_login_required, current_user
from flask_wtf import Form
import six
from six.moves import map
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from wtforms.fields import StringField, SubmitField, HiddenField, SelectField,\
Label
from wtforms.validators import InputRequired, AnyOf, NumberRange
from ..models import db
from ..auth import PermissionType
from ..auth.models import Division, Permission, Entity
from ..util import jsonify, varies
blueprint = Blueprint('divisions', __name__)
@blueprint.route('/')
@fresh_login_required
def permissions():
"""Show a page listing all divisions.
"""
if current_user.admin:
return render_template('divisions.html',
divisions=Division.query.all())
if current_user.has_permission(PermissionType.admin):
admin_permissions = current_user.permissions.filter_by(
permission=PermissionType.admin).values(Permission.division_id)
admin_permissions = map(lambda x: x[0], admin_permissions)
divisions = db.session.query(Division).\
filter(Division.id.in_(admin_permissions))
return render_template('divisions.html', divisions=divisions)
return render_template('permissions.html')
return abort(403)
class AddDivisionForm(Form):
# TRANS: On a form for creating a new division, this is a label for the
# TRANS: name of the division.
name = StringField(lazy_gettext(u'Division Name'),
validators=[InputRequired()])
# TRANS: On a form for creating a new division, this is a button for
# TRANS: creating a new division (by submitting the form).
submit = SubmitField(lazy_gettext(u'Create Division'))
@blueprint.route('/add/', methods=['GET', 'POST'])
@fresh_login_required
def add_division():
"""Present a form for adding a division and also process that form.
Only accesible to adminstrators.
"""
if not current_user.admin:
return abort(403)
form = AddDivisionForm()
if form.validate_on_submit():
division = Division(form.name.data)
db.session.add(division)
db.session.commit()
return redirect(url_for('.get_division_details',
division_id=division.id))
return render_template('form.html', form=form,
# TRANS: The title for a page for creating new divisions.
title=gettext(u'Create Division'))
class ChangeEntity(Form):
form_id = HiddenField(default='entity')
id_ = HiddenField()
name = StringField()
permission = HiddenField(validators=[AnyOf(list(PermissionType.values()))])
action = HiddenField(validators=[AnyOf(('add', 'delete'))])
#: List of tuples enumerating attributes that can be transformed/linked.
#: Mainly used as the choices argument to :py:class:`~.SelectField`
transformer_choices = [
('', u''),
# TRANS: Label for fields showing the name of a pilot.
('pilot', lazy_gettext(u'Pilot')),
# TRANS: Label for the corporation a pilot is in.
('corporation', lazy_gettext(u'Corporation')),
# TRANS: Label for the alliance a pilot is in.
('alliance', lazy_gettext(u'Alliance')),
# TRANS: Label for the solar system a loss occured in.
('system', lazy_gettext(u'Solar System')),
# TRANS: Label for the constellation a loss occured in.
('constellation', lazy_gettext(u'Constellation')),
# TRANS: Label for the region a loss occured in.
('region', lazy_gettext(u'Region')),
# TRANS: Label for the type of ship that was lost.
('ship_type', lazy_gettext(u'Ship')),
# TRANS: Label for the status a request is in (ex: Unevaluated, Approved)
('status', lazy_gettext(u'Request Status')),
]
class ChangeTransformer(Form):
form_id = HiddenField(default='transformer')
# TRANS: The a label for a selection field for selecting which attribute
# TRANS: to transform. See the translation for 'Attribute Transformer'.
attribute = SelectField(lazy_gettext(u'Attribute'),
choices=transformer_choices)
# TRANS: The label for a selection field for selecting the transformer for
# TRANS: an attribute. See the translation for 'Attribute Transformer'.
transformer = SelectField(lazy_gettext(u'Transformer'), choices=[])
def transformer_choices(attr):
"""Conveniece function for generating a list of transformer option tuples.
:param attr str: the name of the attribute to make a list for.
:return: A list of tuples suitable for the choices argument of\
:py:class:`StringField`
:rtype: list
"""
default_transformers = [
('none', 'None'),
]
choices = default_transformers
if attr in current_app.url_transformers:
for transformer in current_app.url_transformers[attr]:
choices.append((transformer, transformer))
return choices
@blueprint.route('/<int:division_id>/', methods=['GET'])
@fresh_login_required
@varies('Accept', 'X-Requested-With')
def get_division_details(division_id=None, division=None):
"""Generate a page showing the details of a division.
Shows which groups and individuals have been granted permissions to each
division.
Only accesible to administrators.
:param int division_id: The ID number of the division
"""
if division is None:
division = Division.query.get_or_404(division_id)
if not current_user.admin and not \
current_user.has_permission(PermissionType.admin, division):
abort(403)
if request.is_json or request.is_xhr:
return jsonify(division._json(True))
return render_template(
'division_detail.html',
division=division,
entity_form=ChangeEntity(formdata=None),
transformer_form=ChangeTransformer(formdata=None),
)
def _modify_division_entity(division):
"""Handle POST requests for adding/removing entities form a Division."""
form = ChangeEntity()
if form.validate():
entity = None
if form.id_.data != '':
current_app.logger.debug("Looking up entity by ID: {}".format(
form.id_.data))
entity = Entity.query.get(form.id_.data)
if entity is None:
# TRANS: This is an error message when there's a problem
# TRANS: granting a permission to a user or group
# TRANS: (collectively called 'entities'). The '#' is not
# TRANS: special, but the '%s(in_num)d' will be replaced with
# TRANS: the ID number that was attempted to be added.
flash(gettext(u"No entity with ID #%(id_num)d.",
id_num=form.id_.data),
category=u'error')
else:
current_app.logger.debug(u"Looking up entity by name: '{}'"\
.format(form.name.data))
try:
entity = Entity.query.filter_by(
name=form.name.data).one()
except NoResultFound:
# TRANS: Error message when a user or group with a given name
# TRANS: cannot be found.
flash(gettext(u"No entities with the name '%(name)s' found.",
name=form.name.data),
category=u'error')
except MultipleResultsFound:
# TRANS: Error message when multiple users and/or groups are
# TRANS: found with a given name.
flash(gettext(
u"Multiple entities with the name '%(name)s' found.",
name=form.name.data),
category=u'error')
else:
current_app.logger.debug("entity lookup success")
if entity is None:
return get_division_details(division=division), 404, None
# The entity has been found, create the query for the requested
# Permission.
permission_type = PermissionType.from_string(
form.permission.data)
permission_query = Permission.query.filter_by(
division=division,
entity=entity,
permission=permission_type)
# The response for both add and delete actions depends on whether the
# Permission is found, so look it up first.
try:
permission = permission_query.one()
except NoResultFound:
if form.action.data == 'add':
db.session.add(
Permission(division, permission_type, entity))
# TRANS: Message show when granting a permission to a user or
# TRANS: group.
flash(gettext(u"%(name)s is now a %(role)s.",
name=entity,
role=permission_type.description.lower()),
category=u"info")
elif form.action.data == 'delete':
# TRANS: Message shown when trying to remove a permission from
# TRANS: a user, but that user didn't have that permission
# TRANS: already.
flash(gettext(u"%(name)s is not a %(role)s.",
name=entity,
role=permission_type.description.lower()),
category=u"warning")
else:
if form.action.data == 'delete':
permission_query.delete()
# TRANS: Confirmation message shown when revoking a permission
# TRANS: from a user or group.
flash(gettext(u"%(name)s is no longer a %(role)s.",
name=entity,
role=permission_type.description.lower()),
category=u"info")
elif form.action.data == 'add':
flash(gettext(u"%(name)s is now a %(role)s.",
name=entity,
role=permission_type.description.lower()),
category=u"info")
db.session.commit()
else:
for field_name, errors in six.iteritems(form.errors):
errors = u", ".join(errors)
# TRANS: Error message that is shown when one or more fields of a
# TRANS: form are shown.
flash(gettext(u"Errors for %(field_name)s: %(error)s.",
field_name=field_name, error=errors), u'error')
current_app.logger.info("Malformed entity permission POST: {}".format(
form.errors))
return get_division_details(division=division)
def _modify_division_transformer(division):
"""Handle POST requests for changing the Transformers for a Division."""
form = ChangeTransformer()
# Set the form's choices
attr = form.attribute.data
form.transformer.choices = transformer_choices(attr)
# Check form and go from there
if form.validate():
name = form.transformer.data
if name == 'none':
division.transformers[attr] = None
else:
# Get the specific map of transformers for the attribute
attr_transformers = current_app.url_transformers[attr]
# Get the new transformer
division.transformers[attr] = attr_transformers[name]
# Explicitly add the TransformerRef to the session
db.session.add(division.division_transformers[attr])
db.session.commit()
# TRANS: Confirmation message shown when a transformer for an
# TRANS: attribute has been set.
flash(gettext(u"'%(attribute)s' set to '%(transformer)s'.",
attribute=attr, transformer=name), u'message')
else:
for field_name, errors in six.iteritems(form.errors):
errors = u", ".join(errors)
# TRANS: Generic error message shown for the fields in a form.
flash(gettext(u"Errors for %(field_name)s: %(error)s.",
field_name=field_name, error=errors), u'error')
current_app.logger.info("Malformed division transformer POST: {}".
format(form.errors))
return get_division_details(division=division)
@blueprint.route('/<int:division_id>/', methods=['POST'])
@fresh_login_required
def modify_division(division_id):
"""Dispatches modification requests to the specialized view function for
that operation.
"""
division = Division.query.get_or_404(division_id)
if not current_user.admin and not \
current_user.has_permission(PermissionType.admin, division):
abort(403)
form_id = request.form.get('form_id')
if form_id == 'entity':
return _modify_division_entity(division)
elif form_id == 'transformer':
return _modify_division_transformer(division)
else:
current_app.logger.warn("Invalid division modification POST: {}"
.format(request.form))
abort(400)
@blueprint.route('/<int:division_id>/transformers/')
@blueprint.route('/<int:division_id>/transformers/<attribute>/')
@login_required
def list_transformers(division_id, attribute=None):
"""API method to get a list of transformers for a division.
:param division_id int: the ID of the division to look up
:param attribute str: a specific attribute to look up. Optional.
:return: JSON
"""
division = Division.query.get_or_404(division_id)
if not current_user.admin and not \
current_user.has_permission(PermissionType.admin, division):
abort(403)
if attribute is None:
attrs = six.iterkeys(current_app.url_transformers)
else:
attrs = (attribute,)
choices = {}
for attr in attrs:
raw_choices = transformer_choices(attr)
current = division.transformers.get(attr, None)
if current is not None:
choices[attr] = \
[(c[0], c[1], c[1] == current.name) for c in raw_choices]
else:
choices[attr] = \
[(c[0], c[1], False) for c in raw_choices]
return jsonify(choices)
| bsd-2-clause |
wycats/protobuf | src/protobuf/lib.rs | 476 | #[link(name = "protobuf", vers = "0.1.0")];
#[crate_type = "lib"];
#[feature(globs)];
#[feature(managed_boxes)];
#[desc = "protobuf implementation for rust"];
#[license = "BSD"];
#[author = "Stepan Koltsov"];
pub use core::*;
mod core;
pub mod descriptor;
pub mod codegen;
pub mod rt;
mod misc;
mod zigzag;
mod hex;
// so `use protobuf::*` could work in descriptor mod
pub mod protobuf {
pub use descriptor;
pub use codegen;
pub use core::*;
pub use rt;
}
| bsd-2-clause |
Linuxbrew/homebrew-core | Formula/fastme.rb | 1590 | class Fastme < Formula
desc "Accurate and fast distance-based phylogeny inference program"
homepage "http://www.atgc-montpellier.fr/fastme/"
url "https://gite.lirmm.fr/atgc/FastME/raw/v2.1.6.1/tarball/fastme-2.1.6.1.tar.gz"
sha256 "ac05853bc246ccb3d88b8bc075709a82cfe096331b0f4682b639f37df2b30974"
revision OS.mac? ? 3 : 4
bottle do
sha256 arm64_big_sur: "a63f7a94429ad21604091dbec3fa347d83c81f335a0e112e3a601975c26593f3"
sha256 cellar: :any, big_sur: "57efef94306e3b9dcbaa2b91289951b545b4ae49cdfe14fb444903e145485a49"
sha256 cellar: :any, catalina: "0024bfdb601cd133d2d7a544fa04bb8ad6650f846eba08310a7d69458432d591"
sha256 cellar: :any, mojave: "a685f1feb457d32b6df4444edec59913957347ae5bb3e3374ffedf334d07b210"
sha256 cellar: :any_skip_relocation, x86_64_linux: "e975f7a641a215a4d8c8b0826907dbdc2e05b6cee616bf5ea718f50b850fb0ba"
end
on_macos do
depends_on "gcc"
end
fails_with :clang # no OpenMP support
def install
system "./configure", "--disable-debug",
"--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make", "install"
end
test do
(testpath/"test.dist").write <<~EOS
4
A 0.0 1.0 2.0 4.0
B 1.0 0.0 3.0 5.0
C 2.0 3.0 0.0 6.0
D 4.0 5.0 6.0 0.0
EOS
system "#{bin}/fastme", "-i", "test.dist"
assert_predicate testpath/"test.dist_fastme_tree.nwk", :exist?
end
end
| bsd-2-clause |
dreamsxin/ultimatepp | uppsrc/Geom/linsolv.cpp | 2779 | #include "Geom.h"
NAMESPACE_UPP
LinearSolver::LinearSolver(int count, double tolerance)
: rows(count)
, col1(count + 1)
, tolerance(tolerance)
{
ASSERT(tolerance >= 0);
matrix.SetCount(count * (count + 1), 0);
left_rows.SetCount(rows);
left_cols.SetCount(rows);
for(int i = 0; i < rows; i++)
left_rows[i] = left_cols[i] = i;
}
void LinearSolver::AddLSI(const double *bases, double value)
{
double *row = matrix.Begin();
const double *bi = bases;
for(int i = 0; i < rows; i++) {
const double *bj = bases;
for(int j = 0; j < rows; j++)
*row++ += *bi * *bj++;
*row++ += *bi++ * value;
}
}
Vector<double> LinearSolver::Solve()
{
while(!left_rows.IsEmpty())
{
int er = -1, ec = -1;
double best = tolerance;
for(int pr = 0; pr < left_rows.GetCount(); pr++)
{
const double *p = Row(left_rows[pr]);
for(int pc = 0; pc < left_cols.GetCount(); pc++)
{
double v = fabs(p[left_cols[pc]]);
if(v > best)
{
best = v;
ec = pc;
er = pr;
}
}
}
if(er < 0 || best <= 0) // just to be sure
{ // no more fixed variables
for(int i = 0; i < left_rows.GetCount(); i++)
if(fabs(Right(left_rows[i])) > tolerance)
return Vector<double>(); // error
break;
}
int cr = left_rows[er], cc = left_cols[ec];
int p = left_rows.Pop();
if(er < left_rows.GetCount()) left_rows[er] = p;
p = left_cols.Pop();
if(ec < left_cols.GetCount()) left_cols[ec] = p;
const double *src = Row(cr);
const int *xb = left_cols.Begin(), *xe = left_cols.End();
for(int i = 0; i < left_rows.GetCount(); i++)
{
double *dest = Row(left_rows[i]);
double r = -dest[cc] / src[cc];
for(const int *xp = xb; xp < xe; xp++)
dest[*xp] += src[*xp] * r;
dest[rows] += src[rows] * r;
}
pivots.Add(Point(cc, cr));
}
Vector<double> result;
result.SetCount(rows, Null);
for(int r = pivots.GetCount(); --r >= 0;)
{
Point pivot = pivots[r];
const double *row = Row(pivot.y);
int px = pivot.x;
double out = row[rows]; // right side
for(int s = r; ++s < pivots.GetCount();)
{
int c = pivots[s].x;
out -= row[c] * result[c];
}
result[pivot.x] = out / row[pivot.x];
}
return result;
}
void LinearSolver::SelfTest()
{
for(int i = 0; i < 1000; i++)
{
int ord = rand() % 10 + 1;
Vector<double> res;
while(res.GetCount() < ord)
res.Add(rand());
LinearSolver ls(ord);
for(int r = 0; r < ord; r++)
{
double rs = 0;
for(int c = 0; c < ord; c++)
rs += res[c] * (ls(r, c) = rand());
ls(r) = rs;
}
Vector<double> out = ls.Solve();
if(!out.IsEmpty())
{
ASSERT(out.GetCount() == ord);
for(int c = 0; c < out.GetCount(); c++)
if(!IsNull(out[c]))
{
double d = out[c] - res[c];
ASSERT(fabs(d) <= 1e-3);
}
}
}
}
END_UPP_NAMESPACE
| bsd-2-clause |
Linuxbrew/homebrew-core | Formula/hfstospell.rb | 1573 | class Hfstospell < Formula
desc "Helsinki Finite-State Technology ospell"
homepage "https://hfst.github.io/"
url "https://github.com/hfst/hfst-ospell/releases/download/v0.5.2/hfst-ospell-0.5.2.tar.bz2"
sha256 "ab9ccf3c2165c0efd8dd514e0bf9116e86a8a079d712c0ed6c2fabf0052e9aa4"
license "Apache-2.0"
revision 2
livecheck do
url :stable
strategy :github_latest
end
bottle do
sha256 cellar: :any, arm64_big_sur: "1a5437ebb7e8abeae096734d53edbbc8cf154f6635f8e15ac3a1cfa038782e85"
sha256 cellar: :any, big_sur: "6fb2851153c12aa38ed01a7335781df78be3490380e6713b2a9c642f88e737d0"
sha256 cellar: :any, catalina: "0651d2057fcf3c0242bcd277b0ddafb247c0f00fc78d2652e9eae9c82776f923"
sha256 cellar: :any, mojave: "25a4f7bfe15fae7efd0ce6cf1ccedb150571935de5e0266cbf7fa472290bbf6d"
sha256 cellar: :any_skip_relocation, x86_64_linux: "ea2697fe154ae351227cb6a249248657bc94239acaf19fafffb8cd99b36eb5d2"
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "pkg-config" => :build
depends_on "icu4c"
depends_on "libarchive"
def install
ENV.cxx11
system "autoreconf", "-fiv"
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--without-libxmlpp",
"--prefix=#{prefix}"
system "make", "install"
end
test do
system "#{bin}/hfst-ospell", "--version"
end
end
| bsd-2-clause |
mDibyo/berkeley-scheduler | client/ts/angular/timePicker.directive.ts | 2315 | import angular = require('angular');
import BaseCtrl = require('./_base.controller');
import Time = require('../models/time');
import SchedulingOptionsService from "./schedulingOptions.service";
interface timePickerDirectiveScope extends angular.IScope {
applyClass?: string;
model: Time;
label?: string;
timeOptions?: Time[];
onChange?: any;
}
function bsTimePickerDirective() {
const defaultTimeOptions: Time[] = [];
const startHour = 0;
const endHour = 24;
let h = startHour;
for (; h < endHour; h++) {
defaultTimeOptions.push(new Time(h, 0));
defaultTimeOptions.push(new Time(h, 30));
}
defaultTimeOptions.push(new Time(h, 0));
class bsTimePickerCtrl extends BaseCtrl {
selectedTime?: Time;
constructor(
$state: angular.ui.IStateService,
$window: angular.IWindowService,
private $timeout: angular.ITimeoutService,
private $scope: timePickerDirectiveScope,
schedulingOptionsService: SchedulingOptionsService
) {
super($state, $window, schedulingOptionsService);
$scope.applyClass = $scope.applyClass || '';
$scope.timeOptions = $scope.timeOptions || defaultTimeOptions;
this.selectedTime = $scope.model;
}
timeIsSelected(time: Time): boolean {
if (!this.$scope.model) {
return false;
}
return this.$scope.model.hours === time.hours
&& this.$scope.model.minutes === time.minutes;
}
save() {
if (this.selectedTime) {
const newTime = Time.parse(this.selectedTime);
if (!this.$scope.model || this.$scope.model.compareTo(newTime) !== 0) {
this.$scope.model = newTime;
if (this.$scope.onChange) {
this.$timeout(() => this.$scope.onChange({time: this.$scope.model}));
}
}
}
}
}
return {
scope: {
applyClass: '@?',
model: '=',
label: '=?',
timeOptions: '=?',
onChange: '&?'
},
controller: [
'$state',
'$window',
'$timeout',
'$scope',
'schedulingOptionsService',
bsTimePickerCtrl
],
controllerAs: 'vm',
templateUrl: 'assets/static/html/time_picker.partial.html'
}
}
angular.module('berkeleyScheduler').directive('bsTimePicker', [
bsTimePickerDirective
]);
| bsd-2-clause |
dmurph/protobee | core-tests/src/main/java/org/protobee/compatability/ProtocolModuleFilterTests.java | 4443 | package org.protobee.compatability;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
import org.protobee.compatability.CompatabilityHeader;
import org.protobee.compatability.Headers;
import org.protobee.modules.ProtocolModule;
import org.protobee.session.SessionProtocolModules;
import org.protobee.session.handshake.ProtocolModuleFilter;
import org.protobee.util.VersionComparator;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.eventbus.EventBus;
public class ProtocolModuleFilterTests {
@Headers(required = {@CompatabilityHeader(name = "a", minVersion = "1", maxVersion = "2")}, requested = {})
private static class a12 extends ProtocolModule {}
@Headers(required = {@CompatabilityHeader(name = "a", minVersion = "2", maxVersion = "+")}, requested = {})
private static class a2plus extends ProtocolModule {}
@Headers(required = {}, silentExcluding={@CompatabilityHeader(name = "a", minVersion = "0.1", maxVersion = "+")})
private static class noa extends ProtocolModule {}
@Test
public void testLowerVersion() {
Set<ProtocolModule> modules = Sets.newHashSet((ProtocolModule) new a12());
SessionProtocolModules pmodules = new SessionProtocolModules(modules);
EventBus bus = mock(EventBus.class);
ProtocolModuleFilter filter = new ProtocolModuleFilter(new VersionComparator(), pmodules, bus);
Map<String, String> httpHeaders = Maps.newHashMap();
httpHeaders.put("a", "0");
filter.filterModules(httpHeaders);
assertEquals(0, pmodules.getMutableModules().size());
}
@Test
public void testRequiredNotPresent() {
Set<ProtocolModule> modules = Sets.newHashSet((ProtocolModule) new a12());
SessionProtocolModules pmodules = new SessionProtocolModules(modules);
EventBus bus = mock(EventBus.class);
ProtocolModuleFilter filter = new ProtocolModuleFilter(new VersionComparator(), pmodules, bus);
Map<String, String> httpHeaders = Maps.newHashMap();
filter.filterModules(httpHeaders);
assertEquals(0, pmodules.getMutableModules().size());
}
@Test
public void testToHigh() {
Set<ProtocolModule> modules = Sets.newHashSet((ProtocolModule) new a12());
SessionProtocolModules pmodules = new SessionProtocolModules(modules);
EventBus bus = mock(EventBus.class);
ProtocolModuleFilter filter = new ProtocolModuleFilter(new VersionComparator(), pmodules, bus);
Map<String, String> httpHeaders = Maps.newHashMap();
httpHeaders.put("a", "3");
filter.filterModules(httpHeaders);
assertEquals(0, pmodules.getMutableModules().size());
}
@Test
public void testFits() {
Set<ProtocolModule> modules = Sets.newHashSet((ProtocolModule) new a12());
SessionProtocolModules pmodules = new SessionProtocolModules(modules);
EventBus bus = mock(EventBus.class);
ProtocolModuleFilter filter = new ProtocolModuleFilter(new VersionComparator(), pmodules, bus);
Map<String, String> httpHeaders = Maps.newHashMap();
httpHeaders.put("a", "1.5");
filter.filterModules(httpHeaders);
assertEquals(1, pmodules.getMutableModules().size());
}
@Test
public void testAboveExpandable() {
Set<ProtocolModule> modules = Sets.newHashSet((ProtocolModule) new a2plus());
SessionProtocolModules pmodules = new SessionProtocolModules(modules);
EventBus bus = mock(EventBus.class);
ProtocolModuleFilter filter = new ProtocolModuleFilter(new VersionComparator(), pmodules, bus);
Map<String, String> httpHeaders = Maps.newHashMap();
httpHeaders.put("a", "4");
filter.filterModules(httpHeaders);
assertEquals(1, pmodules.getMutableModules().size());
}
@Test
public void testRemoveSilently() {
Set<ProtocolModule> modules = Sets.<ProtocolModule>newHashSet(new a2plus(), new noa());
SessionProtocolModules pmodules = new SessionProtocolModules(modules);
EventBus bus = mock(EventBus.class);
ProtocolModuleFilter filter = new ProtocolModuleFilter(new VersionComparator(), pmodules, bus);
Map<String, String> httpHeaders = Maps.newHashMap();
httpHeaders.put("a", "4");
filter.filterModules(httpHeaders);
assertEquals(1, pmodules.getMutableModules().size());
}
}
| bsd-2-clause |
tidepool-org/platform | data/types/dosingdecision/test/insulin_on_board.go | 888 | package test
import (
dataTypesDosingDecision "github.com/tidepool-org/platform/data/types/dosingdecision"
"github.com/tidepool-org/platform/pointer"
"github.com/tidepool-org/platform/test"
)
func RandomInsulinOnBoard() *dataTypesDosingDecision.InsulinOnBoard {
datum := dataTypesDosingDecision.NewInsulinOnBoard()
datum.StartTime = pointer.FromTime(test.RandomTime())
datum.Amount = pointer.FromFloat64(test.RandomFloat64FromRange(dataTypesDosingDecision.InsulinOnBoardAmountMinimum, dataTypesDosingDecision.InsulinOnBoardAmountMaximum))
return datum
}
func CloneInsulinOnBoard(datum *dataTypesDosingDecision.InsulinOnBoard) *dataTypesDosingDecision.InsulinOnBoard {
if datum == nil {
return nil
}
clone := dataTypesDosingDecision.NewInsulinOnBoard()
clone.StartTime = pointer.CloneTime(datum.StartTime)
clone.Amount = pointer.CloneFloat64(datum.Amount)
return clone
}
| bsd-2-clause |
ericmorand/twing | test/tests/integration/fixtures/tags/use/inheritance.ts | 824 | import TestBase from "../../../TestBase";
export default class extends TestBase {
getDescription() {
return '"use" tag';
}
getTemplates() {
return {
'ancestor.twig': `
{% block container %}
<div class="container">{{ block('sub_container') }}</div>
{% endblock %}
{% block sub_container %}
<div class="sub_container">sub_container</div>
{% endblock %}`,
'index.twig': `
{% use "parent.twig" %}
{{ block('container') }}`,
'parent.twig': `
{% use "ancestor.twig" %}
{% block sub_container %}
<div class="overridden_sub_container">overridden sub_container</div>
{% endblock %}`
};
}
getExpected() {
return `
<div class="container"> <div class="overridden_sub_container">overridden sub_container</div>
</div>`;
}
}
| bsd-2-clause |
stelfrich/imagej-ops | src/test/java/net/imagej/ops/logic/AndConditionTest.java | 2589 | /*
* #%L
* ImageJ software for multidimensional image processing and analysis.
* %%
* Copyright (C) 2014 - 2016 Board of Regents of the University of
* Wisconsin-Madison, University of Konstanz and Brian Northan.
* %%
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package net.imagej.ops.logic;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import net.imagej.ops.AbstractOpTest;
import net.imglib2.type.logic.BoolType;
import org.junit.Test;
/** Tests {@link AndCondition}. */
public class AndConditionTest extends AbstractOpTest {
@Test
public void test() {
@SuppressWarnings("unchecked")
final Condition<Double> c1 = ops.op(ComparableGreaterThan.class,
Double.class, 3.0);
@SuppressWarnings("unchecked")
final Condition<Double> c2 = ops.op(ComparableLessThan.class, Double.class,
6.0);
final BoolType result = (BoolType) ops.run(AndCondition.class, 5.0, c1, c2);
assertTrue(result.get());
final BoolType result2 = (BoolType) ops.run(AndCondition.class, 2.0, c1,
c2);
assertFalse(result2.get());
final BoolType result3 = (BoolType) ops.run(AndCondition.class, 7.0, c1,
c2);
assertFalse(result3.get());
final BoolType result4 = (BoolType) ops.run(AndCondition.class, Double.NaN,
c1, c2);
assertFalse(result4.get());
}
}
| bsd-2-clause |
bobmagicii/atlantis | core/Atlantis/Struct/PopularPost.php | 297 | <?php
namespace Atlantis\Struct;
use
\Atlantis as Atlantis;
class PopularPost {
public Atlantis\Prototype\BlogPost $Post;
public int $Views = 0;
public function
__Construct(Atlantis\Prototype\BlogPost $Post, Int $Views) {
$this->Post = $Post;
$this->Views = $Views;
return;
}
}
| bsd-2-clause |
Norad-Eduapp4syria/Norad-Eduapp4syria | finalApprovedVersion/Antura/EA4S_Antura_U3D/Assets/_games/_common/_scripts/UIGadgets/RadialGadget.cs | 1833 | // Author: Daniele Giardini - http://www.demigiant.com
// Created: 2016/11/09
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
namespace EA4S
{
public class RadialGadget : MonoBehaviour
{
public Image Radial;
public bool IsPulsing { get; private set; }
Tween pulseTween;
#region Unity
void Awake()
{
pulseTween = Radial.transform.DOScale(Radial.transform.localScale * 1.05f, 0.3f).SetEase(Ease.InOutQuad).SetLoops(-1, LoopType.Yoyo)
.SetAutoKill(false).Pause();
}
void OnDestroy()
{
pulseTween.Kill();
}
#endregion
#region Public Methods
/// <summary>
/// Sets the timer at the given percentage, 0 to 1
/// </summary>
/// <param name="_percentage">Fill percentage, 0 to 1 (fills counterclockwise, contrary to minigamesUI timer)</param>
/// <param name="_pulse">If TRUE also pulses the filled percentage, otherwise stops any pulsing already playing
/// (same as calling <code>PulseOn</code> or <code>PulseOff</code> after setting the percentage)</param>
public void SetPercentage(float _percentage, bool _pulse = true)
{
Radial.fillAmount = _percentage;
if (_pulse) PulseOn();
else PulseOff();
}
/// <summary>
/// Starts the pulsing of the filled percentage
/// </summary>
public void PulseOn()
{
IsPulsing = true;
pulseTween.PlayForward();
}
/// <summary>
/// Stops the pulsing of the filled percentage
/// </summary>
public void PulseOff()
{
IsPulsing = false;
pulseTween.Rewind();
}
#endregion
}
} | bsd-2-clause |
zhester/hzpy | modules/dbschema.py | 7294 | #!/usr/bin/env python
##############################################################################
#
# dbschema.py
#
# Abstracts representation of a database's structure. Allows modules to
# define entire schemas in a compact representation, and then build the
# appropriate queries to create, synchronize, backup, and restore the
# structure of a database.
#
# Schemas are free-form node graphs represented by nested dictionaries in
# Python, and stored as JSON files.
#
# The target database API for the generated queries is sqlite3.
#
##############################################################################
# Minimal example of the schema document structure
_example_schema = """
{
"serial" : 20130612,
"tables" : [
{
"name" : "example",
"columns" : [
{
"name" : "id",
"type" : "integer",
"null" : false
},
{
"name" : "name",
"type" : "text",
"default" : "",
"null" : false
},
{
"name" : "age",
"type" : "integer"
},
{
"name" : "compkey",
"type" : "integer"
}
],
"indexes" : [
[ "name" ],
[ "age", "compkey" ]
],
"initdata" : [
[ 1, "adam", 11, 8 ],
[ 2, "baker", 12, 5 ],
[ 3, "charlie", 13, 4 ]
]
}
]
}
"""
#=============================================================================
class dbdict( dict ):
"""
Extends the basic dictionary type to enable auto-loading existing
dictionaries, and dot-style element access.
"""
# Statically assign attribute access methods to dictionary access methods.
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
#=========================================================================
def __init__( self, data = {} ):
"""
Initialize the dbdict instance.
"""
super( dbdict, self ).__init__( data )
#=============================================================================
class dbcolumn( dbdict ):
#=========================================================================
def __init__( self, table, schema, prikey = False ):
super( dbcolumn, self ).__init__( schema )
self.table = table
self.prikey = prikey
#=========================================================================
def __str__( self ):
s = '%s %s' % ( self.name, self.type )
if ( 'null' in self ) and ( self.null == False ):
s += ' not null'
if 'default' in self:
s += " default '%s'" % self.default
if self.prikey == True:
s += ' primary key'
return s
#=============================================================================
class dbindex( list ):
#=========================================================================
def __init__( self, table, schema ):
super( dbindex, self ).__init__( schema )
self.table = table
#=========================================================================
def __str__( self ):
return 'create index %s_i on %s (%s)' % (
'_'.join( self ),
self.table.name,
','.join( self )
)
#=============================================================================
class dbtable( dbdict ):
#=========================================================================
def __init__( self, schema ):
super( dbtable, self ).__init__( schema )
self.dbcolumns = []
self.dbindexes = []
first = True
for c in self.columns:
self.dbcolumns.append( dbcolumn( self, c, first ) )
first = False
for i in self.indexes:
self.dbindexes.append( dbindex( self, i ) )
#=========================================================================
def __str__( self ):
return 'create table %s (\n %s\n)' % (
self.name,
',\n '.join( [ str( c ) for c in self.dbcolumns ] )
)
#=========================================================================
def get_column_names( self ):
return [ c.name for c in self.dbcolumns ]
#=========================================================================
def get_columns( self ):
return self.dbcolumns
#=========================================================================
def get_indexes( self ):
return self.dbindexes
#=========================================================================
def get_init_data( self ):
markers = ','.join( [ '?' ] * len( self.columns ) )
q = 'insert into %s values (%s)' % ( self.name, markers )
return { 'query' : q, 'values' : self.initdata }
#=============================================================================
class dbschema( dbdict ):
#=========================================================================
def __init__( self, schema ):
super( dbdict, self ).__init__( schema )
#=========================================================================
def get_table_by_name( self, name ):
for t in self.tables:
if t[ 'name' ] == name:
return dbtable( t )
return None
#=============================================================================
def main( argv ):
""" Script execution entry point """
import argparse
import json
# Create and configure an argument parser
parser = argparse.ArgumentParser(
description = 'Development and testing script for dbschema module.'
)
parser.add_argument(
'-j', '--json', default = None,
help = 'Load schema from JSON file for testing'
)
parser.add_argument(
'-t', '--table', default = None,
help = 'Specify table to display'
)
# The parser only wants the arguments (not the program "argument")
args = parser.parse_args( argv[ 1 : ] )
# See if the user wants to check out their own JSON schema
if args.json != None:
schema = json.load( arts.json )
else:
schema = json.loads( _example_schema )
# Initialize the schema object
dbs = dbschema( schema )
# Check for a table to display
if args.table != None:
table_name = args.table
else:
table_name = 'example'
# Demonstrate query generation
table = dbs.get_table_by_name( table_name )
print str( table )
indexes = table.get_indexes()
for i in indexes:
print str( i )
data = table.get_init_data()
print data[ 'query' ]
for d in data[ 'values' ]:
print ' %s' % ','.join( [ str( v ) for v in d ] )
# Return success.
return 0
#=============================================================================
if __name__ == "__main__":
import sys
sys.exit( main( sys.argv ) )
| bsd-2-clause |
Submanifold/psalm | SubdivisionAlgorithms/DooSabin.cpp | 13863 | /*!
* @file DooSabin.cpp
* @brief Implementation of Doo and Sabin's subdivision scheme
*/
#include "DooSabin.h"
namespace psalm
{
/*!
* Sets default attributes for the Doo-Sabin algorithm.
*/
DooSabin::DooSabin()
{
weight_function = weights_doo_sabin;
}
/*!
* Sets weights for the Doo-Sabin scheme.
*
* @param new_weights New weights for the Doo-Sabin scheme
* @return true if the new weights could be set, else false
*/
bool DooSabin::set_weights(weights new_weights)
{
switch(new_weights)
{
case catmull_clark:
weight_function = weights_catmull_clark;
break;
case doo_sabin:
weight_function = weights_doo_sabin;
break;
case degenerate:
weight_function = weights_degenerate;
break;
// weights not found
default:
return(false);
}
return(true);
}
/*!
* Applies Doo and Sabin's subdivision algorithm to the given mesh. The
* mesh will be irreversibly _changed_ by this function.
*
* @param input_mesh Mesh on which the algorithm is applied
* @return true on success, else false
*/
bool DooSabin::apply_to(mesh& input_mesh)
{
mesh output_mesh;
if(use_geometric_point_creation)
create_face_vertices_geometrically(input_mesh, output_mesh);
else
create_face_vertices_parametrically(input_mesh, output_mesh);
create_f_faces(input_mesh, output_mesh);
create_e_faces(input_mesh, output_mesh);
create_v_faces(input_mesh, output_mesh);
input_mesh.replace_with(output_mesh);
return(true);
}
/*!
* Creates the new face vertices for the Doo-Sabin scheme. This algorithm
* follows the geometrical approach as presented in the paper of Doo and
* Sabin.
*
* @param input_mesh Original input mesh, will not be modified
* @param output_mesh Mesh that will contain the new face vertices
*/
void DooSabin::create_face_vertices_geometrically(mesh& input_mesh, mesh& output_mesh)
{
for(size_t i = 0; i < input_mesh.num_faces(); i++)
{
print_progress( "Creating points [geometrically]",
i,
input_mesh.num_faces()-1);
face* f = input_mesh.get_face(i);
// Find centroid of face
v3ctor centroid;
for(size_t j = 0; j < f->num_vertices(); j++)
{
const vertex* v = f->get_vertex(j);
centroid += v->get_position();
}
centroid *= 1.0/f->num_vertices();
// For a fixed vertex of the face, find the two edges that are
// incident on this vertex and calculate their midpoints.
for(size_t j = 0; j < f->num_vertices(); j++)
{
const vertex* v = f->get_vertex(j);
const edge* e1 = NULL;
const edge* e2 = NULL;
for(size_t k = 0; k < f->num_edges(); k++)
{
if( f->get_edge(k).e->get_u() == v ||
f->get_edge(k).e->get_v() == v)
{
if(e1 == NULL)
e1 = f->get_edge(k).e;
else
{
e2 = f->get_edge(k).e;
break;
}
}
}
// TODO: Handle error by returning false
if(e1 == NULL || e2 == NULL)
throw(std::runtime_error("DooSabin::create_face_vertices_parametrically(): One of the stored edges is NULL -- unable to continue"));
// Calculate midpoints of the edges and the position of
// face vertex
v3ctor midpoint1;
v3ctor midpoint2;
midpoint1 = (e1->get_u()->get_position()+e1->get_v()->get_position())/2;
midpoint2 = (e2->get_u()->get_position()+e2->get_v()->get_position())/2;
v3ctor face_vertex_position = (midpoint1+midpoint2+centroid+v->get_position())/4;
// Add new vertex to new mesh and store it in the
// vector of face vertices for the old face -- this
// vector will be used when creating the topology of
// the new mesh.
vertex* face_vertex = output_mesh.add_vertex(face_vertex_position);
f->add_face_vertex(face_vertex);
}
}
}
/*!
* Creates the new face vertices for the Doo-Sabin scheme. This algorithm
* employs a parametrical approach, thereby making it possible for the
* user to specify different weights in order to fine-tune the algorithm.
*
* @param input_mesh Original input mesh, will not be modified
* @param output_mesh Mesh that will contain the new face vertices
*/
void DooSabin::create_face_vertices_parametrically(mesh& input_mesh, mesh& output_mesh)
{
// Only used if extra_weights has been defined
weights_map::const_iterator it;
std::vector<double> weights;
for(size_t i = 0; i < input_mesh.num_faces(); i++)
{
print_progress( "Creating points [parametrically]",
i,
input_mesh.num_faces()-1);
face* f = input_mesh.get_face(i);
size_t n = f->num_vertices();
std::vector<const vertex*> vertices = sort_vertices(f, f->get_vertex(0));
// Check if weights for a face with n vertices can be found
weights.clear();
if( custom_weights.size() != 0 &&
((it = custom_weights.find(n)) != custom_weights.end()))
weights = it->second;
for(size_t j = 0; j < vertices.size(); j++)
{
v3ctor face_vertex_position;
// If user-defined weights are present and weights for the current
// number of vertices have been found
if(!weights.empty())
{
for(size_t k = 0; k < weights.size(); k++)
face_vertex_position += vertices[k]->get_position()*weights[k];
}
// Use weight distribution function
else
{
// By default, use original weights for quadrangles
if(n == 4 && use_bspline_weights)
{
face_vertex_position = vertices[0]->get_position()*9.0/16.0+
vertices[1]->get_position()*3.0/16.0+
vertices[2]->get_position()*1.0/16.0+
vertices[3]->get_position()*3.0/16.0;
}
else
{
for(size_t k = 0; k < vertices.size(); k++)
face_vertex_position += vertices[k]->get_position()*weight_function(n,k);
}
}
vertex* face_vertex = output_mesh.add_vertex(face_vertex_position);
f->add_face_vertex(face_vertex);
// Shift the vector
const vertex* v = vertices[0];
vertices.erase(vertices.begin());
vertices.push_back(v);
}
}
}
/*!
* Creates F-faces for the Doo-Sabin algorithm.
*
* @param input_mesh Original input mesh, will not be modified
* @param output_mesh Mesh that will contain the new face vertices
*/
void DooSabin::create_f_faces(mesh& input_mesh, mesh& output_mesh)
{
// Create new F-faces by connecting the appropriate vertex points
// (generated elsewhere) of the face
for(size_t i = 0; i < input_mesh.num_faces(); i++)
{
print_progress( "Creating F-faces",
i,
input_mesh.num_faces()-1);
face* f = input_mesh.get_face(i);
// Since the vertex points are visited in the order of the old
// vertices, this step is orientation-preserving
std::vector<vertex*> vertices;
for(size_t j = 0; j < f->num_vertices(); j++)
vertices.push_back(f->get_face_vertex(j));
output_mesh.add_face(vertices);
}
}
/*!
* Creates quadrilateral E-faces for the Doo-Sabin algorithm.
*
* @param input_mesh Original input mesh, will not be modified
* @param output_mesh Mesh that will contain the new face vertices
*/
void DooSabin::create_e_faces(mesh& input_mesh, mesh& output_mesh)
{
for(size_t i = 0 ; i < input_mesh.num_edges(); i++)
{
print_progress( "Creating E-faces",
i,
input_mesh.num_edges()-1);
edge* e = input_mesh.get_edge(i);
// Skip border edges--we cannot create any new faces here
if(e->get_g() == NULL)
continue;
/*
The situation is as follows:
---------- v ----------
| | |
| F | G |
| | |
| | |
---------- u ----------
Since F is the first face that we encountered when
traversing the edge in its natural direction, we know
that the orientation is preserved if the corresponding
face points are connected like:
u_F -- u_G -- v_G -- v_F -- u_F
*/
vertex* v1 = find_face_vertex(e->get_f(), e->get_u());
vertex* v2 = find_face_vertex(e->get_g(), e->get_u());
vertex* v3 = find_face_vertex(e->get_g(), e->get_v());
vertex* v4 = find_face_vertex(e->get_f(), e->get_v());
output_mesh.add_face(v1, v2, v3, v4);
}
}
/*!
* Creates V-faces for the Doo-Sabin algorithm.
*
* @param input_mesh Original input mesh, will not be modified
* @param output_mesh Mesh that will contain the new face vertices
*/
void DooSabin::create_v_faces(mesh& input_mesh, mesh& output_mesh)
{
// Create V-faces by connecting the face vertices of all faces that are
// adjacent to a fixed vertex.
for(size_t i = 0; i < input_mesh.num_vertices(); i++)
{
print_progress("Creating V-faces",
i,
input_mesh.num_vertices()-1);
vertex* v = input_mesh.get_vertex(i);
// This is a quick fix required for processing some meshes that
// are degenerate
if(v->num_adjacent_faces() < 3)
continue;
// The faces need to be sorted in counterclockwise order around
// the vertex.
std::vector<face*> faces = sort_faces(v);
// Note that for non-manifold meshes, faces.size() may not be
// equal to the number of adjacent faces. Faces can only be
// sorted correctly if a manifold mesh is assumed.
std::vector<vertex*> vertices;
for(size_t j = 0; j < faces.size(); j++)
vertices.push_back(find_face_vertex(faces[j], v));
output_mesh.add_face(vertices);
}
}
/*!
* Given a face and a vertex v, sort all vertices of the face in
* counterclockwise order, starting with vertex v.
*
* @param f Pointer to the face
* @param v Pointer to the "first" vertex
*
* @return Sorted vector of vertices
*/
std::vector<const vertex*> DooSabin::sort_vertices(face* f, const vertex* v)
{
std::vector<const vertex*> vertices;
size_t pos_v = std::numeric_limits<std::size_t>::max();
directed_edge d_edge_v;
for(size_t i = 0; i < f->num_edges(); i++)
{
d_edge_v = f->get_edge(i);
if( d_edge_v.e->get_u() == v ||
d_edge_v.e->get_v() == v)
{
pos_v = i;
break;
}
}
if(pos_v == std::numeric_limits<size_t>::max())
throw(std::runtime_error("DooSabin::sort_vertices(): Unable to find vertex"));
bool take_first = false; // signals whether the first or the second
// edge is to be taken for each edge
if(d_edge_v.e->get_u() == v)
{
vertices.push_back(d_edge_v.e->get_u());
take_first = !d_edge_v.inverted;
}
else
{
vertices.push_back(d_edge_v.e->get_v());
take_first = d_edge_v.inverted;
}
for(size_t i = pos_v; (i-pos_v) < f->num_edges(); i++)
{
const vertex* w;
directed_edge d_e;
// Index must wrap around once the end is reached
if(i >= f->num_edges())
d_e = f->get_edge(i-f->num_edges());
else
d_e = f->get_edge(i);
// Always take the _same_ vertex of each edge (depending on the
// position of v)
if(d_e.inverted)
w = (take_first ? d_e.e->get_v() : d_e.e->get_u());
else
w = (take_first ? d_e.e->get_u() : d_e.e->get_v());
// Avoid duplicates. They can only occur with v because v will
// always be the first vertex in the result vector regardless
// of whether it was the first or second vertex of the edge
if(w != v)
vertices.push_back(w);
}
return(vertices);
}
/*!
* Given a vertex, sort all the vertex's adjacent faces in
* counterclockwise order around the vertex.
*
* @param v Pointer to vertex
* @return Sorted vector of faces
*/
std::vector<face*> DooSabin::sort_faces(vertex* v)
{
std::vector<face*> faces;
std::vector<edge*> edges;
for(size_t i = 0; i < v->valency(); i++)
edges.push_back(v->get_edge(i));
/*
The vector of edges is sorted by the following considerations:
(1) All incident edges of the vertex are known
(2) By using the adjacent faces of an edge, a list of
adjacent faces can be built:
(2.1) Start with any edge
(2.2) Search for any other edge which shares
any face with the start edge. If the edge is
found, store it after the start edge and repeat
the process with the new edge.
This works because there are only two edges which share one
face. So the next edge that is found will _not_ point to any
face that has already been processed (i.e., that will _not_ be
touched by the algorithm anymore).
*/
for(size_t i = 0; i < edges.size(); i++)
{
for(size_t j = i+1; j < edges.size(); j++)
{
if( edges[j]->get_f() == edges[i]->get_f() ||
edges[j]->get_g() == edges[i]->get_g() ||
edges[j]->get_f() == edges[i]->get_g() ||
edges[j]->get_g() == edges[i]->get_f())
{
std::swap(edges[j], edges[i+1]);
break;
}
}
}
/*
From the sorted edges, the faces can be extracted in sorted
order by checking which faces of the edges coincide: If edges
e1 and e2 have adjacent faces (f1,f2), (f2,f3), f3 will be
added to the face vector. The face vector has to be initialized
with one face, which would be missing otherwise.
*/
faces.push_back(edges[0]->get_f());
for(size_t i = 1; i < edges.size(); i++)
{
if( edges[i]->get_f() == edges[i-1]->get_f() ||
edges[i]->get_f() == edges[i-1]->get_g())
{
// Border edges are simply ignored
if(edges[i]->get_g() != NULL)
faces.push_back(edges[i]->get_g());
}
else
faces.push_back(edges[i]->get_f());
}
// Check whether orientation is CW or CCW by enumerating all relevant
// configurations.
bool revert = false;
if(edges[0]->get_u() == v)
{
if(faces[1] == edges[0]->get_g())
revert = true;
}
else
{
if(faces[1] != edges[0]->get_g())
revert = true;
}
if(revert)
std::reverse(faces.begin(), faces.end());
return(faces);
}
/*!
* Given a vertex and a face (of which the vertex is assumed to be a
* part), find the corresponding face vertex and return a pointer to it.
*
* @param f Face
* @param v Vertex, which is assumed to be a part of the face.
*
* @return Pointer to the face vertex that corresponds to vertex v in the
* face.
*/
vertex* DooSabin::find_face_vertex(face* f, const vertex* v)
{
if(f == NULL || v == NULL)
return(NULL);
for(size_t i = 0; i < f->num_vertices(); i++)
{
// NOTE: Speed could be increased by using lookup tables that
// map the "old" id to the "new id"
if(f->get_vertex(i)->get_id() == v->get_id())
return(f->get_face_vertex(i));
}
return(NULL);
}
} // end of namespace "psalm"
| bsd-2-clause |
rogerapras/laravel-repository | src/Torann/LaravelRepository/AbstractValidator.php | 2136 | <?php namespace Torann\LaravelRepository;
use Illuminate\Validation\Factory;
abstract class AbstractValidator
{
/**
* The Validator instance
*
* @var \Illuminate\Validation\Factory
*/
protected $validator;
/**
* Inject the Validator instance
*
* @param \Illuminate\Validation\Factory $validator
*/
public function __construct(Factory $validator)
{
$this->validator = $validator;
}
/**
* Replace placeholders with attributes
*
* @return array
*/
public function replace($rules, $data)
{
array_walk($rules, function(&$rule) use ($data)
{
preg_match_all('/\{(.*?)\}/', $rule, $matches);
foreach($matches[0] as $key => $placeholder)
{
if(isset($data[$matches[1][$key]]))
{
$rule = str_replace($placeholder, $data[$matches[1][$key]], $rule);
}
}
});
return $rules;
}
/**
* Validates the data
*
* @param string $method
* @param array $data
*
* @return boolean
*/
public function validate($method, array $data)
{
$rules = [];
$property = lcfirst($method) . 'Rules';
// Get general rules
if (isset($this->rules) && is_array($this->rules)) {
$rules = $this->replace($this->rules, $data);
}
// Get rules for method
if (isset($this->$property) && is_array($this->$property)) {
$rules = array_merge(
$rules,
$this->replace($this->$property, $data)
);
}
$validator = $this->validator->make($data, $rules);
if ($validator->passes()) {
return true;
}
$this->errors = $validator->messages();
}
/**
* Return errors
*
* @return \Illuminate\Support\MessageBag
*/
public function getErrors()
{
return $this->errors;
}
} | bsd-2-clause |
rsling/cow | src/de/BerkeleyTopoCOW/edu/berkeley/nlp/ling/StateSet.java | 6443 | package edu.berkeley.nlp.ling;
import java.text.NumberFormat;
import edu.berkeley.nlp.math.DoubleArrays;
import edu.berkeley.nlp.util.Numberer;
import edu.berkeley.nlp.util.ScalingTools;
/**
* Represent parsetrees, with each node consisting of a label and a list of children.
* The score tables are not allocated by the constructor and allocate() and deallocate()
* must be called manually. This is to allow more control over memory usage.
* @author Slav Petrov
* @author Romain Thibaux
*/
public class StateSet {
public static final double SCALE = Math.exp(100);
double[] iScores; // the log-probabilities for each sublabels
double[] oScores;
int iScale;
int oScale;
String word; /** the word of this node, if it is a terminal node; else null*/
public int wordIndex, sigIndex;
short numSubStates;
short state;
public short from, to;
// Run allocate() before any other operation
public void allocate() {
iScores = new double[numSubStates];
oScores = new double[numSubStates];
}
// run deallocate() if the scores are no longer needed and
// this object will not be used for a long time
public void deallocate() {
iScores = null;
oScores = null;
}
@Override
public String toString(){
if (word!=null) return word+" "+from+"-"+to;// + " " + substates.length;
String s = Numberer.getGlobalNumberer("tags").object(state)+" ";//"[";
// for (int i = 0; i < numSubStates; i++){
// NumberFormat f = NumberFormat.getInstance();
// f.setMaximumFractionDigits(5);
// String iS = "";
// String oS = "";
// if (iScores != null && iScores[i]!=0)
// iS = ": iS="+f.format(iScores[i]);//Math.log(iScores[i])+100*iScale);
// if (oScores != null && oScores[i]!=0)
// oS = " oS="+f.format(oScores[i]);//Math.log(oScores[i])+100*oScale);
//// String iS = Double.toString(Math.log(iScores[i])+100*iScale);
//// String oS = Double.toString(Math.log(oScores[i])+100*oScale);
//// String iS = "";
//// String oS = "";
// if (iScores != null && DoubleArrays.max(iScores)==0) iS = ", iS=0";
// if (oScores != null && DoubleArrays.max(oScores)==0) oS = ", oS=0";
// s=s.concat(" ["+state+"-"+i+iS+oS+"]");
// }
// s=s.concat(" ]");
return s;
}
public final short getState(){
return state;
}
public final double getIScore(int i){
return iScores[i];
}
public final double[] getIScores() {
return iScores;
}
public final double getOScore(int i){
return oScores[i];
}
public final double[] getOScores() {
return oScores;
}
public final void setIScores(double[] s) {
iScores = s;
}
public final void setIScore(int i, double s) {
if (iScores == null) iScores = new double[numSubStates];
iScores[i] = s;
}
public final void setOScores(double[] s) {
oScores = s;
}
public final void setOScore(int i, double s) {
if (oScores == null) oScores = new double[numSubStates];
oScores[i] = s;
}
/* public void logAddIScore(short i, double s) {
iScores[i] = SloppyMath.logAdd(iScores[i], s);
}
public void logAddOScore(short i,double s) {
oScores[i] = SloppyMath.logAdd(oScores[i], s);
}
*/
public final int numSubStates() {
return numSubStates;
}
/*
public StateSet(int nSubStates) {
this.numSubStates = nSubStates;
this.iScores = new double[nSubStates];
this.oScores = new double[nSubStates];
for ( int i = 0; i < nSubStates; i++ ) {
iScores[i] = Double.NEGATIVE_INFINITY;
oScores[i] = Double.NEGATIVE_INFINITY;
}
}*/
public StateSet(short state, short nSubStates) {
this.numSubStates = nSubStates;
this.state = state;
}
public StateSet(short s, short nSubStates, String word, short from, short to) {
this.numSubStates = nSubStates;
this.state = s;
this.word = word;
this.from = from;
this.to = to;
}
public StateSet(StateSet oldS, short nSubStates) {
this.numSubStates = nSubStates;
this.state = oldS.state;
this.word = oldS.word;
this.from = oldS.from;
this.to = oldS.to;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public void scaleIScores(int previousScale){
iScale = ScalingTools.scaleArray(iScores, previousScale);
// int logScale = 0;
// double scale = 1.0;
// double max = ArrayMath.max(iScores);
// //if (max==0) System.out.println("All iScores are 0!");
// if (SloppyMath.isVeryDangerous(max)) return;
// while (max > SCALE) {
// max /= SCALE;
// scale *= SCALE;
// logScale += 1;
// }
// while (max > 0.0 && max < 1.0 / SCALE) {
// max *= SCALE;
// scale /= SCALE;
// logScale -= 1;
// }
// if (logScale != 0) {
// for (int i = 0; i < numSubStates; i++) {
// iScores[i] /= scale;
// }
// }
// if ((max!=0) && ArrayMath.max(iScores)==0){
// System.out.println("Undeflow when scaling iScores!");
// }
// iScale = previousScale + logScale;
}
public void scaleOScores(int previousScale){
oScale = ScalingTools.scaleArray(oScores, previousScale);
// int logScale = 0;
// double scale = 1.0;
// double max = ArrayMath.max(oScores);
// if (SloppyMath.isVeryDangerous(max)) return;
// //if (max==0) System.out.println("All oScores are 0!");
// while (max > SCALE) {
// max /= SCALE;
// scale *= SCALE;
// logScale += 1;
// }
// while (max > 0.0 && max < 1.0 / SCALE) {
// max *= SCALE;
// scale /= SCALE;
// logScale -= 1;
// }
// if (logScale != 0) {
// for (int i = 0; i < numSubStates; i++) {
// oScores[i] /= scale;
// }
// }
// if ((max!=0) && ArrayMath.max(oScores)==0){
// System.out.println("Undeflow when scaling oScores!");
// }
// oScale = previousScale + logScale;
}
public int getIScale() {
return iScale;
}
public void setIScale(int scale) {
iScale = scale;
}
public int getOScale() {
return oScale;
}
public void setOScale(int scale) {
oScale = scale;
}
/**
* @return
*/
public StateSet copy() {
return new StateSet(this, this.numSubStates);
}
}
| bsd-2-clause |
insionng/yougam | libraries/pingcap/tidb/optimizer/typeinferer_test.go | 8207 | // Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package optimizer_test
import (
. "github.com/insionng/yougam/libraries/pingcap/check"
"github.com/insionng/yougam/libraries/pingcap/tidb"
"github.com/insionng/yougam/libraries/pingcap/tidb/ast"
"github.com/insionng/yougam/libraries/pingcap/tidb/context"
"github.com/insionng/yougam/libraries/pingcap/tidb/model"
"github.com/insionng/yougam/libraries/pingcap/tidb/mysql"
"github.com/insionng/yougam/libraries/pingcap/tidb/optimizer"
"github.com/insionng/yougam/libraries/pingcap/tidb/sessionctx"
"github.com/insionng/yougam/libraries/pingcap/tidb/util/charset"
"github.com/insionng/yougam/libraries/pingcap/tidb/util/testkit"
"github.com/insionng/yougam/libraries/pingcap/tidb/util/testleak"
)
var _ = Suite(&testTypeInferrerSuite{})
type testTypeInferrerSuite struct {
}
func (ts *testTypeInferrerSuite) TestInferType(c *C) {
store, err := tidb.NewStore(tidb.EngineGoLevelDBMemory)
c.Assert(err, IsNil)
defer store.Close()
testKit := testkit.NewTestKit(c, store)
testKit.MustExec("use test")
testKit.MustExec("create table t (c1 int, c2 double, c3 text)")
cases := []struct {
expr string
tp byte
chs string
}{
{"c1", mysql.TypeLong, charset.CharsetBin},
{"+1", mysql.TypeLonglong, charset.CharsetBin},
{"-1", mysql.TypeLonglong, charset.CharsetBin},
{"-'1'", mysql.TypeDouble, charset.CharsetBin},
{"~1", mysql.TypeLonglong, charset.CharsetBin},
{"!true", mysql.TypeLonglong, charset.CharsetBin},
{"c1 is true", mysql.TypeLonglong, charset.CharsetBin},
{"c2 is null", mysql.TypeLonglong, charset.CharsetBin},
{"isnull(1/0)", mysql.TypeLonglong, charset.CharsetBin},
{"cast(1 as decimal)", mysql.TypeNewDecimal, charset.CharsetBin},
{"1 and 1", mysql.TypeLonglong, charset.CharsetBin},
{"1 or 1", mysql.TypeLonglong, charset.CharsetBin},
{"1 xor 1", mysql.TypeLonglong, charset.CharsetBin},
{"'1' & 2", mysql.TypeLonglong, charset.CharsetBin},
{"'1' | 2", mysql.TypeLonglong, charset.CharsetBin},
{"'1' ^ 2", mysql.TypeLonglong, charset.CharsetBin},
{"'1' << 1", mysql.TypeLonglong, charset.CharsetBin},
{"'1' >> 1", mysql.TypeLonglong, charset.CharsetBin},
{"1 + '1'", mysql.TypeDouble, charset.CharsetBin},
{"1 + 1.1", mysql.TypeNewDecimal, charset.CharsetBin},
{"1 div 2", mysql.TypeLonglong, charset.CharsetBin},
{"1 > any (select 1)", mysql.TypeLonglong, charset.CharsetBin},
{"exists (select 1)", mysql.TypeLonglong, charset.CharsetBin},
{"1 in (2, 3)", mysql.TypeLonglong, charset.CharsetBin},
{"'abc' like 'abc'", mysql.TypeLonglong, charset.CharsetBin},
{"'abc' rlike 'abc'", mysql.TypeLonglong, charset.CharsetBin},
{"(1+1)", mysql.TypeLonglong, charset.CharsetBin},
// Functions
{"version()", mysql.TypeVarString, "utf8"},
{"count(c1)", mysql.TypeLonglong, charset.CharsetBin},
{"abs(1)", mysql.TypeLonglong, charset.CharsetBin},
{"abs(1.1)", mysql.TypeNewDecimal, charset.CharsetBin},
{"abs(cast(\"20150817015609\" as DATETIME))", mysql.TypeDouble, charset.CharsetBin},
{"IF(1>2,2,3)", mysql.TypeLonglong, charset.CharsetBin},
{"IFNULL(1,0)", mysql.TypeLonglong, charset.CharsetBin},
{"POW(2,2)", mysql.TypeDouble, charset.CharsetBin},
{"POWER(2,2)", mysql.TypeDouble, charset.CharsetBin},
{"rand()", mysql.TypeDouble, charset.CharsetBin},
{"curdate()", mysql.TypeDate, charset.CharsetBin},
{"current_date()", mysql.TypeDate, charset.CharsetBin},
{"DATE('2003-12-31 01:02:03')", mysql.TypeDate, charset.CharsetBin},
{"curtime()", mysql.TypeDuration, charset.CharsetBin},
{"current_time()", mysql.TypeDuration, charset.CharsetBin},
{"curtime()", mysql.TypeDuration, charset.CharsetBin},
{"current_timestamp()", mysql.TypeDatetime, charset.CharsetBin},
{"microsecond('2009-12-31 23:59:59.000010')", mysql.TypeLonglong, charset.CharsetBin},
{"second('2009-12-31 23:59:59.000010')", mysql.TypeLonglong, charset.CharsetBin},
{"minute('2009-12-31 23:59:59.000010')", mysql.TypeLonglong, charset.CharsetBin},
{"hour('2009-12-31 23:59:59.000010')", mysql.TypeLonglong, charset.CharsetBin},
{"day('2009-12-31 23:59:59.000010')", mysql.TypeLonglong, charset.CharsetBin},
{"week('2009-12-31 23:59:59.000010')", mysql.TypeLonglong, charset.CharsetBin},
{"month('2009-12-31 23:59:59.000010')", mysql.TypeLonglong, charset.CharsetBin},
{"year('2009-12-31 23:59:59.000010')", mysql.TypeLonglong, charset.CharsetBin},
{"dayofweek('2009-12-31 23:59:59.000010')", mysql.TypeLonglong, charset.CharsetBin},
{"dayofmonth('2009-12-31 23:59:59.000010')", mysql.TypeLonglong, charset.CharsetBin},
{"dayofyear('2009-12-31 23:59:59.000010')", mysql.TypeLonglong, charset.CharsetBin},
{"weekday('2009-12-31 23:59:59.000010')", mysql.TypeLonglong, charset.CharsetBin},
{"weekofyear('2009-12-31 23:59:59.000010')", mysql.TypeLonglong, charset.CharsetBin},
{"yearweek('2009-12-31 23:59:59.000010')", mysql.TypeLonglong, charset.CharsetBin},
{"found_rows()", mysql.TypeLonglong, charset.CharsetBin},
{"length('tidb')", mysql.TypeLonglong, charset.CharsetBin},
{"now()", mysql.TypeDatetime, charset.CharsetBin},
{"sysdate()", mysql.TypeDatetime, charset.CharsetBin},
{"dayname('2007-02-03')", mysql.TypeVarString, "utf8"},
{"version()", mysql.TypeVarString, "utf8"},
{"database()", mysql.TypeVarString, "utf8"},
{"user()", mysql.TypeVarString, "utf8"},
{"current_user()", mysql.TypeVarString, "utf8"},
{"CONCAT('T', 'i', 'DB')", mysql.TypeVarString, "utf8"},
{"CONCAT_WS('-', 'T', 'i', 'DB')", mysql.TypeVarString, "utf8"},
{"left('TiDB', 2)", mysql.TypeVarString, "utf8"},
{"lower('TiDB')", mysql.TypeVarString, "utf8"},
{"lcase('TiDB')", mysql.TypeVarString, "utf8"},
{"repeat('TiDB', 3)", mysql.TypeVarString, "utf8"},
{"replace('TiDB', 'D', 'd')", mysql.TypeVarString, "utf8"},
{"upper('TiDB')", mysql.TypeVarString, "utf8"},
{"ucase('TiDB')", mysql.TypeVarString, "utf8"},
{"trim(' TiDB ')", mysql.TypeVarString, "utf8"},
{"ltrim(' TiDB')", mysql.TypeVarString, "utf8"},
{"rtrim('TiDB ')", mysql.TypeVarString, "utf8"},
{"connection_id()", mysql.TypeLonglong, charset.CharsetBin},
{"if(1>2, 2, 3)", mysql.TypeLonglong, charset.CharsetBin},
{"case c1 when null then 2 when 2 then 1.1 else 1 END", mysql.TypeNewDecimal, charset.CharsetBin},
{"case c1 when null then 2 when 2 then 'tidb' else 1.1 END", mysql.TypeVarchar, "utf8"},
}
for _, ca := range cases {
ctx := testKit.Se.(context.Context)
stmts, err := tidb.Parse(ctx, "select "+ca.expr+" from t")
c.Assert(err, IsNil)
c.Assert(stmts, HasLen, 1)
stmt := stmts[0].(*ast.SelectStmt)
is := sessionctx.GetDomain(ctx).InfoSchema()
err = optimizer.ResolveName(stmt, is, ctx)
c.Assert(err, IsNil)
optimizer.InferType(stmt)
tp := stmt.GetResultFields()[0].Column.Tp
chs := stmt.GetResultFields()[0].Column.Charset
c.Assert(tp, Equals, ca.tp, Commentf("Tp for %s", ca.expr))
c.Assert(chs, Equals, ca.chs, Commentf("Charset for %s", ca.expr))
}
}
func (s *testTypeInferrerSuite) TestColumnInfoModified(c *C) {
defer testleak.AfterTest(c)()
store, err := tidb.NewStore(tidb.EngineGoLevelDBMemory)
c.Assert(err, IsNil)
defer store.Close()
testKit := testkit.NewTestKit(c, store)
testKit.MustExec("use test")
testKit.MustExec("drop table if exists tab0")
testKit.MustExec("CREATE TABLE tab0(col0 INTEGER, col1 INTEGER, col2 INTEGER)")
testKit.MustExec("SELECT + - (- CASE + col0 WHEN + CAST( col0 AS SIGNED ) THEN col1 WHEN 79 THEN NULL WHEN + - col1 THEN col0 / + col0 END ) * - 16 FROM tab0")
ctx := testKit.Se.(context.Context)
is := sessionctx.GetDomain(ctx).InfoSchema()
col, _ := is.ColumnByName(model.NewCIStr("test"), model.NewCIStr("tab0"), model.NewCIStr("col1"))
c.Assert(col.Tp, Equals, mysql.TypeLong)
}
| bsd-2-clause |
jslee02/conan-dart | console_bridge/0.2.7/conanfile.py | 1799 | from conans import ConanFile, CMake
from conans.tools import download, unzip
import os
class ConsoleBridgeConan(ConanFile):
name = "console_bridge"
version = "0.2.7"
settings = "os", "compiler", "build_type", "arch"
options = {"shared": [True, False]}
default_options = "shared=True"
exports = "console_bridge/*"
url="https://github.com/jslee02/conan-dart/tree/master/console_bridge/0.2.7"
def system_requirements(self):
self.global_system_requirements=True
if self.settings.os == "Linux":
self.run("sudo apt-get install libboost-all-dev || true ")
def requirements(self):
if self.settings.os == "Windows":
self.requires("Boost/1.59.0@lasote/stable")
def source(self):
zip_name = "console_bridge-0.2.7.zip"
download("https://github.com/ros/console_bridge/archive/0.2.7.zip", zip_name)
unzip(zip_name)
os.unlink(zip_name)
def build(self):
cmake = CMake(self.settings)
shared = "-DBUILD_SHARED_LIBS=1" if self.options.shared else ""
self.run("cd console_bridge-0.2.7 && cmake . %s %s" % (cmake.command_line, shared))
self.run("cd console_bridge-0.2.7 && cmake --build . %s" % cmake.build_config)
def package(self):
# include
self.copy("*.h", dst="include", src="console_bridge-0.2.7/include")
# lib
self.copy("*.dll", dst="bin", src="fconsole_bridge-0.2.7")
self.copy("*.lib", dst="lib", src="console_bridge-0.2.7")
self.copy("*.a", dst="lib", src="console_bridge-0.2.7")
self.copy("*.so*", dst="lib", src="console_bridge-0.2.7")
self.copy("*.dylib*", dst="lib", src="console_bridge-0.2.7")
def package_info(self):
self.cpp_info.libs = ["console_bridge"]
| bsd-2-clause |
handroll/handroll | handroll/composers/atom.py | 3486 | # Copyright (c) 2017, Matt Layman
import io
import json
import os
from werkzeug.contrib.atom import AtomFeed
from werkzeug.contrib.atom import FeedEntry
from handroll import date, logger
from handroll.composers import Composer
from handroll.exceptions import AbortError
from handroll.i18n import _
class AtomComposer(Composer):
"""Compose an Atom feed from an Atom metadata file (``.atom``).
The ``AtomComposer`` parses the metadata specified in the source file and
produces an XML Atom feed. ``AtomComposer`` uses parameters that are needed
by Werkzeug's ``AtomFeed`` API. Refer to the `Werkzeug documentation
<http://werkzeug.pocoo.org/docs/contrib/atom/>`_ for all the available
options.
The dates in the feed should be in `RfC 3339
<http://www.ietf.org/rfc/rfc3339.txt>`_ format (e.g.,
``2014-06-13T11:39:30``).
Here is a sample feed:
.. literalinclude:: ../sample/atom_sample.atom
"""
output_extension = '.xml'
def compose(self, catalog, source_file, out_dir):
root, ext = os.path.splitext(os.path.basename(source_file))
filename = root + self.output_extension
output_file = os.path.join(out_dir, filename)
if self._needs_update(source_file, output_file):
logger.info(_('Generating Atom XML for {source_file} ...').format(
source_file=source_file))
feed = self._parse_feed(source_file)
with open(output_file, 'wb') as out:
out.write(feed.to_string().encode('utf-8'))
out.write(b'<!-- handrolled for excellence -->\n')
else:
logger.debug(_('Skipping {filename} ... It is up to date.').format(
filename=filename))
def get_output_extension(self, filename):
return self.output_extension
@property
def permit_frontmatter(self):
return False
def _needs_update(self, source_file, out_file):
"""Check if the output file needs to be updated by looking at the
modified times of the source file and output file."""
if self._config.force:
return True
if os.path.exists(out_file):
return os.path.getmtime(source_file) > os.path.getmtime(out_file)
else:
# The file doesn't exist so it definitely needs to be "updated."
return True
def _parse_feed(self, source_file):
try:
with io.open(source_file, 'r', encoding='utf-8') as f:
metadata = json.loads(f.read())
if metadata.get('entries') is None:
raise ValueError(_('Missing entries list.'))
entries = metadata['entries']
# AtomFeed expects FeedEntry objects for the entries keyword so
# remove it from the metadata and add it after the feed is built.
del metadata['entries']
feed = AtomFeed(**metadata)
[feed.add(self._make_entry(entry)) for entry in entries]
except ValueError as error:
raise AbortError(_('Invalid feed {source_file}: {error}').format(
source_file=source_file, error=str(error)))
return feed
def _make_entry(self, data):
# Convert dates into datetime instances.
if 'updated' in data:
data['updated'] = date.convert(data['updated'])
if 'published' in data:
data['published'] = date.convert(data['published'])
return FeedEntry(**data)
| bsd-2-clause |
mirumee/google-measurement-protocol | tests/test_event.py | 666 | from prices import Money, TaxedMoney
from google_measurement_protocol import event
def test_required_params():
generator = event('category', 'action')
assert list(generator) == [{'t': 'event', 'ec': 'category', 'ea': 'action'}]
def test_optional_params():
generator = event('category', 'action', label='label', value=7)
assert list(generator) == [
{
't': 'event', 'ec': 'category', 'ea': 'action', 'el': 'label',
'ev': '7'}]
def test_extra_params():
generator = event('category', 'action', ex='extra')
assert list(generator) == [
{'t': 'event', 'ec': 'category', 'ea': 'action', 'ex': 'extra'}]
| bsd-2-clause |
shodimaggio/SaivDr | appendix/torch_nsolt/nsoltLayerExceptions.py | 819 | class InvalidDirection(Exception):
def __init__(self,msg):
super().__init__(self,msg)
class InvalidTargetChannels(Exception):
def __init__(self,msg):
super().__init__(self,msg)
class InvalidMode(Exception):
def __init__(self,msg):
super().__init__(self,msg)
class InvalidMus(Exception):
def __init__(self,msg):
super().__init__(self,msg)
class InvalidNumberOfChannels(Exception):
def __init__(self,msg):
super().__init__(self,msg)
class InvalidPolyPhaseOrder(Exception):
def __init__(self,msg):
super().__init__(self,msg)
class InvalidNumberOfVanishingMoments(Exception):
def __init__(self,msg):
super().__init__(self,msg)
class InvalidNumberOfLevels(Exception):
def __init__(self,msg):
super().__init__(self,msg) | bsd-2-clause |
anushreejangid/csmpe-main | csmpe/core_plugins/csm_install_operations/exr/commit.py | 5046 | # =============================================================================
#
# Copyright (c) 2016, Cisco Systems
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.
# =============================================================================
import re
import json
import pdb
import types
from csmpe.plugins import CSMPlugin
from install import watch_operation, log_install_errors, report_install_status
from csmpe.core_plugins.csm_get_inventory.exr.plugin import get_package, get_inventory
class Plugin(CSMPlugin):
"""This plugin commits packages on the device."""
name = "Install Commit Plugin"
platforms = {'ASR9K', 'NCS1K', 'NCS4K', 'NCS5K', 'NCS5500', 'NCS6K', 'IOS-XRv'}
phases = {'Commit'}
os = {'eXR'}
def dump_obj(self, obj, level=0):
for a in dir(obj):
val = getattr(obj, a)
if isinstance(val, (int, float, str, unicode, list, dict, set)):
print level*' ', val
else:
self.dump_obj(val, level=level+1)
def run(self):
"""
It performs commit operation
RP/0/RP0/CPU0:Deploy#install commit
May 27 16:34:04 Install operation 32 started by root:
install commit
May 27 16:34:05 Install operation will continue in the background
RP/0/RP0/CPU0:Deploy#May 27 16:34:11 Install operation 32 finished successfully
"""
cmd = "install commit"
if self.ctx.shell == "Admin":
self.ctx.info("Switching to admin mode")
self.ctx.send("admin", timeout=30)
output = self.ctx.send(cmd)
result = re.search('Install operation (\d+)', output)
if result:
op_id = result.group(1)
watch_operation(self.ctx, op_id)
else:
report_install_status(self.ctx, output=output)
if self.ctx.shell == "Admin":
self.ctx.info("Switching to admin mode")
self.ctx.send("exit", timeout=30)
#self.ctx.error("Operation ID not found.")
return
#serialized = jsonpickle.encode(self.ctx.__dict__)
#print json.dumps(json.loads(serialized), indent=2)
#self.dump_obj(self.ctx)
aborted_oper = r'Install operation {} aborted'.format(op_id)
success_oper = r'Install operation (\d+) finished successfully'
failed_oper = r'Install operation {} failed'.format(op_id)
# Not sure if this is still the message on NCS6K
completed_with_failure = 'Install operation (\d+) completed with failure'
cmd = "show install log {} detail".format(op_id)
output = self.ctx.send(cmd)
if re.search(failed_oper, output) or re.search(aborted_oper, output):
report_install_status(self.ctx, op_id, output)
if self.ctx.shell == "Admin":
self.ctx.info("Switching to admin mode")
self.ctx.send("exit", timeout=30)
#self.ctx.error("Install operation failed.")
return
if re.search(completed_with_failure, output):
self.ctx.info("Completed with failure but failure was after Point of No Return.")
elif re.search(success_oper, output):
self.ctx.info("Operation {} finished successfully.".format(op_id))
report_install_status(self.ctx, op_id, output)
if self.ctx.shell == "Admin":
self.ctx.info("Switching to admin mode")
self.ctx.send("exit", timeout=30)
try:
self.ctx.post_status("Trying to disconnect")
self.ctx.disconnect()
self.ctx.post_status("Disconnected")
except:
pass
# Refresh package and inventory information
#get_package(self.ctx)
#get_inventory(self.ctx)
| bsd-2-clause |
chop-dbhi/django-dicom-models | dicom_models/core/models/data/radiology.py | 2178 | # Copyright (c) 2012, The Children's Hospital of Philadelphia
# 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.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.from datetime import datetime
from django.db import models
from django.core.urlresolvers import reverse
from dicom_models.core.models.base import Base
__all__ = ('RadiologyStudy',)
class RadiologyStudy(Base):
study_uid = models.CharField(max_length=64, null=True, blank=True)
modality = models.CharField(max_length=5, null=True, blank=True)
sop_class = models.CharField(max_length=30, null=True, blank=True)
number_of_series = models.IntegerField(null=True, blank=True)
total_images = models.IntegerField(null=True, blank=True)
impression = models.TextField(null=True, blank=True)
class Meta(object):
abstract = True
# TODO turn this into a resource
def get_absolute_url(self):
path = reverse('dicom')
return '%s?studyUID=%s' % (path, self.study_uid)
| bsd-2-clause |
Arez0101/That-s-A-Big-Furnace | src/main/java/net/arez0101/tabf/init/ItemInit.java | 1973 | package net.arez0101.tabf.init;
import net.arez0101.tabf.TABF;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class ItemInit {
public static void initCommon() {
initItems();
}
@SideOnly(Side.CLIENT)
public static void initClient() {
registerRender(CONTROLLER);
registerRender(WALL);
registerRender(FUEL_INPUT);
registerRender(SMELTING_INPUT);
registerRender(SMELTING_OUTPUT);
}
private static void initItems() {
CONTROLLER = new ItemBlock(BlockInit.CONTROLLER).setUnlocalizedName("furnace_controller").setRegistryName(TABF.MODID, "furnace_controller");
WALL = new ItemBlock(BlockInit.WALL).setUnlocalizedName("furnace_wall").setRegistryName(TABF.MODID, "furnace_wall");
FUEL_INPUT = new ItemBlock(BlockInit.FUEL_INPUT).setUnlocalizedName("fuel_input").setRegistryName(TABF.MODID, "fuel_input");
SMELTING_INPUT = new ItemBlock(BlockInit.SMELTING_INPUT).setUnlocalizedName("smelting_input").setRegistryName(TABF.MODID, "smelting_input");
SMELTING_OUTPUT = new ItemBlock(BlockInit.SMELTING_OUTPUT).setUnlocalizedName("smelting_output").setRegistryName(TABF.MODID, "smelting_output");
}
private static void registerItem(Item item) {
GameRegistry.register(item);
}
@SideOnly(Side.CLIENT)
private static void registerRender(Item item) {
ModelResourceLocation resource = new ModelResourceLocation(item.getRegistryName(), "inventory");
ModelLoader.setCustomModelResourceLocation(item, 0, resource);
}
public static Item CONTROLLER;
public static Item WALL;
public static Item FUEL_INPUT;
public static Item SMELTING_INPUT;
public static Item SMELTING_OUTPUT;
}
| bsd-2-clause |
safarijv/sbo-sphinx | sbo_sphinx/conf.py | 14039 | # -*- coding: utf-8 -*-
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
"""
Common Sphinx configuration for most Safari projects. To use
in a project-specific ``conf.py`` file::
from sbo_sphinx.conf import *
"""
import os
import re
import sys
from recommonmark.parser import CommonMarkParser
STATIC_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), '_static')
# -- General configuration ----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.viewcode',
'sbo_sphinx.apidoc'
]
autodoc_default_flags = ['members', 'undoc-members', 'show-inheritance']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
source_suffix = ['.rst', '.md']
source_parsers = {
'.md': CommonMarkParser,
}
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
copyright = u'2015, Safari'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = []
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
if not on_rtd: # only import and set the theme if we're building docs locally
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = None # updated in update_configuration()
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
html_favicon = None # updated in update_configuration()
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = [] # updated in update_configuration()
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = '' # updated in update_configuration()
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [] # updated in update_configuration()
# The name of an image file (relative to this directory) to place at the top of
# the title page.
latex_logo = None # updated in update_configuration()
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [] # updated in update_configuration()
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [] # updated in update_configuration()
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = '' # updated in update_configuration()
epub_author = u'Safari'
epub_publisher = '' # updated in update_configuration()
epub_copyright = '' # updated in update_configuration()
epub_cover = ('_static/safari_cover.png', 'epub-cover.html')
# The basename for the epub file. It defaults to the project name.
#epub_basename = project
# The HTML theme for the epub output. Since the default themes are not optimized
# for small screen space, using the same theme for HTML and epub output is
# usually not wise. This defaults to 'epub', a theme designed to save visual
# space.
#epub_theme = 'epub'
epub_theme_options = {
'relbar1': False, # omit the nav links header block in the epub output
'footer': False, # omit the copyright footer block in the epub output
}
# The language of the text. It defaults to the language option
# or 'en' if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#epub_guide = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
epub_tocdup = False
# Choose between 'default' and 'includehidden'.
#epub_tocscope = 'default'
# Fix unsupported image types using the Pillow.
#epub_fix_images = False
# Scale large images.
#epub_max_image_width = 0
# How to display URL addresses: 'footnote', 'no', or 'inline'.
epub_show_urls = 'no'
# If false, no index is generated.
#epub_use_index = True
# Example configuration for intersphinx
intersphinx_mapping = {
'python': ('https://docs.python.org/2/', None),
'django': ('https://docs.djangoproject.com/en/1.11/',
'http://docs.djangoproject.com/en/1.11/_objects/'),
'sphinx': ('http://sphinx-doc.org/', None),
}
def update_configuration(app):
"""Update parameters which are dependent on information from the
project-specific conf.py (including its location on the filesystem)"""
config = app.config
project = config.project
config_dir = app.env.srcdir
sys.path.insert(0, os.path.join(config_dir, '..'))
config.html_theme_path.append(os.path.relpath(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'themes'), config_dir))
if not config.html_logo:
config.html_logo = os.path.relpath(os.path.join(STATIC_PATH, 'safari_logo.png'), config_dir)
if not config.html_favicon:
config.html_favicon = os.path.relpath(os.path.join(STATIC_PATH, 'favicon.ico'), config_dir)
config.html_static_path.append(os.path.relpath(STATIC_PATH, config_dir))
if not config.htmlhelp_basename:
config.htmlhelp_basename = '%sdoc' % project
if not config.latex_logo:
config.latex_logo = os.path.relpath(os.path.join(STATIC_PATH, 'safari_logo.png'), config_dir)
if not config.epub_title:
config.epub_title = u'%s Documentation' % project
if not config.epub_publisher:
config.epub_publisher = config.epub_author
if not config.epub_copyright:
config.epub_copyright = config.copyright
config.latex_documents.append(
(master_doc,
'%s.tex' % project,
u'%s Documentation' % project,
u'Safari',
'manual'))
config.man_pages.append(
(master_doc,
project,
u'%s Documentation' % project,
[u'Safari'],
1))
config.texinfo_documents.append(
(master_doc,
project,
u'%s Documentation' % project,
u'Safari',
project,
'One line description of project.',
'Miscellaneous'))
# Parse the version number from setup.py without actually running setup()
with open(os.path.join(config_dir, '..', 'setup.py'), 'r') as f:
content = f.read()
match = re.search(r"version\s*=\s*['\"]([\d\.]+)['\"]", content)
if match:
config.version = match.group(1)
config.release = config.version
def setup(app):
"""Sphinx extension entry point"""
app.connect('builder-inited', update_configuration)
| bsd-2-clause |
zhester/hzphp | DOM/DOMRenderer.php | 21310 | <?php
/*****************************************************************************
DOM Document Rendering
======================
Provides convenience methods for working with documents that need to be sent
to the client. The intent is to allow a server-side templating mechanism to
build documents from empty HTML/XML files. Unlike traditional templating
systems, these files require no special markers to provide templating beyond
any necessary DOM-style hooks (e.g. `id` attributes, regular document
structure, `data-` attributes, etc.).
TODO
----
- Move DTL features to its own class that depends on this class.
- Make it possible to pass a list of element arrays that then requires the
user to specify their own root node. This would prevent unwanted nested
container nodes since the DTL currently relies on returning a single
node.
- Write automated tests.
- Use exceptions for error reporting rather than magic return values.
- Use/resolve `source` arguments more consistently on all methods.
- Look into auto-detecting the type of DOM insertion when using assignment.
*****************************************************************************/
/*----------------------------------------------------------------------------
Dependencies
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
Default Namespace
----------------------------------------------------------------------------*/
namespace hzphp\DOM;
/*----------------------------------------------------------------------------
Classes
----------------------------------------------------------------------------*/
/**
* DOM document rendering implementation.
*/
class DOMRenderer implements \ArrayAccess {
/*------------------------------------------------------------------------
Public Properties
------------------------------------------------------------------------*/
//the DOMDocument instance used to render the page
public $dom;
/*------------------------------------------------------------------------
Protected Properties
------------------------------------------------------------------------*/
//the automatic setter method for assignment via object property
//references and array subscripts
protected $auto_set = 'append';
/*------------------------------------------------------------------------
Private Properties
------------------------------------------------------------------------*/
/*------------------------------------------------------------------------
Public Methods
------------------------------------------------------------------------*/
/**
* Initializes a rendering instance.
*
* @param template The file from which to read the document template.
*/
public function __construct( $template, $auto_set = 'append' ) {
$this->dom = new \DOMDocument();
$this->dom->formatOutput = true;
$this->dom->loadHTMLFile( $template );
$this->setAutoSet( $auto_set );
}
/**
* Retrieves a node from the document by requesting it by ID using an
* object property reference.
*
* @param id The DOM element ID of the element to retrieve
* @return The requested DOM element, or null on failure
*/
public function __get( $id ) {
return $this->dom->getElementById( $id );
}
/**
* Determines if the document can reference a node given its ID using an
* object property reference.
*
* @param id The DOM element ID of the element to check
* @return True if the element exists, false if it does not
*/
public function __isset( $id ) {
$node = $this->dom->getElementById( $id );
return $node !== null;
}
/**
* Loads a node into the document by specifying it by ID using an object
* property reference. This method depends on the `auto_setter` property
* being set to one of the methods that can be used to load a node into
* the document. Currently, only `append` is used to add the node to the
* DOM element having the specified ID.
*
* @param id The DOM element ID of the element to target
* @param node The DOM element to load into the document
*/
public function __set( $id, $node ) {
//Handle special "IDs" differently than real DOM IDs.
if( in_array( $id, [ 'title', 'body' ] ) == true ) {
//Target the element with the given name.
$target = $this->dom->getElementsByTagName( $id )->item( 0 );
//Target the element with the given ID.
$this->__set( '_' . $id, $node );
}
//Allow subversion of the special "IDs" check.
else if( $id[ 0 ] == '_' ) {
$target = $this->dom->getElementById( substr( $id, 1 ) );
}
//Attempt to resolve target by ID.
else {
$target = $this->dom->getElementById( $id );
}
//Make sure there is a target element.
if( $target != null ) {
if( method_exists( $this, $this->auto_set ) == true ) {
call_user_func( [ $this, $this->auto_set ], $target, $node );
}
}
}
/**
* Retrieves the rendered document as a string.
*
* @return The document as a string
*/
public function __toString() {
return $this->dom->saveHTML();
}
/**
* Removes a node from the document using the `unset()` built-in with an
* object property reference.
*
* @param id The DOM ID of the element to remove from the document
*/
public function __unset( $id ) {
$node = $this->getElementById( $id );
if( $node != null ) {
$node->parentNode->removeChild( $node );
}
}
/**
* Appends several types of nodes or node specifiers to another node in
* the document.
*
* @param target The target parent of the node(s) to be appended
* @param source The node or node specifier to append to the target
* @return The node that was appended to the target node
*/
public function append( $target, $source ) {
$target = $this->resolve( $target );
if( isset( $source->nodeValue ) ) {
$append = $source;
}
else if( is_array( $source ) ) {
$append = $this->build( $source );
}
else if( is_string( $source ) ) {
if( preg_match( '/^<([^>]+)>$/', $source, $m ) == 1 ) {
$append = $this->dom->createElement( $m[ 1 ] );
}
else {
$append = $this->dom->createTextNode( $source );
}
}
else {
$append = $this->dom->createTextNode( strval( $source ) );
}
$target->appendChild( $append );
return $append;
}
/**
* Builds a DOM document fragment using a DTL specification given by a
* nested array. Basic example:
*
* [ 'div', [
* [ 'h1', 'Title' ],
* [ 'h2', 'Subtitle' ],
* ], [ 'class' => 'div-class' ] ]
*
* @param dtl The document template literal value
* @return The root node of the constructed DOM document fragment
* @throws Exception if the DTL contains an invalid/unsupported item
*/
public function build( $dtl, $root = null ) {
//Check for DTL as a string.
if( is_string( $dtl ) ) {
//Check for "slightly compressed" DTL strings.
if( preg_match( '/^\[\w+,/', $dtl ) == 1 ) {
//Expand the DTL string to normal JSON.
$dtl = preg_replace_callback(
'/(\[(\w+),)|({(\w+):)/',
function( $groups ) {
if( $groups[ 0 ][ 0 ] == '{' ) {
return '{"' . $groups[ 4 ] . '":';
}
return '["' . $groups[ 2 ] . '",';
},
$dtl
);
}
//Use the JSON parser to convert the DTL string.
$dtl = json_decode( $dtl, true );
}
//Create the container node for this part of the document.
$node = $this->dom->createElement( $dtl[ 0 ] );
//See if this node needs to be the root node for an entire fragment.
if( $root === null ) {
$root = $node;
}
//Scan through the template to build each element.
$num_args = count( $dtl );
for( $i = 1; $i < $num_args; ++$i ) {
//A null value is ignored.
if( $dtl[ $i ] === null ) {
continue;
}
//Shortcut to the current "argument" in the specifier.
$arg = $dtl[ $i ];
//Strings are used for text node content.
if( is_string( $arg ) ) {
$text_node = $this->dom->createTextNode( $arg );
$node->appendChild( $text_node );
}
//Numbers.
else if( is_numeric( $arg ) ) {
$text_node = $this->dom->createTextNode( strval( $arg ) );
$node->appendChild( $text_node );
}
//Arrays specify child nodes or attributes on the current node.
else if( is_array( $arg ) ) {
//Numeric arrays specify a list of child nodes.
if( isset( $arg[ 0 ] ) ) {
$num_subargs = count( $arg );
for( $j = 0; $j < $num_subargs; ++$j ) {
$subarg = $arg[ $j ];
if( isset( $subarg->nodeType ) ) {
$node->appendChild( $subarg );
}
else {
$node->appendChild( $this->build( $subarg, $root ) );
}
}
}
//Associative arrays specify an attribute list.
else {
//Set each attribute on the current node.
foreach( $arg as $k => $v ) {
//Nodes with an ID attribute get assigned to the root
//node as a property for easier access.
if(
( $k == 'id' )
&&
( isset( $root->$k ) == false )
) {
$root->$v = $node;
}
//Set the attribute value.
$node->setAttribute( $k, $v );
}
}
}
//Objects may contain DOM elements.
else if( is_object( $arg ) ) {
if( isset( $arg->nodeType ) ) {
$node->appendChild( $arg );
}
else {
throw new \Exception( 'Invalid DTL object type.' );
}
}
//DTL argument is not null, a string, or an array.
else {
throw new \Exception( 'Unknown DTL argument type.' );
}
}
//Return the constructed node.
return $node;
}
/**
* Removes all child nodes from a given node.
*
* @param target The target element (or ID) to empty
*/
public function clear( $target ) {
$target = $this->resolve( $target );
if( $target->hasChildNodes() ) {
$num_child_nodes = $target->childNodes->length;
for( $i = ( $num_child_nodes - 1 ); $i >= 0; --$i ) {
$target->removeChild( $target->childNodes->item( $i ) );
}
}
}
/**
* Converts tabular data into a DTL specification of a table.
*
* @param data The data to display in the table
* @return The table's DTL structure
*/
public function convertData( $data, $headings = null ) {
$rows = [];
if( is_array( $headings ) ) {
$heads = [];
for( $i = 0; $i < count( $headings ); ++$i ) {
$heads[] = [ 'th', $headings[ $i ] ];
}
$rows[] = [ 'tr', $heads ];
}
$num_rows = count( $data );
for( $i = 0; $i < $num_rows; ++$i ) {
$cells = [];
$num_cells = count( $data[ $i ] );
for( $j = 0; $j < $num_cells; ++$j ) {
$cells[] = [ 'td', $data[ $i ][ $j ] ];
}
$rows[] = [ 'tr', $cells ];
}
return [ 'table', [ [ 'tbody', $rows ] ] ];
}
/**
* Converts a simplified array of link specifiers into a DTL structure.
*
* Each link is specified by its own array. The first element is the
* anchor element's text. The second element is the value string of the
* `href` attribute. The third element may be an associative array of
* query parameters.
*
* Example:
* [
* [ 'Text', '/path' ],
* [ 'Text 2', '/path2' ],
* [ 'T3', '/p3', [ 'x' => '1', 'y' => '2' ] ]
* ]
*
* @param links The array of link values
* @param list The name of the list's container element
* @param item The name of the anchor wrapping element
* @return The DTL structure for the list of links
*/
public function convertLinks( $links, $list = 'ul', $item = 'li' ) {
$items = [];
$num_links = count( $links );
for( $i = 0; $i < $num_links; ++$i ) {
$link = $links[ $i ];
$href = $link[ 1 ];
if( isset( $link[ 2 ] ) ) {
$params = [];
foreach( $link[ 2 ] as $k => $v ) {
$params[] = $k . '=' . urlencode( $v );
}
$href .= '?' . implode( '&', $params );
}
$anchor = [ 'a', $link[ 0 ], [ 'href' => $href ] ];
$items[] = [ $item, [ $anchor ] ];
}
return [ $list, $items ];
}
/**
* Uses the given HTML to replace the contents of the target node.
*
* @param target The target node (or ID) of the element to update
* @param html The HTML as a string to place in the target element
* @return The target node, or false on failure
*/
public function html( $target, $html ) {
$target = $this->resolve( $target );
$frag = $this->dom->createDocumentFragment();
$frag->appendXML( $html );
$this->clear( $target );
$target->appendChild( $frag );
return $target;
}
/**
* Determines if a given array index exists for this object. Array
* indexes can be used to look up nodes in the document by ID.
*
* @param id The DOM element ID of the element to check
* @return True if the element exists, false if it does not
*/
public function offsetExists( $id ) {
return $this->__isset( $id );
}
/**
* Retrieves a node from the document using array subscript notation to
* specify the ID of the node.
*
* @param id The DOM element ID of the element to retrieve
* @return The requested DOM element, or null on failure
*/
public function offsetGet( $id ) {
return $this->__get( $id );
}
/**
* Loads a node into the document using array subscript notation to
* specifty the target ID of the load operation.
*
* @param id The DOM element ID of the element to target
* @param node The DOM element to load into the document
*/
public function offsetSet( $id, $node ) {
$this->__set( $id, $node );
}
/**
* Removes a node from the document using array subscript notation to
* specify the ID of the node to remove.
*
* @param id The DOM ID of the element to remove from the document
*/
public function offsetUnset( $id ) {
$this->__unset( $id );
}
/**
* Replaces a node in the document with another node.
* Note: This method is intended to be an alternative to `append` when
* using property references and array subscripts for setting nodes in the
* document.
*
* @param target The target node (or ID of a node) to be replaced
* @param source The source node to insert into the document
* @return The node that was replaced, or false on failure
*/
public function replace( $target, $source ) {
$target = $this->resolve( $target );
$parent = $target->parentNode;
return $parent->replaceChild( $source, $target );
}
/**
* Checks and attempts to resolve many different ways of specifying a
* target node in the document.
*
* @param target The target node object, array, string, whatever
* @return If found, the node, otherwise false
*/
public function resolve( $target ) {
if( is_string( $target ) ) {
$node = $this->dom->getElementById( $target );
if( $node == null ) {
return false;
}
return $node;
}
return $target;
}
/**
* Sets the automatic setter method for use in object property reference
* and array subscript assignment.
*
* @param auto_set The name of the method to use for setting new nodes in
* the document. This should be one of the follwing
* method names: `append`, `html`, `replace`, `text`
*/
public function setAutoSet( $auto_set ) {
if( in_array( $auto_set, [ 'append', 'html', 'replace', 'text' ] ) ) {
$this->auto_set = $auto_set;
}
}
/**
* Sets the text for the target node in the document.
*
* @param target The target node (or ID) for which to set the text
* @param text The text to set in the node
* @return The text node of the target node, or false on failure
*/
public function text( $target, $text ) {
$target = $this->resolve( $target );
$this->clear( $target );
$text_node = $this->dom->createTextNode( $text );
$target->appendChild( $text_node );
return $text_node;
}
/*------------------------------------------------------------------------
Protected Methods
------------------------------------------------------------------------*/
/*------------------------------------------------------------------------
Private Methods
------------------------------------------------------------------------*/
}
/*----------------------------------------------------------------------------
Functions
----------------------------------------------------------------------------*/
/*----------------------------------------------------------------------------
Execution
----------------------------------------------------------------------------*/
if( $_SERVER[ 'SCRIPT_FILENAME' ] == __FILE__ ) {
//see what the output looks like
header( 'Content-Type: text/plain' );
//load an empty document template into a new renderer
$doc = new DOMRenderer( 'example.html' );
//set some plain text using the following assignment operations
$doc->setAutoSet( 'text' );
//set the title using a property reference
$doc->title = 'Dynamic Title';
//set the subtitle using array subscripting
$doc[ 'subtitle' ] = 'Dynamic Subtitle';
//use append method to load navigation (next)
$doc->setAutoSet( 'append' );
//demonstrate shorthand navigation generation
$doc->navigation = $doc->convertLinks( [
[ 'Home', '.' ],
[ 'Page 1', 'example.php', [ 'p' => '1' ] ],
[ 'Page 2', null, [ 'p' => '2' ] ]
] );
//we can still get stuff using the `dom` property
$divs = $doc->dom->getElementsByTagName( 'div' );
$divs->item( 1 )->nodeValue = 'This works, too!';
//preserve markup in an element using the `html` method
$doc->html( $divs->item( 2 ), 'Some <strong>marked up</strong> content.' );
//demonstrate complex tree construction using DTL
$part = $doc->build(
[ 'div', [ 'class' => 'section' ], [
[ 'h3', 'Section Heading' ],
[ 'p', 'A paragraph in this section.' ],
[ 'p', 'Before ', [ [ 'a', 'Link Text', [ 'href' => '.' ] ], ], ' After' ],
[ 'p', 'A final paragraph.' ]
] ]
);
$divs->item( 3 )->appendChild( $part );
//maybe the DTL specification is coming from outside PHP
$part = $doc->build( '[h3,"Hello World",{id:"h3id"}]' );
$divs->item( 5 )->appendChild( $part );
//oops, I forgot something
$part->h3id->nodeValue = 'Hello World!';
//make a table
$heads = [ 'A', 'B', 'C', 'D' ];
$data = [
[ 1, 2, 3, 4 ],
[ 2, 3, 4, 5 ],
[ 3, 4, 5, 6 ]
];
$doc->append( $divs->item( 5 ), $doc->convertData( $data, $heads ) );
//send the rendered document to the client
echo $doc;
}
| bsd-2-clause |
marchpig/Dexter | project/dexter-core/src/java/com/samsung/sec/dexter/core/util/EmptyDexterClient.java | 6488 | /**
* Copyright (c) 2016 Samsung Electronics, Inc.,
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.samsung.sec.dexter.core.util;
import com.google.common.base.Strings;
import com.samsung.sec.dexter.core.checker.CheckerConfig;
import com.samsung.sec.dexter.core.config.DefectGroup;
import com.samsung.sec.dexter.core.config.DexterCode;
import com.samsung.sec.dexter.core.config.DexterConfig;
import com.samsung.sec.dexter.core.config.DexterConfig.LANGUAGE;
import com.samsung.sec.dexter.core.defect.Defect;
import com.samsung.sec.dexter.core.filter.EmptyFalseAlarmConfiguration;
import com.samsung.sec.dexter.core.filter.IFalseAlarmConfiguration;
import com.samsung.sec.dexter.core.plugin.IDexterPlugin;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
public class EmptyDexterClient implements IDexterClient {
private final static Logger LOG = Logger.getLogger(EmptyDexterClient.class);
private final static String HTTP_PREFIX = "http://";
@Override
public String getDexterDashboardUrl() {
return "";
}
@Override
public String getDexterWebUrl() {
return "";
}
@Override
public boolean isCurrentUserAdmin() {
return false;
}
@Override
public int getCurrentUserNo() {
return 0;
}
@Override
public void setCurrentUserNo(int userNo) {}
@Override
public int getServerPort() {
return 0;
}
@Override
public String getServerHost() {
return "";
}
@Override
public String getCurrentUserPwd() {
return "";
}
@Override
public String getSourceCode(String modulePath, String fileName) {
return "";
}
@Override
public List<DexterCode> getCodes(String codeKey) {
return new ArrayList<DexterCode>(0);
}
@Override
public List<DefectGroup> getDefectGroupList() {
return new ArrayList<DefectGroup>(0);
}
@Override
public boolean deleteDefectGroup(long defectGroupId) {
return false;
}
@Override
public boolean updateDefectGroup(DefectGroup defectGroup) {
return false;
}
@Override
public void insertDefectGroup(DefectGroup defectGroup) {}
@Override
public List<DefectGroup> getDefectGroupByGroupName(String groupName) {
return new ArrayList<DefectGroup>(0);
}
@Override
public void deleteDefects(String modulePath, String fileName) {}
@Override
public long getGlobalDid(Defect defect) {
return 0;
}
@Override
public IFalseAlarmConfiguration getFalseAlarmTree() {
return new EmptyFalseAlarmConfiguration();
}
@Override
public int getLastFalseAlarmVersion() {
return 0;
}
@Override
public void insertDefectFilter(Defect defect) {}
@Override
public void removeDefectFilter(Defect defect) {}
@Override
public void changeDefectStatus(Defect defect, String status) {}
@Override
public void createAccount(String id, String pwd, boolean isAdmin) {}
@Override
public boolean hasAccount(String id) {
return false;
}
@Override
public boolean isServerAlive() {
return false;
}
@Override
public String getCurrentUserId() {
return "";
}
@Override
public boolean isLogin() {
return false;
}
@Override
public void insertSourceCode(long snapshotId, long defectGroupId, String modulePath, String fileName,
String sourceCode) {}
@Override
public void sendAnalsysisResult(String resultJson) {}
@Override
public void login() {}
@Override
public void login(String id, String pwd) {}
@Override
public void setWebResource(IDexterWebResource resource) {}
@Override
public void setCurrentUserAdmin(boolean isAdmin) {}
@Override
public void setLogin(boolean b) {}
@Override
public String getDexterPluginUpdateUrl() {
return "";
}
@Override
public CheckerConfig getDexterPluginChecker(IDexterPlugin plugin, String pluginName) {
return new CheckerConfig("empty checker config", LANGUAGE.UNKNOWN);
}
@Override
public void handleWhenNotStandaloneMode() {}
@Override
public void handleWhenStandaloneMode() {}
@Override
public String getDexterCodeMetricsUrl() {
return "";
}
@Override
public String getDexterFunctionMetricsUrl() {
return "";
}
@Override
public boolean hasSupportedHelpHtmlFile(StringBuilder url) {
return false;
}
void setWebResource(DummyDexterWebResource webResource) {}
@Override
public boolean isServerAlive(String serverAddress) {
assert Strings.isNullOrEmpty(serverAddress) == false;
try {
IDexterWebResource webResource = new JerseyDexterWebResource();
final String text = webResource.getText(HTTP_PREFIX + serverAddress + DexterConfig.CHECK_SERVER_ADDRESS,
"", "");
return "ok".equals(text);
} catch (Exception e) {
LOG.debug(e.getMessage(), e);
return false;
}
}
}
| bsd-2-clause |
andrejbauer/fakebook | fakebook.py | 13411 | #!/usr/bin/env python3
import sqlite3
import bottle
import hashlib # računanje MD5 kriptografski hash za gesla
from datetime import datetime
######################################################################
# Konfiguracija
# Vklopi debug, da se bodo predloge same osvežile in da bomo dobivali
# lepa sporočila o napakah.
bottle.debug(True)
# Datoteka, v kateri je baza
baza_datoteka = "fakebook.sqlite"
# Mapa s statičnimi datotekami
static_dir = "./static"
# Skrivnost za kodiranje cookijev
secret = "to skrivnost je zelo tezko uganiti 1094107c907cw982982c42"
######################################################################
# Pomožne funkcije
def password_md5(s):
"""Vrni MD5 hash danega UTF-8 niza. Gesla vedno spravimo v bazo
kodirana s to funkcijo."""
h = hashlib.md5()
h.update(s.encode('utf-8'))
return h.hexdigest()
# Funkcija, ki v cookie spravi sporocilo
def set_sporocilo(tip, vsebina):
bottle.response.set_cookie('message', (tip, vsebina), path='/', secret=secret)
# Funkcija, ki iz cookija dobi sporočilo, če je
def get_sporocilo():
sporocilo = bottle.request.get_cookie('message', default=None, secret=secret)
bottle.response.delete_cookie('message')
return sporocilo
# To smo dobili na http://stackoverflow.com/questions/1551382/user-friendly-time-format-in-python
# in predelali v slovenščino. Da se še izboljšati, da bo pravilno delovala dvojina itd.
def pretty_date(time):
"""
Predelaj čas (v formatu Unix epoch) v opis časa, na primer
'pred 4 minutami', 'včeraj', 'pred 3 tedni' ipd.
"""
now = datetime.now()
if type(time) is int:
diff = now - datetime.fromtimestamp(time)
elif isinstance(time,datetime):
diff = now - time
elif not time:
diff = now - now
second_diff = diff.seconds
day_diff = diff.days
if day_diff < 0:
return ''
if day_diff == 0:
if second_diff < 10:
return "zdaj"
if second_diff < 60:
return "pred " + str(second_diff) + " sekundami"
if second_diff < 120:
return "pred minutko"
if second_diff < 3600:
return "pred " + str( second_diff // 60 ) + " minutami"
if second_diff < 7200:
return "pred eno uro"
if second_diff < 86400:
return "pred " + str( second_diff // 3600 ) + " urami"
if day_diff == 1:
return "včeraj"
if day_diff < 7:
return "pred " + str(day_diff) + " dnevi"
if day_diff < 31:
return "pred " + str(day_diff//7) + " tedni"
if day_diff < 365:
return "pred " + str(day_diff//30) + " meseci"
return "pred " + str(day_diff//365) + " leti"
def get_user(auto_login = True):
"""Poglej cookie in ugotovi, kdo je prijavljeni uporabnik,
vrni njegov username in ime. Če ni prijavljen, presumeri
na stran za prijavo ali vrni None (advisno od auto_login).
"""
# Dobimo username iz piškotka
username = bottle.request.get_cookie('username', secret=secret)
# Preverimo, ali ta uporabnik obstaja
if username is not None:
c = baza.cursor()
c.execute("SELECT username, ime FROM uporabnik WHERE username=?",
[username])
r = c.fetchone()
c.close ()
if r is not None:
# uporabnik obstaja, vrnemo njegove podatke
return r
# Če pridemo do sem, uporabnik ni prijavljen, naredimo redirect
if auto_login:
bottle.redirect('/login/')
else:
return None
def traci(limit=10):
"""Vrni dano število tračev (privzeto 10). Rezultat je seznam, katerega
elementi so oblike [trac_id, avtor, ime_avtorja, cas_objave, vsebina, komentarji],
pri čemer so komentarji seznam elementov oblike [avtor, ime_avtorja, vsebina],
urejeni po času objave.
"""
c = baza.cursor()
c.execute(
"""SELECT id, username, ime, cas, vsebina
FROM trac JOIN uporabnik ON trac.avtor = uporabnik.username
ORDER BY cas DESC
LIMIT ?
""", [limit])
# Rezultat predelamo v nabor.
traci = tuple(c)
# Nabor id-jev tračev, ki jih bomo vrnili
tids = (trac[0] for trac in traci)
# Logično bi bilo, da bi zdaj za vsak trač naredili en SELECT za
# komentarje tega trača. Vendar je drago delati veliko število
# SELECTOV, zato se raje potrudimo in napišemo en sam SELECT.
c.execute(
"""SELECT trac.id, username, ime, komentar.vsebina
FROM
(komentar JOIN trac ON komentar.trac = trac.id)
JOIN uporabnik ON uporabnik.username = komentar.avtor
WHERE
trac.id IN (SELECT id FROM trac ORDER BY cas DESC LIMIT ?)
ORDER BY
komentar.cas""", [limit])
# Rezultat poizvedbe ima nerodno obliko, pretvorimo ga v slovar,
# ki id trača preslika v seznam pripadajočih komentarjev.
# Najprej pripravimo slovar, ki vse id-je tračev slika v prazne sezname.
komentar = { tid : [] for tid in tids }
# Sedaj prenesemo rezultate poizvedbe v slovar
for (tid, username, ime, vsebina) in c:
komentar[tid].append((username, ime, vsebina))
c.close()
# Vrnemo nabor, kot je opisano v dokumentaciji funkcije:
return ((tid, u, i, pretty_date(c), v, komentar[tid])
for (tid, u, i, c, v) in traci)
######################################################################
# Funkcije, ki obdelajo zahteve odjemalcev.
@bottle.route("/static/<filename:path>")
def static(filename):
"""Splošna funkcija, ki servira vse statične datoteke iz naslova
/static/..."""
return bottle.static_file(filename, root=static_dir)
@bottle.route("/")
def main():
"""Glavna stran."""
# Iz cookieja dobimo uporabnika (ali ga preusmerimo na login, če
# nima cookija)
(username, ime) = get_user()
# Morebitno sporočilo za uporabnika
sporocilo = get_sporocilo()
# Seznam zadnjih 10 tračev
ts = traci()
# Vrnemo predlogo za glavno stran
return bottle.template("main.html",
ime=ime,
username=username,
traci=ts,
sporocilo=sporocilo)
@bottle.get("/login/")
def login_get():
"""Serviraj formo za login."""
return bottle.template("login.html",
napaka=None,
username=None)
@bottle.get("/logout/")
def logout():
"""Pobriši cookie in preusmeri na login."""
bottle.response.delete_cookie('username')
bottle.redirect('/login/')
@bottle.post("/login/")
def login_post():
"""Obdelaj izpolnjeno formo za prijavo"""
# Uporabniško ime, ki ga je uporabnik vpisal v formo
username = bottle.request.forms.username
# Izračunamo MD5 has gesla, ki ga bomo spravili
password = password_md5(bottle.request.forms.password)
# Preverimo, ali se je uporabnik pravilno prijavil
c = baza.cursor()
c.execute("SELECT 1 FROM uporabnik WHERE username=? AND password=?",
[username, password])
if c.fetchone() is None:
# Username in geslo se ne ujemata
return bottle.template("login.html",
napaka="Nepravilna prijava",
username=username)
else:
# Vse je v redu, nastavimo cookie in preusmerimo na glavno stran
bottle.response.set_cookie('username', username, path='/', secret=secret)
bottle.redirect("/")
@bottle.get("/register/")
def login_get():
"""Prikaži formo za registracijo."""
return bottle.template("register.html",
username=None,
ime=None,
napaka=None)
@bottle.post("/register/")
def register_post():
"""Registriraj novega uporabnika."""
username = bottle.request.forms.username
ime = bottle.request.forms.ime
password1 = bottle.request.forms.password1
password2 = bottle.request.forms.password2
# Ali uporabnik že obstaja?
c = baza.cursor()
c.execute("SELECT 1 FROM uporabnik WHERE username=?", [username])
if c.fetchone():
# Uporabnik že obstaja
return bottle.template("register.html",
username=username,
ime=ime,
napaka='To uporabniško ime je že zavzeto')
elif not password1 == password2:
# Geslo se ne ujemata
return bottle.template("register.html",
username=username,
ime=ime,
napaka='Gesli se ne ujemata')
else:
# Vse je v redu, vstavi novega uporabnika v bazo
password = password_md5(password1)
c.execute("INSERT INTO uporabnik (username, ime, password) VALUES (?, ?, ?)",
(username, ime, password))
# Daj uporabniku cookie
bottle.response.set_cookie('username', username, path='/', secret=secret)
bottle.redirect("/")
@bottle.post("/trac/new/")
def new_trac():
"""Ustvari nov trač."""
# Kdo je avtor trača?
(username, ime) = get_user()
# Vsebina trača
trac = bottle.request.forms.trac
c = baza.cursor()
c.execute("INSERT INTO trac (avtor, vsebina) VALUES (?,?)",
[username, trac])
# Presumerimo na glavno stran
return bottle.redirect("/")
@bottle.route("/user/<username>/")
def user_wall(username, sporocila=[]):
"""Prikaži stran uporabnika"""
# Kdo je prijavljeni uporabnik? (Ni nujno isti kot username.)
(username_login, ime_login) = get_user()
# Ime uporabnika (hkrati preverimo, ali uporabnik sploh obstaja)
c = baza.cursor()
c.execute("SELECT ime FROM uporabnik WHERE username=?", [username])
(ime,) = c.fetchone()
# Koliko tracev je napisal ta uporabnik?
c.execute("SELECT COUNT(*) FROM trac WHERE avtor=?", [username])
(t,) = c.fetchone()
# Koliko komentarjev je napisal ta uporabnik?
c.execute("SELECT COUNT(*) FROM komentar WHERE avtor=?", [username])
(k,) = c.fetchone()
# Prikažemo predlogo
return bottle.template("user.html",
uporabnik_ime=ime,
uporabnik=username,
username=username_login,
ime=ime_login,
trac_count=t,
komentar_count=k,
sporocila=sporocila)
@bottle.post("/user/<username>/")
def user_change(username):
"""Obdelaj formo za spreminjanje podatkov o uporabniku."""
# Kdo je prijavljen?
(username, ime) = get_user()
# Novo ime
ime_new = bottle.request.forms.ime
# Staro geslo (je obvezno)
password1 = password_md5(bottle.request.forms.password1)
# Preverimo staro geslo
c = baza.cursor()
c.execute ("SELECT 1 FROM uporabnik WHERE username=? AND password=?",
[username, password1])
# Pokazali bomo eno ali več sporočil, ki jih naberemo v seznam
sporocila = []
if c.fetchone():
# Geslo je ok
# Ali je treba spremeniti ime?
if ime_new != ime:
c.execute("UPDATE uporabnik SET ime=? WHERE username=?", [ime_new, username])
sporocila.append(("alert-success", "Spreminili ste si ime."))
# Ali je treba spremeniti geslo?
password2 = bottle.request.forms.password2
password3 = bottle.request.forms.password3
if password2 or password3:
# Preverimo, ali se gesli ujemata
if password2 == password3:
# Vstavimo v bazo novo geslo
password2 = password_md5(password2)
c.execute ("UPDATE uporabnik SET password=? WHERE username = ?", [password2, username])
sporocila.append(("alert-success", "Spremenili ste geslo."))
else:
sporocila.append(("alert-danger", "Gesli se ne ujemata"))
else:
# Geslo ni ok
sporocila.append(("alert-danger", "Napačno staro geslo"))
c.close ()
# Prikažemo stran z uporabnikom, z danimi sporočili. Kot vidimo,
# lahko kar pokličemo funkcijo, ki servira tako stran
return user_wall(username, sporocila=sporocila)
@bottle.post("/komentar/<tid:int>/")
def komentar(tid):
"""Vnesi nov komentar."""
(username, ime) = get_user()
komentar = bottle.request.forms.komentar
baza.execute("INSERT INTO komentar (vsebina, trac, avtor) VALUES (?, ?, ?)",
[komentar, tid, username])
bottle.redirect("/#trac-{0}".format(tid))
@bottle.route("/trac/<tid:int>/delete/")
def komentar_delete(tid):
"""Zbriši komentar."""
(username, ime) = get_user()
# DELETE napišemo tako, da deluje samo, če je avtor komentarja prijavljeni uporabnik
r = baza.execute("DELETE FROM trac WHERE id=? AND avtor=?", [tid, username]).rowcount;
if not r == 1:
return "Vi ste hacker."
else:
set_sporocilo('alert-success', "Vaš komentar je IZBRISAN.")
return bottle.redirect("/")
######################################################################
# Glavni program
# priklopimo se na bazo
baza = sqlite3.connect(baza_datoteka, isolation_level=None)
# poženemo strežnik na portu 8080, glej http://localhost:8080/
bottle.run(host='localhost', port=8080, reloader=True)
| bsd-2-clause |
hughperkins/gpu-experiments | gpuexperiments/volkov_mm.py | 8363 | # Note that this will erase your nvidia cache, ~/.nv/ComputeCache This may or may not be an undesirable side-effect for you. For example, cutorch will take 1-2 minutes or so to start after this cache has been emptied.
"""
This software contains source code provided by NVIDIA Corporation.
"""
from __future__ import print_function, division
import time
import string
import random
import jinja2
import argparse
import numpy as np
import pyopencl as cl
import subprocess
import os
from os.path import join
from gpuexperiments.callkernel import call_cl_kernel
#import gpuexperiments.cpu_check
from gpuexperiments.timecheck import inittime, timecheck
import lib_clgpuexp
from lib_clgpuexp import clearComputeCache, getPtx, timeKernel3d, buildKernel, initClGpu
from lib_clgpuexp import dumpSass
parser = argparse.ArgumentParser()
parser.add_argument('--printptx', type=bool, default=False)
args = parser.parse_args()
initClGpu()
times = []
compute_units = lib_clgpuexp.device.get_info(cl.device_info.MAX_COMPUTE_UNITS)
maxShared = lib_clgpuexp.device.get_info(cl.device_info.LOCAL_MEM_SIZE) // 1024
compute_capability = (
lib_clgpuexp.device.get_info(cl.device_info.COMPUTE_CAPABILITY_MAJOR_NV),
lib_clgpuexp.device.get_info(cl.device_info.COMPUTE_CAPABILITY_MINOR_NV)
)
deviceName = lib_clgpuexp.device.get_info(cl.device_info.NAME)
deviceSimpleName = deviceName.replace('GeForce', '').replace('GTX', '').strip().replace(' ', '').lower()
print('deviceName', deviceName, 'compute capability', compute_capability)
print('compute units', compute_units, 'max shared memory', maxShared)
shared_memory_per_sm = None
# data comes from http://developer.download.nvidia.com/compute/cuda/CUDA_Occupancy_calculator.xls
if compute_capability[0] == 5:
if compute_capability[1] == 0:
shared_memory_per_sm = 65536
elif compute_capability[1] == 2:
shared_memory_per_sm = 98304
else:
raise Exception('compute capability %s not recognized' % compute_capability)
else:
raise Exception('compute capability %s not recognized' % compute_capability)
assert shared_memory_per_sm is not None
header = r"""
// adapted from CUDA 7.5 SDK
// original copyright header:
/**
* Copyright 1993-2015 NVIDIA Corporation. All rights reserved.
*
* Please refer to the NVIDIA end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
*/
// Per my understanding, this is licensed under clause 2.1.1 of the EULA:
// 2.1.1. Source Code
//
// Developer shall have the right to modify and create derivative
// works with the Source Code. Developer shall own any derivative
// works ("Derivatives") it creates to the Source Code, provided
// that Developer uses the Materials in accordance with the terms
// and conditions of this Agreement. Developer may distribute the
// Derivatives, provided that all NVIDIA copyright notices and
// trademarks are propagated and used properly and the
// Derivatives include the following statement: "This software
// contains source code provided by NVIDIA Corporation."
"""
code_template_8 = header + r"""
#define BLOCK_SIZE {{BLOCK_SIZE}}
kernel void {{kernelname}} (global float *A, global float *B, global float *C, int wA, int wB) {
int bx = get_group_id(0);
int by = get_group_id(1);
int tx = get_local_id(0);
int ty = get_local_id(1);
int aBegin = wA * BLOCK_SIZE * by;
int aEnd = aBegin + wA - 1;
int aStep = BLOCK_SIZE;
int bBegin = BLOCK_SIZE * bx;
int bStep = BLOCK_SIZE * wB;
float Csub[{{outs}}];
{% for i in range(outs) %}
Csub[{{i}}] = 0;
{% endfor %}
for (int a = aBegin, b = bBegin; a <= aEnd; a += aStep, b += bStep) {
local float As[BLOCK_SIZE][BLOCK_SIZE];
local float Bs[BLOCK_SIZE][BLOCK_SIZE];
{% for i in range(outs) %}
As[ty + {{i}} * BLOCK_SIZE / {{outs}}][tx] = A[a + wA * (ty + {{i}} * BLOCK_SIZE / {{outs}}) + tx];
Bs[ty + {{i}} * BLOCK_SIZE / {{outs}}][tx] = B[b + wB * (ty + {{i}} * BLOCK_SIZE / {{outs}}) + tx];
{% endfor %}
barrier(CLK_LOCAL_MEM_FENCE);
#pragma unroll 32
for(int k = 0; k < BLOCK_SIZE; ++k) {
{% for i in range(outs) %}
Csub[{{i}}] = fma(As[ty + {{i}} * BLOCK_SIZE / {{outs}}][k], Bs[k][tx], Csub[{{i}}]);
{% endfor %}
}
barrier(CLK_LOCAL_MEM_FENCE);
}
int c = wB * BLOCK_SIZE * by + BLOCK_SIZE * bx;
{% for i in range(outs) %}
C[c + wB * (ty + {{i}} * BLOCK_SIZE / {{outs}}) + tx] = Csub[{{i}}];
{% endfor %}
}
"""
# S = 1024
blocksize=32
experiments = [
{'name': 'mm1_s{S}', 'code': code_template_8, 'block': (blocksize, blocksize, 1), 'outs': 1},
{'name': 'mm2_s{S}', 'code': code_template_8, 'block': (blocksize, blocksize//2, 1), 'outs': 2},
{'name': 'mm4_s{S}', 'code': code_template_8, 'block': (blocksize, blocksize//4, 1), 'outs': 4},
{'name': 'mm8_s{S}', 'code': code_template_8, 'block': (blocksize, blocksize//8, 1), 'outs': 8}
]
cl = lib_clgpuexp.cl
ctx = lib_clgpuexp.ctx
q = lib_clgpuexp.q
mf = lib_clgpuexp.mf
times = []
full_occupancy_bsm = 32 # this should probably not be hard coded...
if args.printptx:
clearComputeCache()
for experiment in experiments:
S = 32
while S <= 1024:
name = experiment['name'].format(S=S)
template = jinja2.Template(experiment['code'], undefined=jinja2.StrictUndefined)
source = template.render(kernelname=name, BLOCK_SIZE=blocksize, **experiment)
# print('source', source)
kernel = buildKernel(name, source)
grid = (S//blocksize, S//blocksize, 1)
block = experiment['block']
#A = np.zeros((S,S), dtype=np.float32)
#B = np.zeros((S,S), dtype=np.float32)
lib_clgpuexp.d = np.zeros((S,S), dtype=np.float32)
d = lib_clgpuexp.d
d[:] = np.random.rand(d.size).reshape(S,S) - 0.5
lib_clgpuexp.d_cl = cl.Buffer(ctx, mf.READ_WRITE | mf.COPY_HOST_PTR, hostbuf=d)
A = d.reshape(S,S)
lib_clgpuexp.out = np.zeros((S,S), dtype=np.float32)
out = lib_clgpuexp.out
out[:] = np.random.rand(out.size).reshape(S,S) - 0.5
lib_clgpuexp.out_cl = cl.Buffer(ctx, mf.READ_WRITE | mf.COPY_HOST_PTR, hostbuf=out)
B = out.reshape(S,S)
C = np.zeros((S,S), dtype=np.float32)
C_cl = cl.Buffer(lib_clgpuexp.ctx, lib_clgpuexp.mf.READ_WRITE | lib_clgpuexp.mf.COPY_HOST_PTR, hostbuf=C)
for it in range(2):
t = timeKernel3d(name, kernel, grid=grid, block=block, add_args=[
C_cl, S, S
])
t_sum = 0
for it in range(5):
t_sum += timeKernel3d(name, kernel, grid=grid, block=block, add_args=[
C_cl, S, S
])
t = t_sum / 5
ops = S * S * S * 2
gflops = ops / (t/1000) / 1000 / 1000 / 1000
cl.enqueue_copy(q, C, C_cl)
q.finish()
print(C[0,:10])
print(A.dot(B)[0,:10])
C_cpu = A.dot(B)
cpu_samples = ''
gpu_samples = ''
diffs = ''
for sample in range(20):
x = random.randint(0, S - 1)
y = random.randint(0, S - 1)
c_gpu = C[x,y]
c_local = C_cpu[x,y]
diff = abs(c_gpu - c_local)
cpu_samples += ' %.4f' % c_local
gpu_samples += ' %.4f' % c_gpu
diffs += ' %.5f' % diff
# print(c_gpu, c_local, diff)
assert diff < 1e-4
print('cpu', cpu_samples)
print('gpu', gpu_samples)
print('diffs', diffs)
# print(getPtx(name))
# dumpSass(name)
times.append({'name': name, 'time': t, 'gflops': gflops})
print('name', name, 't', t, 'gflops', gflops)
if S <= 128:
S *= 2
else:
S += 128
f = open('/tmp/volkov_mm_%s.tsv' % deviceSimpleName, 'w')
print('')
line = 'name\ttime\tflops'
print(line)
f.write(line + '\n')
for timeinfo in times:
line = '%s\t%.1f\t%.1f' % (timeinfo['name'], timeinfo['time'], timeinfo['gflops'])
print(line)
f.write(line + '\n')
f.close()
| bsd-2-clause |
fluffyfreak/bgfx | 3rdparty/spirv-tools/source/opt/local_single_block_elim_pass.cpp | 9316 | // Copyright (c) 2017 The Khronos Group Inc.
// Copyright (c) 2017 Valve Corporation
// Copyright (c) 2017 LunarG 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.
#include "source/opt/local_single_block_elim_pass.h"
#include <vector>
#include "source/opt/iterator.h"
namespace spvtools {
namespace opt {
namespace {
const uint32_t kStoreValIdInIdx = 1;
} // anonymous namespace
bool LocalSingleBlockLoadStoreElimPass::HasOnlySupportedRefs(uint32_t ptrId) {
if (supported_ref_ptrs_.find(ptrId) != supported_ref_ptrs_.end()) return true;
if (get_def_use_mgr()->WhileEachUser(ptrId, [this](Instruction* user) {
SpvOp op = user->opcode();
if (IsNonPtrAccessChain(op) || op == SpvOpCopyObject) {
if (!HasOnlySupportedRefs(user->result_id())) {
return false;
}
} else if (op != SpvOpStore && op != SpvOpLoad && op != SpvOpName &&
!IsNonTypeDecorate(op)) {
return false;
}
return true;
})) {
supported_ref_ptrs_.insert(ptrId);
return true;
}
return false;
}
bool LocalSingleBlockLoadStoreElimPass::LocalSingleBlockLoadStoreElim(
Function* func) {
// Perform local store/load, load/load and store/store elimination
// on each block
bool modified = false;
std::vector<Instruction*> instructions_to_kill;
std::unordered_set<Instruction*> instructions_to_save;
for (auto bi = func->begin(); bi != func->end(); ++bi) {
var2store_.clear();
var2load_.clear();
auto next = bi->begin();
for (auto ii = next; ii != bi->end(); ii = next) {
++next;
switch (ii->opcode()) {
case SpvOpStore: {
// Verify store variable is target type
uint32_t varId;
Instruction* ptrInst = GetPtr(&*ii, &varId);
if (!IsTargetVar(varId)) continue;
if (!HasOnlySupportedRefs(varId)) continue;
// If a store to the whole variable, remember it for succeeding
// loads and stores. Otherwise forget any previous store to that
// variable.
if (ptrInst->opcode() == SpvOpVariable) {
// If a previous store to same variable, mark the store
// for deletion if not still used.
auto prev_store = var2store_.find(varId);
if (prev_store != var2store_.end() &&
instructions_to_save.count(prev_store->second) == 0) {
instructions_to_kill.push_back(prev_store->second);
modified = true;
}
bool kill_store = false;
auto li = var2load_.find(varId);
if (li != var2load_.end()) {
if (ii->GetSingleWordInOperand(kStoreValIdInIdx) ==
li->second->result_id()) {
// We are storing the same value that already exists in the
// memory location. The store does nothing.
kill_store = true;
}
}
if (!kill_store) {
var2store_[varId] = &*ii;
var2load_.erase(varId);
} else {
instructions_to_kill.push_back(&*ii);
modified = true;
}
} else {
assert(IsNonPtrAccessChain(ptrInst->opcode()));
var2store_.erase(varId);
var2load_.erase(varId);
}
} break;
case SpvOpLoad: {
// Verify store variable is target type
uint32_t varId;
Instruction* ptrInst = GetPtr(&*ii, &varId);
if (!IsTargetVar(varId)) continue;
if (!HasOnlySupportedRefs(varId)) continue;
uint32_t replId = 0;
if (ptrInst->opcode() == SpvOpVariable) {
// If a load from a variable, look for a previous store or
// load from that variable and use its value.
auto si = var2store_.find(varId);
if (si != var2store_.end()) {
replId = si->second->GetSingleWordInOperand(kStoreValIdInIdx);
} else {
auto li = var2load_.find(varId);
if (li != var2load_.end()) {
replId = li->second->result_id();
}
}
} else {
// If a partial load of a previously seen store, remember
// not to delete the store.
auto si = var2store_.find(varId);
if (si != var2store_.end()) instructions_to_save.insert(si->second);
}
if (replId != 0) {
// replace load's result id and delete load
context()->KillNamesAndDecorates(&*ii);
context()->ReplaceAllUsesWith(ii->result_id(), replId);
instructions_to_kill.push_back(&*ii);
modified = true;
} else {
if (ptrInst->opcode() == SpvOpVariable)
var2load_[varId] = &*ii; // register load
}
} break;
case SpvOpFunctionCall: {
// Conservatively assume all locals are redefined for now.
// TODO(): Handle more optimally
var2store_.clear();
var2load_.clear();
} break;
default:
break;
}
}
}
for (Instruction* inst : instructions_to_kill) {
context()->KillInst(inst);
}
return modified;
}
void LocalSingleBlockLoadStoreElimPass::Initialize() {
// Initialize Target Type Caches
seen_target_vars_.clear();
seen_non_target_vars_.clear();
// Clear collections
supported_ref_ptrs_.clear();
// Initialize extensions whitelist
InitExtensions();
}
bool LocalSingleBlockLoadStoreElimPass::AllExtensionsSupported() const {
// If any extension not in whitelist, return false
for (auto& ei : get_module()->extensions()) {
const char* extName =
reinterpret_cast<const char*>(&ei.GetInOperand(0).words[0]);
if (extensions_whitelist_.find(extName) == extensions_whitelist_.end())
return false;
}
return true;
}
Pass::Status LocalSingleBlockLoadStoreElimPass::ProcessImpl() {
// Assumes relaxed logical addressing only (see instruction.h).
if (context()->get_feature_mgr()->HasCapability(SpvCapabilityAddresses))
return Status::SuccessWithoutChange;
// Do not process if module contains OpGroupDecorate. Additional
// support required in KillNamesAndDecorates().
// TODO(greg-lunarg): Add support for OpGroupDecorate
for (auto& ai : get_module()->annotations())
if (ai.opcode() == SpvOpGroupDecorate) return Status::SuccessWithoutChange;
// If any extensions in the module are not explicitly supported,
// return unmodified.
if (!AllExtensionsSupported()) return Status::SuccessWithoutChange;
// Process all entry point functions
ProcessFunction pfn = [this](Function* fp) {
return LocalSingleBlockLoadStoreElim(fp);
};
bool modified = context()->ProcessEntryPointCallTree(pfn);
return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
}
LocalSingleBlockLoadStoreElimPass::LocalSingleBlockLoadStoreElimPass() =
default;
Pass::Status LocalSingleBlockLoadStoreElimPass::Process() {
Initialize();
return ProcessImpl();
}
void LocalSingleBlockLoadStoreElimPass::InitExtensions() {
extensions_whitelist_.clear();
extensions_whitelist_.insert({
"SPV_AMD_shader_explicit_vertex_parameter",
"SPV_AMD_shader_trinary_minmax",
"SPV_AMD_gcn_shader",
"SPV_KHR_shader_ballot",
"SPV_AMD_shader_ballot",
"SPV_AMD_gpu_shader_half_float",
"SPV_KHR_shader_draw_parameters",
"SPV_KHR_subgroup_vote",
"SPV_KHR_16bit_storage",
"SPV_KHR_device_group",
"SPV_KHR_multiview",
"SPV_NVX_multiview_per_view_attributes",
"SPV_NV_viewport_array2",
"SPV_NV_stereo_view_rendering",
"SPV_NV_sample_mask_override_coverage",
"SPV_NV_geometry_shader_passthrough",
"SPV_AMD_texture_gather_bias_lod",
"SPV_KHR_storage_buffer_storage_class",
"SPV_KHR_variable_pointers",
"SPV_AMD_gpu_shader_int16",
"SPV_KHR_post_depth_coverage",
"SPV_KHR_shader_atomic_counter_ops",
"SPV_EXT_shader_stencil_export",
"SPV_EXT_shader_viewport_index_layer",
"SPV_AMD_shader_image_load_store_lod",
"SPV_AMD_shader_fragment_mask",
"SPV_EXT_fragment_fully_covered",
"SPV_AMD_gpu_shader_half_float_fetch",
"SPV_GOOGLE_decorate_string",
"SPV_GOOGLE_hlsl_functionality1",
"SPV_GOOGLE_user_type",
"SPV_NV_shader_subgroup_partitioned",
"SPV_EXT_descriptor_indexing",
"SPV_NV_fragment_shader_barycentric",
"SPV_NV_compute_shader_derivatives",
"SPV_NV_shader_image_footprint",
"SPV_NV_shading_rate",
"SPV_NV_mesh_shader",
"SPV_NV_ray_tracing",
"SPV_EXT_fragment_invocation_density",
});
}
} // namespace opt
} // namespace spvtools
| bsd-2-clause |
littledan/Factor | vm/math.cpp | 12428 | #include "master.hpp"
namespace factor
{
void factor_vm::primitive_bignum_to_fixnum()
{
ctx->replace(tag_fixnum(bignum_to_fixnum(untag<bignum>(ctx->peek()))));
}
void factor_vm::primitive_float_to_fixnum()
{
ctx->replace(tag_fixnum(float_to_fixnum(ctx->peek())));
}
/* Division can only overflow when we are dividing the most negative fixnum
by -1. */
void factor_vm::primitive_fixnum_divint()
{
fixnum y = untag_fixnum(ctx->pop()); \
fixnum x = untag_fixnum(ctx->peek());
fixnum result = x / y;
if(result == -fixnum_min)
ctx->replace(allot_integer(-fixnum_min));
else
ctx->replace(tag_fixnum(result));
}
void factor_vm::primitive_fixnum_divmod()
{
cell y = ((cell *)ctx->datastack)[0];
cell x = ((cell *)ctx->datastack)[-1];
if(y == tag_fixnum(-1) && x == tag_fixnum(fixnum_min))
{
((cell *)ctx->datastack)[-1] = allot_integer(-fixnum_min);
((cell *)ctx->datastack)[0] = tag_fixnum(0);
}
else
{
((cell *)ctx->datastack)[-1] = tag_fixnum(untag_fixnum(x) / untag_fixnum(y));
((cell *)ctx->datastack)[0] = (fixnum)x % (fixnum)y;
}
}
/*
* If we're shifting right by n bits, we won't overflow as long as none of the
* high WORD_SIZE-TAG_BITS-n bits are set.
*/
inline fixnum factor_vm::sign_mask(fixnum x)
{
return x >> (WORD_SIZE - 1);
}
inline fixnum factor_vm::branchless_max(fixnum x, fixnum y)
{
return (x - ((x - y) & sign_mask(x - y)));
}
inline fixnum factor_vm::branchless_abs(fixnum x)
{
return (x ^ sign_mask(x)) - sign_mask(x);
}
void factor_vm::primitive_fixnum_shift()
{
fixnum y = untag_fixnum(ctx->pop());
fixnum x = untag_fixnum(ctx->peek());
if(x == 0)
return;
else if(y < 0)
{
y = branchless_max(y,-WORD_SIZE + 1);
ctx->replace(tag_fixnum(x >> -y));
return;
}
else if(y < WORD_SIZE - TAG_BITS)
{
fixnum mask = -((fixnum)1 << (WORD_SIZE - 1 - TAG_BITS - y));
if(!(branchless_abs(x) & mask))
{
ctx->replace(tag_fixnum(x << y));
return;
}
}
ctx->replace(tag<bignum>(bignum_arithmetic_shift(
fixnum_to_bignum(x),y)));
}
void factor_vm::primitive_fixnum_to_bignum()
{
ctx->replace(tag<bignum>(fixnum_to_bignum(untag_fixnum(ctx->peek()))));
}
void factor_vm::primitive_float_to_bignum()
{
ctx->replace(tag<bignum>(float_to_bignum(ctx->peek())));
}
#define POP_BIGNUMS(x,y) \
bignum * y = untag<bignum>(ctx->pop()); \
bignum * x = untag<bignum>(ctx->pop());
void factor_vm::primitive_bignum_eq()
{
POP_BIGNUMS(x,y);
ctx->push(tag_boolean(bignum_equal_p(x,y)));
}
void factor_vm::primitive_bignum_add()
{
POP_BIGNUMS(x,y);
ctx->push(tag<bignum>(bignum_add(x,y)));
}
void factor_vm::primitive_bignum_subtract()
{
POP_BIGNUMS(x,y);
ctx->push(tag<bignum>(bignum_subtract(x,y)));
}
void factor_vm::primitive_bignum_multiply()
{
POP_BIGNUMS(x,y);
ctx->push(tag<bignum>(bignum_multiply(x,y)));
}
void factor_vm::primitive_bignum_divint()
{
POP_BIGNUMS(x,y);
ctx->push(tag<bignum>(bignum_quotient(x,y)));
}
void factor_vm::primitive_bignum_divmod()
{
bignum *q, *r;
POP_BIGNUMS(x,y);
bignum_divide(x,y,&q,&r);
ctx->push(tag<bignum>(q));
ctx->push(tag<bignum>(r));
}
void factor_vm::primitive_bignum_mod()
{
POP_BIGNUMS(x,y);
ctx->push(tag<bignum>(bignum_remainder(x,y)));
}
void factor_vm::primitive_bignum_and()
{
POP_BIGNUMS(x,y);
ctx->push(tag<bignum>(bignum_bitwise_and(x,y)));
}
void factor_vm::primitive_bignum_or()
{
POP_BIGNUMS(x,y);
ctx->push(tag<bignum>(bignum_bitwise_ior(x,y)));
}
void factor_vm::primitive_bignum_xor()
{
POP_BIGNUMS(x,y);
ctx->push(tag<bignum>(bignum_bitwise_xor(x,y)));
}
void factor_vm::primitive_bignum_shift()
{
fixnum y = untag_fixnum(ctx->pop());
bignum* x = untag<bignum>(ctx->pop());
ctx->push(tag<bignum>(bignum_arithmetic_shift(x,y)));
}
void factor_vm::primitive_bignum_less()
{
POP_BIGNUMS(x,y);
ctx->push(tag_boolean(bignum_compare(x,y) == bignum_comparison_less));
}
void factor_vm::primitive_bignum_lesseq()
{
POP_BIGNUMS(x,y);
ctx->push(tag_boolean(bignum_compare(x,y) != bignum_comparison_greater));
}
void factor_vm::primitive_bignum_greater()
{
POP_BIGNUMS(x,y);
ctx->push(tag_boolean(bignum_compare(x,y) == bignum_comparison_greater));
}
void factor_vm::primitive_bignum_greatereq()
{
POP_BIGNUMS(x,y);
ctx->push(tag_boolean(bignum_compare(x,y) != bignum_comparison_less));
}
void factor_vm::primitive_bignum_not()
{
ctx->replace(tag<bignum>(bignum_bitwise_not(untag<bignum>(ctx->peek()))));
}
void factor_vm::primitive_bignum_bitp()
{
int bit = (int)to_fixnum(ctx->pop());
bignum *x = untag<bignum>(ctx->pop());
ctx->push(tag_boolean(bignum_logbitp(bit,x)));
}
void factor_vm::primitive_bignum_log2()
{
ctx->replace(tag<bignum>(bignum_integer_length(untag<bignum>(ctx->peek()))));
}
unsigned int factor_vm::bignum_producer(unsigned int digit)
{
unsigned char *ptr = (unsigned char *)alien_offset(ctx->peek());
return *(ptr + digit);
}
unsigned int bignum_producer(unsigned int digit, factor_vm *parent)
{
return parent->bignum_producer(digit);
}
void factor_vm::primitive_byte_array_to_bignum()
{
unsigned int n_digits = (unsigned int)array_capacity(untag_check<byte_array>(ctx->peek()));
bignum * result = digit_stream_to_bignum(n_digits,factor::bignum_producer,0x100,0);
ctx->replace(tag<bignum>(result));
}
cell factor_vm::unbox_array_size_slow()
{
if(tagged<object>(ctx->peek()).type() == BIGNUM_TYPE)
{
bignum *zero = untag<bignum>(bignum_zero);
bignum *max = cell_to_bignum(array_size_max);
bignum *n = untag<bignum>(ctx->peek());
if(bignum_compare(n,zero) != bignum_comparison_less
&& bignum_compare(n,max) == bignum_comparison_less)
{
ctx->pop();
return bignum_to_cell(n);
}
}
general_error(ERROR_ARRAY_SIZE,ctx->pop(),tag_fixnum(array_size_max),NULL);
return 0; /* can't happen */
}
void factor_vm::primitive_fixnum_to_float()
{
ctx->replace(allot_float(fixnum_to_float(ctx->peek())));
}
void factor_vm::primitive_bignum_to_float()
{
ctx->replace(allot_float(bignum_to_float(ctx->peek())));
}
void factor_vm::primitive_float_to_str()
{
byte_array *array = allot_byte_array(33);
SNPRINTF((char *)(array + 1),32,"%.16g",untag_float_check(ctx->pop()));
ctx->push(tag<byte_array>(array));
}
#define POP_FLOATS(x,y) \
double y = untag_float(ctx->pop()); \
double x = untag_float(ctx->pop());
void factor_vm::primitive_float_eq()
{
POP_FLOATS(x,y);
ctx->push(tag_boolean(x == y));
}
void factor_vm::primitive_float_add()
{
POP_FLOATS(x,y);
ctx->push(allot_float(x + y));
}
void factor_vm::primitive_float_subtract()
{
POP_FLOATS(x,y);
ctx->push(allot_float(x - y));
}
void factor_vm::primitive_float_multiply()
{
POP_FLOATS(x,y);
ctx->push(allot_float(x * y));
}
void factor_vm::primitive_float_divfloat()
{
POP_FLOATS(x,y);
ctx->push(allot_float(x / y));
}
void factor_vm::primitive_float_mod()
{
POP_FLOATS(x,y);
ctx->push(allot_float(fmod(x,y)));
}
void factor_vm::primitive_float_less()
{
POP_FLOATS(x,y);
ctx->push(tag_boolean(x < y));
}
void factor_vm::primitive_float_lesseq()
{
POP_FLOATS(x,y);
ctx->push(tag_boolean(x <= y));
}
void factor_vm::primitive_float_greater()
{
POP_FLOATS(x,y);
ctx->push(tag_boolean(x > y));
}
void factor_vm::primitive_float_greatereq()
{
POP_FLOATS(x,y);
ctx->push(tag_boolean(x >= y));
}
void factor_vm::primitive_float_bits()
{
ctx->push(from_unsigned_4(float_bits((float)untag_float_check(ctx->pop()))));
}
void factor_vm::primitive_bits_float()
{
ctx->push(allot_float(bits_float((u32)to_cell(ctx->pop()))));
}
void factor_vm::primitive_double_bits()
{
ctx->push(from_unsigned_8(double_bits(untag_float_check(ctx->pop()))));
}
void factor_vm::primitive_bits_double()
{
ctx->push(allot_float(bits_double(to_unsigned_8(ctx->pop()))));
}
/* Cannot allocate */
fixnum factor_vm::to_fixnum(cell tagged)
{
switch(TAG(tagged))
{
case FIXNUM_TYPE:
return untag_fixnum(tagged);
case BIGNUM_TYPE:
return bignum_to_fixnum(untag<bignum>(tagged));
default:
type_error(FIXNUM_TYPE,tagged);
return 0; /* can't happen */
}
}
VM_C_API fixnum to_fixnum(cell tagged, factor_vm *parent)
{
return parent->to_fixnum(tagged);
}
cell factor_vm::to_cell(cell tagged)
{
return (cell)to_fixnum(tagged);
}
VM_C_API cell to_cell(cell tagged, factor_vm *parent)
{
return parent->to_cell(tagged);
}
cell factor_vm::from_signed_1(s8 n)
{
return tag_fixnum(n);
}
VM_C_API cell from_signed_1(s8 n, factor_vm *parent)
{
return parent->from_signed_1(n);
}
cell factor_vm::from_unsigned_1(u8 n)
{
return tag_fixnum(n);
}
VM_C_API cell from_unsigned_1(u8 n, factor_vm *parent)
{
return parent->from_unsigned_1(n);
}
cell factor_vm::from_signed_2(s16 n)
{
return tag_fixnum(n);
}
VM_C_API cell from_signed_2(s16 n, factor_vm *parent)
{
return parent->from_signed_2(n);
}
cell factor_vm::from_unsigned_2(u16 n)
{
return tag_fixnum(n);
}
VM_C_API cell from_unsigned_2(u16 n, factor_vm *parent)
{
return parent->from_unsigned_2(n);
}
cell factor_vm::from_signed_4(s32 n)
{
return allot_integer(n);
}
VM_C_API cell from_signed_4(s32 n, factor_vm *parent)
{
return parent->from_signed_4(n);
}
cell factor_vm::from_unsigned_4(u32 n)
{
return allot_cell(n);
}
VM_C_API cell from_unsigned_4(u32 n, factor_vm *parent)
{
return parent->from_unsigned_4(n);
}
cell factor_vm::from_signed_cell(fixnum integer)
{
return allot_integer(integer);
}
cell factor_vm::from_unsigned_cell(cell integer)
{
return allot_cell(integer);
}
VM_C_API cell from_signed_cell(fixnum integer, factor_vm *parent)
{
return parent->from_signed_cell(integer);
}
VM_C_API cell from_unsigned_cell(cell integer, factor_vm *parent)
{
return parent->from_unsigned_cell(integer);
}
cell factor_vm::from_signed_8(s64 n)
{
if(n < fixnum_min || n > fixnum_max)
return tag<bignum>(long_long_to_bignum(n));
else
return tag_fixnum((fixnum)n);
}
VM_C_API cell from_signed_8(s64 n, factor_vm *parent)
{
return parent->from_signed_8(n);
}
/* Cannot allocate */
s64 factor_vm::to_signed_8(cell obj)
{
switch(tagged<object>(obj).type())
{
case FIXNUM_TYPE:
return untag_fixnum(obj);
case BIGNUM_TYPE:
return bignum_to_long_long(untag<bignum>(obj));
default:
type_error(BIGNUM_TYPE,obj);
return 0;
}
}
VM_C_API s64 to_signed_8(cell obj, factor_vm *parent)
{
return parent->to_signed_8(obj);
}
cell factor_vm::from_unsigned_8(u64 n)
{
if(n > (u64)fixnum_max)
return tag<bignum>(ulong_long_to_bignum(n));
else
return tag_fixnum((fixnum)n);
}
VM_C_API cell from_unsigned_8(u64 n, factor_vm *parent)
{
return parent->from_unsigned_8(n);
}
/* Cannot allocate */
u64 factor_vm::to_unsigned_8(cell obj)
{
switch(tagged<object>(obj).type())
{
case FIXNUM_TYPE:
return untag_fixnum(obj);
case BIGNUM_TYPE:
return bignum_to_ulong_long(untag<bignum>(obj));
default:
type_error(BIGNUM_TYPE,obj);
return 0;
}
}
VM_C_API u64 to_unsigned_8(cell obj, factor_vm *parent)
{
return parent->to_unsigned_8(obj);
}
VM_C_API cell from_float(float flo, factor_vm *parent)
{
return parent->allot_float(flo);
}
/* Cannot allocate */
float factor_vm::to_float(cell value)
{
return (float)untag_float_check(value);
}
VM_C_API float to_float(cell value, factor_vm *parent)
{
return parent->to_float(value);
}
VM_C_API cell from_double(double flo, factor_vm *parent)
{
return parent->allot_float(flo);
}
/* Cannot allocate */
double factor_vm::to_double(cell value)
{
return untag_float_check(value);
}
VM_C_API double to_double(cell value, factor_vm *parent)
{
return parent->to_double(value);
}
/* The fixnum+, fixnum- and fixnum* primitives are defined in cpu_*.S. On
overflow, they call these functions. */
inline void factor_vm::overflow_fixnum_add(fixnum x, fixnum y)
{
ctx->replace(tag<bignum>(fixnum_to_bignum(
untag_fixnum(x) + untag_fixnum(y))));
}
VM_C_API void overflow_fixnum_add(fixnum x, fixnum y, factor_vm *parent)
{
parent->overflow_fixnum_add(x,y);
}
inline void factor_vm::overflow_fixnum_subtract(fixnum x, fixnum y)
{
ctx->replace(tag<bignum>(fixnum_to_bignum(
untag_fixnum(x) - untag_fixnum(y))));
}
VM_C_API void overflow_fixnum_subtract(fixnum x, fixnum y, factor_vm *parent)
{
parent->overflow_fixnum_subtract(x,y);
}
inline void factor_vm::overflow_fixnum_multiply(fixnum x, fixnum y)
{
bignum *bx = fixnum_to_bignum(x);
GC_BIGNUM(bx);
bignum *by = fixnum_to_bignum(y);
GC_BIGNUM(by);
ctx->replace(tag<bignum>(bignum_multiply(bx,by)));
}
VM_C_API void overflow_fixnum_multiply(fixnum x, fixnum y, factor_vm *parent)
{
parent->overflow_fixnum_multiply(x,y);
}
}
| bsd-2-clause |
mmoening/agg-sharp | examples/GCodeVisualizer/Renderer/RenderFeatures/RenderFeatureBase.cs | 7833 | /*
Copyright (c) 2014, Lars Brubaker
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using MatterHackers.Agg;
using MatterHackers.VectorMath;
namespace MatterHackers.GCodeVisualizer
{
public abstract class RenderFeatureBase
{
protected int extruderIndex;
public abstract void Render(Graphics2D graphics2D, GCodeRenderInfo renderInfo);
public abstract void CreateRender3DData(VectorPOD<ColorVertexData> colorVertexData, VectorPOD<int> indexData, GCodeRenderInfo renderInfo);
public RenderFeatureBase(int extruderIndex)
{
this.extruderIndex = extruderIndex;
}
static public void CreateCylinder(VectorPOD<ColorVertexData> colorVertexData, VectorPOD<int> indexData, Vector3 startPos, Vector3 endPos, double radius, int steps, RGBA_Bytes color, double layerHeight)
{
Vector3 direction = endPos - startPos;
Vector3 directionNormal = direction.GetNormal();
Vector3 startSweepDirection = Vector3.GetPerpendicular(startPos, endPos).GetNormal();
int[] tubeStartIndices = new int[steps];
int[] tubeEndIndices = new int[steps];
int[] capStartIndices = new int[steps];
int[] capEndIndices = new int[steps];
double halfHeight = layerHeight / 2 + (layerHeight * .1);
double halfWidth = (radius * radius) / halfHeight;
double zScale = halfHeight / radius;
double xScale = halfWidth / radius;
Vector3 scale = new Vector3(xScale, xScale, zScale);
for (int i = 0; i < steps; i++)
{
// create tube ends verts
Vector3 tubeNormal = Vector3.Transform(startSweepDirection, Matrix4X4.CreateRotation(direction, MathHelper.Tau / (steps * 2) + MathHelper.Tau / (steps) * i));
Vector3 offset = Vector3.Transform(startSweepDirection * radius, Matrix4X4.CreateRotation(direction, MathHelper.Tau / (steps * 2) + MathHelper.Tau / (steps) * i));
offset *= scale;
Vector3 tubeStart = startPos + offset;
tubeStartIndices[i] = colorVertexData.Count;
colorVertexData.Add(new ColorVertexData(tubeStart, tubeNormal, color));
Vector3 tubeEnd = endPos + offset;
tubeEndIndices[i] = colorVertexData.Count;
colorVertexData.Add(new ColorVertexData(tubeEnd, tubeNormal, color));
// create cap verts
Vector3 rotateAngle = Vector3.Cross(direction, startSweepDirection);
Vector3 capStartNormal = Vector3.Transform(startSweepDirection, Matrix4X4.CreateRotation(rotateAngle, MathHelper.Tau / 8));
capStartNormal = Vector3.Transform(capStartNormal, Matrix4X4.CreateRotation(direction, MathHelper.Tau / (steps * 2) + MathHelper.Tau / (steps) * i));
capStartNormal = (capStartNormal * scale).GetNormal();
Vector3 capStartOffset = capStartNormal * radius;
capStartOffset *= scale;
Vector3 capStart = startPos + capStartOffset;
capStartIndices[i] = colorVertexData.Count;
colorVertexData.Add(new ColorVertexData(capStart, capStartNormal, color));
Vector3 capEndNormal = Vector3.Transform(startSweepDirection, Matrix4X4.CreateRotation(-rotateAngle, MathHelper.Tau / 8));
capEndNormal = Vector3.Transform(capEndNormal, Matrix4X4.CreateRotation(direction, MathHelper.Tau / (steps * 2) + MathHelper.Tau / (steps) * i));
capEndNormal = (capEndNormal * scale).GetNormal();
Vector3 capEndOffset = capEndNormal * radius;
capEndOffset *= scale;
Vector3 capEnd = endPos + capEndOffset;
capEndIndices[i] = colorVertexData.Count;
colorVertexData.Add(new ColorVertexData(capEnd, capEndNormal, color));
}
int tipStartIndex = colorVertexData.Count;
Vector3 tipOffset = directionNormal * radius;
tipOffset *= scale;
colorVertexData.Add(new ColorVertexData(startPos - tipOffset, -directionNormal, color));
int tipEndIndex = colorVertexData.Count;
colorVertexData.Add(new ColorVertexData(endPos + tipOffset, directionNormal, color));
for (int i = 0; i < steps; i++)
{
// create tube polys
indexData.Add(tubeStartIndices[i]);
indexData.Add(tubeEndIndices[i]);
indexData.Add(tubeEndIndices[(i + 1) % steps]);
indexData.Add(tubeStartIndices[i]);
indexData.Add(tubeEndIndices[(i + 1) % steps]);
indexData.Add(tubeStartIndices[(i + 1) % steps]);
// create start cap polys
indexData.Add(tubeStartIndices[i]);
indexData.Add(capStartIndices[i]);
indexData.Add(capStartIndices[(i + 1) % steps]);
indexData.Add(tubeStartIndices[i]);
indexData.Add(capStartIndices[(i + 1) % steps]);
indexData.Add(tubeStartIndices[(i + 1) % steps]);
// create end cap polys
indexData.Add(tubeEndIndices[i]);
indexData.Add(capEndIndices[i]);
indexData.Add(capEndIndices[(i + 1) % steps]);
indexData.Add(tubeEndIndices[i]);
indexData.Add(capEndIndices[(i + 1) % steps]);
indexData.Add(tubeEndIndices[(i + 1) % steps]);
// create start tip polys
indexData.Add(tipStartIndex);
indexData.Add(capStartIndices[i]);
indexData.Add(capStartIndices[(i + 1) % steps]);
// create end tip polys
indexData.Add(tipEndIndex);
indexData.Add(capEndIndices[i]);
indexData.Add(capEndIndices[(i + 1) % steps]);
}
}
static public void CreatePointer(VectorPOD<ColorVertexData> colorVertexData, VectorPOD<int> indexData, Vector3 startPos, Vector3 endPos, double radius, int steps, RGBA_Bytes color)
{
Vector3 direction = endPos - startPos;
Vector3 directionNormal = direction.GetNormal();
Vector3 startSweepDirection = Vector3.GetPerpendicular(startPos, endPos).GetNormal();
int[] tubeStartIndices = new int[steps];
for (int i = 0; i < steps; i++)
{
// create tube ends verts
Vector3 tubeNormal = Vector3.Transform(startSweepDirection, Matrix4X4.CreateRotation(direction, MathHelper.Tau / (steps * 2) + MathHelper.Tau / (steps) * i));
Vector3 offset = Vector3.Transform(startSweepDirection * radius, Matrix4X4.CreateRotation(direction, MathHelper.Tau / (steps * 2) + MathHelper.Tau / (steps) * i));
Vector3 tubeStart = startPos + offset;
tubeStartIndices[i] = colorVertexData.Count;
colorVertexData.Add(new ColorVertexData(tubeStart, tubeNormal, color));
Vector3 tubeEnd = endPos + offset;
}
int tipEndIndex = colorVertexData.Count;
colorVertexData.Add(new ColorVertexData(endPos, directionNormal, color));
for (int i = 0; i < steps; i++)
{
// create tube polys
indexData.Add(tubeStartIndices[i]);
indexData.Add(tubeStartIndices[(i + 1) % steps]);
indexData.Add(tipEndIndex);
}
}
}
} | bsd-2-clause |
ahbeng/homebrew-fonts | Casks/font-cherry-swash.rb | 355 | class FontCherrySwash < Cask
url 'https://github.com/w0ng/googlefontdirectory/trunk/fonts/cherryswash',
:using => :svn,
:revision => '50',
:trust_cert => true
homepage 'http://www.google.com/fonts/specimen/Cherry%20Swash'
version '1.001'
sha256 :no_check
font 'CherrySwash-Bold.ttf'
font 'CherrySwash-Regular.ttf'
end
| bsd-2-clause |
ReflectionBrowser/ReflectionBrowser | lib/RBExtensionsTemplateTable.php | 783 | <?php
final class RBExtensionsTemplateTable extends RBDataTemplateTable {
use RBDataTemplateTableListSorter;
protected function sourceData() {
return get_loaded_extensions();
}
protected function emptyTableText() {
return 'no extensions';
}
protected function rowTupleForData($mixKey, $mixValue, RBRuntime $objRuntime) {
$objExtension = new ReflectionExtension($mixValue);
$lstColumns = [$objExtension->getVersion()];
if ($lstExtraColumns = $objRuntime->extraInfoMapForExtension($objExtension)) {
$lstColumns = array_merge($lstColumns, $lstExtraColumns);
}
$lstColumns[] = $this->manualFragmentForReflector($objExtension);
return [
[$objRuntime->nameFragmentForExtensionName($mixValue)],
$lstColumns
];
}
}
| bsd-2-clause |
kkuhrman/AblePolecat | core/AccessControl/Agent.php | 1322 | <?php
/**
* @file polecat/core/AccessControl/Agent.php
* @brief The access control 'subject'; for example, a user.
*
* Intended to follow interface specified by W3C but does not provide public access to
* properties (get/set methods provided).
*
* @see http://www.w3.org/TR/url/#url
*
* @author Karl Kuhrman
* @copyright [BDS II License] (https://github.com/kkuhrman/AblePolecat/blob/master/LICENSE.md)
* @version 0.7.0
*/
require_once(implode(DIRECTORY_SEPARATOR, array(ABLE_POLECAT_CORE, 'AccessControl', 'Subject.php')));
require_once(ABLE_POLECAT_CORE . DIRECTORY_SEPARATOR . 'CacheObject.php');
interface AblePolecat_AccessControl_AgentInterface extends AblePolecat_AccessControl_SubjectInterface {
}
abstract class AblePolecat_AccessControl_AgentAbstract extends AblePolecat_CacheObjectAbstract implements AblePolecat_AccessControl_AgentInterface {
/********************************************************************************
* Helper functions.
********************************************************************************/
/**
* Extends __construct().
* Sub-classes should override to initialize properties.
*/
protected function initialize() {
//
// Agents invoke their own commands.
//
$this->setDefaultCommandInvoker($this);
}
} | bsd-2-clause |
wolffaxn/homebrew-core | Formula/libxml2.rb | 3117 | class Libxml2 < Formula
desc "GNOME XML library"
homepage "http://xmlsoft.org/"
url "http://xmlsoft.org/sources/libxml2-2.9.9.tar.gz"
mirror "https://ftp.osuosl.org/pub/blfs/conglomeration/libxml2/libxml2-2.9.9.tar.gz"
sha256 "94fb70890143e3c6549f265cee93ec064c80a84c42ad0f23e85ee1fd6540a871"
revision 2
bottle do
cellar :any
sha256 "2a7de29b64f7bd74990ff1fd1b00d52333e587ae567e78bbab811a33b91141d6" => :catalina
sha256 "1e6143e9bfb756fe80e4a1db417b722569429a815365ed9070556e81bd2db02a" => :mojave
sha256 "d6b944e43be98a8e4200eb247c1d4b1254f8026e2e5a39cfa8b67d1c9429a7f2" => :high_sierra
sha256 "e5ac4cca18a3d8795895059253e610b24f8c7c491354ce21e2b19ae4c7e84bd6" => :sierra
end
head do
url "https://gitlab.gnome.org/GNOME/libxml2.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "pkg-config" => :build
end
keg_only :provided_by_macos
depends_on "python"
# Fix crash when using Python 3 using Fedora's patch.
# Reported upstream:
# https://bugzilla.gnome.org/show_bug.cgi?id=789714
# https://gitlab.gnome.org/GNOME/libxml2/issues/12
patch do
url "https://bugzilla.opensuse.org/attachment.cgi?id=746044"
sha256 "37eb81a8ec6929eed1514e891bff2dd05b450bcf0c712153880c485b7366c17c"
end
# Resolves CVE-2018-8048, CVE-2018-3740, CVE-2018-3741
# Upstream hasn't patched this bug, but Nokogiri distributes
# libxml2 with this patch to fixe this issue
# https://bugzilla.gnome.org/show_bug.cgi?id=769760
# https://github.com/sparklemotion/nokogiri/pull/1746
patch do
url "https://raw.githubusercontent.com/sparklemotion/nokogiri/38721829c1df30e93bdfbc88095cc36838e497f3/patches/libxml2/0001-Revert-Do-not-URI-escape-in-server-side-includes.patch"
sha256 "c755e6e17c02584bfbfc8889ffc652384b010c0bd71879d7ff121ca60a218fcd"
end
def install
system "autoreconf", "-fiv" if build.head?
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}",
"--without-python",
"--without-lzma"
system "make", "install"
cd "python" do
# We need to insert our include dir first
inreplace "setup.py", "includes_dir = [",
"includes_dir = ['#{include}', '#{MacOS.sdk_path}/usr/include',"
system "python3", "setup.py", "install", "--prefix=#{prefix}"
end
end
test do
(testpath/"test.c").write <<~EOS
#include <libxml/tree.h>
int main()
{
xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
xmlNodePtr root_node = xmlNewNode(NULL, BAD_CAST "root");
xmlDocSetRootElement(doc, root_node);
xmlFreeDoc(doc);
return 0;
}
EOS
args = shell_output("#{bin}/xml2-config --cflags --libs").split
args += %w[test.c -o test]
system ENV.cc, *args
system "./test"
xy = Language::Python.major_minor_version "python3"
ENV.prepend_path "PYTHONPATH", lib/"python#{xy}/site-packages"
system "python3", "-c", "import libxml2"
end
end
| bsd-2-clause |
alerque/homebrew-fonts | Casks/font-manrope.rb | 294 | cask "font-manrope" do
version :latest
sha256 :no_check
url "https://github.com/google/fonts/raw/master/ofl/manrope/Manrope%5Bwght%5D.ttf",
verified: "github.com/google/fonts/"
name "Manrope"
homepage "https://fonts.google.com/specimen/Manrope"
font "Manrope[wght].ttf"
end
| bsd-2-clause |