code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php /** * The template for displaying the footer. * * Contains the closing of the #content div and all content after * * @package understrap */ $the_theme = wp_get_theme(); $container = get_theme_mod( 'understrap_container_type' ); ?> </div><!-- #page --> <?php wp_footer(); ?> </body> </html>
igaweb/wpiu
wordpress/wp-content/themes/understrap/footer.php
PHP
gpl-3.0
307
$(function() { var animationDuration = 500; $('.portal-menu-siblings').each(function() { var self = $(this); var parent = $(this).parent(); var a = parent.children('a'); var chevron = parent.find('.icon-chevron-down'); var inTimeout, outTimeout; var orientation = 0; parent.hover(function() { a.addClass('hover'); clearTimeout(outTimeout); inTimeout = setTimeout(function() { self.stop(true).css('display', 'block').animate({ left: '100%', opacity: 1 }, animationDuration); chevron.stop(true, true); $({deg: orientation}).animate({deg: -90}, { step: function(now) { chevron.css({transform: 'rotate(' + now + 'deg)'}); orientation = now; }, duration: animationDuration }); }, 400); }, function() { a.removeClass('hover'); clearTimeout(inTimeout); outTimeout = setTimeout(function() { self.stop(true).animate({ left: '0', opacity: 0 }, animationDuration); outTimeout = setTimeout(function() { self.css('display', 'none'); }, animationDuration); chevron.stop(true, true); $({deg: orientation}).animate({deg: 0}, { step: function(now) { chevron.css({transform: 'rotate(' + now + 'deg)'}); orientation = now; }, duration: animationDuration }); }, 400); }); var url = a.attr('href'); var height = parent.height() + 1; var top = -3; $(this).children('li').each(function() { if($(this).children('a').attr('href') == url) return false; top -= height; }); $(this).css('top', top + 'px'); }); });
papedaniel/oioioi
oioioi/portals/static/common/portal.js
JavaScript
gpl-3.0
2,167
/** * Copyright (C) 2001-2016 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.operator.preprocessing.outlier; import com.rapidminer.example.Attribute; import com.rapidminer.example.Attributes; import com.rapidminer.example.Example; import com.rapidminer.example.ExampleSet; import com.rapidminer.example.table.AttributeFactory; import com.rapidminer.operator.OperatorDescription; import com.rapidminer.operator.OperatorException; import com.rapidminer.operator.annotation.ResourceConsumptionEstimator; import com.rapidminer.parameter.ParameterType; import com.rapidminer.parameter.ParameterTypeCategory; import com.rapidminer.parameter.ParameterTypeInt; import com.rapidminer.tools.Ontology; import com.rapidminer.tools.OperatorResourceConsumptionHandler; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * <p> * This operator performs a D^k_n Outlier Search according to the outlier detection approach * recommended by Ramaswamy, Rastogi and Shim in "Efficient Algorithms for Mining Outliers from * Large Data Sets". It is primarily a statistical outlier search based on a distance measure * similar to the DB(p,D)-Outlier Search from Knorr and Ng. But it utilizes a distance search * through the k-th nearest neighbourhood, so it implements some sort of locality as well. * </p> * * <p> * The method states, that those objects with the largest distance to their k-th nearest neighbours * are likely to be outliers respective to the data set, because it can be assumed, that those * objects have a more sparse neighbourhood than the average objects. As this effectively provides a * simple ranking over all the objects in the data set according to the distance to their k-th * nearest neighbours, the user can specify a number of n objects to be the top-n outliers in the * data set. * </p> * * <p> * The operator supports cosine, sine or squared distances in addition to the euclidian distance * which can be specified by a distance parameter. The Operator takes an example set and passes it * on with an boolean top-n D^k outlier status in a new boolean-valued special outlier attribute * indicating true (outlier) and false (no outlier). * </p> * * @author Stephan Deutsch, Ingo Mierswa */ public class DKNOutlierOperator extends AbstractOutlierDetection { /** * The parameter name for &quot;Specifies the k value for the k-th nearest neighbours to be the * analyzed.&quot; */ public static final String PARAMETER_NUMBER_OF_NEIGHBORS = "number_of_neighbors"; /** The parameter name for &quot;The number of top-n Outliers to be looked for.&quot; */ public static final String PARAMETER_NUMBER_OF_OUTLIERS = "number_of_outliers"; /** * The parameter name for &quot;choose which distance function will be used for calculating * &quot; */ public static final String PARAMETER_DISTANCE_FUNCTION = "distance_function"; private static final String[] distanceFunctionList = { "euclidian distance", "squared distance", "cosine distance", "inverted cosine distance", "angle" }; public DKNOutlierOperator(OperatorDescription description) { super(description); } /** * This method implements the main functionality of the Operator but can be considered as a sort * of wrapper to pass the RapidMiner operator chain data deeper into the search space class, so * do not expect a lot of things happening here. */ @Override public ExampleSet apply(ExampleSet eSet) throws OperatorException { // declaration and initializing the necessary fields from input int k = this.getParameterAsInt(PARAMETER_NUMBER_OF_NEIGHBORS); int n = this.getParameterAsInt(PARAMETER_NUMBER_OF_OUTLIERS); n = n - 2; // this has to do with the internal indexing in the SearchSpace's methods int kindOfDistance = this.getParameterAsInt(PARAMETER_DISTANCE_FUNCTION); // create a new SearchSpace for the DKN(p,D)-Outlier search Iterator<Example> reader = eSet.iterator(); int searchSpaceDimension = eSet.getAttributes().size(); SearchSpace sr = new SearchSpace(searchSpaceDimension, k, k); // now read through the Examples of the ExampleSet int counter = 0; while (reader.hasNext()) { Example example = reader.next(); // read the next example & create a search object SearchObject so = new SearchObject(searchSpaceDimension, "object" + counter, k, k + 1); // for // now, // give // so // an // id // like // label counter++; int i = 0; for (Attribute attribute : eSet.getAttributes()) { so.setVektor(i++, example.getValue(attribute)); // get the attributes for the so // from example and pass it on } sr.addObject(so); // finally add the search object to the search room } // set all Outlier Status to ZERO to be sure sr.resetOutlierStatus(); // find all Containers for the DKN first sr.findAllKdContainers(kindOfDistance, this); // perform the outlier search sr.computeDKN(k, n, this); // create a new special attribute for the exampleSet Attribute outlierAttribute = AttributeFactory.createAttribute(Attributes.OUTLIER_NAME, Ontology.BINOMINAL); outlierAttribute.getMapping().mapString("false"); outlierAttribute.getMapping().mapString("true"); eSet.getExampleTable().addAttribute(outlierAttribute); eSet.getAttributes().setOutlier(outlierAttribute); counter = 0; // reset counter to zero Iterator<Example> reader2 = eSet.iterator(); while (reader2.hasNext()) { Example example = reader2.next(); if (sr.getSearchObjectOutlierStatus(counter) == true) { example.setValue(outlierAttribute, outlierAttribute.getMapping().mapString("true")); } else { example.setValue(outlierAttribute, outlierAttribute.getMapping().mapString("false")); } counter++; } return eSet; } @Override public List<ParameterType> getParameterTypes() { List<ParameterType> types = super.getParameterTypes(); types.add(new ParameterTypeInt(PARAMETER_NUMBER_OF_NEIGHBORS, "Specifies the k value for the k-th nearest neighbours to be the analyzed." + "(default value is 10, minimum 1 and max is set to 1 million)", 1, Integer.MAX_VALUE, 10, false)); types.add(new ParameterTypeInt(PARAMETER_NUMBER_OF_OUTLIERS, "The number of top-n Outliers to be looked for." + "(default value is 10, minimum 2 (internal reasons) and max is set to 1 million)", 1, Integer.MAX_VALUE, 10, false)); types.add(new ParameterTypeCategory(PARAMETER_DISTANCE_FUNCTION, "choose which distance function will be used for calculating " + "the distance between two objects", distanceFunctionList, 0, false)); return types; } @Override protected Set<String> getOutlierValues() { HashSet<String> set = new HashSet<>(); set.add("true"); set.add("false"); return set; } @Override public ResourceConsumptionEstimator getResourceConsumptionEstimator() { return OperatorResourceConsumptionHandler.getResourceConsumptionEstimator(getInputPort(), DKNOutlierOperator.class, null); } }
transwarpio/rapidminer
rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/operator/preprocessing/outlier/DKNOutlierOperator.java
Java
gpl-3.0
8,123
/* * A manual example using JCalendarButton. * JCalendarTest.java * Created on Aug 24, 2009, 10:47:11 PM * Copyright © 2012 jbundle.org. All rights reserved. */ package calendartest; import java.text.DateFormat; import java.util.Date; /** * * @author don */ public class JCalendarTest extends javax.swing.JFrame { /** Creates new form NewJFrame */ public JCalendarTest() { initComponents(); } /** * Command line startup * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new JCalendarTest().setVisible(true); } }); } /** This method is called from within the constructor to * initialize the form. */ private void initComponents() { jLabel1 = new javax.swing.JLabel("Name:"); jTextField1 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel("Date:"); jTextField2 = new javax.swing.JTextField(); jTextField2.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { String date = jTextField2.getText(); setDate(date); } }); jLabel3 = new javax.swing.JLabel("Time:"); jTextField3 = new javax.swing.JTextField(); jTextField3.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { String time = jTextField3.getText(); setTime(time); } }); jLabel4 = new javax.swing.JLabel("Date and Time:"); jTextField4 = new javax.swing.JTextField(); jTextField4.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { String dateTime = jTextField4.getText(); setDateTime(dateTime); } }); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); // Layout components javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel1) .addComponent(jLabel3) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE) .addComponent(jTextField4) .addComponent(jTextField3) .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)) .addContainerGap(124, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(33, 33, 33) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(59, Short.MAX_VALUE)) ); pack(); } /** * Validate and set the datetime field on the screen given a datetime string. * @param dateTime The datetime string */ public void setDate(String dateString) { Date date = null; try { if ((dateString != null) && (dateString.length() > 0)) date = dateFormat.parse(dateString); } catch (Exception e) { date = null; } this.setDate(date); } /** * Validate and set the datetime field on the screen given a date. * @param dateTime The datetime object */ public void setDate(Date date) { String dateString = ""; if (date != null) dateString = dateFormat.format(date); jTextField2.setText(dateString); } /** * Validate and set the datetime field on the screen given a datetime string. * @param dateTime The datetime string */ public void setTime(String timeString) { Date time = null; try { if ((timeString != null) && (timeString.length() > 0)) time = timeFormat.parse(timeString); } catch (Exception e) { time = null; } this.setTime(time); } /** * Validate and set the datetime field on the screen given a date. * @param dateTime The datetime object */ public void setTime(Date time) { String timeString = ""; if (time != null) timeString = timeFormat.format(time); jTextField3.setText(timeString); } /** * Validate and set the datetime field on the screen given a datetime string. * @param dateTime The datetime string */ public void setDateTime(String dateTimeString) { Date dateTime = null; try { if ((dateTimeString != null) && (dateTimeString.length() > 0)) dateTime = dateTimeFormat.parse(dateTimeString); } catch (Exception e) { dateTime = null; } this.setDateTime(dateTime); } /** * Validate and set the datetime field on the screen given a date. * @param dateTime The datetime object */ public void setDateTime(Date dateTime) { String dateTimeString = ""; if (dateTime != null) dateTimeString = dateTimeFormat.format(dateTime); jTextField4.setText(dateTimeString); } // Variables declaration private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; public static DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM); public static DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT); public static DateFormat dateTimeFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT); }
jbundle/jcalendarbutton
jcalendarbutton/src/site/resources/manual/code1/JCalendarTest.java
Java
gpl-3.0
8,107
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ECCentral.BizEntity.Common; using ECCentral.Service.Utility; using ECCentral.Service.MKT.IDataAccess; using System.ServiceModel.Web; using ECCentral.QueryFilter.MKT; using ECCentral.BizEntity.MKT; using ECCentral.Service.MKT.AppService; using ECCentral.Service.Utility.WCF; using ECCentral.Service.MKT.IDataAccess.NoBizQuery; using ECCentral.BizEntity.MKT.PageType; using ECCentral.BizEntity.MKT; using System.Data; namespace ECCentral.Service.MKT.Restful { public partial class MKTService { [WebInvoke(UriTemplate = "/ProductRecommend/Query", Method = "POST")] public virtual QueryResult QueryProductRecommend(ProductRecommendQueryFilter filter) { int totalCount; var dt = ObjectFactory<IProductRecommendQueryDA>.Instance.Query(filter, out totalCount); QueryResult result = new QueryResult(); result.Data = dt; result.TotalCount = totalCount; GetInventoryInfoByStock(dt); dt.Columns.Add("PageTypeName", typeof(string)); dt.Columns.Add("PositionName", typeof(string)); //获取页面类型 var pageTypes = ObjectFactory<PageTypeAppService>.Instance.GetPageType(filter.CompanyCode, filter.ChannelID, ModuleType.ProductRecommend); Dictionary<string, List<CodeNamePair>> dictPositionCache = new Dictionary<string, List<CodeNamePair>>(); foreach (DataRow dr in result.Data.Rows) { string pageTypeID = dr["PageType"].ToString(); var foundPageType = pageTypes.FirstOrDefault(item => item.Code == pageTypeID); if (foundPageType != null) { dr["PageTypeName"] = foundPageType.Name; } //根据PageType查询位置信息 List<CodeNamePair> currentPagePosition; if (!dictPositionCache.TryGetValue(pageTypeID, out currentPagePosition)) { currentPagePosition = this.GetProductRecommendPosition(pageTypeID); if(currentPagePosition!=null&&currentPagePosition.Count>0) { currentPagePosition.ForEach(v=> { if(v.Name.Contains("专卖店--")) { v.Name = v.Name.Replace("专卖店--", ""); } }); } dictPositionCache.Add(pageTypeID, currentPagePosition); } var foundPosition = currentPagePosition.FirstOrDefault(item => item.Code == dr["PositionID"].ToString()); if (foundPosition != null) { dr["PositionName"] = foundPosition.Name; } } return result; } #region 商品查询合并分仓库存信息 /// <summary> /// 获取包含分仓库存的数据 /// </summary> /// <param name="product"></param> /// <returns></returns> public virtual void GetInventoryInfoByStock(DataTable product) { if (product == null || product.Rows.Count == 0) return; var stockList = new Dictionary<string, int> { { "Shanghai", 51 }, { "Begjin", 52 }, { "Guangzhou", 53 } }; var displayField = new[] { "OnlineQty"}; var columns = (from k in stockList.Keys from c in displayField select k + c).ToList(); AddTableColumns(product, columns); var productSysNoList = (from e in product.AsEnumerable() select e.Field<int>("ProductSysNo")).ToList(); var prarm = (from k in productSysNoList from c in stockList.Keys select new { ProductSysNo = k, Stock = c }).ToList(); prarm.ForEach(v => { var entity = _productRecommendAppService.GetProductInventoryInfoByStock(v.ProductSysNo, stockList[v.Stock]); var oneProduct = (from e in product.AsEnumerable() where e.Field<int>("ProductSysNo") == v.ProductSysNo select e).FirstOrDefault(); displayField.ForEach(k => { int value = 0; if (entity != null) { object tempvalue = null; var pro = entity.GetType().GetProperty(k); if (pro != null) { tempvalue = Invoker.PropertyGet(entity, k); } value = Convert.ToInt32(tempvalue); } var columnName = v.Stock + k; if (oneProduct != null) oneProduct.SetField(columnName, value); }); }); } /// <summary> /// 合并仓库数据 /// </summary> /// <param name="product"></param> /// <param name="columns"></param> private void AddTableColumns(DataTable product, List<string> columns) { if (columns == null || columns.Count == 0) return; foreach (var item in columns) product.Columns.Add(item).DefaultValue = 0; } #endregion private ProductRecommendAppService _productRecommendAppService = ObjectFactory<ProductRecommendAppService>.Instance; /// <summary> /// 创建 /// </summary> [WebInvoke(UriTemplate = "/ProductRecommend/Create", Method = "POST")] public virtual void CreateProductRecommend(ProductRecommendInfo entity) { _productRecommendAppService.Create(entity); } /// <summary> /// 更新 /// </summary> [WebInvoke(UriTemplate = "/ProductRecommend/Update", Method = "PUT")] public virtual void UpdateProductRecommend(ProductRecommendInfo entity) { _productRecommendAppService.Update(entity); } /// <summary> /// 加载 /// </summary> [WebGet(UriTemplate = "/ProductRecommend/Load/{sysNo}")] public virtual ProductRecommendInfo LoadProductRecommend(string sysNo) { int id = int.Parse(sysNo); return _productRecommendAppService.Load(id); } /// <summary> /// 将商品推荐置为无效 /// </summary> /// <param name="sysNo">系统编号</param> [WebInvoke(UriTemplate = "/ProductRecommend/Deactive/{sysNo}", Method = "PUT")] public virtual void DeactiveProductRecommend(string sysNo) { int id = int.Parse(sysNo); _productRecommendAppService.Deactive(id); } [WebGet(UriTemplate = "/ProductRecommend/GetPosition/{pageTypeID}")] public virtual List<CodeNamePair> GetProductRecommendPosition(string pageTypeID) { int pageType = int.Parse(pageTypeID); var presentationType = PageTypeUtil.ResolvePresentationType(ModuleType.ProductRecommend, pageTypeID); //if (presentationType == PageTypePresentationType.Brand) //{ // //当PageType为专卖店时返回空,专卖店有特殊的加载位置信息的逻辑 // return new List<CodeNamePair>(); //} //商品推荐位置Key格式:ProductRecommend+[PageTypeID],比如ProductRecommend0代表首页的推荐位 var positionConfigKey = ModuleType.ProductRecommend.ToString(); //if (pageType > 100) //{ // //PageTypeID>100表示是首页domain馆 // positionConfigKey += "-DomainList"; //} //else //{ positionConfigKey += pageType.ToString(); //} var result= CodeNamePairManager.GetList("MKT", positionConfigKey); return result; } [WebGet(UriTemplate = "/ProductRecommend/GetBrandPosition/{pageID}/{comapnyCode}/{channelID}")] public virtual List<CodeNamePair> GetProductRecommandBrandPosition(string pageID, string comapnyCode, string channelID) { var brandLocation = _productRecommendAppService.GetBrandPosition(int.Parse(pageID), comapnyCode, channelID); List<CodeNamePair> result = new List<CodeNamePair>(); foreach (var loc in brandLocation) { result.Add(new CodeNamePair { Code = loc.PositionID.ToString(), Name = string.Format("专卖店--{0}", loc.Description) }); } return result; } } }
ZeroOne71/ql
02_ECCentral/03_Service/03_MKT/ECCentral.Service.MKT.Restful/MKTService_ProductRecommend.cs
C#
gpl-3.0
9,469
<?php /** * @package Rakuun Browsergame * @copyright Copyright (C) 2012 Sebastian Mayer, Andreas Sicking, Andre Jährling * @license GNU/GPL, see license.txt * This file is part of Rakuun. * * Rakuun is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * Rakuun is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Rakuun. If not, see <http://www.gnu.org/licenses/>. */ abstract class Rakuun_Intern_GUI_Panel_Tutor_Tipp extends Rakuun_Intern_GUI_Panel_Tutor_Level { public function completed() { return true; } } ?>
Sebioff/Rakuun
source/intern/gui/panel/tutor/tipp.php
PHP
gpl-3.0
998
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author apavel */ public class ABC { public void TskA() { System.out.print("Member of ABC, TskA"); } public void TskB() { System.out.print("TskB does addition"); } public void TskC() { System.out.print("TskC doe mult"); } }
AlexNPavel/APCompSciStuff
APCompSciStuffSince Oct13/src/ABC.java
Java
gpl-3.0
490
/** * MutableLong.java * * Copyright 2010 Jeffrey Finkelstein * * This file is part of jmona. * * jmona is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * jmona is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * jmona. If not, see <http://www.gnu.org/licenses/>. */ package jmona.impl.mutable; import jmona.DeepCopyable; /** * A deep-copyable, mutable long wrapper. * * @author Jeffrey Finkelstein * @since 0.5 */ public class MutableLong extends org.apache.commons.lang.mutable.MutableLong implements DeepCopyable<MutableLong> { /** Default generated serial version UID. */ private static final long serialVersionUID = -270777759872744946L; /** * Instantiates this object by calling the default constructor of the * superclass. */ public MutableLong() { // intentionally unimplemented } /** * Instantiates this object with the specified initial value. * * @param initialValue * The initial value of this object. */ public MutableLong(final long initialValue) { super(initialValue); } /** * Instantiates this object with the specified initial value. * * @param initialValue * The initial value of this object. */ public MutableLong(final Number initialValue) { super(initialValue); } /** * {@inheritDoc} * * @return {@inheritDoc} * @see jmona.DeepCopyable#deepCopy() */ @Override public MutableLong deepCopy() { return new MutableLong(this); } }
jfinkels/jmona
jmona-model/src/main/java/jmona/impl/mutable/MutableLong.java
Java
gpl-3.0
1,950
/** * @author : cromarmot (yexiaorain@gmail.com) * @license : GPL * @created : 星期一 2月 03, 2020 14:39:46 CST */ #include <bits/stdc++.h> using namespace std; typedef long long ll; #define ten5 100000+10 #define MOD 1000000007 #define rep(i,a,n) for (int i=a;i<n;i++) #define iif(c,t,f) ((c)?(t):(f)) #define per(i,a,n) for (int i=n-1;i>=a;i--) #define pb push_back #define mp make_pair const double pi = acos(-1.0); // 1-9 // 10-99 // 100-999 int idx =1; int d[1'001'000]; int len(int v){ int ret = 0; while(v){ ret++; v/=10; } return ret; } int main(){ int i = 0; while(idx <= 1'000'001){ int l = len(i); int ii = i; rep(j,0,l){ d[idx+l-1-j] = ii%10; ii/=10; } i++; idx+=l; } int pos=1; int ans =1; while(pos <= 1'000'000){ cout<<pos<<":"<<d[pos]<<endl; ans*=d[pos]; pos*=10; } cout<<ans<<endl; return 0; } /* * * hash prime 61,83,113,151,211,281,379,509683,911 1217,1627,2179,2909,3881,6907,9209 12281,16381,21841,29123,38833,51787,69061,92083 122777,163729,218357,291143,388211,517619,690163,999983 1226959,1635947,2181271,2908361,3877817,5170427,6893911,9191891 12255871,16341163,21788233,29050993,38734667,51646229,68861641,91815541 122420729,163227661,217636919,290182597,386910137,515880193,687840301,917120411 1000000007,1000000009 * */
CroMarmot/MyOICode
ProjectEuler/p040.cpp
C++
gpl-3.0
1,387
package jeql.jts.geodetic; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.MultiLineString; public class GeodeticSplitter { private Geometry line; public GeodeticSplitter(Geometry line) { this.line = line; } public Geometry split() { MultiCoordinateList mcl = new MultiCoordinateList(false); Coordinate[] pts = line.getCoordinates(); mcl.add(pts[0]); for (int i = 1; i < pts.length; i++) { Coordinate p0 = pts[i-1]; Coordinate p1 = pts[i]; if (crossesDateLine(p0, p1)) { double latCross = latitudeOfCrossing(p0, p1); if (p0.x < 0) { mcl.add(new Coordinate(-180, latCross)); mcl.finish(); mcl.add(new Coordinate(180, latCross)); } else { mcl.add(new Coordinate(180, latCross)); mcl.finish(); mcl.add(new Coordinate(-180, latCross)); } } mcl.add(p1); } return toMultiLineString(mcl); } private static boolean crossesDateLine(Coordinate p0, Coordinate p1) { if (p0.x < -90 && p1.x > 90) return true; if (p1.x < -90 && p0.x > 90) return true; return false; } private static double latitudeOfCrossing(Coordinate p0, Coordinate p1) { // compute in the lon-lat plane - which isn't accurate for long lines double x0 = p0.x; double y0 = p0.y; double x1 = p1.x + 360;; double y1 = p1.y; if (p0.x < 0) { x0 = p1.x; y0 = p1.y; x1 = p0.x + 360; y1 = p0.y; } double dx = x1 - x0; double dy = y1 - y0; double x = 180 - x0; double y = dy/dx * x; return y + y0; } private MultiLineString toMultiLineString(MultiCoordinateList mcl) { Coordinate[][] pts = mcl.toCoordinateArrays(); LineString[] lines = new LineString[pts.length]; for (int i = 0; i < pts.length; i++) { lines[i] = toLineString(pts[i]); } return line.getFactory().createMultiLineString(lines); } private LineString toLineString(Coordinate[] pts) { // prevent lines of length 1 if (pts.length == 1) { pts = new Coordinate[] { pts[0], new Coordinate(pts[0]) }; } return line.getFactory().createLineString(pts); } }
dr-jts/jeql
modules/jeql/src/main/java/jeql/jts/geodetic/GeodeticSplitter.java
Java
gpl-3.0
2,350
page = []; term = new Terminal(); sTerm = new Terminal(); page.server = "http://molly/moiras/server-terminal.php"; //- - - - - Pop page.loaded = function(){ //------------ configuracao term = new Terminal(); sTerm = new Terminal(); term.server = page.server; sTerm.server = page.server; sTerm.on(); term.on(); //------------------ user.get(); } //---- config page.config = function(){ page.popContent(page.tConfig); page.popUp(); } //---- bakup page.backupOpen = function(){ page.popContent(page.tFormBeckup); } page.beckup = function(){ window.open('server-terminal.php?comander=dado.dump()', '_blank'); } //- - - - - PopUp page.checkPop = false; page.popUp = function(){ //console.log("pop"); this.checkPop = !this.checkPop; if(this.checkPop){ document.getElementById("popUp").className = "popUP-true"; } else{ document.getElementById("popUp").className = "popUP-false"; } } page.popContent = function(content){ document.getElementById("popUp-content").innerHTML = content; } page.drop = function(id){ com = "dado.drop(" + id + ")"; console.log(com); term.com(com,page.rDrop); }; page.rDrop = function(msg){ console.log(msg); page.search(); } page.replace = function(base,dados){ var dadosK=Object.keys(dados); for (var i = 0; i < dadosK.length; i++) { base = base.replace(new RegExp("{" + dadosK[i] + "}", 'g'),dados[dadosK[i]]); } return base; } //------------ page.tConfig = document.getElementById("tConfig").innerHTML; page.tFormBeckup = document.getElementById("formBeckup").innerHTML; page.tFirstDado = "<dado onclick='page.novaNota()'><id>Novo Dado</id><valor><img src='resources/img/new.svg'></valor></dado>"; page.notaform = "<div id=\"fNotaCabecario\"></div><form><label>Dado</label><textarea id=\"fNotaDado\"></textarea><label>Tags</label><textarea id=\"fNotaTag\"></textarea><input id=\"fNotaAplic\" onclick=\"\" value=\"Salvar\" type=\"button\"><input id=\"fNotaAplic\" onclick=\"page.popUp()\" value=\"Cancelar\" type=\"button\"></form>"; page.loginform = "<form><label>Dado</label><textarea id=\"novaNotaDado\"></textarea><label>Tags</label><textarea id=\"novaNotaTag\"></textarea><input onclick=\"page.novaNotaAplic()\" value=\"Salvar\" type=\"button\"></form>"; console.log("page.js");
CupBlack/Moiras
resources/js/page.js
JavaScript
gpl-3.0
2,263
package com.ricky30.prispongemine.commands; import java.util.UUID; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.CommandSource; import org.spongepowered.api.command.args.CommandContext; import org.spongepowered.api.command.spec.CommandExecutor; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import com.flowpowered.math.vector.Vector3i; import com.ricky30.prispongemine.config.ManageMines; import com.ricky30.prispongemine.events.interactionevents; import ninja.leaping.configurate.ConfigurationNode; public class commandSave implements CommandExecutor { @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { final String Name = args.<String>getOne("name").get(); final Player player = (Player) src; final UUID world = player.getWorld().getUniqueId(); final boolean OK = ManageMines.SaveMine(Name, false); final ConfigurationNode config = ManageMines.getConfig(); if (!OK) { src.sendMessage(Text.of("Mine ", Name, " already saved. Use update instead or change name.")); return CommandResult.empty(); } if (interactionevents.IsreadytoFill(player)) { final Vector3i positiondepart = interactionevents.getFirst(player); final Vector3i positionfin = interactionevents.getSecond(player); config.getNode("world").setValue(world.toString()); config.getNode("depart_X").setValue(positiondepart.getX()); config.getNode("depart_Y").setValue(positiondepart.getY()); config.getNode("depart_Z").setValue(positiondepart.getZ()); config.getNode("fin_X").setValue(positionfin.getX()); config.getNode("fin_Y").setValue(positionfin.getY()); config.getNode("fin_Z").setValue(positionfin.getZ()); config.getNode("renewtime").setValue(24); config.getNode("renewformat").setValue("HOURS"); config.getNode("autorun").setValue(false); config.getNode("random").setValue(false); config.getNode("set").setValue(0); config.getNode("startupdelay").setValue(300); ManageMines.SaveMine(Name, true); src.sendMessage(Text.of("Mine " , Name, " saved")); return CommandResult.success(); } else { src.sendMessage(Text.of("Not ready to save yet")); } return CommandResult.empty(); } }
rickyminecraft/prispongemine
src/main/java/com/ricky30/prispongemine/commands/commandSave.java
Java
gpl-3.0
2,354
/* * Copyright 2010-2013 Eric Kok et al. * * Transdroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Transdroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Transdroid. If not, see <http://www.gnu.org/licenses/>. */ package org.transdroid.core.seedbox; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import org.transdroid.core.app.settings.ServerSetting; import org.transdroid.daemon.Daemon; import org.transdroid.daemon.OS; /** * Implementation of {@link SeedboxSettings} for Dediseedbox seedboxes. * @author Eric Kok */ public class DediseedboxSettings extends SeedboxSettingsImpl implements SeedboxSettings { @Override public String getName() { return "Dediseedbox"; } @Override public ServerSetting getServerSetting(SharedPreferences prefs, int orderOffset, int order) { // @formatter:off String server = prefs.getString("seedbox_dediseedbox_server_" + order, null); if (server == null) { return null; } String user = prefs.getString("seedbox_dediseedbox_user_" + order, null); String pass = prefs.getString("seedbox_dediseedbox_pass_" + order, null); return new ServerSetting( orderOffset + order, prefs.getString("seedbox_dediseedbox_name_" + order, null), Daemon.rTorrent, server, null, 443, null, 443, true, false, null, "/rutorrent/plugins/httprpc/action.php", true, user, pass, null, OS.Linux, "/", "ftp://" + user + "@" + server + "/", pass, 6, true, true, true); // @formatter:on } @Override public Intent getSettingsActivityIntent(Context context) { return DediseedboxSettingsActivity_.intent(context).get(); } @Override public int getMaxSeedboxOrder(SharedPreferences prefs) { return getMaxSeedboxOrder(prefs, "seedbox_dediseedbox_server_"); } @Override public void removeServerSetting(SharedPreferences prefs, int order) { removeServerSetting(prefs, "seedbox_dediseedbox_server_", new String[] { "seedbox_dediseedbox_name_", "seedbox_dediseedbox_server_", "seedbox_dediseedbox_user_", "seedbox_dediseedbox_pass_" }, order); } }
0359xiaodong/transdroid
app/src/main/java/org/transdroid/core/seedbox/DediseedboxSettings.java
Java
gpl-3.0
2,641
#!/usr/bin/env python #coding=utf-8 # Nathive (and this file) is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or newer. # # You should have received a copy of the GNU General Public License along with # this file. If not, see <http://www.gnu.org/licenses/>. import gtk import webbrowser from nathive.lib.plugin import * class Home(PluginLauncher): def __init__(self): # Subclass it. PluginLauncher.__init__(self) # Common attributes. self.name = 'home' self.author = 'nathive-dev' self.type = 'launcher' self.menu = 'help' self.label = _('Nathive website') self.icon = 'gtk-home' def callback(self): """To do when the plugin is called.""" webbrowser.open('http://www.nathive.org')
johnnyLadders/Nathive_CITA
nathive/plugins/home.py
Python
gpl-3.0
933
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SNet.Net { public enum PacketFlags : ushort { None = 0, ISerializable = 1, Raw = 2 } }
sanderele1/FileHub
Tcp16/SNet_Net/Networking/PacketFlags.cs
C#
gpl-3.0
253
/* * ================================ * eli960@qq.com * http://www.mailhonor.com/ * 2015-11-20 * ================================ */ #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #include "zcc.h" #include <signal.h> #include <sys/types.h> #include <dirent.h> bool var_test_mode = false; namespace zcc { static master_event_server *___instance; static bool flag_init = false; static bool flag_run = false; static bool flag_inner_event_loop = false; static bool flag_clear = false; static pid_t parent_pid = 0; static event_io *ev_status = 0; static std::list<event_io *> event_ios; static void load_global_config_by_dir(config &cf, const char *config_path) { DIR *dir; struct dirent ent, *ent_list; char *fn, *p; char pn[4100]; dir = opendir(config_path); if (!dir) { return; } while ((!readdir_r(dir, &ent, &ent_list)) && (ent_list)) { fn = ent.d_name; if (fn[0] == '.') { continue; } p = strrchr(fn, '.'); if ((!p) || (strcasecmp(p + 1, "gcf"))) { continue; } snprintf(pn, 4096, "%s/%s", config_path, fn); cf.load_by_filename(pn); } closedir(dir); } static char *stop_file = 0; static void stop_file_check(event_timer &tm) { if (file_get_size(stop_file) < 0) { var_proc_stop = true; } else { tm.start(stop_file_check, 1000 * 1); } } static void on_master_reload(event_io &ev) { var_proc_stop = true; } static void ___inet_server_accept(event_io &ev) { int fd, listen_fd = ev.get_fd(); void (*cb)(int) = (void(*)(int))ev.get_context(); fd = inet_accept(listen_fd); if (fd < 0) { if (errno != EAGAIN) { zcc_fatal("inet_server_accept: %m"); } return; } nonblocking(fd); close_on_exec(fd); if (cb) { cb(fd); } else { ___instance->simple_service(fd); } } static void ___unix_server_accept(event_io &ev) { int fd, listen_fd = ev.get_fd(); void (*cb)(int) = (void(*)(int))ev.get_context(); fd = unix_accept(listen_fd); if (fd < 0) { if (errno != EAGAIN) { zcc_fatal("unix_server_accept: %m"); } return; } nonblocking(fd); close_on_exec(fd); if (cb) { cb(fd); } else { ___instance->simple_service(fd); } } static void ___fifo_server_accept(event_io &ev) { int listen_fd = ev.get_fd(); void (*cb)(int) = (void(*)(int))ev.get_context(); if (cb) { cb(listen_fd); } else { ___instance->simple_service(listen_fd); } } master_event_server::master_event_server() { if (!flag_init) { signal(SIGPIPE, SIG_IGN); flag_init = true; flag_run = false; parent_pid = getppid(); ev_status = 0; /* private */ flag_inner_event_loop = false; flag_clear = false; } } master_event_server::~master_event_server() { } void master_event_server::clear() { if (flag_clear) { return; } flag_clear = true; if (ev_status) { /* The master would receive the signal of closing ZMASTER_SERVER_STATUS_FD. */ delete ev_status; ev_status = 0; close(var_master_server_status_fd); close(var_master_master_status_fd); } std_list_walk_begin(event_ios, eio) { int fd = eio->get_fd(); delete eio; close(fd); } std_list_walk_end; event_ios.clear(); } void master_event_server::stop_notify() { var_proc_stop = true; default_evbase.notify(); } void master_event_server::alone_register(char *alone_url) { char service_buf[1024]; char *service, *url, *p; strtok splitor(alone_url); while(splitor.tok(" \t,;\r\n")) { if (splitor.size() > 1000) { zcc_fatal("alone_register: url too long"); } memcpy(service_buf, splitor.ptr(), splitor.size()); service_buf[splitor.size()] = 0; p = strstr(service_buf, "://"); if (p) { *p=0; service = service_buf; url = p+3; } else { service = blank_buffer; url = service_buf; } int fd_type; int fd = listen(url, &fd_type); if (fd < 0) { zcc_fatal("alone_register: open %s(%m)", alone_url); } close_on_exec(fd); nonblocking(fd); service_register(service, fd, fd_type); } } void master_event_server::master_register(char *master_url) { zcc::argv service_argv; service_argv.split(master_url, ","); for (size_t i = 0; i < service_argv.size(); i++) { char *service_name, *typefd; zcc::argv stfd; stfd.split(service_argv[i], ":"); if (stfd.size() == 1) { service_name = blank_buffer; typefd = stfd[0]; } else { service_name = stfd[0]; typefd = stfd[1]; } int fdtype = typefd[0]; switch(fdtype) { case var_tcp_listen_type_inet: case var_tcp_listen_type_unix: case var_tcp_listen_type_fifo: break; default: zcc_fatal("master_event_server: unknown service type %c", fdtype); break; } int fd = atoi(typefd+1); if (fd < var_master_server_listen_fd) { zcc_fatal("master_event_server: fd(%s) is invalid", typefd+1); } close_on_exec(fd); nonblocking(fd); service_register(service_name, fd, fdtype); } } void master_event_server::before_service() { } void master_event_server::event_loop() { flag_inner_event_loop = true; } void master_event_server::before_exit() { } void master_event_server::simple_service(int fd) { zcc_fatal("must be make a new simple_service when use simpe mode"); } event_io *master_event_server::general_service_register(int fd, int fd_type , void (*service) (int) , event_base &eb) { event_io *ev = new event_io(); ev->bind(fd, eb); ev->set_context((void *)service); if (fd_type == var_tcp_listen_type_inet) { ev->enable_read(___inet_server_accept); } else if (fd_type == var_tcp_listen_type_unix) { ev->enable_read(___unix_server_accept); } else if (fd_type == var_tcp_listen_type_fifo) { ev->enable_read(___fifo_server_accept); } event_ios.push_back(ev); return ev; } void master_event_server::service_register(const char *service_name, int fd, int fd_type) { general_service_register(fd, fd_type, 0); } void master_event_server::run(int argc, char ** argv) { if (flag_run) { zcc_fatal("master_event_server:: only run one time"); } flag_run = true; ___instance = this; char *attr; main_parameter_run(argc, argv); attr = default_config.get_str("server-config-path", ""); if (!empty(attr)) { config cf; load_global_config_by_dir(cf, attr); cf.load_another(default_config); default_config.load_another(cf); } var_masterlog_listen = default_config.get_str("master-log-listen", ""); stop_file = default_config.get_str("stop-file", ""); log_use_by(argv[0], default_config.get_str("server-log")); if (default_config.get_bool("MASTER", false)) { ev_status = new event_io(); close_on_exec(var_master_master_status_fd); nonblocking(var_master_master_status_fd); ev_status->bind(var_master_master_status_fd); ev_status->enable_read(on_master_reload); ev_status->set_context(this); if (!empty(stop_file)) { event_timer *stop_file_timer = new event_timer(); stop_file_timer->bind(); stop_file_timer->start(stop_file_check, 1000 * 1); } } before_service(); if (!default_config.get_bool("MASTER", false)) { alone_register(default_config.get_str("server-service", "")); } else { master_register(default_config.get_str("server-service", "")); } attr = default_config.get_str("server-user", ""); if (!empty(attr)) { if(!chroot_user(0, attr)) { zcc_fatal("ERR chroot_user %s", attr); } } while (1) { if (var_proc_stop) { break; } default_evbase.dispatch(); if (var_proc_stop) { break; } if (!flag_inner_event_loop) { event_loop(); } } clear(); before_exit(); } }
mailhonor/zcc
src/master/event_server.cpp
C++
gpl-3.0
8,544
package de.dorianscholz.openlibre; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import android.util.Log; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.TimeUnit; import de.dorianscholz.openlibre.model.GlucoseData; import de.dorianscholz.openlibre.model.RawTagData; import de.dorianscholz.openlibre.model.ReadingData; import io.realm.Realm; import io.realm.RealmResults; import io.realm.Sort; import static de.dorianscholz.openlibre.OpenLibre.parseRawData; import static de.dorianscholz.openlibre.OpenLibre.realmConfigProcessedData; import static de.dorianscholz.openlibre.OpenLibre.realmConfigRawData; import static de.dorianscholz.openlibre.OpenLibre.setupRealm; import static de.dorianscholz.openlibre.model.ReadingData.historyIntervalInMinutes; import static de.dorianscholz.openlibre.model.ReadingData.numHistoryValues; import static de.dorianscholz.openlibre.model.ReadingData.numTrendValues; import static java.lang.Math.abs; import static java.lang.Math.max; import static java.lang.Math.min; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.everyItem; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.greaterThanOrEqualTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; @RunWith(AndroidJUnit4.class) public class ReadingDataTest { private static final int MAX_READINGS_TO_TEST = 1000; private Realm realmRawData; private Realm realmProcessedData; private ArrayList<ReadingData> readingDataList = new ArrayList<>(); private ArrayList<RawTagData> rawTagDataList = new ArrayList<>(); @Before public void setUp() throws Exception { Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); Realm.init(context); setupRealm(context); realmRawData = Realm.getInstance(realmConfigRawData); } private void parseTestData() { // open empty processed data realm for use in parsing data Realm.deleteRealm(realmConfigProcessedData); realmProcessedData = Realm.getInstance(realmConfigProcessedData); // get all raw data RealmResults<RawTagData> rawTags = realmRawData.where(RawTagData.class).findAllSorted(RawTagData.DATE, Sort.ASCENDING); // reduce data set to just the raw data of the most recent sensor String tagId = rawTags.last().getTagId(); rawTags = rawTags.where().equalTo(RawTagData.TAG_ID, tagId).findAllSorted(RawTagData.DATE, Sort.ASCENDING); // reduce data set further to only MAX_READINGS_TO_TEST sensor readings for (int i = 0; i < min(MAX_READINGS_TO_TEST, rawTags.size()); i++) { addDataIfValid(rawTags.get(i)); } /* // add oldest readings of sensor for (int i = 0; i < min(MAX_READINGS_TO_TEST / 2, rawTags.size() / 2); i++) { addDataIfValid(rawTags.get(i)); } // add newest readings of sensor for (int i = max(rawTags.size() / 2, rawTags.size() - 1 - MAX_READINGS_TO_TEST / 2); i < rawTags.size() - 1; i++) { addDataIfValid(rawTags.get(i)); } */ assertThat(realmRawData.isEmpty(), is(false)); assertThat(readingDataList.size(), greaterThan(0)); } private void addDataIfValid(RawTagData rawTagData) { // check if sensor has been initialized and is not yet over due date if (rawTagData.getSensorAgeInMinutes() < numHistoryValues * historyIntervalInMinutes || rawTagData.getSensorAgeInMinutes() > TimeUnit.DAYS.toMinutes(14)) return; // check if data contains enough history and trend data for the tests to work ReadingData readingData = new ReadingData(rawTagData); if (readingData.getHistory().size() < numHistoryValues || readingData.getTrend().size() != numTrendValues) { //Log.d("OpenLibre::Test", "history size: " + readingData.getHistory().size() + " trend size: " + readingData.getTrend().size()); return; } // add reading to realm, so when parsing the next reading, it can access this data realmProcessedData.beginTransaction(); realmProcessedData.copyToRealmOrUpdate(readingData); realmProcessedData.commitTransaction(); rawTagDataList.add(rawTagData); readingDataList.add(readingData); } @After public void tearDown() { realmRawData.close(); // if any test opened the processed data realm, close it and delete the data if (realmProcessedData != null) { realmProcessedData.close(); Realm.deleteRealm(realmConfigProcessedData); } } //@Ignore @Test public void testReparseAllData() { // delete all parsed readings before the tests Realm.deleteRealm(realmConfigProcessedData); // reparse all readings from raw data parseRawData(); Realm realmProcessedData = Realm.getInstance(realmConfigProcessedData); assertThat(realmProcessedData.isEmpty(), is(false)); realmProcessedData.close(); } @Test public void testTrendIndexVsSensorAge() { parseTestData(); ArrayList<Integer> results = new ArrayList<>(); for (RawTagData rawTagData : rawTagDataList) { int diff = ((rawTagData.getSensorAgeInMinutes() % numTrendValues) - rawTagData.getIndexTrend() + numTrendValues) % numTrendValues; results.add(diff); if (diff > 1) Log.w("OpenLibre::TEST", "failed for: sensorAge: " + rawTagData.getSensorAgeInMinutes() + " trendIndex: " + rawTagData.getIndexTrend()); } Log.d("OpenLibre::TEST", "sensorAge % numTrendValues - trendIndex: " + results); assertThat("trend index drifted away from sensor age more than one minute", results, everyItem(lessThanOrEqualTo(1))); } @Test public void testHistoryDatesMatchOnOverlappingReadings() { parseTestData(); ArrayList<Integer> results = new ArrayList<>(); ReadingData oldReadingData = readingDataList.get(0); results.add(0); for (ReadingData readingData : readingDataList.subList(1, readingDataList.size())) { GlucoseData oldGlucoseData = oldReadingData.getHistory().last(); boolean found = false; for (GlucoseData glucoseData : readingData.getHistory()) { if (oldGlucoseData.glucose() == glucoseData.glucose()) { if (oldGlucoseData.getAgeInSensorMinutes() - glucoseData.getAgeInSensorMinutes() == 0) { // well matched results.add(0); found = true; break; } else if (abs(oldGlucoseData.getAgeInSensorMinutes() - glucoseData.getAgeInSensorMinutes()) < historyIntervalInMinutes) { results.add(oldGlucoseData.getAgeInSensorMinutes() - glucoseData.getAgeInSensorMinutes()); found = true; break; } } } if (!found) results.add(0); oldReadingData = readingData; } Log.d("OpenLibre::TEST", "age diff: " + results); assertThat("history dates on overlapping readings don't match", results, everyItem(equalTo(0))); assertThat("no overlapping readings found", results.size(), greaterThan(0)); } @Test public void testHistoryDatesFitTrendData() { parseTestData(); ArrayList<Integer> firstTrendResults = new ArrayList<>(); ArrayList<Integer> lastTrendResults = new ArrayList<>(); for (ReadingData readingData : readingDataList) { GlucoseData lastHistory = readingData.getHistory().get(readingData.getHistory().size() - 1); GlucoseData firstTrend = readingData.getTrend().get(0); GlucoseData lastTrend = readingData.getTrend().get(readingData.getTrend().size() - 1); long lastHistoryMinutes = TimeUnit.MILLISECONDS.toMinutes(lastHistory.getDate()); long lastTrendMinutes = TimeUnit.MILLISECONDS.toMinutes(lastTrend.getDate()); long firstTrendMinutes = TimeUnit.MILLISECONDS.toMinutes(firstTrend.getDate()); firstTrendResults.add((int)(lastHistoryMinutes - firstTrendMinutes)); lastTrendResults.add((int)(lastTrendMinutes - lastHistoryMinutes)); } Log.d("OpenLibre::TEST", "last history - first trend date: " + firstTrendResults); Log.d("OpenLibre::TEST", "last trend - last history date: " + lastTrendResults); assertThat("history ends more than 3 minutes before first trend", firstTrendResults, everyItem(greaterThanOrEqualTo(-3))); assertThat("history ends after last trend", lastTrendResults, everyItem(greaterThanOrEqualTo(0))); } @Test public void testHistoryValuesFitTrendData() { parseTestData(); ArrayList<Float> minTrendResults = new ArrayList<>(); ArrayList<Float> maxTrendResults = new ArrayList<>(); for (ReadingData readingData : readingDataList) { GlucoseData lastHistory = readingData.getHistory().get(readingData.getHistory().size() - 1); ArrayList<Float> trendValues = new ArrayList<>(); for (GlucoseData glucoseData : readingData.getTrend()) { trendValues.add(glucoseData.glucose(false)); } minTrendResults.add(lastHistory.glucose(false) - Collections.min(trendValues)); maxTrendResults.add(Collections.max(trendValues) - lastHistory.glucose(false)); } Log.d("OpenLibre::TEST", "last history - min trend value: " + minTrendResults); Log.d("OpenLibre::TEST", "max trend value - last history: " + maxTrendResults); assertThat("last history value far smaller than trend values", minTrendResults, everyItem(greaterThanOrEqualTo(-10f))); assertThat("last history value far greater than trend values", maxTrendResults, everyItem(greaterThanOrEqualTo(-10f))); } }
DorianScholz/OpenLibre
app/src/androidTest/java/de/dorianscholz/openlibre/ReadingDataTest.java
Java
gpl-3.0
10,467
class CreateCharacters < ActiveRecord::Migration def self.up create_table :characters do |t| t.string :name t.string :path t.string :virtue t.string :vice t.integer :cabal_id, :null => false, :options => "CONSTRAINT fk_character_cabals REFERENCES cabal(id)" t.integer :order_id, :null => false, :options => "CONSTRAINT fk_character_order REFERENCES order(id)" t.text :description t.text :background t.integer :intelligence t.integer :strength t.integer :presence t.integer :wits t.integer :dexterity t.integer :manipulation t.integer :resolve t.integer :stamina t.integer :composure t.integer :academics t.integer :athletics t.integer :animal_ken t.integer :computer t.integer :brawl t.integer :empathy t.integer :crafts t.integer :drive t.integer :expression t.integer :investigation t.integer :firearms t.integer :intimidation t.integer :medicine t.integer :larceny t.integer :persuasion t.integer :occult t.integer :stealth t.integer :socialize t.integer :politics t.integer :survival t.integer :streetwise t.integer :science t.integer :weaponry t.integer :subterfuge t.text :skill_specialties t.string :health t.string :willpower t.integer :speed t.integer :initiative t.integer :defense t.integer :armor t.integer :wisdom t.text :derangements t.text :merits t.integer :gnosis t.integer :death t.integer :fate t.integer :forces t.integer :life t.integer :matter t.integer :mind t.integer :prime t.integer :space t.integer :spirit t.integer :time t.text :equipment t.text :common_spells t.timestamps end end def self.down drop_table :characters end end
yithian/personae
db/migrate/20090507003935_create_characters.rb
Ruby
gpl-3.0
1,968
import os import sys import numpy as np from copy import deepcopy import argparse sys.path.append(os.path.join(os.path.dirname(__file__),"../projects/tools")) import msh import executable_paths as exe def parse(): parser = argparse.ArgumentParser(description="Creates mandible and masseter files for the database creation") parser.add_argument("-i", "--input", help="input .mesh object", type=str, required=True) parser.add_argument("-t", "--template", help="template mandible in full size", type=str, required=True) return parser.parse_args() def checkArgs(args): if not os.path.isfile(args.input): print args.input + " is not a valid file" sys.exit() if not os.path.splitext(args.input)[1] == ".mesh": print args.input + " is not a .mesh file" sys.exit() if not os.path.isfile(args.template): print args.template + " is not a valid file" sys.exit() if not os.path.splitext(args.template)[1] == ".mesh": print args.template + " is not a .mesh file" sys.exit() def command(cmd, displayOutput=False): err = 1 print "Running the command '" + cmd + "'" if displayOutput: err = os.system(cmd) else: err = os.system(cmd + " > tmp_out.txt 2>tmp_err.txt") if err: print "An error happened while executing:\n"+cmd+"\nLook in tmp_out.txt or tmp_err.txt for info\nExiting..." sys.exit() else: os.system("rm tmp_out.txt tmp_err.txt >/dev/null 2>&1") if __name__=="__main__": args = parse() checkArgs(args) # 3 - Align to the template full mandibule command(exe.align + " -i " + args.input + " " + args.template + " -d 50 -o 0.95", displayOutput=True) command(exe.pythonICP + " -s " + args.input + " -t " + args.template + " -m mat_PythonICP.txt") # 1 - Reading the input file fullMandible = msh.Mesh(args.input) fullMandible.applyMatrix(matFile="mat_Super4PCS.txt") fullMandible.applyMatrix(matFile="mat_PythonICP.txt") # 2 - Scale to [0,1] MAT = fullMandible.toUnitMatrix() np.savetxt("mat_toUnit.txt",MAT) fullMandible.applyMatrix(mat=MAT) fullMandible.write("mandible.mesh") # 4 - Cut the mandible in two rightMandible = deepcopy(fullMandible) leftMandible = fullMandible #Generate the mask mask = [1 for i in range(len(leftMandible.tris))] mid = np.mean(leftMandible.verts,axis=0)[0] print mid for i,t in enumerate(leftMandible.tris): for v in t: x = leftMandible.verts[v][0] if x < mid: mask[i] = 0 #Create the left mandible leftMandible.tris = np.array([t for i,t in enumerate(leftMandible.tris) if mask[i]==1]) print len(leftMandible.tris) leftMandible.discardUnused() leftMAT = leftMandible.toUnitMatrix() np.savetxt("1_leftMandibleToUnit.txt", leftMAT) leftMandible.applyMatrix(mat=leftMAT) leftMandible.write("leftMandible.mesh") #And the right one, symetrized rightMandible.tris = np.array([t for i,t in enumerate(rightMandible.tris) if mask[i]==0]) rightMandible.discardUnused() rightMAT = rightMandible.toUnitMatrix() np.savetxt("1_rightMandibleToUnit.txt", rightMAT) rightMandible.applyMatrix(mat=rightMAT) rightMandible.verts[:,0] = 1-rightMandible.verts[:,0] rightMandible.write("rightMandible.mesh") # 5 - Create the shells for left and right mandibles #command(exe.boundingMesh + " leftMandible.mesh", displayOutput=True) command(exe.shell + " -i leftMandible.mesh -o leftShell.mesh -c", displayOutput=True) command(exe.shell + " -i rightMandible.mesh -o rightShell.mesh -c", displayOutput=True) sys.exit() # 6 - Warp the shell to the mandibles command(exe.warping + " leftMandible.shell.mesh leftMandible.mesh") command(exe.warping + " rightMandible.shell.mesh rightMandible.mesh") # 7 - Create a domain for mshdist computation #Right mandible cube=msh.Mesh(cube=[0,1,0,1,0,1]) cube.write("rightBox.mesh") command( "tetgen -pgANEF rightBox.mesh") command( "mmg3d_O3 rightBox.1.mesh -hausd " + str(np.max(mesh.dims)/25) + " -hmax " + str(np.max(mesh.dims)/25)) command( "mshdist -ncpu 4 -noscale rightBox.1.o.mesh rightMandible.warped.mesh") # 9 - Morphing the template_mandibule surface to the computed boxes command(morphing + " template_halfMandible_volume.mesh rightBox.1.o.mesh") # 10 - Extract the surface from the morphing results morphed = msh.Mesh("morphed.mesh") morphed.readSol() morphed.extractSurfaces#Placeholder
ISCDtoolbox/FaciLe
pipeline/processMandibleAndMasseter.py
Python
gpl-3.0
4,598
using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; namespace HelpDesk.WorkerWebApp.Identity { // Чтобы добавить данные профиля для пользователя, можно добавить дополнительные свойства в класс ApplicationUser. Дополнительные сведения см. по адресу: http://go.microsoft.com/fwlink/?LinkID=317594. public class ApplicationUser : IUser<long> { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, long> manager) { // Обратите внимание, что authenticationType должен совпадать с типом, определенным в CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Здесь добавьте утверждения пользователя return userIdentity; } public string Password { get; set; } public string UserName { get; set; } public long Id { get; set; } public string Email { get; set; } } }
knyazkov-ma/HelpDesk
WebApp/HelpDesk.WorkerWebApp/Identity/ApplicationUser.cs
C#
gpl-3.0
1,310
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the Qt Charts module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 or (at your option) any later version ** approved by the KDE Free Qt Foundation. The licenses are as published by ** the Free Software Foundation and appearing in the file LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtWidgets/QApplication> #include <QtWidgets/QMainWindow> #include <QtCharts/QChartView> #include <QtCharts/QBarSeries> #include <QtCharts/QBarSet> #include <QtCharts/QLegend> #include <QtCharts/QBarCategoryAxis> #include <QtCharts/QStackedBarSeries> QT_CHARTS_USE_NAMESPACE int main(int argc, char *argv[]) { QApplication a(argc, argv); //![1] QBarSet *low = new QBarSet("Min"); QBarSet *high = new QBarSet("Max"); *low << -52 << -50 << -45.3 << -37.0 << -25.6 << -8.0 << -6.0 << -11.8 << -19.7 << -32.8 << -43.0 << -48.0; *high << 11.9 << 12.8 << 18.5 << 26.5 << 32.0 << 34.8 << 38.2 << 34.8 << 29.8 << 20.4 << 15.1 << 11.8; //![1] //![2] QStackedBarSeries *series = new QStackedBarSeries(); series->append(low); series->append(high); //![2] //![3] QChart *chart = new QChart(); chart->addSeries(series); chart->setTitle("Temperature records in celcius"); chart->setAnimationOptions(QChart::SeriesAnimations); //![3] //![4] QStringList categories; categories << "Jan" << "Feb" << "Mar" << "Apr" << "May" << "Jun" << "Jul" << "Aug" << "Sep" << "Oct" << "Nov" << "Dec"; QBarCategoryAxis *axis = new QBarCategoryAxis(); axis->append(categories); axis->setTitleText("Month"); chart->createDefaultAxes(); chart->setAxisX(axis, series); chart->axisY(series)->setRange(-52, 52); chart->axisY(series)->setTitleText("Temperature [&deg;C]"); //![4] //![5] chart->legend()->setVisible(true); chart->legend()->setAlignment(Qt::AlignBottom); //![5] //![6] QChartView *chartView = new QChartView(chart); chartView->setRenderHint(QPainter::Antialiasing); //![6] //![7] QMainWindow window; window.setCentralWidget(chartView); window.resize(600, 300); window.show(); //![7] return a.exec(); }
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtcharts/examples/charts/temperaturerecords/main.cpp
C++
gpl-3.0
3,166
#include "RepRapFirmware.h" #include "DriveMovement.h" // The remaining functions are speed-critical, so use full optimisation #pragma GCC optimize ("O3") // Fast 62-bit integer square root function (thanks dmould) uint32_t isqrt64(uint64_t num) { uint32_t numHigh = (uint32_t)(num >> 32); if (numHigh == 0) { // 32-bit square root - thanks to Wilco Dijksra for this efficient ARM algorithm uint32_t num32 = (uint32_t)num; uint32_t res = 0; #define iter32(N) \ { \ uint32_t temp = res | (1 << N); \ if (num32 >= temp << N) \ { \ num32 -= temp << N; \ res |= 2 << N; \ } \ } // We need to do 16 iterations iter32(15); iter32(14); iter32(13); iter32(12); iter32(11); iter32(10); iter32(9); iter32(8); iter32(7); iter32(6); iter32(5); iter32(4); iter32(3); iter32(2); iter32(1); iter32(0); return res >> 1; } else if ((numHigh & (3u << 30)) != 0) { // Input out of range - probably negative, so return -1 return 0xFFFFFFFF; } else { // 62-bit square root uint32_t res = 0; #define iter64a(N) \ { \ res <<= 1; \ uint32_t temp = (res | 1) << (N); \ if (numHigh >= temp) \ { \ numHigh -= temp; \ res |= 2; \ } \ } // We need to do 15 iterations (not 16 because we have eliminated the top 2 bits) iter64a(28) iter64a(26) iter64a(24) iter64a(22) iter64a(20) iter64a(18) iter64a(16) iter64a(14) iter64a(12) iter64a(10) iter64a(8) iter64a(6) iter64a(4) iter64a(2) iter64a(0) // resHigh is twice the square root of the msw, in the range 0..2^17-1 uint64_t numAll = ((uint64_t)numHigh << 32) | (uint32_t)num; #define iter64b(N) \ { \ res <<= 1; \ uint64_t temp = ((uint64_t)res | 1) << (N); \ if (numAll >= temp) \ { \ numAll -= temp; \ res |= 2; \ } \ } // We need to do 16 iterations. // After the last iteration, numAll may be between 0 and (1 + 2 * res) inclusive. // So to take square roots of numbers up to 64 bits, we need to do all these iterations using 64 bit maths. // If we restricted the input to e.g. 48 bits, then we could do some of the final iterations using 32-bit maths. iter64b(30) iter64b(28) iter64b(26) iter64b(24) iter64b(22) iter64b(20) iter64b(18) iter64b(16) iter64b(14) iter64b(12) iter64b(10) iter64b(8) iter64b(6) iter64b(4) iter64b(2) iter64b(0) return res >> 1; #undef iter64a #undef iter64b } } #if 0 // Fast 64-bit integer square root function uint32_t isqrt2(uint64_t num) { uint32_t numHigh = (uint32_t)(num >> 32); uint32_t resHigh = 0; #define iter64a(N) \ { \ uint32_t temp = resHigh + (1 << (N)); \ if (numHigh >= temp << (N)) \ { \ numHigh -= temp << (N); \ resHigh |= 2 << (N); \ } \ } // We need to do 16 iterations iter64a(15); iter64a(14); iter64a(13); iter64a(12); iter64a(11); iter64a(10); iter64a(9); iter64a(8); iter64a(7); iter64a(6); iter64a(5); iter64a(4); iter64a(3); iter64a(2); iter64a(1); iter64a(0); // resHigh is twice the square root of the msw, in the range 0..2^17-1 uint64_t res = (uint64_t)resHigh << 16; uint64_t numAll = ((uint64_t)numHigh << 32) | (uint32_t)num; #define iter64b(N) \ { \ uint64_t temp = res | (1 << (N)); \ if (numAll >= temp << (N)) \ { \ numAll -= temp << (N); \ res |= 2 << (N); \ } \ } // We need to do 16 iterations. // After the last iteration, numAll may be between 0 and (1 + 2 * res) inclusive. // So to take square roots of numbers up to 64 bits, we need to do all these iterations using 64 bit maths. // If we restricted the input to e.g. 48 bits, then we could do some of the final iterations using 32-bit maths. iter64b(15) iter64b(14) iter64b(13) iter64b(12) iter64b(11) iter64b(10) iter64b(9) iter64b(8) iter64b(7) iter64b(6) iter64b(5) iter64b(4) iter64b(3) iter64b(2) iter64b(1) iter64b(0) return (uint32_t)(res >> 1); #undef iter64a #undef iter64b #undef iter32 } uint32_t sqSum1 = 0, sqSum2 = 0, sqCount = 0, sqErrors = 0, lastRes1 = 0, lastRes2 = 0; uint64_t lastNum = 0; /* static */ uint32_t isqrt64(uint64_t num) { irqflags_t flags = cpu_irq_save(); uint32_t t2 = Platform::GetInterruptClocks(); uint32_t res1 = isqrt1(num); uint32_t t3 = Platform::GetInterruptClocks(); uint32_t res2 = isqrt2(num); uint32_t t4 = Platform::GetInterruptClocks(); cpu_irq_restore(flags); sqSum1 += (t3 - t2); sqSum2 += (t4 - t3); ++sqCount; if (res1 != res2) { ++sqErrors; lastNum = num; lastRes1 = res1; lastRes2 = res2; } return res2; } #endif // End
dcnewman/RepRapFirmware
src/Isqrt.cpp
C++
gpl-3.0
4,744
# No Loop. # # The noLoop() function causes draw() to only # execute once. Without calling noLoop(), draw() # executed continually. attr_reader :y def setup sketch_title 'No Loop' @y = height / 2 stroke 255 frame_rate 30 no_loop end def draw background 0 @y = y - 1 @y = height if y < 0 line 0, y, width, y end def settings size 640, 360 end
ruby-processing/JRubyArt-examples
processing_app/basics/structure/noloop.rb
Ruby
gpl-3.0
365
package com.travelport.service.hotel_v29_0; /** * Please modify this class to meet your needs * This class is not complete */ import java.io.File; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.bind.annotation.XmlSeeAlso; /** * This class was generated by Apache CXF 2.7.12 * 2014-09-19T15:09:40.850-06:00 * Generated source version: 2.7.12 * */ public final class RetrieveHotelSearchAvailabilityServicePortType_RetrieveHotelSearchAvailabilityServicePort_Client { private static final QName SERVICE_NAME = new QName("http://www.travelport.com/service/hotel_v29_0", "HotelService"); private RetrieveHotelSearchAvailabilityServicePortType_RetrieveHotelSearchAvailabilityServicePort_Client() { } public static void main(String args[]) throws java.lang.Exception { URL wsdlURL = HotelService.WSDL_LOCATION; if (args.length > 0 && args[0] != null && !"".equals(args[0])) { File wsdlFile = new File(args[0]); try { if (wsdlFile.exists()) { wsdlURL = wsdlFile.toURI().toURL(); } else { wsdlURL = new URL(args[0]); } } catch (MalformedURLException e) { e.printStackTrace(); } } HotelService ss = new HotelService(wsdlURL, SERVICE_NAME); RetrieveHotelSearchAvailabilityServicePortType port = ss.getRetrieveHotelSearchAvailabilityServicePort(); { System.out.println("Invoking service..."); com.travelport.schema.hotel_v29_0.RetrieveHotelSearchAvailabilityReq _service_parameters = null; try { com.travelport.schema.hotel_v29_0.RetrieveHotelSearchAvailabilityRsp _service__return = port.service(_service_parameters); System.out.println("service.result=" + _service__return); } catch (HotelFaultMessage e) { System.out.println("Expected exception: HotelFaultMessage has occurred."); System.out.println(e.toString()); } } System.exit(0); } }
angecab10/travelport-uapi-tutorial
src/com/travelport/service/hotel_v29_0/RetrieveHotelSearchAvailabilityServicePortType_RetrieveHotelSearchAvailabilityServicePort_Client.java
Java
gpl-3.0
2,307
package org.thoughtcrime.securesms.database.helpers; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.os.SystemClock; import android.support.annotation.NonNull; import android.text.TextUtils; import android.util.Log; import net.sqlcipher.database.SQLiteDatabase; import net.sqlcipher.database.SQLiteDatabaseHook; import net.sqlcipher.database.SQLiteOpenHelper; import org.thoughtcrime.securesms.ApplicationContext; import org.thoughtcrime.securesms.crypto.DatabaseSecret; import org.thoughtcrime.securesms.crypto.MasterSecret; import org.thoughtcrime.securesms.database.AttachmentDatabase; import org.thoughtcrime.securesms.database.DraftDatabase; import org.thoughtcrime.securesms.database.GroupDatabase; import org.thoughtcrime.securesms.database.GroupReceiptDatabase; import org.thoughtcrime.securesms.database.IdentityDatabase; import org.thoughtcrime.securesms.database.MmsDatabase; import org.thoughtcrime.securesms.database.OneTimePreKeyDatabase; import org.thoughtcrime.securesms.database.PushDatabase; import org.thoughtcrime.securesms.database.RecipientDatabase; import org.thoughtcrime.securesms.database.SearchDatabase; import org.thoughtcrime.securesms.database.SessionDatabase; import org.thoughtcrime.securesms.database.SignedPreKeyDatabase; import org.thoughtcrime.securesms.database.SmsDatabase; import org.thoughtcrime.securesms.database.ThreadDatabase; import org.thoughtcrime.securesms.jobs.RefreshPreKeysJob; import org.thoughtcrime.securesms.service.KeyCachingService; import org.thoughtcrime.securesms.util.TextSecurePreferences; import java.io.File; public class SQLCipherOpenHelper extends SQLiteOpenHelper { @SuppressWarnings("unused") private static final String TAG = SQLCipherOpenHelper.class.getSimpleName(); private static final int RECIPIENT_CALL_RINGTONE_VERSION = 2; private static final int MIGRATE_PREKEYS_VERSION = 3; private static final int MIGRATE_SESSIONS_VERSION = 4; private static final int NO_MORE_IMAGE_THUMBNAILS_VERSION = 5; private static final int ATTACHMENT_DIMENSIONS = 6; private static final int QUOTED_REPLIES = 7; private static final int SHARED_CONTACTS = 8; private static final int FULL_TEXT_SEARCH = 9; private static final int BAD_IMPORT_CLEANUP = 10; private static final int DATABASE_VERSION = 10; private static final String DATABASE_NAME = "signal.db"; private final Context context; private final DatabaseSecret databaseSecret; public SQLCipherOpenHelper(@NonNull Context context, @NonNull DatabaseSecret databaseSecret) { super(context, DATABASE_NAME, null, DATABASE_VERSION, new SQLiteDatabaseHook() { @Override public void preKey(SQLiteDatabase db) { db.rawExecSQL("PRAGMA cipher_default_kdf_iter = 1;"); db.rawExecSQL("PRAGMA cipher_default_page_size = 4096;"); } @Override public void postKey(SQLiteDatabase db) { db.rawExecSQL("PRAGMA kdf_iter = '1';"); db.rawExecSQL("PRAGMA cipher_page_size = 4096;"); } }); this.context = context.getApplicationContext(); this.databaseSecret = databaseSecret; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SmsDatabase.CREATE_TABLE); db.execSQL(MmsDatabase.CREATE_TABLE); db.execSQL(AttachmentDatabase.CREATE_TABLE); db.execSQL(ThreadDatabase.CREATE_TABLE); db.execSQL(IdentityDatabase.CREATE_TABLE); db.execSQL(DraftDatabase.CREATE_TABLE); db.execSQL(PushDatabase.CREATE_TABLE); db.execSQL(GroupDatabase.CREATE_TABLE); db.execSQL(RecipientDatabase.CREATE_TABLE); db.execSQL(GroupReceiptDatabase.CREATE_TABLE); db.execSQL(OneTimePreKeyDatabase.CREATE_TABLE); db.execSQL(SignedPreKeyDatabase.CREATE_TABLE); db.execSQL(SessionDatabase.CREATE_TABLE); for (String sql : SearchDatabase.CREATE_TABLE) { db.execSQL(sql); } executeStatements(db, SmsDatabase.CREATE_INDEXS); executeStatements(db, MmsDatabase.CREATE_INDEXS); executeStatements(db, AttachmentDatabase.CREATE_INDEXS); executeStatements(db, ThreadDatabase.CREATE_INDEXS); executeStatements(db, DraftDatabase.CREATE_INDEXS); executeStatements(db, GroupDatabase.CREATE_INDEXS); executeStatements(db, GroupReceiptDatabase.CREATE_INDEXES); if (context.getDatabasePath(ClassicOpenHelper.NAME).exists()) { ClassicOpenHelper legacyHelper = new ClassicOpenHelper(context); android.database.sqlite.SQLiteDatabase legacyDb = legacyHelper.getWritableDatabase(); SQLCipherMigrationHelper.migratePlaintext(context, legacyDb, db); MasterSecret masterSecret = KeyCachingService.getMasterSecret(context); if (masterSecret != null) SQLCipherMigrationHelper.migrateCiphertext(context, masterSecret, legacyDb, db, null); else TextSecurePreferences.setNeedsSqlCipherMigration(context, true); if (!PreKeyMigrationHelper.migratePreKeys(context, db)) { ApplicationContext.getInstance(context).getJobManager().add(new RefreshPreKeysJob(context)); } SessionStoreMigrationHelper.migrateSessions(context, db); PreKeyMigrationHelper.cleanUpPreKeys(context); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database: " + oldVersion + ", " + newVersion); db.beginTransaction(); try { if (oldVersion < RECIPIENT_CALL_RINGTONE_VERSION) { db.execSQL("ALTER TABLE recipient_preferences ADD COLUMN call_ringtone TEXT DEFAULT NULL"); db.execSQL("ALTER TABLE recipient_preferences ADD COLUMN call_vibrate INTEGER DEFAULT " + RecipientDatabase.VibrateState.DEFAULT.getId()); } if (oldVersion < MIGRATE_PREKEYS_VERSION) { db.execSQL("CREATE TABLE signed_prekeys (_id INTEGER PRIMARY KEY, key_id INTEGER UNIQUE, public_key TEXT NOT NULL, private_key TEXT NOT NULL, signature TEXT NOT NULL, timestamp INTEGER DEFAULT 0)"); db.execSQL("CREATE TABLE one_time_prekeys (_id INTEGER PRIMARY KEY, key_id INTEGER UNIQUE, public_key TEXT NOT NULL, private_key TEXT NOT NULL)"); if (!PreKeyMigrationHelper.migratePreKeys(context, db)) { ApplicationContext.getInstance(context).getJobManager().add(new RefreshPreKeysJob(context)); } } if (oldVersion < MIGRATE_SESSIONS_VERSION) { db.execSQL("CREATE TABLE sessions (_id INTEGER PRIMARY KEY, address TEXT NOT NULL, device INTEGER NOT NULL, record BLOB NOT NULL, UNIQUE(address, device) ON CONFLICT REPLACE)"); SessionStoreMigrationHelper.migrateSessions(context, db); } if (oldVersion < NO_MORE_IMAGE_THUMBNAILS_VERSION) { ContentValues update = new ContentValues(); update.put("thumbnail", (String)null); update.put("aspect_ratio", (String)null); update.put("thumbnail_random", (String)null); try (Cursor cursor = db.query("part", new String[] {"_id", "ct", "thumbnail"}, "thumbnail IS NOT NULL", null, null, null, null)) { while (cursor != null && cursor.moveToNext()) { long id = cursor.getLong(cursor.getColumnIndexOrThrow("_id")); String contentType = cursor.getString(cursor.getColumnIndexOrThrow("ct")); if (contentType != null && !contentType.startsWith("video")) { String thumbnailPath = cursor.getString(cursor.getColumnIndexOrThrow("thumbnail")); File thumbnailFile = new File(thumbnailPath); thumbnailFile.delete(); db.update("part", update, "_id = ?", new String[] {String.valueOf(id)}); } } } } if (oldVersion < ATTACHMENT_DIMENSIONS) { db.execSQL("ALTER TABLE part ADD COLUMN width INTEGER DEFAULT 0"); db.execSQL("ALTER TABLE part ADD COLUMN height INTEGER DEFAULT 0"); } if (oldVersion < QUOTED_REPLIES) { db.execSQL("ALTER TABLE mms ADD COLUMN quote_id INTEGER DEFAULT 0"); db.execSQL("ALTER TABLE mms ADD COLUMN quote_author TEXT"); db.execSQL("ALTER TABLE mms ADD COLUMN quote_body TEXT"); db.execSQL("ALTER TABLE mms ADD COLUMN quote_attachment INTEGER DEFAULT -1"); db.execSQL("ALTER TABLE part ADD COLUMN quote INTEGER DEFAULT 0"); } if (oldVersion < SHARED_CONTACTS) { db.execSQL("ALTER TABLE mms ADD COLUMN shared_contacts TEXT"); } if (oldVersion < FULL_TEXT_SEARCH) { for (String sql : SearchDatabase.CREATE_TABLE) { db.execSQL(sql); } Log.i(TAG, "Beginning to build search index."); long start = SystemClock.elapsedRealtime(); db.execSQL("INSERT INTO sms_fts (rowid, body) SELECT _id, body FROM sms"); long smsFinished = SystemClock.elapsedRealtime(); Log.i(TAG, "Indexing SMS completed in " + (smsFinished - start) + " ms"); db.execSQL("INSERT INTO mms_fts (rowid, body) SELECT _id, body FROM mms"); long mmsFinished = SystemClock.elapsedRealtime(); Log.i(TAG, "Indexing MMS completed in " + (mmsFinished - smsFinished) + " ms"); Log.i(TAG, "Indexing finished. Total time: " + (mmsFinished - start) + " ms"); } if (oldVersion < BAD_IMPORT_CLEANUP) { String trimmedCondition = " NOT IN (SELECT _id FROM mms)"; db.delete("group_receipts", "mms_id" + trimmedCondition, null); String[] columns = new String[] { "_id", "unique_id", "_data", "thumbnail"}; try (Cursor cursor = db.query("part", columns, "mid" + trimmedCondition, null, null, null, null)) { while (cursor != null && cursor.moveToNext()) { db.delete("part", "_id = ? AND unique_id = ?", new String[] { String.valueOf(cursor.getLong(0)), String.valueOf(cursor.getLong(1)) }); String data = cursor.getString(2); String thumbnail = cursor.getString(3); if (!TextUtils.isEmpty(data)) { new File(data).delete(); } if (!TextUtils.isEmpty(thumbnail)) { new File(thumbnail).delete(); } } } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } if (oldVersion < MIGRATE_PREKEYS_VERSION) { PreKeyMigrationHelper.cleanUpPreKeys(context); } } public SQLiteDatabase getReadableDatabase() { return getReadableDatabase(databaseSecret.asString()); } public SQLiteDatabase getWritableDatabase() { return getWritableDatabase(databaseSecret.asString()); } public void markCurrent(SQLiteDatabase db) { db.setVersion(DATABASE_VERSION); } private void executeStatements(SQLiteDatabase db, String[] statements) { for (String statement : statements) db.execSQL(statement); } }
FeuRenard/Signal-Android
src/org/thoughtcrime/securesms/database/helpers/SQLCipherOpenHelper.java
Java
gpl-3.0
10,969
# -*- coding: utf-8 -*- """ Created on Thu Jun 23 13:52:07 2016 @author: huliqun """ import unittest import json import binascii from falcon import testing import sys sys.path.append('..') from workserver.util.AES_PKCS7_extension import Cryptor from MainServer import app class TestAuth(testing.TestCase): def setUp(self): self.api = app # def test_regUser(self): # headers = {'content-type':'application/json'} # body = '{"username":"wahaha@qq.com","displayname":"wahaha","email":"wahaha@qq.com","password":"123456","mobile":"18698729476"}' # result =self.simulate_post('/api/users',headers=headers,body=body ) # self.assertEqual(result.status_code, 201) def test_auth(self): import hashlib def md5(s): m = hashlib.md5() m.update(s.encode("utf-8")) return m.hexdigest() # print("pwd : %s" % md5('123456')) iv, encrypted = Cryptor.encrypt('aaa', md5('12345678')) print(md5('12345678')) # print("iv : %s" % iv.decode()) # print("encrypted : %s" % binascii.b2a_base64(encrypted).rstrip()) print(Cryptor.decrypt(encrypted,md5('12345678'), iv)) # headers = {'content-type':'application/json'} # body = { # 'oid': 2, # 'username':'admin', # 'identifyCode':encrypted, # 'magicNo':iv.decode() # } # result =self.simulate_post('/api/auth',headers=headers,body=json.dumps(body) ) # self.assertEqual(result.status_code, 200) # print(result.text) # should raise an exception for an immutable sequence # self.assertRaises(TypeError, random.shuffle, (1,2,3)) if __name__ == '__main__': unittest.main()
LiqunHu/MVPN
testing/testAuth.py
Python
gpl-3.0
1,873
#region PRODUCTION READY® ELEFLEX® Software License. Copyright © 2015 Production Ready, LLC. All Rights Reserved. //Copyright © 2015 Production Ready, LLC. All Rights Reserved. //For more information, visit http://www.ProductionReady.com //This file is part of PRODUCTION READY® ELEFLEX®. // //This program is free software: you can redistribute it and/or modify //it under the terms of the GNU Affero General Public License as //published by the Free Software Foundation, either version 3 of the //License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU Affero General Public License for more details. // //You should have received a copy of the GNU Affero General Public License //along with this program. If not, see <http://www.gnu.org/licenses/>. #endregion using System; using Eleflex.Security.Message; using Eleflex.Services; namespace Eleflex.Security.Message.RoleCommand { /// <summary> /// Delete response. /// </summary> public class RoleDeleteResponse : ServiceCommandResponse { } }
ProductionReady/Eleflex
V2.1/src/Security Module/Eleflex.Security.Message/RoleCommand/RoleDeleteResponse.cs
C#
gpl-3.0
1,226
package sprax.aligns; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.TreeMap; import sprax.files.FileUtil; import sprax.files.TextFileReader; import sprax.sprout.Sx; /** * TODO: Separate classes for dictionary parsing and storage? * TODO: abstract and wrap the gets and puts, and guard against * multiple entries for same key. Merge the value sets. Add * Spanish word list to check for loan words triggering the * "no Spanish definition" check. * * @author sprax */ public abstract class Lexicon { String mTitle; final String mSrcLanguageCode; final String mDstLanguageCode; final String mSourceLanguage; final String mTargetLanguage; TreeMap<String, Set<String>> mDict_1_1; TreeMap<String, Set<String>> mDict_2_1; TreeMap<String, Set<String>> mDict_3_1; // HashMap<String, ArrayList<String>> mDict_1_2; // HashMap<String, ArrayList<String>> mDict_1_3; // HashMap<String, ArrayList<String>> mDict_2_2; // HashMap<String, ArrayList<String>> mDict_3_3; // HashMap<String, ArrayList<String>> mDict_N_N; TreeMap<String, String> mPastTenseToRoot; String getSrcCode() { return mSrcLanguageCode; } String getDstCode() { return mDstLanguageCode; } String getTitle() { return mTitle; } static int sDbg = 2; static char sSepTermsDefns = ':'; static char sSepDefinitions = ';'; final String mFsSourceWordList; final String mFsTargetWordList; static WordSet sSourceWordSet; static WordSet sTargetWordSet; /** * Is first char of string upper case? * No error checking. */ static boolean isCapitalized(String str) { return Character.isUpperCase(str.charAt(0)); } /** * If the supplied word is a capitalized form of a word * whose lower-case form is in the (source/target lexicon, * return the lower-case form; otherwise, return null. */ String sourceUnCapitalized(String wordA) { if (isCapitalized(wordA)) { String uncappedA = wordA.toLowerCase(); if (isSourceWord(uncappedA)) return uncappedA; } return null; } String targetUnCapitalized(String wordB) { if (isCapitalized(wordB)) { String uncappedB = wordB.toLowerCase(); if (isTargetWord(uncappedB)) return uncappedB; String lowSingB = targetSingular(uncappedB); if (lowSingB != null && isTargetWord(lowSingB)) return uncappedB; String lowPresB = targetPresent(uncappedB); if (lowPresB != null && isTargetWord(lowPresB)) return uncappedB; } return null; } /** * If the argument is a known plural word, return the singular form; * otherwise, return null. * TODO: Use look-up table, either loaded or memoized on the fly. * @param possibly plural form of a word in the source language * @return singular form of the same word, if known */ String defaultSingular(String word) { int lastIdx = word.length() - 1; char lastChar = word.charAt(lastIdx); if (lastChar == 's') return word.substring(0, lastIdx); return null; } String sourceSingular(String word) { return defaultSingular(word); } String targetSingular(String word) { return defaultSingular(word); } /** * If the argument is a known past tense word, * return the present tense form; * otherwise, return null. */ String defaultUnPast(String word) { int lastIdx = word.length() - 1; if (lastIdx < 3) return null; char lastChar = word.charAt(lastIdx); if (lastChar == 'd') { int punultIdx = lastIdx - 1; char penultChar = word.charAt(punultIdx); if (penultChar == 'e') { String sansD = word.substring(0, lastIdx); if (isSourceWord(sansD)) return sansD; String sansED = word.substring(0, punultIdx); if (isSourceWord(sansED)) return sansED; } } return null; } String sourceUnPast(String word) { return defaultUnPast(word); } String targetUnPast(String word) { return defaultUnPast(word); } /** * If the argument is a known present participle, * return the present tense form; * otherwise, return null. */ String defaultUnPresentParticiple(String word) { int lastIdx = word.length() - 1; if (lastIdx < 5) return null; char lastChar = word.charAt(lastIdx); if (lastChar == 'g' && word.endsWith("ing")) { String sansING = word.substring(0, lastIdx-2); if (isSourceWord(sansING)) return sansING; String plusE = sansING.concat("e"); if (isSourceWord(plusE)) return plusE; } return null; } String sourceUnPresentParticiple(String word) { return defaultUnPresentParticiple(word); } String targetUnPresentParticiple(String word) { return defaultUnPresentParticiple(word); } /** * If the argument is a known past or future tense word, * return the present tense form; * otherwise, return null. */ String sourcePresent(String word) { String present; if (null != (present = sourceUnPast(word))) return present; if (null != (present = sourceUnPresentParticiple(word))) return present; return null; } String targetPresent(String word) { String present; if (null != (present = targetUnPast(word))) return present; if (null != (present = targetUnPresentParticiple(word))) return present; return null; } Lexicon(final String srcLangCode, final String dstLangCode) { mSrcLanguageCode = srcLangCode; mDstLanguageCode = dstLangCode; mSourceLanguage = languageNameFromCode(srcLangCode); mTargetLanguage = languageNameFromCode(dstLangCode); mFsSourceWordList = FileUtil.getTextFilePath(mSrcLanguageCode + "/" + mSrcLanguageCode + "NamesWords.txt"); mFsTargetWordList = FileUtil.getTextFilePath(mDstLanguageCode + "/" + mDstLanguageCode + "NamesWords.txt"); mPastTenseToRoot = new TreeMap<String, String>(); } /** * Get language name from 2-letter code * TODO: Use enum const strings */ static String languageNameFromCode(final String code) { if (code.equals("En")) return "English"; if (code.equals("Es")) return "Spanish"; return "unsupported language"; } boolean isSourceWord(String word) { return getSourceWordSet().contains(word); } boolean isTargetWord(String word) { return getTargetWordSet().contains(word); } WordSet getSourceWordSet() { if (sSourceWordSet == null) sSourceWordSet = readWordList(mFsSourceWordList, mSourceLanguage); return sSourceWordSet; } WordSet getTargetWordSet() { if (sTargetWordSet == null) sTargetWordSet = readWordList(mFsTargetWordList, mTargetLanguage); return sTargetWordSet; } static WordSet readWordList(String textFileSpec, String languageName) { WordSet wordSet = new WordSet(); TextFileReader tfr = new TextFileReader(textFileSpec); Sx.debug(2, "Reading %s words from file: %s, ", languageName, textFileSpec); int numWords = tfr.readIntoStringCollector(wordSet); if (numWords == 0) { throw new IllegalStateException("Invalid "+languageName+" word list file: "+textFileSpec); } else { Sx.debug(2, "found %6d entries.\n", numWords); if (sDbg > 8) { for (String word : wordSet.getCollector() ) Sx.puts(word); } } return wordSet; } static void compareWordListFiles(String wordListFileA, String wordListFileB) { HashSet<String> wordsA = TextFileReader.readFileIntoHashSet(wordListFileA); HashSet<String> wordsB = TextFileReader.readFileIntoHashSet(wordListFileB); compareWordLists(wordsA, wordsB); } // TODO: make symmetric static void compareWordLists(Collection<String> wordsA, Collection<String> wordsB) { for (String wordB : wordsB) { if ( ! wordsA.contains(wordB)) Sx.puts(wordB); } } void compareWordListFilesWithSource(String wordListFileA, String wordListFileB) { HashSet<String> wordsA = TextFileReader.readFileIntoHashSet(wordListFileA); HashSet<String> wordsB = TextFileReader.readFileIntoHashSet(wordListFileB); compareWordLists(wordsA, wordsB, getSourceWordSet().getCollector()); } // TODO: make symmetric static void compareWordLists(Collection<String> wordsA, Collection<String> wordsB, Collection<String> wordsC) { for (String wordB : wordsB) { if ( ! wordsA.contains(wordB) && ! wordsC.contains(wordB)) Sx.puts(wordB); } } public static void main(String[] args) { DictionaryRawFileParserEnEs.unit_test(2); } }
sprax/java
aligns/Lexicon.java
Java
gpl-3.0
9,573
/* canvas.lineWidth=int; canvas.rect() canvas.fillRect() window.onorientationchange */ var position=[0,0,0,0];//---位置信息 //-------------------------------------------功能绑定区 canvas_View.addEventListener('touchstart',function(){//---把开始触摸点定为起点 if(config.type=='pen'){ drawTable.getStarPosition(2); } else if(config.type=='rect_new'||config.type=='coordinate'){ drawTable.getStarPosition(0); rect_box.style.display='block'; rect_box.style.border=canvas.lineWidth+'px '+drawTable.colorOpacity(config.color,config.opacity)+' solid'; } }); canvas_View.addEventListener('click',function(){//---画点 if(config.type!='pen')return; var x=event.pageX;//--click主要是不与划线时的位置混淆 var y=event.pageY; if(config.dot[2]==0){//--没有记录时添加一个记录 config.dot[0]=x; config.dot[1]=y; } config.dot[2]+=1; drawTable.dot(x,y);//--其实是画圆 if(config.dot[2]==2){ config.dot[2]=0;//--重置 drawTable.matchDot(x,y);//--连线开始 } }); canvas_View.addEventListener('touchmove',function(){//---更新位置信息 if(config.type=='pen'){ position[0]=position[2]; position[1]=position[3]; drawTable.getPosition(); drawTable.pen(); } else if(config.type=='rect_new'||config.type=='coordinate'){ drawTable.getPosition(); drawTable.rect_new(); if(config.type=='coordinate'){ rect_box.style.borderTop='none'; rect_box.style.borderRight='none'; } } event.preventDefault();//---阻止默认事件 }); canvas_View.addEventListener('touchend',function(){//----写入结束,保存入栈 if(config.type=='rect_new'||config.type=='coordinate'){ drawTable.getPosition(); drawTable.rect_new(); if(config.type=='coordinate'){ drawTable.coordinate(); } else drawTable.rect(); rect_box.style.cssText='display:none;left:0;top:0;width0;height:0;'; } drawTable.createImg(); }); color_View.addEventListener('touchstart',function(){//----指定坐标,获取颜色 position[2]=event.touches[0].pageX; position[3]=event.touches[0].pageY; drawTable.getColor(); }); color_View.addEventListener('touchmove',function(){//---获取移动坐标,获取颜色 drawTable.getPosition(); drawTable.getColor(); event.preventDefault(); }); lineW.addEventListener('click',function(){//---划线粗细显示选项 span_layout(); range.value=range.nextElementSibling.innerText=canvas.lineWidth; range.max=config.lineWidth[1];//--设置最大值 config.rangeType='lineWidth'; }); line.addEventListener('click',function(){//---默认模式 config.type='pen'; }); rect.addEventListener('click',function(){//---矩形模式 config.type='rect_new'; }); clear.addEventListener('click',function(){//---清空 drawTable.clear(); }); cure.addEventListener('click',function(){//----回复 drawTable.cure(); }); download.addEventListener('click',function(){//----下载【pc】 drawTable.download(); }); opacity.addEventListener('click',function(){ span_layout(); range.max=100;//--设置最大值 range.value=(range.nextElementSibling.innerText=config.opacity)*100;//init config.rangeType='opacity'; }); coordinate.addEventListener('click',function(){ ul_coordinate.style.display=ul_coordinate.style.display!='block'?'block':'none'; }); ul_coordinate.getElementsByTagName('li')[0].addEventListener('click',function(){ mathFunction.style.display='block'; }); calculate.addEventListener('click',function(){//--进行计算 drawTable.coordinate(); drawTable.mathFunction(equation.value); drawTable.createImg();//--可恢复 }); close_equation.addEventListener('click',function(){//--关闭窗口 mathFunction.style.display='none'; }); ul_coordinate.getElementsByTagName('li')[1].addEventListener('click',function(){ config.type='coordinate'; }); character.addEventListener('click',function(){//--弹出字体写入框 if(rect_box.style.display!='block'){//--显示 rect_box.innerHTML="<div id='sureButton'></div><input placeholder='text' type='text' style='width:100px'>"; rect_box.style.cssText='width:120px;display:block;background:rgba(240,240,240,0.7);padding:30px;left:100px;top:100px;'; } else{//--关闭并还原rect_box rect_box.innerHTML=''; rect_box.style.cssText='display:none;left:0;top:0;width:0;height:0;'; rangeBox.style.display='none'; return; } var inputText=rect_box.getElementsByTagName('input')[0]; var sureButton=document.getElementById('sureButton'); inputText.style.cssText="font-size:"+config.fontSize+"px;width:120px;background:rgba(255,255,255,.3);border:none;"; inputText.focus(); inputText.addEventListener('click',function(){ event.cancelBubble=true; }) //--rect_box里面再加入一层元素 sureButton.addEventListener('click',function(){//--确定 event.cancelBubble=true; var x=rect_box.offsetLeft+30; var y=rect_box.offsetTop+sureButton.clientHeight+30+inputText.clientHeight; drawTable.fillText(inputText.value,x,y); }); rect_box.addEventListener('click',function(){//--弹出字体大小选择框 span_layout(); range.nextElementSibling.innerText=(range.value=config.fontSize)+'px'; range.max=config.maxFontSize//--设置最大值 config.rangeType='font'; }); rect_box.addEventListener('touchstart',function(){ drawTable.getStarPosition(2); }); rect_box.addEventListener('touchmove',function(){event.preventDefault(); position[0]=position[2]; position[1]=position[3]; drawTable.getPosition(); drawTable.move(rect_box); }); rect_box.addEventListener('touchend',function(){ drawTable.getStarPosition[2]; }); }); rangeBox_drag.addEventListener('click',function(){ rangeBox.style.display='none'; }); rangeBox_drag.addEventListener('touchstart',function(){ drawTable.getStarPosition(2); }); rangeBox_drag.addEventListener('touchmove',function(){event.preventDefault(); position[0]=position[2]; position[1]=position[3]; drawTable.getPosition(); drawTable.move(rangeBox); }); range.addEventListener('touchmove',function(){ if(config.rangeType=='opacity'){ range.nextElementSibling.innerText=range.value/100; }else if(config.rangeType=='font'){ range.nextElementSibling.innerText=rect_box.getElementsByTagName('input')[0].style.fontSize=range.value+'px'; } else{ range.nextElementSibling.innerText=range.value; } }); range.addEventListener('touchend',function(){ switch(config.rangeType){ case 'lineWidth':canvas.lineWidth=range.value;;break; case 'opacity':config.opacity=range.value/100;break; case 'font':config.fontSize=range.value;break; } }); //----------------------------------------------------------------- var operate = function(){//----操作函数集合 canvas = canvas_View.getContext('2d');//---init canvas_tmp = canvas_tmp_View.getContext('2d');//---init var color_c = color_View.getContext('2d'); var linear = color_c.createLinearGradient(0,0,config.size[0],0); linear.addColorStop(0, 'rgb(255,0,0)'); //红 linear.addColorStop(0.5, 'rgb(0,255,0)');//绿 linear.addColorStop(1, 'rgb(0,0,255)'); //蓝 color_c.fillStyle=linear; color_c.fillRect(0,0,config.size[0],40); this.colorOpacity=function(color,opacity){ var start=color.lastIndexOf(','); var end=color.lastIndexOf(')'); var res=color.substr(0,start+1)+opacity+color.substr(end); return res; } this.pen=function(x1,y1,x2,y2){//----划线 var X1=x1||position[0],Y1=y1||position[1],X2=x2||position[2],Y2=y2||position[3]; canvas.beginPath();//--上行为缺省值 canvas.moveTo(X1,Y1); canvas.lineTo(X2,Y2); canvas.strokeStyle=drawTable.colorOpacity(config.color,config.opacity); canvas.closePath(); canvas.stroke(); } this.rect_new=function(){//--矩形div模拟 rect_box.style.left=position[0]+'px'; rect_box.style.top=position[1]+'px'; rect_box.style.width=position[2]-position[0]-1+'px'; rect_box.style.height=position[3]-position[1]-1+'px'; } this.rect=function(){//----写入矩形 if(position[0]==position[2])return; canvas.beginPath(); canvas.strokeStyle=drawTable.colorOpacity(config.color,config.opacity); canvas.rect(position[0]+canvas.lineWidth/2,position[1]+canvas.lineWidth/2,position[2]-position[0]+canvas.lineWidth,position[3]-position[1]+canvas.lineWidth); //---div元素的border和画矩形的边框不是同一个机制 canvas.closePath(); canvas.stroke(); } this.dot=function(x,y,type){//--点的生成 用于连线 canvas.beginPath(); var type=type||'stroke'; if(type=='fill'){ canvas.fillStyle=drawTable.colorOpacity(config.color,config.opacity); canvas.arc(x,y,config.radius,0,Math.PI*2,false); } if(type=='stroke'){ canvas.strokeStyle=config.color; canvas.arc(x,y,config.radius,0,Math.PI*2,false); canvas.stroke(); } canvas.closePath(); } this.matchDot=function(x,y){//--连接两个点 canvas.beginPath(); canvas.strokeStyle=drawTable.colorOpacity(config.color,config.opacity); canvas.moveTo(config.dot[0],config.dot[1]); canvas.lineTo(x,y); canvas.closePath(); canvas.stroke(); } this.coordinate=function(){//--建立坐标 //---在进行画矩形时,只保留邻边就可以自定义建立起简易坐标 drawTable.pen(position[0],position[3],position[0],position[1]); drawTable.pen(position[0],position[3],position[2],position[3]); config.basePoint[0]=position[0];//--保存坐标轴基本点 config.basePoint[1]=position[3]; config.basePoint[2]=position[0]; config.basePoint[3]=position[1]; config.basePoint[4]=position[2]; config.basePoint[5]=position[3]; } this.mathFunction=function(equation){//---数学函数y=2*x var equation=equation||"0.5*x";var y; //--标准转换式 y=k*x --> y=-k*(x-config.basePoint[0])+config.basePoint[1] //--将坐标轴的方向进行转换 //--存在转换缺陷,x*x时图形完全不形象,需要缩短x,y轴 equation=equation.replace('x','(x-'+config.basePoint[0]+')');//--x值进行替换 equation='-1*('+equation+')+'+config.basePoint[1]; for(var x=config.basePoint[0];x<config.basePoint[4];x+=0.01){//--0.01为精度 eval('y='+equation);//---y=k*x drawTable.pen(x,y,++x,eval('y='+equation));//--传入两个坐标 } } this.move=function(obj){ var obj_left=rPx(getComputedStyle(obj)['left'],'left'); var obj_top=rPx(getComputedStyle(obj)['top'],'top'); obj.style.left=obj_left+position[2]-position[0]+'px'; obj.style.top=obj_top+position[3]-position[1]+'px'; } this.fillText=function(text,x,y,type){//---生成文字 var x=x||10,y=y||10,type=type||'fill'; canvas.font='normal '+config.fontSize+'px 微软雅黑'; if(config.fontSize<16){ var compatibility=0; }else{ var compatibility=config.fontSize/3; } if(type='fill'){ canvas.fillStyle=drawTable.colorOpacity(config.color,config.opacity); canvas.fillText(text,x,y-compatibility); }else{ canvas.strokeText(text,x,y); } drawTable.createImg(); } this.getColor=function(){//---获取点击处的颜色[rgba模式,a/255为可用a] var offsetT=color_View.offsetTop; var color=color_c.getImageData(position[2],position[3]-config.size[1]-3,1,1).data; cure.style.background="rgba("+color[0]+','+color[1]+','+color[2]+','+color[3]/255+")"; config.color="rgba("+color[0]+','+color[1]+','+color[2]+','+color[3]/255+")"; } this.getStarPosition=function(offset){ position[offset]=event.touches[0].pageX; position[offset+1]=event.touches[0].pageY; } this.getPosition=function(){ position[2]=event.changedTouches[0].pageX; position[3]=event.changedTouches[0].pageY; } this.clear=function(val){//---清除最后操作 if(val==0){ canvas.clearRect(0,0,config.size[0],config.size[1]); } else if(true){//----清除所有操作和记录 config.stage='null'; config.stage=[]; canvas.clearRect(0,0,config.size[0],config.size[1]); config.pointer=-1; drawTable.createImg(); } } this.cure=function(){//---回复上一步 if(config.pointer>=1){ config.dot[2]=0; config.img_tmp = new Image(); config.img_tmp.src=config.stage[config.pointer-1]; config.img_tmp.onload=function(){//---加载完成再清除不会出现闪烁 drawTable.clear(0);//---清空,不改变记录 canvas.drawImage(config.img_tmp,0,0);//---加载上一步 } config.pointer--;//--指针减一 } } this.createImg=function(){//---canvas生成base64码 //---64码保存在数组中,指针指向当前画面 if(config.pointer>=config.cure_len-1){//---超出长度就清除最前面的操作,再最后追加最新操作 for(var i=0;i<config.cure_len-1;i++){ config.stage[i]=config.stage[i+1]; } } if(config.pointer<config.cure_len-1){//--指针后移 config.pointer++; } config.stage[config.pointer]=canvas_View.toDataURL(); } this.download=function(){//-----下载图片 var a=document.createElement('a'); a.href=config.stage[config.pointer].replace('png','octet-stream'); a.download="save.png"; a.click(); } } {//---所有初始化操作 drawTable = new operate();//---初始化功能函数 drawTable.createImg();//---第一个图片保存 canvas.lineWidth=3; canvas.font='normal '+config.fontSize+'px 微软雅黑'; }
DFFXT/DFFXT.github.io
canvas/css_js/main.js
JavaScript
gpl-3.0
13,453
from nltk.chat.util import Chat, reflections pairs = [ [ r"My name is (.*)", ['hello %1', '%1 mabuhay ka'], ], [ r'hi', ['hello', 'kamusta', 'mabuhay',], ], [ r'(.*) (hungry|sleepy|groot)', [ "%1 %2" ] ], [ r'(.*)(mahal|love)(.*)', [ "https://goo.gl/ndTZVq", "I always thought Love was a static class until you made an instance of it.", "I love user interfaces it's because that's where U and I are always together.", ], ], [ r'(.*)(relationship)(.*)', [ "Mabuti pa sa database may relationship. Eh tayo, wala.", ], ], [ r'(meron|mayron|ano|does|is there|what) (.*) (forever)(.*)', [ "Loading...", "None", "while True: pass", ], ], [ r'(.*)', # default response if no patterns from above is found [ "http://lmgtfy.com/?q=%1", "Sorry I don't know what `%1` is?", ], ], ] def hugot_bot(): print("Hi what's your name?") chat = Chat(pairs, reflections) chat.converse() if __name__ == "__main__": hugot_bot()
davidam/python-examples
nlp/nltk/hugotbot.py
Python
gpl-3.0
1,251
package it.unisannio.catman.screens.inbox.client; import java.util.List; import it.unisannio.catman.common.client.AbstractQuery; import it.unisannio.catman.common.client.App; import it.unisannio.catman.common.client.DataStore; import it.unisannio.catman.common.client.Query; import it.unisannio.catman.common.client.QueryDataProvider; import it.unisannio.catman.common.client.cell.InteractiveCellAdapter; import it.unisannio.catman.common.client.ui.DataList; import it.unisannio.catman.domain.workflow.client.CustomerProxy; import com.github.gwtbootstrap.client.ui.Button; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import com.google.web.bindery.requestfactory.shared.Request; public class MasterView extends Composite { private static MasterViewUiBinder uiBinder = GWT.create(MasterViewUiBinder.class); interface MasterViewUiBinder extends UiBinder<Widget, MasterView> { } @UiField Button makeNew; @UiField DataList<CustomerProxy> dataList; private Inbox.Master activity; public MasterView(Inbox.Master activity) { initWidget(uiBinder.createAndBindUi(this)); this.activity = activity; dataList.setPageSize(20); dataList.setCellAdapter(new InteractiveCellAdapter<CustomerProxy>() { @Override public SafeHtml getNorth(CustomerProxy object) { return new SafeHtmlBuilder().appendEscaped(object.getName()).toSafeHtml(); } }); final DataStore store = App.getInstance().getDataStore(); Query<CustomerProxy> query = new AbstractQuery<CustomerProxy>() { @Override public Request<List<CustomerProxy>> list(int start, int length) { return store.customers().listAll(start, length); } @Override public Request<Integer> count() { return store.customers().count(); } }; dataList.setDataProvider(new QueryDataProvider<CustomerProxy>(query)); } @UiHandler("makeNew") void handleNew(ClickEvent e) { activity.openNewDialog(); } @UiHandler("dataList") void handleCellClick(ClickEvent e) { Window.alert("Hello "+ ((CustomerProxy) e.getSource()).getName()); } }
danilox6/catman
src/it/unisannio/catman/screens/inbox/client/MasterView.java
Java
gpl-3.0
2,489
/* * Copyright (C) 2010 The Sipdroid Open Source Project * * This file is part of Sipdroid (http://www.sipdroid.org) * * Sipdroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This source code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this source code; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.sipdroid.codecs; import java.util.HashMap; import java.util.Vector; import com.sipgate.R; import com.sipgate.sipua.ui.Receiver; import com.sipgate.sipua.ui.Settings; import org.zoolu.sdp.MediaField; import org.zoolu.sdp.SessionDescriptor; import org.zoolu.sdp.AttributeField; import android.content.Context; import android.content.res.Resources; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.ListPreference; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView.AdapterContextMenuInfo; public class Codecs { private static final Vector<Codec> codecs = new Vector<Codec>() {/** * */ private static final long serialVersionUID = 5423816327968842601L; { add(new G722()); add(new SILK24()); add(new SILK16()); add(new SILK8()); add(new alaw()); add(new ulaw()); add(new Speex()); add(new GSM()); add(new BV16()); }}; private static final HashMap<Integer, Codec> codecsNumbers; private static final HashMap<String, Codec> codecsNames; static { final int size = codecs.size(); codecsNumbers = new HashMap<Integer, Codec>(size); codecsNames = new HashMap<String, Codec>(size); for (Codec c : codecs) { codecsNames.put(c.name(), c); codecsNumbers.put(c.number(), c); } SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext); String prefs = sp.getString(Settings.PREF_CODECS, Settings.DEFAULT_CODECS); if (prefs == null) { String v = ""; SharedPreferences.Editor e = sp.edit(); for (Codec c : codecs) v = v + c.number() + " "; e.putString(Settings.PREF_CODECS, v); e.commit(); } else { String[] vals = prefs.split(" "); for (String v: vals) { try { int i = Integer.parseInt(v); Codec c = codecsNumbers.get(i); /* moves the codec to the end * of the list so we end up * with the new codecs (if * any) at the top and the * remaining ones ordered * according to the user */ codecs.remove(c); codecs.add(c); } catch (Exception e) { // do nothing (expecting // NumberFormatException and // indexnot found } } } } public static Codec get(int key) { return codecsNumbers.get(key); } public static Codec getName(String name) { return codecsNames.get(name); } public static void check() { HashMap<String, String> old = new HashMap<String, String>(codecs.size()); for(Codec c : codecs) { old.put(c.name(), c.getValue()); if (!c.isLoaded()) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext); SharedPreferences.Editor e = sp.edit(); e.putString(c.key(), "never"); e.commit(); } } for(Codec c : codecs) if (!old.get(c.name()).equals("never")) { c.init(); if (c.isLoaded()) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext); SharedPreferences.Editor e = sp.edit(); e.putString(c.key(), old.get(c.name())); e.commit(); c.init(); } else c.fail(); } } private static void addPreferences(PreferenceScreen ps) { Context cx = ps.getContext(); Resources r = cx.getResources(); ps.setOrderingAsAdded(true); for(Codec c : codecs) { ListPreference l = new ListPreference(cx); l.setEntries(r.getStringArray(R.array.compression_display_values)); l.setEntryValues(r.getStringArray(R.array.compression_values)); l.setKey(c.key()); l.setPersistent(true); l.setEnabled(!c.isFailed()); c.setListPreference(l); if (c.number() == 9) if (ps.getSharedPreferences().getString(Settings.PREF_SERVER, Settings.DEFAULT_SERVER).equals(Settings.DEFAULT_SERVER)) l.setSummary(l.getEntry()+" ("+r.getString(R.string.settings_improve2)+")"); else l.setSummary(l.getEntry()+" ("+r.getString(R.string.settings_hdvoice)+")"); else l.setSummary(l.getEntry()); l.setTitle(c.getTitle()); ps.addPreference(l); } } public static int[] getCodecs() { Vector<Integer> v = new Vector<Integer>(codecs.size()); for (Codec c : codecs) { if (!c.isValid()) continue; v.add(c.number()); } int i[] = new int[v.size()]; for (int j = 0; j < i.length; j++) i[j] = v.elementAt(j); return i; } public static class Map { public int number; public Codec codec; Vector<Integer> numbers; Vector<Codec> codecs; Map(int n, Codec c, Vector<Integer> ns, Vector<Codec> cs) { number = n; codec = c; numbers = ns; codecs = cs; } public boolean change(int n) { int i = numbers.indexOf(n); if (i >= 0 && codecs.elementAt(i) != null) { codec.close(); number = n; codec = codecs.elementAt(i); return true; } return false; } public String toString() { return "Codecs.Map { " + number + ": " + codec + "}"; } }; public static Map getCodec(SessionDescriptor offers) { MediaField m = offers.getMediaDescriptor("audio").getMedia(); if (m==null) return null; String proto = m.getTransport(); //see http://tools.ietf.org/html/rfc4566#page-22, paragraph 5.14, <fmt> description if ( proto.equals("RTP/AVP") || proto.equals("RTP/SAVP") ) { Vector<String> formats = m.getFormatList(); Vector<String> names = new Vector<String>(formats.size()); Vector<Integer> numbers = new Vector<Integer>(formats.size()); Vector<Codec> codecmap = new Vector<Codec>(formats.size()); //add all avail formats with empty names for (String fmt : formats) { try { int number = Integer.parseInt(fmt); numbers.add(number); names.add(""); codecmap.add(null); } catch (NumberFormatException e) { // continue ... remote sent bogus rtp setting } }; //if we have attrs for format -> set name Vector<AttributeField> attrs = offers.getMediaDescriptor("audio").getAttributes("rtpmap"); for (AttributeField a : attrs) { String s = a.getValue(); // skip over "rtpmap:" s = s.substring(7, s.indexOf("/")); int i = s.indexOf(" "); try { String name = s.substring(i + 1); int number = Integer.parseInt(s.substring(0, i)); int index = numbers.indexOf(number); if (index >=0) names.set(index, name.toLowerCase()); } catch (NumberFormatException e) { // continue ... remote sent bogus rtp setting } } Codec codec = null; int index = formats.size() + 1; for (Codec c : codecs) { if (!c.isValid()) continue; //search current codec in offers by name int i = names.indexOf(c.userName().toLowerCase()); if (i >= 0) { codecmap.set(i, c); if ( (codec==null) || (i < index) ) { codec = c; index = i; continue; } } //search current codec in offers by number i = numbers.indexOf(c.number()); if (i >= 0) { if ( names.elementAt(i).equals("")) { codecmap.set(i, c); if ( (codec==null) || (i < index) ) { //fmt number has no attr with name codec = c; index = i; continue; } } } } if (codec!=null) return new Map(numbers.elementAt(index), codec, numbers, codecmap); else // no codec found ... we can't talk return null; } else /*formats of other protocols not supported yet*/ return null; } public static class CodecSettings extends PreferenceActivity { private static final int MENU_UP = 0; private static final int MENU_DOWN = 1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.codec_settings); // for long-press gesture on a profile preference registerForContextMenu(getListView()); addPreferences(getPreferenceScreen()); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle(R.string.codecs_move); menu.add(Menu.NONE, MENU_UP, 0, R.string.codecs_move_up); menu.add(Menu.NONE, MENU_DOWN, 0, R.string.codecs_move_down); } @Override public boolean onContextItemSelected(MenuItem item) { int posn = (int)((AdapterContextMenuInfo)item.getMenuInfo()).position; Codec c = codecs.elementAt(posn); if (item.getItemId() == MENU_UP) { if (posn == 0) return super.onContextItemSelected(item); Codec tmp = codecs.elementAt(posn - 1); codecs.set(posn - 1, c); codecs.set(posn, tmp); } else if (item.getItemId() == MENU_DOWN) { if (posn == codecs.size() - 1) return super.onContextItemSelected(item); Codec tmp = codecs.elementAt(posn + 1); codecs.set(posn + 1, c); codecs.set(posn, tmp); } PreferenceScreen ps = getPreferenceScreen(); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Receiver.mContext); String v = ""; SharedPreferences.Editor e = sp.edit(); for (Codec d : codecs) v = v + d.number() + " "; e.putString(Settings.PREF_CODECS, v); e.commit(); ps.removeAll(); addPreferences(ps); return super.onContextItemSelected(item); } @Override public boolean onPreferenceTreeClick(PreferenceScreen ps, Preference p) { ListPreference l = (ListPreference) p; for (Codec c : codecs) if (c.key().equals(l.getKey())) { c.init(); if (!c.isLoaded()) { l.setValue("never"); c.fail(); l.setEnabled(false); l.setSummary(l.getEntry()); if (l.getDialog() != null) l.getDialog().dismiss(); } } return super.onPreferenceTreeClick(ps,p); } @Override public void onDestroy() { super.onDestroy(); unregisterForContextMenu(getListView()); } } }
sipgate/sipgate-for-android
src/org/sipdroid/codecs/Codecs.java
Java
gpl-3.0
10,906
from urlparse import urlparse import sys import socket import os import re class HttpClient(object): def __init__(self,proxy=None,logfile='headers.log'): self.proxy = proxy self.LOGFILE = logfile self.parsed_url = None # Instance of class urlparse self.http_version = "HTTP/1.1" self.buffer = 4096 self.separador = '\r\n\r\n' # Separador de header y content de la respuesta HTTP self.download_file = 'download.part' self._header_detected = False self._url = None try: # Si quedo una descarga trunca, la limpiamos with open(self.download_file): os.remove(self.download_file) except IOError: pass def _get_host(self,use_proxy=False): """Devuelve el hostname de la url de forma inteligente(?)""" if use_proxy: return urlparse(self.proxy).hostname else: if self.parsed_url is None: return 'localhost' else: if self.parsed_url.hostname in (None,''): return 'localhost' else: return self.parsed_url.hostname def _get_port(self,use_proxy=False): """Devuelve el puerto de la url de forma inteligente(?)""" if use_proxy: return urlparse(self.proxy).port else: if self.parsed_url is None: return 80 else: if self.parsed_url.port in (None,''): return 80 else: return self.parsed_url.port def _get_path(self): """Devuelve el path de la url de forma inteligente(?)""" if self.proxy is not None: return self.parsed_url.scheme + '://' + self.parsed_url.netloc + self.parsed_url.path else: if self.parsed_url is None: return '/' else: if self.parsed_url.path in (None,''): return '/' else: return self.parsed_url.path def retrieve(self,url=None,method="GET"): """Punto de acceso del cliente, crea la peticion, la envia al servidor, y guarda la respuesta. Maneja redireccion 301 (movido permanente).""" if url: self._retrieve(url=url,method=method) #~ Soporta redireccion infinita, lo cual es un problema. Deberia tener un contador. Maximo? while self.headers["status"] == "301": self._retrieve(url=self.headers["Location"],method=method) else: raise Exception("Expect parameter url") def _retrieve(self,url=None,method="GET"): """Metodo de alto nivel que recupera la url solicitada""" if url: self._url = url self.parsed_url = urlparse(url) if self.parsed_url.scheme is '': raise Exception("Formato de url incorrecto. Formato esperado: (http|ftp|https)://url[:port][/path_to_resource]") self.method = method # GET o HEAD self._conect() # self.s socket created self._build_request() # self.request string created self._send_request() # Realiza la peticion y gestiona la descarga del recurso else: raise Exception("Expect parameter url") def _conect(self): """Crea el socket con el servidor""" self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: if self.proxy: self.s.connect((self._get_host(use_proxy=True) , self._get_port(use_proxy=True))) else: self.s.connect((self._get_host() , self._get_port())) except socket.error, msg: sys.stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(2) def _build_request(self): """Construye el str de request para el servidor""" self.request = "%(method)s %(path)s %(http_version)s\r\n" self.request += "Host: %(host)s\r\n" self.request += "User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0) Gecko/20100101 Firefox/23.0\r\n" self.request += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" self.request += "Accept-Language: es-ar,es;q=0.8,en-us;q=0.5,en;q=0.3\r\n" #~ self.request += "Accept-Encoding: gzip, deflate\r\n" # No soporta encoding en esta version self.request += "Connection: keep-alive\r\n\r\n" self.request = self.request % { 'method':self.method, \ 'path':self._get_path(), \ 'http_version':self.http_version, \ 'host':self._get_host()} def _send_request(self): """Envia el request y recibe la respuesta""" self.s.sendall(self.request) response = self.s.recv(self.buffer) self.data = "" self._header_detected = False while len(response): self.data += response # Se controla que detecte solo la primera vez las cabeceras if not self._header_detected: self._header_detect() if not self.method == "HEAD": self._sync_data() if self.headers.has_key("status"): if self.headers["status"] == "301": break response = self.s.recv(self.buffer) if not self.method == "HEAD" and not self.headers["status"] == "301": self._sync_data() self._save_file() # Guardar el archivo self._log_headers() # Logs a un header def _sync_data(self): """ Este metodo se encarga de descargar la memoria si el archivo que se descarga es demasiado grande""" if len(self.data) > 100000: f = open(self.download_file,'a') f.write(self.data) self.data = "" f.close() def _header_detect(self): """Metodo que detecta si en la descarga se encuentra el header. En caso afirmativo, lo carga en la instancia y lo elimina del stream de descarga.""" headers = self.data.split(self.separador) # Si len es mayor a 1, el header ya esta completo if len(headers) > 1: self.data = self.separador.join(headers[1:]) # Arma la informacion de descarga sin el header self.str_headers = headers[0] self.headers = dict(re.findall(r"(?P<name>.*?): (?P<value>.*?)\r\n", self.str_headers)) # Arma un dic con los headers # Primer linea del header HTTP/1.1 self.headers["http"] = headers[0].split('\r\n')[0] self.headers["http_version"] = self.headers["http"].split(' ')[0] self.headers["status"] = self.headers["http"].split(' ')[1] self.headers["status_message"] = ' '.join(self.headers["http"].split(' ')[2:]) self._header_detected = True def _log_headers(self): """Descarga las cabeceras de response a un archivo de log""" if self.LOGFILE is not None: f = open(self.LOGFILE,'a') f.write("== HEADER: Response from %s\n" % self._url) f.write("== Method: %s\n" % self.method) f.write("%s\n" % self.str_headers) f.close() def _save_file(self): """Guarda el archivo a disco, teniendo en cuenta si la descarga ya lo hizo o no""" file_in_disk = self._saved_file() filename = self._filename() if file_in_disk: os.rename(self.download_file, filename) else: f = open(filename,'w') f.write(self.data) f.close() def _content_encoding(self): """Soporte para encoding de contenido con gzip. No soportado""" if self.headers.has_key('Content-Encoding'): return self.headers['Content-Encoding'] else: return None def _file_type(self): """Retorna la extension segun el tipo de archivo""" if self.headers.has_key('Content-Type'): return '.' + self.headers['Content-Type'].split('; ')[0].split('/')[1] else: return '.html' # Que habria que devolver por default? vacio? def _filename(self): """Retorna el mejor nombre de archivo en funcion de la informacion disponible""" if self.headers["status"] == "404": return "error_page_404.html" else: extension = self._file_type() if self.proxy is not None: resource_name = self._get_path().split('/') if resource_name[-1] is not '': return resource_name[-1] + extension else: return resource_name[-2] + extension else: if self._get_path() in ('/', ''): return self._get_host() + extension else: return self._get_path().split('/')[-1] def _saved_file(self): """Controla si durante la descarga el archivo fue bajado temporalmente a disco""" try: open(self.download_file) except: return False return True
tomasdelvechio/py-net-dev
Protocolos/3 - http client/http_client_object.py
Python
gpl-3.0
9,464
/** * 支持ArcGIS Online地图 */ max.Layer.AGSTileLayer = function (serviceUrl) { this.serviceUrl = serviceUrl; this._imageList = []; this.cors=false; this.fullExtent = new max.Extent({ xmin:-20037508.3427892, ymin:-20037508.3427892, xmax:20037508.3427892, ymax:20037508.3427892 }); this.originPoint = { x:-20037508.3427892, y:20037508.3427892 } this.picWidth = 256; this.picHeight = 256; this.wkid = 102100; this.resolutions = [1591657527.591555,78271.51696402031, 39135.75848201016, 19567.87924100508, 9783.939620502539, 4891.96981025127, 2445.984905125635, 1222.992452562817, 611.4962262814087, 305.7481131407043, 152.8740565703522, 76.43702828517608, 38.21851414258804, 19.10925707129402, 9.554628535647009]; this.init(); } max.Layer.AGSTileLayer.prototype = new max.Layer.TileLayer(); max.Layer.AGSTileLayer.prototype._updateImageList = function (rule) { this._imageList = []; for (var i = rule.lmin; i <= rule.lmax; ++i) { for (var j = rule.dmin; j <= rule.dmax; ++j) { if(this.serviceUrl[this.serviceUrl.length-1]!=="/"){ this.serviceUrl+="/"; } var url = this.serviceUrl+"tile/"+(rule.z-1)+"/"+j+"/"+i; var xmin = i * this.picWidth * rule.resolution + this.originPoint.x; var ymax = this.originPoint.y-j * this.picHeight * rule.resolution; for (var k in this._imageList) { var _image = this._imageList[k]; if (_image.url === url) { break; } } var image = new max.Layer._TitleImage(url, this, i, j, rule.z, xmin, ymax); this._imageList.push(image); } } return this._imageList; }
Maxgis/maxCanvasMap
src/Layer/AGSTileLayer.js
JavaScript
gpl-3.0
1,811
/* * Copyright 2010-16 Fraunhofer ISE * * This file is part of jMBus. * For more information visit http://www.openmuc.org * * jMBus is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * jMBus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with jMBus. If not, see <http://www.gnu.org/licenses/>. * */ package org.openmuc.jmbus; import java.io.DataInputStream; import java.io.DataOutputStream; import java.util.HashMap; abstract class AbstractWMBusSap implements WMBusSap { final static int BUFFER_LENGTH = 1000; final byte[] outputBuffer = new byte[BUFFER_LENGTH]; final byte[] inputBuffer = new byte[BUFFER_LENGTH]; final WMBusListener listener; final WMBusMode mode; SerialTransceiver serialTransceiver; final HashMap<String, byte[]> keyMap = new HashMap<String, byte[]>(); volatile boolean closed = true; DataOutputStream os; DataInputStream is; AbstractWMBusSap(WMBusMode mode, WMBusListener listener) { this.listener = listener; this.mode = mode; } @Override public void close() { if (closed) { return; } closed = true; serialTransceiver.close(); } @Override public void setKey(SecondaryAddress address, byte[] key) { keyMap.put(HexConverter.toShortHexString(address.asByteArray()), key); } @Override public void removeKey(SecondaryAddress address) { keyMap.remove(HexConverter.toShortHexString(address.asByteArray())); } }
pokerazor/jmbus
src/main/java/org/openmuc/jmbus/AbstractWMBusSap.java
Java
gpl-3.0
1,961
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2016-2018 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import yaml from testtools.matchers import Equals import snapcraft.internal from tests import unit class StageStateBaseTestCase(unit.TestCase): def setUp(self): super().setUp() class Project: pass self.project = Project() self.files = {"foo"} self.directories = {"bar"} self.part_properties = { "filesets": {"qux": "quux"}, "override-stage": "touch override-stage", "stage": ["baz"], } self.state = snapcraft.internal.states.StageState( self.files, self.directories, self.part_properties, self.project ) class StateStageTestCase(StageStateBaseTestCase): def test_yaml_conversion(self): state_from_yaml = yaml.load(yaml.dump(self.state)) self.assertThat(state_from_yaml, Equals(self.state)) def test_comparison(self): other = snapcraft.internal.states.StageState( self.files, self.directories, self.part_properties, self.project ) self.assertTrue(self.state == other, "Expected states to be identical") def test_properties_of_interest(self): properties = self.state.properties_of_interest(self.part_properties) self.assertThat(len(properties), Equals(3)) self.assertThat(properties["filesets"], Equals({"qux": "quux"})) self.assertThat(properties["override-stage"], Equals("touch override-stage")) self.assertThat(properties["stage"], Equals(["baz"])) def test_project_options_of_interest(self): self.assertFalse(self.state.project_options_of_interest(self.project)) class StageStateNotEqualTestCase(StageStateBaseTestCase): scenarios = [ ("no files", dict(other_property="files", other_value=set())), ("no directories", dict(other_property="directories", other_value=set())), ( "no part properties", dict(other_property="part_properties", other_value=None), ), ] def test_comparison_not_equal(self): setattr(self, self.other_property, self.other_value) other_state = snapcraft.internal.states.StageState( self.files, self.directories, self.part_properties, self.project ) self.assertFalse(self.state == other_state, "Expected states to be different")
cprov/snapcraft
tests/unit/states/test_stage.py
Python
gpl-3.0
3,005
/* * Pixel Dungeon * Copyright (C) 2012-2014 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.watabou.legacy.actors.mobs; import java.util.HashSet; import com.watabou.legacy.Badges; import com.watabou.legacy.Dungeon; import com.watabou.legacy.Statistics; import com.watabou.legacy.actors.Char; import com.watabou.legacy.actors.blobs.ToxicGas; import com.watabou.legacy.actors.buffs.Burning; import com.watabou.legacy.actors.buffs.Frost; import com.watabou.legacy.actors.buffs.Paralysis; import com.watabou.legacy.actors.buffs.Roots; import com.watabou.legacy.items.food.MysteryMeat; import com.watabou.legacy.levels.Level; import com.watabou.legacy.sprites.PiranhaSprite; import com.watabou.utils.Random; public class Piranha extends Mob { { name = "giant piranha"; spriteClass = PiranhaSprite.class; baseSpeed = 2f; EXP = 0; } public Piranha() { super(); HP = HT = 10 + Dungeon.depth * 5; defenseSkill = 10 + Dungeon.depth * 2; } @Override protected boolean act() { if (!Level.water[pos]) { die( null ); return true; } else { return super.act(); } } @Override public int damageRoll() { return Random.NormalIntRange( Dungeon.depth, 4 + Dungeon.depth * 2 ); } @Override public int attackSkill( Char target ) { return 20 + Dungeon.depth * 2; } @Override public int dr() { return Dungeon.depth; } @Override public void die( Object cause ) { Dungeon.level.drop( new MysteryMeat(), pos ).sprite.drop(); super.die( cause ); Statistics.piranhasKilled++; Badges.validatePiranhasKilled(); } @Override public boolean reset() { return true; } @Override protected boolean getCloser( int target ) { if (rooted) { return false; } int step = Dungeon.findPath( this, pos, target, Level.water, Level.fieldOfView ); if (step != -1) { move( step ); return true; } else { return false; } } @Override protected boolean getFurther( int target ) { int step = Dungeon.flee( this, pos, target, Level.water, Level.fieldOfView ); if (step != -1) { move( step ); return true; } else { return false; } } @Override public String description() { return "These carnivorous fish are not natural inhabitants of underground pools. " + "They were bred specifically to protect flooded treasure vaults."; } private static final HashSet<Class<?>> IMMUNITIES = new HashSet<Class<?>>(); static { IMMUNITIES.add( Burning.class ); IMMUNITIES.add( Paralysis.class ); IMMUNITIES.add( ToxicGas.class ); IMMUNITIES.add( Roots.class ); IMMUNITIES.add( Frost.class ); } @Override public HashSet<Class<?>> immunities() { return IMMUNITIES; } }
sloanr333/opd-legacy
src/com/watabou/legacy/actors/mobs/Piranha.java
Java
gpl-3.0
3,326
/** * Copyright (C) 2007-2011, Jens Lehmann * * This file is part of DL-Learner. * * DL-Learner is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * DL-Learner is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.dllearner.core; import java.text.DecimalFormat; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeSet; import org.dllearner.core.owl.Description; import org.dllearner.learningproblems.PosNegLPStandard; import org.dllearner.utilities.datastructures.DescriptionSubsumptionTree; import org.dllearner.utilities.owl.ConceptComparator; import org.dllearner.utilities.owl.ConceptTransformation; import org.dllearner.utilities.owl.EvaluatedDescriptionSet; import org.springframework.beans.factory.annotation.Autowired; /** * Abstract superclass of all class expression learning algorithm implementations. * Includes support for anytime learning algorithms and resumable * learning algorithms. Provides methods for filtering the best * descriptions found by the algorithm. As results of the algorithm, * you can either get only descriptions or evaluated descriptions. * Evaluated descriptions have information about accuracy and * example coverage associated with them. However, retrieving those * may require addition reasoner queries, because the learning * algorithms usually use but do not necessarily store this information. * * Changes (March/April 2011): Learning algorithms no longer have to use * this class, but it still serves as a prototypical template for class * expression learning algorithms. * * @author Jens Lehmann * */ public abstract class AbstractCELA extends AbstractComponent implements ClassExpressionLearningAlgorithm, StoppableLearningAlgorithm { protected EvaluatedDescriptionSet bestEvaluatedDescriptions = new EvaluatedDescriptionSet(AbstractCELA.MAX_NR_OF_RESULTS); protected DecimalFormat dfPercent = new DecimalFormat("0.00%"); protected ConceptComparator descriptionComparator = new ConceptComparator(); protected String baseURI; protected Map<String, String> prefixes; /** * The learning problem variable, which must be used by * all learning algorithm implementations. */ protected AbstractLearningProblem learningProblem; /** * The reasoning service variable, which must be used by * all learning algorithm implementations. */ protected AbstractReasonerComponent reasoner; /** * Default Constructor */ public AbstractCELA(){ } /** * Each learning algorithm gets a learning problem and * a reasoner as input. * @param learningProblem The learning problem to solve. * @param reasoningService The reasoner connecting to the * underlying knowledge base. */ public AbstractCELA(AbstractLearningProblem learningProblem, AbstractReasonerComponent reasoningService) { this.learningProblem = learningProblem; this.reasoner = reasoningService; baseURI = reasoner.getBaseURI(); prefixes = reasoner.getPrefixes(); } /** * Call this when you want to change the learning problem, but * leave everything else as is. Method can be used to apply * a configured algorithm to different learning problems. * Implementations, which do not only use the provided learning * algorithm variable, must make sure that a call to this method * indeed changes the learning problem. * @param learningProblem The new learning problem. */ public void changeLearningProblem(AbstractLearningProblem learningProblem) { this.learningProblem = learningProblem; } /** * Call this when you want to change the reasoning service, but * leave everything else as is. Method can be used to use * a configured algorithm with different reasoners. * Implementations, which do not only use the provided reasoning * service class variable, must make sure that a call to this method * indeed changes the reasoning service. * @param reasoningService The new reasoning service. */ public void changeReasonerComponent(AbstractReasonerComponent reasoningService) { this.reasoner = reasoningService; } /** * This is the maximum number of results, which the learning * algorithms are asked to store. (Note, that algorithms are not * required to store any results except the best one, so this limit * is used to limit the performance cost for those which * choose to store results.) */ public static final int MAX_NR_OF_RESULTS = 100; /** * Every algorithm must be able to return the score of the * best solution found. * * @return Best score. */ // @Deprecated // public abstract Score getSolutionScore(); /** * @see #getCurrentlyBestEvaluatedDescription() * @return The best class description found by the learning algorithm so far. */ public abstract Description getCurrentlyBestDescription(); /** * @see #getCurrentlyBestEvaluatedDescriptions() * @return The best class descriptions found by the learning algorithm so far. */ public List<Description> getCurrentlyBestDescriptions() { List<Description> ds = new LinkedList<Description>(); ds.add(getCurrentlyBestDescription()); return ds; } /** * @see #getCurrentlyBestEvaluatedDescriptions(int) * @param nrOfDescriptions Limit for the number or returned descriptions. * @return The best class descriptions found by the learning algorithm so far. */ public synchronized List<Description> getCurrentlyBestDescriptions(int nrOfDescriptions) { return getCurrentlyBestDescriptions(nrOfDescriptions, false); } /** * @see #getCurrentlyBestEvaluatedDescriptions(int,double,boolean) * @param nrOfDescriptions Limit for the number or returned descriptions. * @param filterNonMinimalDescriptions Remove non-minimal descriptions (e.g. those which can be shortened * to an equivalent concept) from the returned set. * @return The best class descriptions found by the learning algorithm so far. */ public synchronized List<Description> getCurrentlyBestDescriptions(int nrOfDescriptions, boolean filterNonMinimalDescriptions) { List<Description> currentlyBest = getCurrentlyBestDescriptions(); List<Description> returnList = new LinkedList<Description>(); for(Description ed : currentlyBest) { if(returnList.size() >= nrOfDescriptions) { return returnList; } if(!filterNonMinimalDescriptions || ConceptTransformation.isDescriptionMinimal(ed)) { returnList.add(ed); } } return returnList; } /** * Returns the best descriptions obtained so far. * @return Best class description found so far. */ public abstract EvaluatedDescription getCurrentlyBestEvaluatedDescription(); /** * Returns a sorted set of the best descriptions found so far. We * assume that they are ordered such that the best ones come in * last. (In Java, iterators traverse a SortedSet in ascending order.) * @return Best class descriptions found so far. */ public TreeSet<? extends EvaluatedDescription> getCurrentlyBestEvaluatedDescriptions() { TreeSet<EvaluatedDescription> ds = new TreeSet<EvaluatedDescription>(); ds.add(getCurrentlyBestEvaluatedDescription()); return ds; } /** * Returns a filtered list of currently best class descriptions. * * @param nrOfDescriptions Maximum number of restrictions. Use Integer.MAX_VALUE * if you do not want this filter to be active. * * @param accuracyThreshold Minimum accuracy. All class descriptions with lower * accuracy are disregarded. Specify a value between 0.0 and 1.0. Use 0.0 if * you do not want this filter to be active. * * @param filterNonMinimalDescriptions If true, non-minimal descriptions are * filtered, e.g. ALL r.TOP (being equivalent to TOP), male AND male (can be * shortened to male). Currently, non-minimal descriptions are just skipped, * i.e. they are completely omitted from the return list. Later, implementation * might be changed to return shortened versions of those descriptions. * * @return A list of currently best class descriptions. */ public synchronized List<? extends EvaluatedDescription> getCurrentlyBestEvaluatedDescriptions(int nrOfDescriptions, double accuracyThreshold, boolean filterNonMinimalDescriptions) { TreeSet<? extends EvaluatedDescription> currentlyBest = getCurrentlyBestEvaluatedDescriptions(); List<EvaluatedDescription> returnList = new LinkedList<EvaluatedDescription>(); for(EvaluatedDescription ed : currentlyBest.descendingSet()) { // once we hit a description with a below threshold accuracy, we simply return // because learning algorithms are advised to order descriptions by accuracy, // so we won't find any concept with higher accuracy in the remaining list // if(ed.getAccuracy() < accuracyThreshold) { if(ed.getAccuracy() < accuracyThreshold) { return returnList; } // return if we have sufficiently many descriptions if(returnList.size() >= nrOfDescriptions) { return returnList; } if(!filterNonMinimalDescriptions || ConceptTransformation.isDescriptionMinimal(ed.getDescription())) { // before we add the description we replace EXISTS r.TOP with // EXISTS r.range(r) if range(r) is atomic // (we need to clone, otherwise we change descriptions which could // be in the search of the learning algorith, which leads to // unpredictable behaviour) Description d = ed.getDescription().clone(); //commented out because reasoner is called. leads in swing applications sometimes to exceptions // ConceptTransformation.replaceRange(d, reasoner); ed.setDescription(d); returnList.add(ed); } } return returnList; } /** * Return the best currently found concepts up to some maximum * count (no minimality filter used). * @param nrOfDescriptions Maximum number of descriptions returned. * @return Return value is getCurrentlyBestDescriptions(nrOfDescriptions, 0.0, false). */ public synchronized List<? extends EvaluatedDescription> getCurrentlyBestEvaluatedDescriptions(int nrOfDescriptions) { return getCurrentlyBestEvaluatedDescriptions(nrOfDescriptions, 0.0, false); } /** * Returns a fraction of class descriptions with sufficiently high accuracy. * @param accuracyThreshold Only return solutions with this accuracy or higher. * @return Return value is getCurrentlyBestDescriptions(Integer.MAX_VALUE, accuracyThreshold, false). */ public synchronized List<? extends EvaluatedDescription> getCurrentlyBestEvaluatedDescriptions(double accuracyThreshold) { return getCurrentlyBestEvaluatedDescriptions(Integer.MAX_VALUE, accuracyThreshold, false); } public synchronized List<? extends EvaluatedDescription> getCurrentlyBestMostGeneralEvaluatedDescriptions() { List<? extends EvaluatedDescription> l = getCurrentlyBestEvaluatedDescriptions(getCurrentlyBestEvaluatedDescriptions().last().getAccuracy()); DescriptionSubsumptionTree t = new DescriptionSubsumptionTree(reasoner); t.insert(l); return t.getMostGeneralDescriptions(true); } /** * Returns all learning problems supported by this component. This can be used to indicate that, e.g. * an algorithm is only suitable for positive only learning. * @return All classes implementing learning problems, which are supported by this learning algorithm. */ public static Collection<Class<? extends AbstractLearningProblem>> supportedLearningProblems() { return new LinkedList<Class<? extends AbstractLearningProblem>>(); } // central function for printing description protected String descriptionToString(Description description) { return description.toManchesterSyntaxString(baseURI, prefixes); } protected String getSolutionString() { int current = 1; String str = ""; for(EvaluatedDescription ed : bestEvaluatedDescriptions.getSet().descendingSet()) { // temporary code if(learningProblem instanceof PosNegLPStandard) { str += current + ": " + descriptionToString(ed.getDescription()) + " (pred. acc.: " + dfPercent.format(((PosNegLPStandard)learningProblem).getPredAccuracyOrTooWeakExact(ed.getDescription(),1)) + ", F-measure: "+ dfPercent.format(((PosNegLPStandard)learningProblem).getFMeasureOrTooWeakExact(ed.getDescription(),1)) + ")\n"; } else { str += current + ": " + descriptionToString(ed.getDescription()) + " " + dfPercent.format(ed.getAccuracy()) + "\n"; // System.out.println(ed); } current++; } return str; } /** * The learning problem variable, which must be used by * all learning algorithm implementations. */ @Override public AbstractLearningProblem getLearningProblem() { return learningProblem; } @Autowired @Override public void setLearningProblem(LearningProblem learningProblem) { this.learningProblem = (AbstractLearningProblem) learningProblem; } /** * The reasoning service variable, which must be used by * all learning algorithm implementations. */ public AbstractReasonerComponent getReasoner() { return reasoner; } @Autowired public void setReasoner(AbstractReasonerComponent reasoner) { this.reasoner = reasoner; } }
daftano/dl-learner
components-core/src/main/java/org/dllearner/core/AbstractCELA.java
Java
gpl-3.0
13,698
package preez.uva; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class UVA496 { static ArrayList<char[]> a; static int N, M, T, qi, qj; // S,SE,E,NE,N,NW,W,SW neighbors static int dr[] = { 1, 1, 0, -1, -1, -1, 0, 1 }; static int dc[] = { 0, 1, 1, 1, 0, -1, -1, -1 }; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter pr = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer st; static int floodFill(int i, int j, char c1, char c2) { if (i >= N || i < 0 || j >= M || j < 0 || a.get(i)[j] != c1) return 0; a.get(i)[j] = c2; int ans = 1; for (int k = 0; k < dr.length; k++) ans += floodFill(i + dr[k], j + dc[k], c1, c2); return ans; } public static void main(String[] args) throws NumberFormatException, IOException { T = Integer.parseInt(br.readLine()); br.readLine(); while (T-- > 0) { String s = br.readLine(); a = new ArrayList<>(); while (s.charAt(0) == 'W' || s.charAt(0) == 'L') { a.add(s.toCharArray()); s = br.readLine(); } N = a.size(); M = a.get(0).length; while (s != null && s.length() != 0) { st = new StringTokenizer(s); qi = Integer.parseInt(st.nextToken()) - 1; qj = Integer.parseInt(st.nextToken()) - 1; System.out.println(floodFill(qi, qj, 'W', '.')); floodFill(qi, qj, '.', 'W'); s = br.readLine(); } if(T>0) System.out.println(); } br.close(); } }
msskzx/preez
src/preez/uva/UVA496.java
Java
gpl-3.0
1,630
""" Author: Tom Daniels, Kaitlin Keenan Purpose: Creates a force graph of IP addresses and any connections they made """ import igraph import json import plotly import plotly.graph_objs as pg import sys GEN_INFO = 0 # General information PHYS = 1 # Physical layer information DATA = 2 # Data link layer information NET = 3 # Network layer information TRANS = 4 # Transport layer information SRC_IP = 12 DST_IP=14 LOWER_MULTICAST = 224 # First octect of the lowest multicast addresses UPPER_MULTICAST = 240 # First octect of the highest multicast addresses BROADCAST = 255 f = open('jsonOut.json', 'rb') jsonData = json.loads(f.read()) packets = jsonData['pdml']['packet'] nodeID = {} # Maps: Node -> ID nodes = [] # List of nodes mapping = {} # Maps: Node interation with Node -> # times nodeNumber = 0 # Give the Nodes an ID nodeCounter = {} # Maps: Node -> # of times we've seen it for packet in packets: if(len(packet['proto']) > NET and packet['proto'][NET]['@name'] == 'ip'): src = packet['proto'][NET]['field'][SRC_IP]['@show'].encode('ascii') dst = packet['proto'][NET]['field'][DST_IP]['@show'].encode('ascii') # If either address is multi/broadcast address, ignore it if(LOWER_MULTICAST <= int(src.split('.')[0]) < UPPER_MULTICAST or LOWER_MULTICAST <= int(dst.split('.')[0]) < UPPER_MULTICAST or int(dst.split('.')[3]) == 255): continue # Add the address(es) to our database if they're not in them if(not(nodeID.has_key(src))): nodes.append(src) nodeID[src] = nodeNumber nodeNumber = nodeNumber + 1 if(not(nodeID.has_key(dst))): nodes.append(dst) nodeID[dst] = nodeNumber nodeNumber = nodeNumber + 1 # Increment the counter for the number of times we've seen this node if(nodeCounter.has_key(src)): nodeCounter[src] += 1 else: nodeCounter[src] = 1 if(nodeCounter.has_key(dst)): nodeCounter[dst] += 1 else: nodeCounter[dst] = 1 # Replace string IP addresses with numbers src = str(nodeID[src]) dst = str(nodeID[dst]) # Add the mapping to the dictionary if(not(mapping.has_key(src + ':' + dst) and mapping.has_key(dst + ':' + src))): mapping[src + ':' + dst] = 1 totalPackets = len(packets) colors = [] # Set the colors for each node based on how many packets they sent out for node in nodes: colors.append(nodeCounter[node] / float(totalPackets)) edges = [(int(key.split(':')[0]), int(key.split(':')[1])) for key in mapping.keys()] graph = igraph.Graph(edges, directed=False) layout = graph.layout('kk', dim=3) length = len(nodes) Xn = [layout[i][0] for i in range(length)] Yn = [layout[i][1] for i in range(length)] Zn = [layout[i][2] for i in range(length)] Xe = [] Ye = [] Ze = [] for e in edges: Xe+=[layout[e[0]][0], layout[e[1]][0], None] Ye+=[layout[e[0]][1], layout[e[1]][1], None] Ze+=[layout[e[0]][2], layout[e[1]][2], None] # Makes the edges trace1 = pg.Scatter3d(x=Xe, y=Ye, z=Ze, mode='lines', line=pg.Line(color='rgb(125,125,125)', width=1), hoverinfo='none') # Makes the nodes trace2 = pg.Scatter3d(x=Xn, y=Yn, z=Zn, mode='markers', name='IP Addresses', marker=pg.Marker(symbol='dot',size=6, line=pg.Line(color='rgb(50,50,50)', width=0.5), colorscale=[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']], color=colors), text=nodes, hoverinfo='text') axis = dict(showbackground=False, showline=False, zeroline=False, showgrid=False, showticklabels=False, title='') trueLayout = pg.Layout(title='test', width=1000, height=1000, showlegend=False, scene=pg.Scene(xaxis=pg.XAxis(axis), yaxis=pg.YAxis(axis), zaxis=pg.ZAxis(axis)), margin=pg.Margin(t=100), hovermode='closest') plotly.offline.plot(pg.Figure(data=pg.Data([trace1, trace2]), layout=trueLayout), filename=sys.argv[1] + '/' + 'forceGraph.html')
TRDan6577/networkStatistics
networkNodes.py
Python
gpl-3.0
4,386
/* * Demo application using USBtinLib, the Java Library for USBtin * http://www.fischl.de/usbtin * * Copyright (C) 2014 Thomas Fischl * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package USBtinLibDemo; import de.fischl.usbtin.*; /** * Demo application using USBtinLib, the Java Library for USBtin. * * @author Thomas Fischl */ public class USBtinLibDemo implements CANMessageListener { /** CAN message identifier we look for */ static final int WATCHID = 0x002; /** * This method is called every time a CAN message is received. * * @param canmsg Received CAN message */ @Override public void receiveCANMessage(CANMessage canmsg) { // In this example we look for CAN messages with given ID if (canmsg.getId() == WATCHID) { // juhuu.. match! // print out message infos System.out.println("Watched message: " + canmsg); System.out.println( " id:" + canmsg.getId() + " dlc:" + canmsg.getData().length + " ext:" + canmsg.isExtended() + " rtr:" + canmsg.isRtr()); // and now print payload for (byte b : canmsg.getData()) { System.out.print(" " + b); } System.out.println(); } else { // no match, just print the message string System.out.println(canmsg); } } /** * Entry method for our demo programm * * @param args Arguments */ public static void main(String[] args) { try { // create the instances USBtin usbtin = new USBtin(); USBtinLibDemo libDemo = new USBtinLibDemo(); // connect to USBtin and open CAN channel with 10kBaud in Active-Mode usbtin.connect("/dev/ttyACM1"); // Windows e.g. "COM3" usbtin.addMessageListener(libDemo); usbtin.openCANChannel(10000, USBtin.OpenMode.ACTIVE); // send an example CAN message (standard) usbtin.send(new CANMessage(0x100, new byte[]{0x11, 0x22, 0x33})); // send an example CAN message (extended) usbtin.send(new CANMessage(0x101, new byte[]{0x44}, true, false)); // now wait for user input System.out.println("Listen for CAN messages (watch id=" + WATCHID + ") ... press ENTER to exit!"); System.in.read(); // close the CAN channel and close the connection usbtin.closeCANChannel(); usbtin.disconnect(); } catch (USBtinException ex) { // Ohh.. something goes wrong while accessing/talking to USBtin System.err.println(ex); } catch (java.io.IOException ex) { // this we need because of the System.in.read() System.err.println(ex); } } }
EmbedME/USBtinLibDemo
src/USBtinLibDemo.java
Java
gpl-3.0
3,657
// Copyright 2015-2022, University of Colorado Boulder /** * Class that represents messenger ribonucleic acid, or mRNA, in the model. This class is fairly complex, due to the * need for mRNA to wind up and unwind as it is transcribed, translated, and destroyed. * * @author John Blanco * @author Mohamed Safi * @author Aadish Gupta */ import BooleanProperty from '../../../../axon/js/BooleanProperty.js'; import Vector2 from '../../../../dot/js/Vector2.js'; import { Shape } from '../../../../kite/js/imports.js'; import geneExpressionEssentials from '../../geneExpressionEssentials.js'; import GEEConstants from '../GEEConstants.js'; import MessengerRnaAttachmentStateMachine from './attachment-state-machines/MessengerRnaAttachmentStateMachine.js'; import AttachmentSite from './AttachmentSite.js'; import FlatSegment from './FlatSegment.js'; import MessengerRnaDestroyer from './MessengerRnaDestroyer.js'; import PlacementHint from './PlacementHint.js'; import Ribosome from './Ribosome.js'; import WindingBiomolecule from './WindingBiomolecule.js'; // constants const RIBOSOME_CONNECTION_DISTANCE = 400; // picometers - distance within which this will connect to a ribosome const MRNA_DESTROYER_CONNECT_DISTANCE = 400; // picometers - Distance within which this will connect to a mRNA destroyer const INITIAL_MRNA_SHAPE = Shape.circle( 0, 0, 0.1 ); // tiny circle until the strand starts to grow const MIN_LENGTH_TO_ATTACH = 75; // picometers - min length before attachments are allowed class MessengerRna extends WindingBiomolecule { /** * Constructor. This creates the mRNA as a single point, with the intention of growing it. * * @param {GeneExpressionModel} model * @param {Protein} proteinPrototype * @param {Vector2} position * @param {Object} [options] */ constructor( model, proteinPrototype, position, options ) { super( model, INITIAL_MRNA_SHAPE, position, options ); // @private {Object} - object that maps from ribosomes to the shape segment to which they are attached this.mapRibosomeToShapeSegment = {}; // @public {BooleanProperty} - externally visible indicator for whether this mRNA is being synthesized, assumes that // it is being synthesized when initially created this.beingSynthesizedProperty = new BooleanProperty( true ); //@public // @private - protein prototype, used to keep track of protein that should be synthesized from this particular // strand of mRNA this.proteinPrototype = proteinPrototype; // @private - local reference to the non-generic state machine used by this molecule this.mRnaAttachmentStateMachine = this.attachmentStateMachine; // @private - mRNA destroyer that is destroying this mRNA. Null until and unless destruction has begun. this.messengerRnaDestroyer = null; // @private - Shape segment where the mRNA destroyer is connected. This is null until destruction has begun. this.segmentBeingDestroyed = null; // @private {AttachmentSite} - site where ribosomes or mRNA destroyers can attach this.attachmentSite = new AttachmentSite( this, new Vector2( 0, 0 ), 1 ); // set the initial position this.setPosition( position ); // Add the first segment to the shape segment list. This segment will contain the "leader" for the mRNA. const segment = new FlatSegment( this, Vector2.ZERO ); segment.setCapacity( GEEConstants.LEADER_LENGTH ); this.shapeSegments.push( segment ); // Add the placement hints for the positions where the user can attach a ribosome or an mRNA destroyer. const ribosome = new Ribosome( model ); this.ribosomePlacementHint = new PlacementHint( ribosome ); //@public(read-only) this.mRnaDestroyerPlacementHint = new PlacementHint( new MessengerRnaDestroyer( model ) ); //@public(read-only) const updateHintPositions = shape => { // All hints always sit at the beginning of the RNA strand and are positioned relative to its center. const strandStartPosition = new Vector2( shape.bounds.minX, shape.bounds.maxY ); this.ribosomePlacementHint.setPosition( strandStartPosition.minus( ribosome.offsetToTranslationChannelEntrance ) ); this.mRnaDestroyerPlacementHint.setPosition( strandStartPosition ); }; this.shapeProperty.link( updateHintPositions ); // update the attachment site position when the mRNA moves or changes shape const attachmentSitePositionUpdater = this.updateAttachmentSitePosition.bind( this ); this.positionProperty.link( attachmentSitePositionUpdater ); this.shapeProperty.link( attachmentSitePositionUpdater ); this.disposeMessengerRna = function() { this.shapeProperty.unlink( updateHintPositions ); this.shapeProperty.unlink( attachmentSitePositionUpdater ); this.positionProperty.unlink( attachmentSitePositionUpdater ); }; } /** * @public */ dispose() { this.mapRibosomeToShapeSegment = null; this.disposeMessengerRna(); super.dispose(); } /** * Command this mRNA strand to fade away when it has become fully formed. This was created for use in the 2nd * screen, where mRNA is never translated once it is produced. * @param {boolean} fadeAwayWhenFormed * @public */ setFadeAwayWhenFormed( fadeAwayWhenFormed ) { // Just pass this through to the state machine. this.mRnaAttachmentStateMachine.setFadeAwayWhenFormed( fadeAwayWhenFormed ); } /** * Advance the translation of the mRNA through the given ribosome by the specified length. The given ribosome must * already be attached to the mRNA. * @param {Ribosome} ribosome - The ribosome by which the mRNA is being translated. * @param {number} length - The amount of mRNA to move through the translation channel. * @returns - true if the mRNA is completely through the channel, indicating, that transcription is complete, and false * if not. * @public */ advanceTranslation( ribosome, length ) { const segmentToAdvance = this.mapRibosomeToShapeSegment[ ribosome.id ]; // Error checking. assert && assert( segmentToAdvance !== null ); // Should never happen, since it means that the ribosome isn't attached. // Advance the translation by advancing the position of the mRNA in the segment that corresponds to the translation // channel of the ribosome. segmentToAdvance.advance( length, this, this.shapeSegments ); // Realign the segments, since they may well have changed shape. if ( this.shapeSegments.indexOf( segmentToAdvance ) !== -1 ) { this.realignSegmentsFrom( segmentToAdvance ); this.recenter(); } // Since the sizes and relationships of the segments probably changed, the winding algorithm needs to be rerun. this.windPointsThroughSegments(); // If there is anything left in this segment, then transcription is not yet complete. return segmentToAdvance.getContainedLength() <= 0; } /** * Advance the destruction of the mRNA by the specified length. This pulls the strand into the lead segment much like * translation does, but does not move the points into new segment, it just gets rid of them. * @param {number} length * @returns {boolean} * @public */ advanceDestruction( length ) { // Error checking. assert && assert( this.segmentBeingDestroyed !== null, 'error - attempt to advance the destruction of mRNA that has no content left' ); // Advance the destruction by reducing the length of the mRNA. this.reduceLength( length ); // Realign the segments, since they may well have changed shape. if ( this.shapeSegments.indexOf( this.segmentBeingDestroyed ) !== -1 ) { this.realignSegmentsFrom( this.segmentBeingDestroyed ); } if ( this.shapeSegments.length > 0 ) { // Since the sizes and relationships of the segments probably changed, the winding algorithm needs to be rerun. this.windPointsThroughSegments(); } // If there is any length left, then the destruction is not yet complete. This is a quick way to test this. return this.firstShapeDefiningPoint === this.lastShapeDefiningPoint; } /** * Reduce the length of the mRNA. This handles both the shape segments and the shape-defining points. * @param {number} reductionAmount * @private */ reduceLength( reductionAmount ) { if ( reductionAmount >= this.getLength() ) { // Reduce length to be zero. this.lastShapeDefiningPoint = this.firstShapeDefiningPoint; this.lastShapeDefiningPoint.setNextPoint( null ); this.shapeSegments.length = 0; } else { // Remove the length from the shape segments. this.segmentBeingDestroyed.advanceAndRemove( reductionAmount, this, this.shapeSegments ); // Remove the length from the shape defining points. for ( let amountRemoved = 0; amountRemoved < reductionAmount; ) { if ( this.lastShapeDefiningPoint.getTargetDistanceToPreviousPoint() <= reductionAmount - amountRemoved ) { // Remove the last point from the list. amountRemoved += this.lastShapeDefiningPoint.getTargetDistanceToPreviousPoint(); this.lastShapeDefiningPoint = this.lastShapeDefiningPoint.getPreviousPoint(); this.lastShapeDefiningPoint.setNextPoint( null ); } else { // Reduce the distance of the last point from the previous point. this.lastShapeDefiningPoint.setTargetDistanceToPreviousPoint( this.lastShapeDefiningPoint.getTargetDistanceToPreviousPoint() - ( reductionAmount - amountRemoved ) ); amountRemoved = reductionAmount; } } } } /** * @private */ updateAttachmentSitePosition() { if ( this.shapeSegments.length > 0 ) { const leadingShapeSegment = this.shapeSegments[ 0 ]; this.attachmentSite.positionProperty.set( new Vector2( this.positionProperty.get().x + leadingShapeSegment.bounds.minX, this.positionProperty.get().y + leadingShapeSegment.bounds.minY ) ); } else { this.attachmentSite.positionProperty.set( this.positionProperty.get() ); } } /** * Create a new version of the protein that should result when this strand of mRNA is translated. * @returns {Protein} * @public */ getProteinPrototype() { return this.proteinPrototype; } /** * Get the point in model space where the entrance of the given ribosome's translation channel should be in order to * be correctly attached to this strand of messenger RNA. This allows the ribosome to "follow" the mRNA if it is * moving or changing shape. * @param {Ribosome} ribosome * @returns {Vector2} * @public */ getRibosomeGenerateInitialPosition3D( ribosome ) { assert && assert( this.mapRibosomeToShapeSegment[ ribosome.id ], 'attempt made to get attachment position for unattached ribosome' ); let generateInitialPosition3D; const mRnaPosition = this.positionProperty.get(); const segment = this.mapRibosomeToShapeSegment[ ribosome.id ]; let segmentCornerPosition; if ( this.getPreviousShapeSegment( segment ) === null ) { // There is no previous segment, which means that the segment to which this ribosome is attached is the leader // segment. The attachment point is thus the leader length from its rightmost edge. segmentCornerPosition = segment.getLowerRightCornerPosition(); generateInitialPosition3D = mRnaPosition.plusXY( segmentCornerPosition.x - GEEConstants.LEADER_LENGTH, segmentCornerPosition.y ); } else { // The segment has filled up the channel, so calculate the position based on its left edge. segmentCornerPosition = segment.getUpperLeftCornerPosition(); generateInitialPosition3D = mRnaPosition.plusXY( segmentCornerPosition.x + ribosome.getTranslationChannelLength(), segmentCornerPosition.y ); } return generateInitialPosition3D; } /** * Release this mRNA from a ribosome. If this is the only ribosome to which the mRNA is connected, the mRNA will * start wandering. * @param {Ribosome} ribosome * @public */ releaseFromRibosome( ribosome ) { delete this.mapRibosomeToShapeSegment[ ribosome.id ]; if ( _.keys( this.mapRibosomeToShapeSegment ).length === 0 ) { this.mRnaAttachmentStateMachine.allRibosomesDetached(); } } /** * Release this mRNA from the polymerase which is, presumably, transcribing it. * @public */ releaseFromPolymerase() { this.mRnaAttachmentStateMachine.detach(); } /** * This override checks to see if the mRNA is about to be translated and destroyed and, if so, aborts those * operations. If translation or destruction are in progress, nothing is done, since those can't be stopped once * they've started. * @override * @public */ handleGrabbedByUser() { const attachedOrAttachingMolecule = this.attachmentSite.attachedOrAttachingMoleculeProperty.get(); if ( attachedOrAttachingMolecule instanceof Ribosome ) { // if a ribosome is moving towards this mRNA strand but translation hasn't started, call off the wedding if ( !attachedOrAttachingMolecule.isTranslating() ) { attachedOrAttachingMolecule.cancelTranslation(); this.releaseFromRibosome( attachedOrAttachingMolecule ); this.attachmentStateMachine.forceImmediateUnattachedAndAvailable(); } } else if ( attachedOrAttachingMolecule instanceof MessengerRnaDestroyer ) { // state checking assert && assert( this.messengerRnaDestroyer === attachedOrAttachingMolecule, 'something isn\t right - the destroyer for the attachment site doesn\'t match the expected reference' ); // if an mRNA destroyer is moving towards this mRNA strand but translation hasn't started, call off the wedding if ( !this.isDestructionInProgress() ) { attachedOrAttachingMolecule.cancelMessengerRnaDestruction(); this.messengerRnaDestroyer = null; this.attachmentStateMachine.forceImmediateUnattachedAndAvailable(); } } } /** * Activate the placement hint(s) as appropriate for the given biomolecule. * @param {MobileBiomolecule} biomolecule - instance of the type of biomolecule for which any matching hints * should be activated. * @public */ activateHints( biomolecule ) { this.ribosomePlacementHint.activateIfMatch( biomolecule ); this.mRnaDestroyerPlacementHint.activateIfMatch( biomolecule ); } /** * Deactivate placement hints for all biomolecules * @public */ deactivateAllHints() { this.ribosomePlacementHint.activeProperty.set( false ); this.mRnaDestroyerPlacementHint.activeProperty.set( false ); } /** * Initiate the translation process by setting up the segments as needed. This should only be called after a ribosome * that was moving to attach with this mRNA arrives at the attachment point. * @param {Ribosome} ribosome * @public */ initiateTranslation( ribosome ) { assert && assert( this.mapRibosomeToShapeSegment[ ribosome.id ] ); // State checking. // Set the capacity of the first segment to the size of the channel through which it will be pulled plus the // leader length. const firstShapeSegment = this.shapeSegments[ 0 ]; assert && assert( firstShapeSegment.isFlat() ); firstShapeSegment.setCapacity( ribosome.getTranslationChannelLength() + GEEConstants.LEADER_LENGTH ); } /** * Initiate the destruction of this mRNA strand by setting up the segments as needed. This should only be called * after an mRNA destroyer has attached to the front of the mRNA strand. Once initiated, destruction cannot be stopped. * @param {MessengerRnaDestroyer} messengerRnaDestroyer * @public */ initiateDestruction( messengerRnaDestroyer ) { assert && assert( this.messengerRnaDestroyer === messengerRnaDestroyer ); // Shouldn't get this from unattached destroyers. // Set the capacity of the first segment to the size of the channel through which it will be pulled plus the leader length. this.segmentBeingDestroyed = this.shapeSegments[ 0 ]; assert && assert( this.segmentBeingDestroyed.isFlat() ); this.segmentBeingDestroyed.setCapacity( this.messengerRnaDestroyer.getDestructionChannelLength() + GEEConstants.LEADER_LENGTH ); } /** * returns true if destruction has started, false if not - note that destruction must actually have started, and * the state where an mRNA destroyer is moving towards the mRNA doesn't count * @private */ isDestructionInProgress() { return this.segmentBeingDestroyed !== null; } /** * Get the proportion of the entire mRNA that has been translated by the given ribosome. * @param {Ribosome} ribosome * @returns {number} * @public */ getProportionOfRnaTranslated( ribosome ) { const translatedLength = this.getLengthOfRnaTranslated( ribosome ); return Math.max( translatedLength / this.getLength(), 0 ); } /** * Get the length of the mRNA that has been translated by the given ribosome. * @param {Ribosome} ribosome * @returns {number} * @public */ getLengthOfRnaTranslated( ribosome ) { assert && assert( this.mapRibosomeToShapeSegment[ ribosome.id ] ); // Makes no sense if ribosome isn't attached. let translatedLength = 0; const segmentInRibosomeChannel = this.mapRibosomeToShapeSegment[ ribosome.id ]; assert && assert( segmentInRibosomeChannel.isFlat() ); // Make sure things are as we expect. // Add the length for each segment that precedes this ribosome. for ( let i = 0; i < this.shapeSegments.length; i++ ) { const shapeSegment = this.shapeSegments[ i ]; if ( shapeSegment === segmentInRibosomeChannel ) { break; } translatedLength += shapeSegment.getContainedLength(); } // Add the length for the segment that is inside the translation channel of this ribosome. translatedLength += segmentInRibosomeChannel.getContainedLength() - ( segmentInRibosomeChannel.getLowerRightCornerPosition().x - segmentInRibosomeChannel.attachmentSite.positionProperty.get().x ); return translatedLength; } /** * returns true if this messenger RNA is in a state where attachments can occur * @returns {boolean} * @private */ attachmentAllowed() { // For an attachment proposal to be considered, the mRNA can't be controlled by the user, too short, or in the // process of being destroyed. return !this.userControlledProperty.get() && this.getLength() >= MIN_LENGTH_TO_ATTACH && this.messengerRnaDestroyer === null; } /** * Consider proposal from ribosome, and, if the proposal is accepted, return the attachment position * @param {Ribosome} ribosome * @returns {AttachmentSite} * @public */ considerProposalFromRibosome( ribosome ) { assert && assert( !this.mapRibosomeToShapeSegment[ ribosome.id ] ); // Shouldn't get redundant proposals from a ribosome. let returnValue = null; if ( this.attachmentAllowed() ) { // See if the attachment site at the leading edge of the mRNA is available and close by. if ( this.attachmentSite.attachedOrAttachingMoleculeProperty.get() === null && this.attachmentSite.positionProperty.get().distance( ribosome.getEntranceOfRnaChannelPosition() ) < RIBOSOME_CONNECTION_DISTANCE ) { // This attachment site is in range and available. returnValue = this.attachmentSite; // Update the attachment state machine. this.mRnaAttachmentStateMachine.attachedToRibosome(); // Enter this connection in the map. this.mapRibosomeToShapeSegment[ ribosome.id ] = this.shapeSegments[ 0 ]; } } return returnValue; } /** * Consider proposal from mRnaDestroyer and if it can attach return the attachment position * @param {MessengerRnaDestroyer} messengerRnaDestroyer * @returns {AttachmentSite} * @public */ considerProposalFromMessengerRnaDestroyer( messengerRnaDestroyer ) { assert && assert( this.messengerRnaDestroyer !== messengerRnaDestroyer ); // Shouldn't get redundant proposals from same destroyer. let returnValue = null; if ( this.attachmentAllowed() ) { // See if the attachment site at the leading edge of the mRNA is available and close by. if ( this.attachmentSite.attachedOrAttachingMoleculeProperty.get() === null && this.attachmentSite.positionProperty.get().distance( messengerRnaDestroyer.getPosition() ) < MRNA_DESTROYER_CONNECT_DISTANCE ) { // This attachment site is in range and available. returnValue = this.attachmentSite; // Update the attachment state machine. this.mRnaAttachmentStateMachine.attachToDestroyer(); // Keep track of the destroyer. this.messengerRnaDestroyer = messengerRnaDestroyer; } } return returnValue; } /** * Aborts the destruction process, used if the mRNA destroyer was on its way to the mRNA but the user picked up * once of the two biomolecules before destruction started. * @public */ abortDestruction() { this.messengerRnaDestroyer = null; this.attachmentStateMachine.forceImmediateUnattachedAndAvailable(); } /** * @override * @returns {MessengerRnaAttachmentStateMachine} * @public */ createAttachmentStateMachine() { return new MessengerRnaAttachmentStateMachine( this ); } /** * Get the point in model space where the entrance of the given destroyer's translation channel should be in order to * be correctly attached to this strand of messenger RNA. * @returns {Vector2} * @public */ getDestroyerGenerateInitialPosition3D() { // state checking - shouldn't be called before this is set assert && assert( this.segmentBeingDestroyed !== null ); // the attachment position is at the right most side of the segment minus the leader length return this.attachmentSite.positionProperty.get(); } } geneExpressionEssentials.register( 'MessengerRna', MessengerRna ); export default MessengerRna;
phetsims/gene-expression-essentials
js/common/model/MessengerRna.js
JavaScript
gpl-3.0
22,291
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.URL; import java.util.List; import java.util.Scanner; import java.util.Stack; /************************************************************************** * The {@code TagQuery} class. * * @author Jonathan A. Henly **/ public class TagQuery { // TODO: Remove the line of debugging code following this private static PrintWriter log; // TODO: Remove the static block of debugging code following this static { try { log = new PrintWriter("./zout/out_QUERY"); } catch (FileNotFoundException e) { e.printStackTrace(); } } /************************************************************************** * * @author Jonathan A. Henly **/ public static class InvalidQueryException extends Exception { private static final long serialVersionUID = -6002360782575126129L; public InvalidQueryException(String query, int index) { super("Parsing of the query: \"" + query + "\" failed at character index: " + index + "\n"); } } private static enum QueryType { CLASS, ID, TAG, TAG_CLASS, TAG_ID } private Tag root; private Stack<Tag> result; private Stack<Tag> sub; private Stack<String> instructions; public TagQuery() { this.root = null; this.instructions = null; this.sub = null; this.result = new Stack<Tag>(); } public TagQuery(FileReader file) { this(); init(file); } public TagQuery(URL url) throws IOException { this(); init(url.openStream()); } public TagQuery(InputStream stream) { this(); init(stream); } private void init(FileReader file) { StringBuilder sb = new StringBuilder(); Scanner inFile = new Scanner(file); while(inFile.hasNextLine()) { sb.append(inFile.nextLine()); } inFile.close(); this.root = Tag.parseTags(sb); } private void init(InputStream stream) { StringBuilder sb = new StringBuilder(); Scanner inFile = new Scanner(stream); while(inFile.hasNextLine()) { sb.append(inFile.nextLine()); } inFile.close(); this.root = Tag.parseTags(sb); } /************************************************************************** * * * * @param file - * @return a reference to this {@code TagQuery} object. **/ public TagQuery loadSource(FileReader file) { init(file); return this; } /************************************************************************** * * * * @param url - * @return a reference to this {@code TagQuery} object. * @throws IOException **/ public TagQuery loadSource(URL url) throws IOException { init(url.openStream()); return this; } /************************************************************************** * * * * @param stream - * @return a reference to this {@code TagQuery} object. * @throws IOException **/ public TagQuery loadSource(InputStream stream) { init(stream); return this; } /************************************************************************** * * * * @param query - * @return a reference to this object. * @throws InvalidQueryException **/ public List<Tag> query(String query) throws InvalidQueryException { this.instructions = this.buildQuery(query); this.runInstructions(); return this.getResult(); } private Stack<String> buildQuery(String query) throws InvalidQueryException { Stack<String> tasks = new Stack<String>(); String task = ""; char[] command; boolean space = false; boolean comma = false; boolean dot = false; boolean hash = false; query = query.trim(); command = query.toCharArray(); for(int i = 0; i < query.length(); i++) { switch(command[i]) { case ' ': if(space || comma) { continue; } space = true; dot = false; hash = false; tasks.push(task); tasks.push(" "); task = ""; break; case ',': if(comma || (i == query.length() - 1)) { throw new InvalidQueryException(query, i); } comma = true; space = false; dot = false; hash = false; tasks.push(task); tasks.push(","); task = ""; break; case '.': if(dot) { throw new InvalidQueryException(query, i); } dot = true; task += command[i]; break; case '#': if(hash) { throw new InvalidQueryException(query, i); } hash = true; task += command[i]; break; default : space = false; comma = false; dot = false; hash = false; task += command[i]; break; } } if(!task.isEmpty()) { tasks.push(task); } return tasks; } private void runInstructions() { String instruction = ""; int height = 0; this.sub = new Stack<Tag>(); while(this.instructions.size() > 0) { instruction = this.instructions.pop(); if(" ".equals(instruction)) { height += 1; } else if(",".equals(instruction)) { height = 0; this.result.addAll(this.sub); this.sub = new Stack<Tag>(); } else { if(height > 0) { this.runQuery(instruction, height); } else { this.runInitQuery(instruction); } } } this.result.addAll(this.sub); } private void runQuery(String q, int height) { if(q.indexOf('.') == q.indexOf('#')) { this.find(height, q, QueryType.TAG); } else if(q.indexOf('#') >= 0) { if(q.indexOf('#') == 0) { q = q.substring(1); this.find(height, q, QueryType.ID); } else { this.find(height, q, QueryType.TAG_ID); } } else if(q.indexOf('.') >= 0) { if(q.indexOf('.') == 0) { q = q.substring(1); this.find(height, q, QueryType.CLASS); } else { this.find(height, q, QueryType.TAG_CLASS); } } } private void runInitQuery(String q) { if(q.indexOf('.') == q.indexOf('#')) { this.findInit(this.root, q, QueryType.TAG); } else if(q.indexOf('#') >= 0) { if(q.indexOf('#') == 0) { q = q.substring(1); this.findInit(this.root, q, QueryType.ID); } else { this.findInit(this.root, q, QueryType.TAG_ID); } } else if(q.indexOf('.') >= 0) { if(q.indexOf('.') == 0) { q = q.substring(1); this.findInit(this.root, q, QueryType.CLASS); } else { this.findInit(this.root, q, QueryType.TAG_CLASS); } } } private void find(int height, String q, QueryType qt) { Stack<Tag> tmp = new Stack<Tag>(); Tag t = null; Tag p = null; nullParent: while(!this.sub.isEmpty()) { t = this.sub.pop(); p = t; for(int pCount = 0; pCount < height; pCount++) { if(p == null) { continue nullParent; } p = p.getParent(); } switch(qt) { case TAG: if(q.equals(p.getName())) { tmp.push(t); } break; case CLASS: if(p.hasClass(q)) { tmp.push(t); } break; case ID: if(t.hasID(q)) { tmp.push(t); } break; case TAG_CLASS: if(p.getName().equals(q.substring(0, q.indexOf('.')))) { if(p.hasClass(q.substring(q.indexOf('.') + 1))) { tmp.push(t); } } break; case TAG_ID: if(p.getName().equals(q.substring(0, q.indexOf('#')))) { if(p.hasClass(q.substring(q.indexOf('#') + 1))) { tmp.push(t); } } break; } } this.sub = tmp; } private void findInit(Tag t, String q, QueryType qt) { if(t.hasChildren()) { List<Tag> c = t.getChildren(); for(Tag child : c) { if(!child.isStartTag()) { continue; } this.findInit(child, q, qt); } } switch(qt) { case TAG: if(q.equals(t.getName())) { this.sub.push(t); } break; case CLASS: if(t.hasClass(q)) { this.sub.push(t); } break; case ID: if(t.hasID(q)) { this.sub.push(t); } break; case TAG_CLASS: if(t.getName().equals(q.substring(0, q.indexOf('.')))) { if(t.hasClass(q.substring(q.indexOf('.') + 1))) { this.sub.push(t); } } break; case TAG_ID: if(t.getName().equals(q.substring(0, q.indexOf('#')))) { if(t.hasClass(q.substring(q.indexOf('#') + 1))) { this.sub.push(t); } } break; } } public List<Tag> getResult() { return this.result; } public void reset() { this.result = new Stack<Tag>(); } }
JonathanHenly/HTMLParser
src/TagQuery.java
Java
gpl-3.0
8,311
package service; import java.util.List; import javax.ejb.Stateless; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import modelo.Menu; @Stateless public class MenuService extends GenericService<Menu>{ public MenuService() { super(Menu.class); } public List<Menu> obtemMenuComMenuItens(){ final CriteriaBuilder cb = getEntityManager().getCriteriaBuilder(); final CriteriaQuery<Menu> cQuery = cb.createQuery(Menu.class); cQuery.select(cQuery.from(Menu.class)); List<Menu> menu = getEntityManager().createQuery(cQuery).getResultList(); for (Menu m : menu) { m.getItens().size(); } return menu; } }
kashm1r/photoiff
src/service/MenuService.java
Java
gpl-3.0
699
/* * Copyright (C) 2015 Information Retrieval Group at Universidad Autonoma * de Madrid, http://ir.ii.uam.es * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package es.uam.eps.ir.ranksys.core.util.topn; import it.unimi.dsi.fastutil.objects.AbstractObject2DoubleMap.BasicEntry; import it.unimi.dsi.fastutil.objects.Object2DoubleMap.Entry; /** * Bounded min-heap to keep just the top-n greatest object-double pairs according to the value of the double. * * @author Saúl Vargas (saul.vargas@uam.es) * * @param <T> type of the object */ public class ObjectDoubleTopN<T> extends AbstractTopN<Entry<T>> { private final T[] keys; private final double[] values; /** * Constructor. * * @param capacity maximum capacity of the heap */ @SuppressWarnings("unchecked") public ObjectDoubleTopN(int capacity) { super(capacity); keys = (T[]) new Object[capacity]; values = new double[capacity]; } /** * Tries to add an object-double pair to the heap. * * @param object object to be added * @param value double to be added * @return true if the pair was added to the heap, false otherwise */ public boolean add(T object, double value) { return add(new BasicEntry<>(object, value)); } @Override protected Entry<T> get(int i) { return new BasicEntry<>(keys[i], values[i]); } @Override protected void set(int i, Entry<T> e) { keys[i] = e.getKey(); values[i] = e.getDoubleValue(); } @SuppressWarnings("unchecked") @Override protected int compare(int i, Entry<T> e) { double v = e.getDoubleValue(); int c = Double.compare(values[i], v); if (c != 0) { return c; } else { c = ((Comparable<T>) keys[i]).compareTo(e.getKey()); return c; } } @SuppressWarnings("unchecked") @Override protected int compare(int i, int j) { int c = Double.compare(values[i], values[j]); if (c != 0) { return c; } else { c = ((Comparable<T>) keys[i]).compareTo(keys[j]); return c; } } @Override protected void swap(int i, int j) { T k = keys[i]; keys[i] = keys[j]; keys[j] = k; double v = values[i]; values[i] = values[j]; values[j] = v; } }
OlafLee/RankSys
RankSys-core/src/main/java/es/uam/eps/ir/ranksys/core/util/topn/ObjectDoubleTopN.java
Java
gpl-3.0
3,023
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.11.24 at 09:50:34 AM AEDT // package org.isotc211._2005.gco; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for TypeName_PropertyType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="TypeName_PropertyType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence minOccurs="0"> * &lt;element ref="{http://www.isotc211.org/2005/gco}TypeName"/> * &lt;/sequence> * &lt;attGroup ref="{http://www.isotc211.org/2005/gco}ObjectReference"/> * &lt;attribute ref="{http://www.isotc211.org/2005/gco}nilReason"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TypeName_PropertyType", propOrder = { "typeName" }) public class TypeNamePropertyType { @XmlElement(name = "TypeName") protected TypeNameType typeName; @XmlAttribute(name = "nilReason", namespace = "http://www.isotc211.org/2005/gco") protected List<String> nilReason; @XmlAttribute(name = "uuidref") protected String uuidref; @XmlAttribute(name = "type", namespace = "http://www.w3.org/1999/xlink") protected String type; @XmlAttribute(name = "href", namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anyURI") protected String href; @XmlAttribute(name = "role", namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anyURI") protected String role; @XmlAttribute(name = "arcrole", namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anyURI") protected String arcrole; @XmlAttribute(name = "title", namespace = "http://www.w3.org/1999/xlink") protected String title; @XmlAttribute(name = "show", namespace = "http://www.w3.org/1999/xlink") protected String show; @XmlAttribute(name = "actuate", namespace = "http://www.w3.org/1999/xlink") protected String actuate; /** * Gets the value of the typeName property. * * @return * possible object is * {@link TypeNameType } * */ public TypeNameType getTypeName() { return typeName; } /** * Sets the value of the typeName property. * * @param value * allowed object is * {@link TypeNameType } * */ public void setTypeName(TypeNameType value) { this.typeName = value; } /** * Gets the value of the nilReason property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the nilReason property. * * <p> * For example, to add a new item, do as follows: * <pre> * getNilReason().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getNilReason() { if (nilReason == null) { nilReason = new ArrayList<String>(); } return this.nilReason; } /** * Gets the value of the uuidref property. * * @return * possible object is * {@link String } * */ public String getUuidref() { return uuidref; } /** * Sets the value of the uuidref property. * * @param value * allowed object is * {@link String } * */ public void setUuidref(String value) { this.uuidref = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { if (type == null) { return "simple"; } else { return type; } } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the href property. * * @return * possible object is * {@link String } * */ public String getHref() { return href; } /** * Sets the value of the href property. * * @param value * allowed object is * {@link String } * */ public void setHref(String value) { this.href = value; } /** * Gets the value of the role property. * * @return * possible object is * {@link String } * */ public String getRole() { return role; } /** * Sets the value of the role property. * * @param value * allowed object is * {@link String } * */ public void setRole(String value) { this.role = value; } /** * Gets the value of the arcrole property. * * @return * possible object is * {@link String } * */ public String getArcrole() { return arcrole; } /** * Sets the value of the arcrole property. * * @param value * allowed object is * {@link String } * */ public void setArcrole(String value) { this.arcrole = value; } /** * Gets the value of the title property. * * @return * possible object is * {@link String } * */ public String getTitle() { return title; } /** * Sets the value of the title property. * * @param value * allowed object is * {@link String } * */ public void setTitle(String value) { this.title = value; } /** * Gets the value of the show property. * * @return * possible object is * {@link String } * */ public String getShow() { return show; } /** * Sets the value of the show property. * * @param value * allowed object is * {@link String } * */ public void setShow(String value) { this.show = value; } /** * Gets the value of the actuate property. * * @return * possible object is * {@link String } * */ public String getActuate() { return actuate; } /** * Sets the value of the actuate property. * * @param value * allowed object is * {@link String } * */ public void setActuate(String value) { this.actuate = value; } }
anu-doi/anudc
DataCommons/src/main/java/org/isotc211/_2005/gco/TypeNamePropertyType.java
Java
gpl-3.0
7,642
package de.jdellert.iwsa.tokenize; /** * Models a configuration for an IPATokenizer, essentially just a combination of * binary flags, with the default configuration tuned towards NorthEuraLex. * */ public class IPATokenizerConfiguration { public final boolean SEPARATE_EJECTIVITY; public final boolean SEPARATE_ASPIRATION; public final boolean SEPARATE_NASAL_RELEASE; public final boolean SEPARATE_LATERAL_RELEASE; public final boolean SEPARATE_LABIALIZATION; public final boolean SEPARATE_PALATALIZATION; public final boolean SEPARATE_VELARIZATION; public final boolean SEPARATE_NASALIZATION; public final boolean SEPARATE_GLOTTALIZATION; public final boolean SEPARATE_PHARYNGEALIZATION; public final boolean SINGLE_SEGMENT_AFFRICATES; public final boolean SINGLE_SEGMENT_DIPHTHONGS; public final boolean SINGLE_SEGMENT_LONG_VOWELS; public final boolean SINGLE_SEGMENT_GEMINATES; public final boolean IGNORE_TONES; public final boolean IGNORE_STRESS; public final boolean IGNORE_SYLLABICITY; public final boolean IGNORE_PHONATION_DIACRITICS; public final boolean IGNORE_ARTICULATION_DIACRITICS; public final boolean IGNORE_UNKNOWN_SYMBOLS; // default tokenization: as in my dissertation (Dellert 2017) public IPATokenizerConfiguration() { SEPARATE_EJECTIVITY = true; SEPARATE_ASPIRATION = true; SEPARATE_NASAL_RELEASE = true; SEPARATE_LATERAL_RELEASE = true; SEPARATE_LABIALIZATION = true; SEPARATE_PALATALIZATION = true; SEPARATE_VELARIZATION = true; SEPARATE_NASALIZATION = true; SEPARATE_GLOTTALIZATION = true; SEPARATE_PHARYNGEALIZATION = true; SINGLE_SEGMENT_AFFRICATES = true; SINGLE_SEGMENT_DIPHTHONGS = false; SINGLE_SEGMENT_LONG_VOWELS = false; SINGLE_SEGMENT_GEMINATES = false; IGNORE_TONES = true; IGNORE_STRESS = true; IGNORE_SYLLABICITY = true; IGNORE_PHONATION_DIACRITICS = true; IGNORE_ARTICULATION_DIACRITICS = true; IGNORE_UNKNOWN_SYMBOLS = true; } public IPATokenizerConfiguration(boolean SEPARATE_EJECTIVITY, boolean SEPARATE_ASPIRATION, boolean SEPARATE_NASAL_RELEASE, boolean SEPARATE_LATERAL_RELEASE, boolean SEPARATE_LABIALIZATION, boolean SEPARATE_PALATALIZATION, boolean SEPARATE_VELARIZATION, boolean SEPARATE_NASALIZATION, boolean SEPARATE_GLOTTALIZATION, boolean SEPARATE_PHARYNGEALIZATION, boolean SINGLE_SEGMENT_AFFRICATES, boolean SINGLE_SEGMENT_DIPHTHONGS, boolean SINGLE_SEGMENT_LONG_VOWELS, boolean SINGLE_SEGMENT_GEMINATES, boolean IGNORE_TONES, boolean IGNORE_STRESS, boolean IGNORE_SYLLABICITY, boolean IGNORE_PHONATION_DIACRITICS, boolean IGNORE_ARTICULATION_DIACRITICS, boolean IGNORE_UNKNOWN_SYMBOLS) { this.SEPARATE_EJECTIVITY = SEPARATE_EJECTIVITY; this.SEPARATE_ASPIRATION = SEPARATE_ASPIRATION; this.SEPARATE_NASAL_RELEASE = SEPARATE_NASAL_RELEASE; this.SEPARATE_LATERAL_RELEASE = SEPARATE_LATERAL_RELEASE; this.SEPARATE_LABIALIZATION = SEPARATE_LABIALIZATION; this.SEPARATE_PALATALIZATION = SEPARATE_PALATALIZATION; this.SEPARATE_VELARIZATION = SEPARATE_VELARIZATION; this.SEPARATE_NASALIZATION = SEPARATE_NASALIZATION; this.SEPARATE_GLOTTALIZATION = SEPARATE_GLOTTALIZATION; this.SEPARATE_PHARYNGEALIZATION = SEPARATE_PHARYNGEALIZATION; this.SINGLE_SEGMENT_AFFRICATES = SINGLE_SEGMENT_AFFRICATES; this.SINGLE_SEGMENT_DIPHTHONGS = SINGLE_SEGMENT_DIPHTHONGS; this.SINGLE_SEGMENT_LONG_VOWELS = SINGLE_SEGMENT_LONG_VOWELS; this.SINGLE_SEGMENT_GEMINATES = SINGLE_SEGMENT_GEMINATES; this.IGNORE_TONES = IGNORE_TONES; this.IGNORE_STRESS = IGNORE_STRESS; this.IGNORE_SYLLABICITY = IGNORE_SYLLABICITY; this.IGNORE_PHONATION_DIACRITICS = IGNORE_PHONATION_DIACRITICS; this.IGNORE_ARTICULATION_DIACRITICS = IGNORE_ARTICULATION_DIACRITICS; this.IGNORE_UNKNOWN_SYMBOLS = IGNORE_UNKNOWN_SYMBOLS; } }
jdellert/iwsa
src/de/jdellert/iwsa/tokenize/IPATokenizerConfiguration.java
Java
gpl-3.0
3,782
package jeql.workbench.ui.geomview.style; import java.util.*; import java.awt.Graphics2D; import jeql.workbench.ui.geomview.Viewport; import org.locationtech.jts.geom.Geometry; /** * Contains a list of styles and allows Geometrys * to be rendered using those styles. * * @author mbdavis * */ public class StyleList implements Style { private List styleList = new ArrayList(); public void paint(Geometry geom, Viewport viewport, Graphics2D g) throws Exception { for (Iterator i = styleList.iterator(); i.hasNext(); ) { StyleEntry styleEntry = (StyleEntry) i.next(); if (styleEntry.isFullyEnabled()) styleEntry.getStyle().paint(geom, viewport, g); } } public void add(Style style) { add(style, null); } public void add(Style style, StyleFilter filter) { styleList.add(new StyleEntry(style, filter)); } public void setEnabled(Style style, boolean isEnabled) { StyleEntry entry = getEntry(style); if (entry == null) return; entry.setEnabled(isEnabled); } private StyleEntry getEntry(Style style) { int index = getEntryIndex(style); if (index < 0) return null; return (StyleEntry) styleList.get(index); } private int getEntryIndex(Style style) { for (int i = 0; i < styleList.size(); i++) { StyleEntry entry = (StyleEntry) styleList.get(i); if (entry.getStyle() == style) return i; } return -1; } public interface StyleFilter { boolean isFiltered(Style style); } } class StyleEntry { private Style style; private boolean isEnabled = true; private StyleList.StyleFilter filter = null; public StyleEntry(Style style) { this.style = style; } public StyleEntry(Style style, StyleList.StyleFilter filter) { this.style = style; this.filter = filter; } public void setEnabled(boolean isEnabled) { this.isEnabled = isEnabled; } public boolean isEnabled() { return isEnabled; } public boolean isFiltered() { if (filter == null) return false; return filter.isFiltered(style); } public boolean isFullyEnabled() { return isEnabled() && ! isFiltered(); } public Style getStyle() { return style; } }
dr-jts/jeql
modules/jeqlw/src/main/java/jeql/workbench/ui/geomview/style/StyleList.java
Java
gpl-3.0
2,177
package com.drexel.septaplanner; import java.util.ArrayList; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Menu; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMapLoadedCallback; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.LatLngBounds.Builder; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; public class MyMapFrag extends FragmentActivity { String tag = "mymapfrag"; LatLngBounds bounds; public GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map_fragment); // get arraylist passed into intent Intent i = getIntent(); ArrayList<septaTrain> trains = i.getParcelableArrayListExtra("trains"); // make map object mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)) .getMap(); // set markers on map ArrayList<Marker> markers = new ArrayList<Marker>(); LatLng l; Builder bBounds = new LatLngBounds.Builder(); //get bounds for the group of trains and also the add markers on //map for those trains for (int k = 0; k < trains.size(); k++) { l = trains.get(k).getLatlong(); if (l.latitude != 0 && l.longitude != 0) { bBounds.include(l); markers.add(mMap.addMarker(new MarkerOptions().position(l) .title("#" + trains.get(k).getTrainNum()))); } } if (markers.size() == 0){ //create bounds for philadelphia septa area bBounds.include(new LatLng(39.863371,-75.411728)); bBounds.include(new LatLng(40.295894,-74.681652)); Toast.makeText( MyMapFrag.this, "There are no trains with gps coordinates on this route", Toast.LENGTH_LONG).show(); } bounds = bBounds.build(); mMap.setOnMapLoadedCallback(new OnMapLoadedCallback() { @Override public void onMapLoaded() { mMap.animateCamera( CameraUpdateFactory.newLatLngBounds(bounds, 100), 1500, null); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.map, menu); return true; } }
JamesBarnes88/SeptaPlanner
src/com/drexel/septaplanner/MyMapFrag.java
Java
gpl-3.0
2,520
package net.qrab.watchit.stages; import com.badlogic.gdx.scenes.scene2d.Stage; public class HudStage extends Stage { public HudStage() { } }
jkleininger/BaggageClimb
core/src/net/qrab/watchit/stages/HudStage.java
Java
gpl-3.0
148
'use strict'; /** * Module dependencies */ var path = require('path'), config = require(path.resolve('./config/config')); /** * Quiz module init function. */ module.exports = function (app, db) { };
AnnaGenev/pokeapp-meanjs
modules/quiz/server/config/quiz.server.config.js
JavaScript
gpl-3.0
208
/* * Copyright (C) 2014 Robert Stark * * This program is free software; you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, see <http://www.gnu.org/licenses/>. */ package de.rs.scrumit.entity; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.OrderBy; import org.hibernate.envers.Audited; @Entity @Table(name="release") public class ReleaseModel extends BaseEntityAuditModel { private static final long serialVersionUID = 1L; @Audited(withModifiedFlag=true) private String description; @ManyToOne(optional=false) private ReleasePlanModel releasePlan; @Temporal(TemporalType.TIMESTAMP) @Column(nullable=false) @Audited(withModifiedFlag=true) private Date releaseDate; @OneToMany(mappedBy="release", targetEntity=SprintModel.class, fetch=FetchType.LAZY) @OrderBy(clause="startdate") private List<SprintModel> sprints; public ReleaseModel(){} public ReleaseModel(String code, Date releaseDate) { super(code); this.releaseDate = releaseDate; } public ReleaseModel(String code, ReleasePlanModel releasePlan, Date releaseDate) { super(code); this.releasePlan = releasePlan; this.releaseDate = releaseDate; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public ReleasePlanModel getReleasePlan() { return releasePlan; } public void setReleasePlan(ReleasePlanModel releasePlan) { this.releasePlan = releasePlan; } public Date getReleaseDate() { return releaseDate; } public void setReleaseDate(Date releaseDate) { this.releaseDate = releaseDate; } public List<SprintModel> getSprints() { return sprints; } public void setSprints(List<SprintModel> sprints) { this.sprints = sprints; } }
StarkoMania/scrum-it
src/main/java/de/rs/scrumit/entity/ReleaseModel.java
Java
gpl-3.0
2,590
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ancienttiles; import ancienttiles.griddisplay.TileDisplay; import ancienttiles.tiles.ai.TimedObject; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import java.util.Collection; import java.util.HashSet; import java.util.Set; import javax.swing.ActionMap; import javax.swing.InputMap; import javax.swing.Timer; import javax.swing.event.MouseInputAdapter; /** * * @author krr428 */ public abstract class AbstractGameManager { private AbstractMapManager mapManager = null; private HumIntManager humanIntelligenceManager = null; private AbstractAIManager aiManager = null; private ViewManager viewManager = null; private AbstractTimingManager timingManager = null; private AbstractInputManager inputManager = null; //<editor-fold defaultstate="collapsed" desc="Field Gets/Sets"> public AbstractMapManager getMapManager() { return mapManager; } protected void setMapManager(AbstractMapManager mapManager) { this.mapManager = mapManager; } public HumIntManager getHIManager() { return humanIntelligenceManager; } protected void setHIManager(HumIntManager humanIntelligenceManager) { this.humanIntelligenceManager = humanIntelligenceManager; } public AbstractAIManager getAIManager() { return aiManager; } protected void setAIManager(AbstractAIManager aiManager) { this.aiManager = aiManager; } public ViewManager getViewManager() { return viewManager; } protected void setViewManager(ViewManager viewManager) { this.viewManager = viewManager; } public AbstractTimingManager getTimingManager() { return timingManager; } protected void setTimingManager(AbstractTimingManager timingManager) { this.timingManager = timingManager; } public AbstractInputManager getInputManager() { return inputManager; } protected void setInputManager(AbstractInputManager inputManager) { this.inputManager = inputManager; } //</editor-fold> // This method provided for convenience and compatibility. public LayerStack getCurrentMap() { return getMapManager().getCurrent(); } public interface MapChangedListener { public void mapChanged(); } public abstract class AbstractMapManager { //<editor-fold defaultstate="collapsed" desc="MapChangedEvent"> private Set<MapChangedListener> mapChangedListeners = null; public AbstractMapManager() { mapChangedListeners = new HashSet<MapChangedListener>(); } public void addMapChangedListener(MapChangedListener mcl) { mapChangedListeners.add(mcl); } public void removeMapChangedListener(MapChangedListener mcl) { mapChangedListeners.remove(mcl); } public void fireMapChanged() { for (MapChangedListener mcl: mapChangedListeners) { mcl.mapChanged(); } getViewManager().setUpdateOn(); } //</editor-fold> public abstract LayerStack getCurrent(); public abstract LayerStack getMap(String name); public abstract void addMap(String name, LayerStack map); public abstract void setCurrentMap(String name); public abstract void setCurrentMap(LayerStack ls); public abstract Collection<Tile> getCurTiles(int x, int y); public abstract void resetCurrent(); public abstract void loadMap(URL location, int width, int height); public abstract void loadMap(URL location); public abstract void loadParent(); // @Deprecated // public void initTimedObjects() // { // getAIManager().initTimedObjects(); // } } public class HumIntManager { private HumanIntelligence humanIntelligence = null; public HumanIntelligence getHI() { return humanIntelligence; } void setHI(HumanIntelligence hi) { this.humanIntelligence = hi; this.humanIntelligence.setManager(AbstractGameManager.this); } } public abstract class AbstractAIManager { public abstract void killTimedObjects(); public abstract void initTimedObjects(); } public abstract class AbstractInputManager { protected InputMap inputMap = null; protected ActionMap actionMap = null; public AbstractInputManager() { } public AbstractInputManager(InputMap im, ActionMap am) { setActionMap(am); setInputMap(im); } public AbstractInputManager(AbstractInputManager formerManager) { this(formerManager.getInputMap(), formerManager.getActionMap()); } public InputMap getInputMap() { return inputMap; } public final void setInputMap(InputMap inputMap) { this.inputMap = inputMap; } public ActionMap getActionMap() { return actionMap; } public final void setActionMap(ActionMap actionMap) { this.actionMap = actionMap; } public abstract void init(); //Called when the //public abstract void bindKeys(); public abstract MouseInputAdapter getMouseInputAdapter(); } public class ViewManager implements ActionListener { private TileDisplay view = null; private Timer paintTimer = null; private boolean updateViewFlag = true; public ViewManager(TileDisplay td) { this.setDisplay(td); //Set to 1000ms / 40 frames per second. paintTimer = new Timer(1000/60, this); paintTimer.start(); } public void setUpdateOn() { updateViewFlag = true; } public TileDisplay getView() { return view; } public final void setDisplay(TileDisplay td) { view = td; } @Override public void actionPerformed(ActionEvent e) { if (view != null && updateViewFlag) { view.repaint(); updateViewFlag = false; } } } public abstract class AbstractTimingManager { public abstract void addListener(String timer, TimedObject t); public abstract void removeListener(String timer, TimedObject t); public abstract void createTimer(String name, int interval); public abstract void pauseTimer(String name); public abstract void removeTimer(String name); public abstract boolean containsTimer(String name); } }
krrg/ancient-tiles-java
src/ancienttiles/AbstractGameManager.java
Java
gpl-3.0
7,396
<?php /** * Extensions list template * * @package notification */ $premium_extensions = (array) $this->get_var( 'premium_extensions' ); ?> <div class="wrap notification-extensions"> <h1><?php esc_html_e( 'Extensions', 'notification' ); ?></h1> <?php if ( ! empty( $premium_extensions ) ) : ?> <h2><?php esc_html_e( 'Premium extensions', 'notification' ); ?></h2> <div id="the-list"> <?php foreach ( $premium_extensions as $extension ) : ?> <?php $this->set_var( 'extension', $extension, true ); $this->get_view( 'extension/extension-box-premium' ); ?> <?php endforeach; ?> </div> <div class="clear"></div> <?php endif ?> <?php if ( ! empty( $premium_extensions ) ) : ?> <h2><?php esc_html_e( 'Available extensions', 'notification' ); ?></h2> <?php endif ?> <div id="the-list"> <?php foreach ( (array) $this->get_var( 'extensions' ) as $extension ) : ?> <?php $this->set_var( 'extension', $extension, true ); $this->get_view( 'extension/extension-box' ); ?> <?php endforeach; ?> <?php $this->get_view( 'extension/promo-box' ); ?> </div> </div>
Kubitomakita/Notification
views/extension/page.php
PHP
gpl-3.0
1,120
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ /** * The "jobs" collection of methods. * Typical usage is: * <code> * $dataprocService = new Google_Service_Dataproc(...); * $jobs = $dataprocService->jobs; * </code> */ class Google_Service_Dataproc_Resource_ProjectsRegionsJobs extends Google_Service_Resource { /** * Starts a job cancellation request. To access the job resource after * cancellation, call regions/{region}/jobs.list or regions/{region}/jobs.get. * (jobs.cancel) * * @param string $projectId Required. The ID of the Google Cloud Platform * project that the job belongs to. * @param string $region Required. The Cloud Dataproc region in which to handle * the request. * @param string $jobId Required. The job ID. * @param Google_Service_Dataproc_CancelJobRequest $postBody * @param array $optParams Optional parameters. * @return Google_Service_Dataproc_Job */ public function cancel($projectId, $region, $jobId, Google_Service_Dataproc_CancelJobRequest $postBody, $optParams = array()) { $params = array('projectId' => $projectId, 'region' => $region, 'jobId' => $jobId, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('cancel', array($params), "Google_Service_Dataproc_Job"); } /** * Deletes the job from the project. If the job is active, the delete fails, and * the response returns FAILED_PRECONDITION. (jobs.delete) * * @param string $projectId Required. The ID of the Google Cloud Platform * project that the job belongs to. * @param string $region Required. The Cloud Dataproc region in which to handle * the request. * @param string $jobId Required. The job ID. * @param array $optParams Optional parameters. * @return Google_Service_Dataproc_DataprocEmpty */ public function delete($projectId, $region, $jobId, $optParams = array()) { $params = array('projectId' => $projectId, 'region' => $region, 'jobId' => $jobId); $params = array_merge($params, $optParams); return $this->call('delete', array($params), "Google_Service_Dataproc_DataprocEmpty"); } /** * Gets the resource representation for a job in a project. (jobs.get) * * @param string $projectId Required. The ID of the Google Cloud Platform * project that the job belongs to. * @param string $region Required. The Cloud Dataproc region in which to handle * the request. * @param string $jobId Required. The job ID. * @param array $optParams Optional parameters. * @return Google_Service_Dataproc_Job */ public function get($projectId, $region, $jobId, $optParams = array()) { $params = array('projectId' => $projectId, 'region' => $region, 'jobId' => $jobId); $params = array_merge($params, $optParams); return $this->call('get', array($params), "Google_Service_Dataproc_Job"); } /** * Lists regions/{region}/jobs in a project. (jobs.listProjectsRegionsJobs) * * @param string $projectId Required. The ID of the Google Cloud Platform * project that the job belongs to. * @param string $region Required. The Cloud Dataproc region in which to handle * the request. * @param array $optParams Optional parameters. * * @opt_param string filter Optional. A filter constraining the jobs to list. * Filters are case-sensitive and have the following syntax:field = value AND * field = value ...where field is status.state or labels.[KEY], and [KEY] is a * label key. value can be * to match all values. status.state can be either * ACTIVE or INACTIVE. Only the logical AND operator is supported; space- * separated items are treated as having an implicit AND operator.Example * filter:status.state = ACTIVE AND labels.env = staging AND labels.starred = * * @opt_param string jobStateMatcher Optional. Specifies enumerated categories * of jobs to list (default = match ALL jobs). * @opt_param string pageToken Optional. The page token, returned by a previous * call, to request the next page of results. * @opt_param int pageSize Optional. The number of results to return in each * response. * @opt_param string clusterName Optional. If set, the returned jobs list * includes only jobs that were submitted to the named cluster. * @return Google_Service_Dataproc_ListJobsResponse */ public function listProjectsRegionsJobs($projectId, $region, $optParams = array()) { $params = array('projectId' => $projectId, 'region' => $region); $params = array_merge($params, $optParams); return $this->call('list', array($params), "Google_Service_Dataproc_ListJobsResponse"); } /** * Updates a job in a project. (jobs.patch) * * @param string $projectId Required. The ID of the Google Cloud Platform * project that the job belongs to. * @param string $region Required. The Cloud Dataproc region in which to handle * the request. * @param string $jobId Required. The job ID. * @param Google_Service_Dataproc_Job $postBody * @param array $optParams Optional parameters. * * @opt_param string updateMask Required. Specifies the path, relative to Job, * of the field to update. For example, to update the labels of a Job the * update_mask parameter would be specified as labels, and the PATCH request * body would specify the new value. Note: Currently, labels is the only field * that can be updated. * @return Google_Service_Dataproc_Job */ public function patch($projectId, $region, $jobId, Google_Service_Dataproc_Job $postBody, $optParams = array()) { $params = array('projectId' => $projectId, 'region' => $region, 'jobId' => $jobId, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('patch', array($params), "Google_Service_Dataproc_Job"); } /** * Submits a job to a cluster. (jobs.submit) * * @param string $projectId Required. The ID of the Google Cloud Platform * project that the job belongs to. * @param string $region Required. The Cloud Dataproc region in which to handle * the request. * @param Google_Service_Dataproc_SubmitJobRequest $postBody * @param array $optParams Optional parameters. * @return Google_Service_Dataproc_Job */ public function submit($projectId, $region, Google_Service_Dataproc_SubmitJobRequest $postBody, $optParams = array()) { $params = array('projectId' => $projectId, 'region' => $region, 'postBody' => $postBody); $params = array_merge($params, $optParams); return $this->call('submit', array($params), "Google_Service_Dataproc_Job"); } }
dannydes/ecologie
vendor/google/apiclient-services/src/Google/Service/Dataproc/Resource/ProjectsRegionsJobs.php
PHP
gpl-3.0
7,165
/* Copyright (c) 2009 Andrew Caudwell (acaudwell@gmail.com) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "seeklog.h" long gSeekLogMaxBufferSize = 104857600; //StreamLog StreamLog::StreamLog() { this->stream = &std::cin; fcntl_fail = false; #ifdef _WIN32 stdin_handle = GetStdHandle(STD_INPUT_HANDLE); #else int ret = fcntl(STDIN_FILENO, F_GETFL, 0); if (fcntl (STDIN_FILENO, F_SETFL, ret | O_NONBLOCK) < 0) { debugLog("fcntl(stdin) failed\n"); fcntl_fail = true; } #endif } StreamLog::~StreamLog() { } bool StreamLog::getNextLine(std::string& line) { //try and fix the stream if(isFinished()) stream->clear(); #ifdef _WIN32 DWORD available_bytes; if (!PeekNamedPipe(stdin_handle, 0, 0, 0, &available_bytes, 0)) return false; if(available_bytes==0) return false; #endif std::getline(*stream, line); //remove carriage returns if (line.size() > 0 && line[line.size()-1] == '\r') { line.resize(line.size() - 1); } if(isFinished()) { return false; } return true; } bool StreamLog::isFinished() { if(fcntl_fail || stream->fail() || stream->eof()) { return true; } return false; } // SeekLog SeekLog::SeekLog(std::string logfile) { this->logfile = logfile; this->stream = 0; if(!readFully()) { throw SeekLogException(logfile); } } bool SeekLog::readFully() { if(stream!=0) delete stream; std::ifstream* file = new std::ifstream(logfile.c_str(), std::ios::in | std::ios::binary | std::ios::ate); file_size = file->tellg(); if(!file->is_open()) return false; file->seekg (0, std::ios::beg); //dont load into memory if larger than if(file_size > gSeekLogMaxBufferSize) { stream = file; return true; } //buffer entire file into memory char* filebuffer = new char[file_size+1]; if(!file->read(filebuffer, file_size)) { file->close(); delete file; return false; } filebuffer[file_size] = '\0'; file->close(); delete file; stream = new std::istringstream(std::string(filebuffer)); delete[] filebuffer; return true; } SeekLog::~SeekLog() { if(stream!=0) delete stream; } float SeekLog::getPercent() { return current_percent; } void SeekLog::setPointer(std::streampos pointer) { stream->seekg(pointer); } std::streampos SeekLog::getPointer() { return stream->tellg(); } void SeekLog::seekTo(float percent) { if(isFinished()) stream->clear(); std::streampos mem_offset = (std::streampos) (percent * file_size); setPointer(mem_offset); //throw away end of line if(mem_offset != (std::streampos)0) { std::string eol; getNextLine(eol); } } bool SeekLog::getNextLine(std::string& line) { //try and fix the stream if(isFinished()) stream->clear(); std::getline(*stream, line); //remove carriage returns if (line.size() > 0 && line[line.size()-1] == '\r') { line.resize(line.size() - 1); } if(stream->fail()) { return false; } current_percent = (float) stream->tellg() / file_size; //debugLog("current_percent = %.2f\n", current_percent); return true; } // temporarily move the file pointer to get a line somewhere else in the file bool SeekLog::getNextLineAt(std::string& line, float percent) { stream->clear(); std::streampos currpointer = getPointer(); seekTo(percent); bool success = getNextLine(line); stream->clear(); //set the pointer back setPointer(currpointer); return success; } bool SeekLog::isFinished() { bool finished = false; if(stream->fail() || stream->eof()) { debugLog("stream is finished\n"); finished=true; } return finished; }
dos1/Logstalgia
src/core/seeklog.cpp
C++
gpl-3.0
5,269
namespace InsuranceSystem.BLL.Services.Catalogs { using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using DTO.Catalogs; using Interfaces; using Interfaces.Catalogs; using Library.Models.Catalogs; using UnitOfWork; using UnitOfWork.Catalogs; using static Validation.CheckValues; using InsuranceSystem.BLL.Infrastructure; public class BankAccountService : IBankAccountService { readonly AutoMapperConfig autoMapperConfig; readonly IUnitOfWork<BankAccount> bankAccountUnit; public BankAccountService() { autoMapperConfig = AutoMapperConfig.Instance; bankAccountUnit = new BankAccountUnit(); } public int Delete(BankAccountDTO entity) { CheckForNull(entity); bankAccountUnit.Repository.Delete(entity.Id); return bankAccountUnit.Commit(); } public int Delete(int? id) { CheckForNull(id); bankAccountUnit.Repository.Delete((int)id); return bankAccountUnit.Commit(); } public async Task<int> DeleteAsync(BankAccountDTO entity) { CheckForNull(entity); bankAccountUnit.Repository.Delete(entity.Id); return await bankAccountUnit.CommitAsync(); } public async Task<int> DeleteAsync(int? id) { CheckForNull(id); bankAccountUnit.Repository.Delete((int)id); return await bankAccountUnit.CommitAsync(); } public void Dispose() { bankAccountUnit.Dispose(); } public IEnumerable<BankAccountDTO> GetAll() { return Mapper.Map<IEnumerable<BankAccount>, IEnumerable<BankAccountDTO>>( bankAccountUnit.Repository.GetAll()); } public async Task<List<BankAccountDTO>> GetAllAsync() { return Mapper.Map<List<BankAccount>, List<BankAccountDTO>>(await bankAccountUnit.Repository.GetAllAsync()); } public async Task<List<BankAccountDTO>> GetByAccountNumberAsync(string number) { return Mapper.Map<List<BankAccount>, List<BankAccountDTO>>(await bankAccountUnit.Repository.GetManyAsync(p => p.AccountNumber.Trim() == number)); } public async Task<List<BankAccountDTO>> GetByBankIdAsync(int? id) { CheckForNull(id); return Mapper.Map<List<BankAccount>, List<BankAccountDTO>>(await bankAccountUnit.Repository.GetManyAsync(p => p.BankId == (int)id)); } public async Task<List<BankAccountDTO>> GetByCloseDate(DateTime date) { CheckForNull(date); return Mapper.Map<List<BankAccount>, List<BankAccountDTO>>(await bankAccountUnit.Repository.GetManyAsync(p => p.CloseDate == date)); } public async Task<List<BankAccountDTO>> GetByCurrencyIdAsync(int? id) { CheckForNull(id); return Mapper.Map<List<BankAccount>, List<BankAccountDTO>>(await bankAccountUnit.Repository.GetManyAsync(p => p.CurrencyId == (int)id)); } public BankAccountDTO GetById(int? id) { CheckForNull(id); return Mapper.Map<BankAccount, BankAccountDTO>( bankAccountUnit.Repository.GetById((int)id)); } public async Task<BankAccountDTO> GetByIdAsync(int? id) { CheckForNull(id); return Mapper.Map<BankAccount, BankAccountDTO>(await bankAccountUnit.Repository.GetAsync(p => p.Id == id)); } public async Task<List<BankAccountDTO>> GetByOpenDate(DateTime date) { CheckForNull(date); return Mapper.Map<List<BankAccount>, List<BankAccountDTO>>(await bankAccountUnit.Repository.GetManyAsync(p => p.OpenDate == date)); } public int Insert(BankAccountDTO entity) { CheckForNull(entity); bankAccountUnit.Repository.Insert(Mapper .Map<BankAccountDTO, BankAccount>(entity)); return bankAccountUnit.Commit(); } public async Task<int> InsertAsync(BankAccountDTO entity) { CheckForNull(entity); bankAccountUnit.Repository.Insert(Mapper .Map<BankAccountDTO, BankAccount>(entity)); return await bankAccountUnit.CommitAsync(); } public int Update(BankAccountDTO entity) { CheckForNull(entity); BankAccount item = FillBankAccount(entity); bankAccountUnit.Repository.Insert(item); return bankAccountUnit.Commit(); } private BankAccount FillBankAccount(BankAccountDTO entity) { var item = bankAccountUnit.Repository.GetById(entity.Id); item.ModifiedDate = DateTime.Now; item.AccountNumber = entity.AccountNumber; item.BankId = entity.BankId; item.CloseDate = entity.CloseDate; item.CurrencyId = entity.CurrencyId; item.IsDelete = entity.IsDelete; item.IsGroup = entity.IsGroup; item.Name = entity.Name; item.OpenDate = entity.OpenDate; item.ParentId = entity.ParentId; item.PurposeOfPayment = entity.PurposeOfPayment; return item; } public async Task<int> UpdateAsync(BankAccountDTO entity) { CheckForNull(entity); BankAccount item = FillBankAccount(entity); bankAccountUnit.Repository.Insert(item); return await bankAccountUnit.CommitAsync(); } public async Task<List<BankAccountDTO>> GetByNameAsync(string name) { return Mapper.Map<List<BankAccount>, List<BankAccountDTO>>( await bankAccountUnit.Repository .GetManyAsync(p => p.Name.ToUpper().Contains(name.ToUpper()))); } } }
mishakos/InsuranceSystem.Library
InsuranceSystem.BLL/Services/Catalogs/BankAccountService.cs
C#
gpl-3.0
6,165
<?php $this->load->view('global/validasi_form'); ?> <div class='modal-body'> <div class="row"> <div class="col-sm-12"> <div class="box box-danger"> <div class="box-body"> <table class="table table-bordered table-striped table-hover" > <tbody> <tr> <td style="padding-top : 10px;padding-bottom : 10px; width:40%;" ><?= $judul_terdata_nama?></td> <td> : <?= $terdata_nama?></td> </tr> <tr> <td style="padding-top : 10px;padding-bottom : 10px; width:40%;" ><?= $judul_terdata_info?></td> <td> : <?= $terdata_info?></td> </tr> </tbody> </table> </div> </div> </div> <div class="col-sm-12"> <div class="box box-danger"> <div class="box-body"> <form id="validasi" action="<?= $form_action?>" method="POST" enctype="multipart/form-data" class="form-horizontal"> <?php include("donjo-app/views/covid19/form_isian_pemudik.php"); ?> </form> </div> </div> </div> </div> <div class="modal-footer"> <button type="reset" class="btn btn-social btn-flat btn-danger btn-sm" data-dismiss="modal"><i class='fa fa-sign-out'></i> Tutup</button> <button type="submit" class="btn btn-social btn-flat btn-info btn-sm" onclick="$('#'+'validasi').submit();"><i class="fa fa-check"></i> Simpan</button> </div> </div>
OpenSID/OpenSID
donjo-app/views/covid19/edit_pemudik.php
PHP
gpl-3.0
1,333
/* * This file is part of oclp. * * oclp is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * oclp is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with oclp. If not, see <http://www.gnu.org/licenses/>. */ #include "oclp.h" namespace cl { CommandQueue::CommandQueue (void) : queue (NULL) { } CommandQueue::CommandQueue (cl_command_queue cq) : queue (cq) { } CommandQueue::CommandQueue (const CommandQueue &cq) : queue (cq.queue) { if (queue) { clRetainCommandQueue (queue); } } CommandQueue::CommandQueue (CommandQueue &&cq) : queue (cq.queue) { cq.queue = NULL; } CommandQueue::~CommandQueue (void) { if (queue != NULL) { clReleaseCommandQueue (queue); queue = NULL; } } CommandQueue &CommandQueue::operator= (CommandQueue &&cq) { queue = cq.queue; cq.queue = NULL; } CommandQueue &CommandQueue::operator= (const CommandQueue &cq) { queue = cq.queue; if (queue) { clRetainCommandQueue (queue); } } void CommandQueue::Flush (void) { cl_int err; err = clFlush (queue); if (err != CL_SUCCESS) throw Exception ("Cannot flush an OpenCL command queue.", err); } void CommandQueue::Finish (void) { cl_int err; err = clFinish (queue); if (err != CL_SUCCESS) throw Exception ("Cannot finish an OpenCL command queue.", err); } void CommandQueue::EnqueueNDRangeKernel (const Kernel &kernel, cl_uint work_dim, const size_t *global_work_offset, const size_t *global_work_size, const size_t *local_work_size, cl_uint num_events_in_wait_list, const cl_event *event_wait_list, cl_event *event) { cl_int err; err = clEnqueueNDRangeKernel (queue, kernel.get (), work_dim, global_work_offset, global_work_size, local_work_size, num_events_in_wait_list, event_wait_list, event); if (err != CL_SUCCESS) throw Exception ("Cannot enqueue an OpenCL kernel.", err); } void CommandQueue::EnqueueAcquireGLObjects (std::vector<Memory> objects, cl_uint num_events_in_wait_list, const cl_event *event_wait_list, cl_event *event) { cl_int err; std::vector<cl_mem> objs; for (Memory &mem : objects) { objs.push_back (mem.get ()); } err = clEnqueueAcquireGLObjects (queue, objs.size (), &objs[0], num_events_in_wait_list, event_wait_list, event); if (err != CL_SUCCESS) throw Exception ("Cannot enqueue an OpenGL object acquisition to " "an OpenCL command queue.", err); } void CommandQueue::EnqueueReleaseGLObjects (std::vector<Memory> objects, cl_uint num_events_in_wait_list, const cl_event *event_wait_list, cl_event *event) { cl_int err; std::vector<cl_mem> objs; for (Memory &mem : objects) { objs.push_back (mem.get ()); } err = clEnqueueReleaseGLObjects (queue, objs.size (), &objs[0], num_events_in_wait_list, event_wait_list, event); if (err != CL_SUCCESS) throw Exception ("Cannot enqueue an OpenGL object release to " "an OpenCL command queue.", err); } void CommandQueue::EnqueueCopyBufferToImage (const Memory &src, const Memory &dst, size_t src_offset, const size_t *dst_origin, const size_t *region, cl_uint num_events_in_wait_list, const cl_event *event_wait_list, cl_event *event) { cl_int err; err = clEnqueueCopyBufferToImage (queue, src.get (), dst.get (), src_offset, dst_origin, region, num_events_in_wait_list, event_wait_list, event); if (err != CL_SUCCESS) throw Exception ("Cannot enqueue a copy operation from a bufer to" " an image.", err); } void CommandQueue::EnqueueWriteBuffer (const Memory &buffer, cl_bool blocking_write, size_t offset, size_t cb, const void *ptr, cl_uint num_events_in_wait_list, const cl_event *event_wait_list, cl_event *event) { cl_int err; err = clEnqueueWriteBuffer (queue, buffer.get (), blocking_write, offset, cb, ptr, num_events_in_wait_list, event_wait_list, event); if (err != CL_SUCCESS) throw Exception ("Cannot enqueue a buffer write operation", err); } void CommandQueue::EnqueueReadBuffer (const Memory &buffer, cl_bool blocking_read, size_t offset, size_t cb, void *ptr, cl_uint num_events_in_wait_list, const cl_event *event_wait_list, cl_event *event) { cl_int err; err = clEnqueueReadBuffer (queue, buffer.get (), blocking_read, offset, cb, ptr, num_events_in_wait_list, event_wait_list, event); if (err != CL_SUCCESS) throw Exception ("Cannot enqueue a buffer read operation", err); } cl_event CommandQueue::EnqueueMarker (void) { cl_event event; cl_int err; err = clEnqueueMarker (queue, &event); if (err != CL_SUCCESS) throw Exception ("Cannot enqueue a marker", err); return event; } void CommandQueue::EnqueueWaitForEvents (cl_uint num_events, const cl_event *event_list) { cl_int err; err = clEnqueueWaitForEvents (queue, num_events, event_list); if (err != CL_SUCCESS) throw Exception ("Cannot enqueue a wait for events", err); } void CommandQueue::EnqueueBarrier (void) { cl_int err; err = clEnqueueBarrier (queue); if (err != CL_SUCCESS) throw Exception ("Cannot enqueue a barrier operation", err); } } /* namespace cl */
ekpyron/oclp
src/commandqueue.cpp
C++
gpl-3.0
6,274
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package InterfazBasica; import java.util.ArrayList; import javax.swing.table.AbstractTableModel; /** * * @author omar */ class ModeloTablaProducto extends AbstractTableModel{ private ArrayList<Register> list = new ArrayList<Register>(); @Override public int getColumnCount() { return 3; } @Override public int getRowCount() { return list.size(); } public void addRegister(String producto, double precio, String unidad, String categoria){ list.add(new Register(producto, precio, unidad,categoria)); this.fireTableDataChanged(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { Register r = list.get(rowIndex); switch (columnIndex) { case 0: return r.producto; case 1: return r.precio; case 2: return r.unidad; case 3: return r.categoria; } return null; } void addRegister(String manzana, String string, String kg, String frutas) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } class Register{ String producto; double precio; String unidad; String categoria; public Register(String producto, double precio, String unidad,String categoria) { this.producto = producto.toUpperCase(); this.precio = precio; this.unidad = unidad; this.categoria = categoria.toUpperCase(); } } }
quincyg13/puntodeventa
InterfazBasica/InterfazBasica/InterfazBasica/src/InterfazBasica/ModeloTablaProducto.java
Java
gpl-3.0
1,813
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def invertTree(self, root: TreeNode) -> TreeNode: def recurse(node): if not node: return node node.left, node.right = recurse(node.right), recurse(node.left) return node return recurse(root)
1337/yesterday-i-learned
leetcode/226e.py
Python
gpl-3.0
474
/* * Copyright appNativa Inc. All Rights Reserved. * * This file is part of the Real-time Application Rendering Engine (RARE). * * RARE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.appnativa.rare.viewer; import javax.swing.ActionMap; import com.appnativa.rare.iConstants; import com.appnativa.rare.platform.ActionHelper; import com.appnativa.rare.platform.swing.ui.DataItemListModel; import com.appnativa.rare.platform.swing.ui.EditableListBoxListHandler; import com.appnativa.rare.platform.swing.ui.util.SwingHelper; import com.appnativa.rare.platform.swing.ui.view.ListView; import com.appnativa.rare.spot.ListBox; import com.appnativa.rare.spot.Viewer; import com.appnativa.rare.ui.Column; import com.appnativa.rare.ui.RenderableDataItem; import com.appnativa.rare.ui.ScrollPanePanel; import com.appnativa.rare.ui.iListView.EditingMode; import com.appnativa.rare.ui.iToolBar; import com.appnativa.rare.ui.event.iExpansionListener; import com.appnativa.rare.ui.renderer.ListItemRenderer; import com.appnativa.rare.widget.iWidget; /** * A widget that allows a user to select one or more choices from a * scrollable list of items. * * @author Don DeCoteau */ public class ListBoxViewer extends aListViewer { /** * Constructs a new instance */ public ListBoxViewer() { this(null); } /** * Constructs a new instance * * @param parent the parent */ public ListBoxViewer(iContainer parent) { super(parent); widgetType = WidgetType.ListBox; initiallySelectedIndex = -1; } @Override public void configure(Viewer vcfg) { configureEx((ListBox) vcfg); handleDataURL(vcfg); fireConfigureEvent(vcfg, iConstants.EVENT_CONFIGURE); } /** * Creates a new listbox widget * * @param parent the parent * @param cfg the configuration * * @return the listbox widget */ public static ListBoxViewer create(iContainer parent, ListBox cfg) { ListBoxViewer widget = new ListBoxViewer(parent); widget.configure(cfg); return widget; } @Override public void dispose() { if (!isDisposable()) { return; } super.dispose(); if (listModel != null) { listModel.dispose(); } listModel = null; } /** * Notifies the list that the contents of the specified row has changed * * @param index the index of the row that changed */ @Override public void repaintRow(int index) { if (listModel != null) { listModel.rowChanged(index); } } /** * Notifies the list that the contents of the specified row has changed * * @param item the instance of the row that changed */ @Override public void rowChanged(RenderableDataItem item) { if (listModel != null) { listModel.rowChanged(item); } } /** * Notifies the list that the contents of the specified range of rows have changed * * @param firstRow the first row * @param lastRow the last row */ @Override public void rowsChanged(int firstRow, int lastRow) { listModel.rowsChanged(firstRow, lastRow); } @Override public void setAutoSizeRowsToFit(boolean autoSize) { ListView v = (ListView) getDataView(); v.setAutoSizeRows(autoSize); } @Override public void setEditModeListener(iExpansionListener l) { ListView v = (ListView) getDataView(); v.setEditModeListener(l); } @Override public void setRowEditModeListener(iExpansionListener l) { ListView v = (ListView) getDataView(); v.setRowEditModeListener(l); } @Override public void setItemDescription(Column itemDescription) { super.setItemDescription(itemDescription); if (itemDescription != null) { ((ListView) getDataView()).getItemRenderer().setItemDescription(itemDescription); if (itemDescription.getFont() != null) { dataComponent.setFont(itemDescription.getFont()); formComponent.setFont(itemDescription.getFont()); } } } @Override public void setRowEditingWidget(iWidget widget, boolean centerVertically) { super.setRowEditingWidget(widget, centerVertically); ListView v = (ListView) getDataView(); v.setRowEditingComponent(widget.getContainerComponent(), centerVertically); } @Override public void setSelectionMode(SelectionMode selectionMode) { super.setSelectionMode(selectionMode); ListView v = (ListView) getDataView(); v.setSelectionMode(selectionMode); } @Override public void setShowLastDivider(boolean show) { ListView v = (ListView) getDataView(); v.setShowLastDivider(show); } @Override protected void createModelAndComponents(Viewer vcfg) { ListBox cfg = (ListBox) vcfg; listModel = new DataItemListModel(); ListView list = getAppContext().getComponentCreator().getList(this, cfg); ActionMap am = list.getList().getActionMap(); am.put("Rare.origSelectNextRow", am.get("selectNextRow")); am.put("Rare.origSelectPreviousRow", am.get("selectPreviousRow")); am.put("selectNextRow", ActionHelper.selectNextRow); am.put("selectPreviousRow", ActionHelper.selectPreviousRow); formComponent = dataComponent = new ScrollPanePanel(list); formComponent=SwingHelper.configureScrollPane(this,formComponent, list, cfg.getScrollPane()); list.setItemRenderer(new ListItemRenderer(list, true)); listComponent = new EditableListBoxListHandler(list, listModel); list.setListModel(listModel); iToolBar tb = createEditingToolbarIfNecessary(cfg); if (tb != null) { list.setEditModeToolBar(tb); } registerWithWidget(list.getListComponent()); } @Override protected void setEditingMode(EditingMode mode, boolean autoEnd, boolean allowSwiping) { ListView v = (ListView) getDataView(); v.setAutoEndEditing(autoEnd); v.setEditingMode(mode); v.setEditingSwipingAllowed(allowSwiping); } }
appnativa/rare
source/rare/swingx/com/appnativa/rare/viewer/ListBoxViewer.java
Java
gpl-3.0
6,719
package domain.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; /** * The Class PlaneModel. */ @Entity public class PlaneModel { /** The id. */ @Id @GeneratedValue private Integer id; /** The name. */ private String name; /** The plane maker. */ @ManyToOne(optional = false) @OnDelete(action = OnDeleteAction.CASCADE) private PlaneMaker planeMaker; /** * Gets the id. * * @return the id */ public Integer getId() { return id; } /** * Sets the id. * * @param id * the new id */ public void setId(Integer id) { this.id = id; } /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Sets the name. * * @param name * the new name */ public void setName(String name) { this.name = name; } /** * Gets the plane maker. * * @return the plane maker */ public PlaneMaker getPlaneMaker() { return planeMaker; } /** * Sets the plane maker. * * @param planeMaker * the new plane maker */ public void setPlaneMaker(PlaneMaker planeMaker) { this.planeMaker = planeMaker; } }
Maracars/POPBL5
src/domain/model/PlaneModel.java
Java
gpl-3.0
1,329
import requests import random import time user_agent_generic="Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0" # In case of providers whose request do not follow a regular pattern, you can use code here to form it ############################################################################################################ # list of affected provider_codes custom_url_list=('DK','DOP40','NIB','Here') custom_url_list = custom_url_list+tuple([x + '_NAIP' for x in ( 'AL','AR','AZ','CA','CO','CT','DE','FL','GA','IA','ID','IL', 'IN','KS','KY','LA','MA','MD','ME','MI','MN','MO','MS','MT', 'NC','ND','NE','NH','NJ','NM','NV','NY','OH','OK','OR','PA', 'RI','SC','SD','TN','TX','UT','VA','VT','WA','WI','WV','WY')]) ############################################################################################################ ############################################################################################################ # might get some session tokens here ############################################################################################################ # Denmark DK_time=time.time() DK_ticket=None def get_DK_ticket(): global DK_time, DK_ticket while DK_ticket=="loading": print(" Waiting for DK ticket to be updated.") time.sleep(3) if (not DK_ticket) or (time.time()-DK_time)>=3600: DK_ticket="loading" tmp=requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS='HIGH:!DH:!aNULL' DK_ticket=requests.get("https://sdfekort.dk/spatialmap?").content.decode().split('ticket=')[1].split("'")[0] requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS=tmp DK_time=time.time() return DK_ticket # Germany DOP40 DOP40_time=time.time() DOP40_cookie=None def get_DOP40_cookie(): global DOP40_time, DOP40_cookie while DOP40_cookie=="loading": print(" Waiting for DOP40 cookie to be updated.") time.sleep(3) if (not DOP40_cookie) or (time.time()-DOP40_time)>=3600: DOP40_cookie="loading" DOP40_cookie=requests.Session().get('https://sg.geodatenzentrum.de/web_bkg_webmap/lib/bkgwebmap-0.12.4.all.min.js?bkg_appid=4cc455dc-a595-bbcf-0d00-c1d81caab5c3').headers['Set-Cookie'].split(';')[0] DOP40_time=time.time() return DOP40_cookie # NorgeIbilder NIB_time=time.time() NIB_token=None def get_NIB_token(): global NIB_time, NIB_token while NIB_token=="loading": print(" Waiting for NIB token to be updated.") time.sleep(3) if (not NIB_token) or (time.time()-NIB_time)>=3600: NIB_token="loading" NIB_token=str(requests.get('http://www.norgeibilder.no').content).split('nibToken')[1].split("'")[1][:-1] NIB_time=time.time() return NIB_token # Here Here_time=time.time() Here_value=None def get_Here_value(): global Here_time, Here_value while Here_value=="loading": print(" Waiting for Here value to be updated.") time.sleep(3) if (not Here_value) or (time.time()-Here_time)>=10000: Here_value="loading" Here_value=str(requests.get('https://wego.here.com').content).split('aerial.maps.api.here.com/maptile/2.1')[1][:100].split('"')[4] Here_time=time.time() return Here_value ############################################################################################################ def custom_wms_request(bbox,width,height,provider): if provider['code']=='DK': (xmin,ymax,xmax,ymin)=bbox bbox_string=str(xmin)+','+str(ymin)+','+str(xmax)+','+str(ymax) url="http://kortforsyningen.kms.dk/orto_foraar?TICKET="+get_DK_ticket()+"&SERVICE=WMS&VERSION=1.1.1&FORMAT=image/jpeg&REQUEST=GetMap&LAYERS=orto_foraar&STYLES=&SRS=EPSG:3857&WIDTH="+str(width)+"&HEIGHT="+str(height)+"&BBOX="+bbox_string return (url,None) elif provider['code']=='DOP40': (xmin,ymax,xmax,ymin)=bbox bbox_string=str(xmin)+','+str(ymin)+','+str(xmax)+','+str(ymax) url="http://sg.geodatenzentrum.de/wms_dop40?&SERVICE=WMS&VERSION=1.1.1&FORMAT=image/jpeg&REQUEST=GetMap&LAYERS=rgb&STYLES=&SRS=EPSG:25832&WIDTH="+str(width)+"&HEIGHT="+str(height)+"&BBOX="+bbox_string fake_headers={'User-Agent':user_agent_generic,'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','Connection':'keep-alive','Accept-Encoding':'gzip, deflate','Cookie':get_DOP40_cookie(),'Referer':'http://sg.geodatenzentrum.de/web_bkg_webmap/applications/dop/dop_viewer.html'} return (url,fake_headers) elif '_NAIP' in provider['code']: (xmin,ymax,xmax,ymin)=bbox url="https://gis.apfo.usda.gov/arcgis/rest/services/NAIP_Historical/"+provider['code']+"/ImageServer/exportImage?f=image&bbox="+str(xmin)+"%2C"+str(ymin)+"%2C"+str(xmax)+"%2C"+str(ymax)+"&imageSR=102100&bboxSR=102100&size="+str(width)+"%2C"+str(height) return (url,None) def custom_tms_request(tilematrix,til_x,til_y,provider): if provider['code']=='NIB': NIB_token=get_NIB_token() url="http://agsservices.norgeibilder.no/arcgis/rest/services/Nibcache_UTM33_EUREF89_v2/MapServer/tile/"+str(tilematrix)+"/"+str(til_y)+"/"+str(til_x)+"?token="+NIB_token return (url,None) elif provider['code']=='Here': Here_value=get_Here_value() url="https://"+random.choice(['1','2','3','4'])+".aerial.maps.api.here.com/maptile/2.1/maptile/"+Here_value+"/satellite.day/"+str(tilematrix)+"/"+str(til_x)+"/"+str(til_y)+"/256/jpg?app_id=bC4fb9WQfCCZfkxspD4z&app_code=K2Cpd_EKDzrZb1tz0zdpeQ" return (url,None)
oscarpilote/Ortho4XP
Providers/O4_Custom_URL.py
Python
gpl-3.0
5,644
#include "chunk.h" #include "chunk_model.h" #include "voxel.h" using minecpp::Chunk; Chunk::Chunk(const ChunkLocation& location, ResourceContainer& resourceContainer) noexcept : model{std::make_unique<ChunkModel>(location, resourceContainer)}, location{location} { } Chunk::Chunk(Chunk&&) noexcept = default; Chunk::~Chunk() = default; Chunk& Chunk::operator=(Chunk&&) noexcept = default; const Chunk* Chunk::findChunk(int x, int y, int z, ptrdiff_t& index) const noexcept { if (x >= 0 && x < constants::CHUNK_WIDTH && z >= 0 && z < constants::CHUNK_WIDTH && y >= 0 && y < constants::CHUNK_HEIGHT) { index = Chunk::getVoxelIndex(x, y, z); return this; } if (x < 0) { if (neightbors.left) { return neightbors.left->findChunk(constants::CHUNK_WIDTH + x, y, z, index); } } else if (x >= constants::CHUNK_WIDTH) { if (neightbors.right) { return neightbors.right->findChunk(x - constants::CHUNK_WIDTH, y, z, index); } } if (z < 0) { if (neightbors.back) { return neightbors.back->findChunk(x, y, constants::CHUNK_WIDTH + z, index); } } else if (z >= constants::CHUNK_WIDTH) { if (neightbors.front) { return neightbors.front->findChunk(x, y, z - constants::CHUNK_WIDTH, index); } } return nullptr; } Chunk* Chunk::findChunk(int x, int y, int z, ptrdiff_t& index) noexcept { return const_cast<Chunk*>(const_cast<const Chunk*>(this)->findChunk(x, y, z, index)); } unsigned Chunk::findVoxel(int x, int y, int z) const noexcept { ptrdiff_t index; const Chunk* const chunkFound = findChunk(x, y, z, index); if (chunkFound) return *(chunkFound->voxels + index); return voxel::Types::NUM_TYPES; } unsigned Chunk::findLight(int x, int y, int z) const noexcept { ptrdiff_t index; const Chunk* const chunkFound = findChunk(x, y, z, index); if (chunkFound) return *(chunkFound->lights + index); return 0; }
jangolare/MineCPP
src/chunk.cpp
C++
gpl-3.0
2,096
#!/usr/bin/env python import argparse import errno import glob import os import subprocess import sys import zipfile dirs = ("", "entity", "entity/chest", "colormap", "blocks", "entity/shulker", "entity/bed") assets = "assets/minecraft/textures/" files = [ ("entity/chest/normal.png", assets + "entity/chest/normal.png"), ("entity/chest/normal_double.png", assets + "entity/chest/normal_double.png"), ("entity/chest/ender.png", assets + "entity/chest/ender.png"), ("entity/chest/trapped.png", assets + "entity/chest/trapped.png"), ("entity/chest/trapped_double.png", assets + "entity/chest/trapped_double.png"), ("colormap/foliage.png", assets + "colormap/foliage.png"), ("colormap/grass.png", assets + "colormap/grass.png"), ("entity/shulker/shulker_black.png", assets + "entity/shulker/shulker_black.png"), ("entity/shulker/shulker_blue.png", assets + "entity/shulker/shulker_blue.png"), ("entity/shulker/shulker_brown.png", assets + "entity/shulker/shulker_brown.png"), ("entity/shulker/shulker_cyan.png", assets + "entity/shulker/shulker_cyan.png"), ("entity/shulker/shulker_gray.png", assets + "entity/shulker/shulker_gray.png"), ("entity/shulker/shulker_green.png", assets + "entity/shulker/shulker_green.png"), ("entity/shulker/shulker_light_blue.png", assets + "entity/shulker/shulker_light_blue.png"), ("entity/shulker/shulker_lime.png", assets + "entity/shulker/shulker_lime.png"), ("entity/shulker/shulker_magenta.png", assets + "entity/shulker/shulker_magenta.png"), ("entity/shulker/shulker_orange.png", assets + "entity/shulker/shulker_orange.png"), ("entity/shulker/shulker_pink.png", assets + "entity/shulker/shulker_pink.png"), ("entity/shulker/shulker_purple.png", assets + "entity/shulker/shulker_purple.png"), ("entity/shulker/shulker_red.png", assets + "entity/shulker/shulker_red.png"), ("entity/shulker/shulker_silver.png", assets + "entity/shulker/shulker_silver.png"), ("entity/shulker/shulker_white.png", assets + "entity/shulker/shulker_white.png"), ("entity/shulker/shulker_yellow.png", assets + "entity/shulker/shulker_yellow.png"), ("entity/bed/black.png", assets + "entity/bed/black.png"), ("entity/bed/blue.png", assets + "entity/bed/blue.png"), ("entity/bed/brown.png", assets + "entity/bed/brown.png"), ("entity/bed/cyan.png", assets + "entity/bed/cyan.png"), ("entity/bed/gray.png", assets + "entity/bed/gray.png"), ("entity/bed/green.png", assets + "entity/bed/green.png"), ("entity/bed/light_blue.png", assets + "entity/bed/light_blue.png"), ("entity/bed/lime.png", assets + "entity/bed/lime.png"), ("entity/bed/magenta.png", assets + "entity/bed/magenta.png"), ("entity/bed/orange.png", assets + "entity/bed/orange.png"), ("entity/bed/pink.png", assets + "entity/bed/pink.png"), ("entity/bed/purple.png", assets + "entity/bed/purple.png"), ("entity/bed/red.png", assets + "entity/bed/red.png"), ("entity/bed/silver.png", assets + "entity/bed/silver.png"), ("entity/bed/white.png", assets + "entity/bed/white.png"), ("entity/bed/yellow.png", assets + "entity/bed/yellow.png"), ] def has_imagemagick(): try: # try to call convert command subprocess.check_output("convert") return True except subprocess.CalledProcessError: # command exited with error status, probably because we didn't specify any files to convert return True except OSError as e: # return False if command not found if e.errno == errno.ENOENT: return False raise e if __name__ == "__main__": parser = argparse.ArgumentParser(description="Extracts from a Minecraft Jar file the textures required for mapcrafter.") parser.add_argument("-f", "--force", help="forces overwriting eventually already existing textures", action="store_true") parser.add_argument("jarfile", help="the Minecraft Jar file to use", metavar="<jarfile>") parser.add_argument("outdir", help="the output texture directory", metavar="<outdir>") args = vars(parser.parse_args()) jar = zipfile.ZipFile(args["jarfile"]) for dir in dirs: if not os.path.exists(os.path.join(args["outdir"], dir)): os.mkdir(os.path.join(args["outdir"], dir)) print("Extracting block images:") found, extracted, skipped = 0, 0, 0 for info in jar.infolist(): if info.filename.startswith("assets/minecraft/textures/blocks/") and info.filename != "assets/minecraft/textures/blocks/": filename = info.filename.replace("assets/minecraft/textures/", "") # unpack only PNGs, no other files (or directory entries) if not filename.endswith(".png"): continue # make sure to not unpack subdirectories base_path = os.path.dirname(filename) if base_path != os.path.dirname("blocks/test.png"): continue filename = os.path.join(args["outdir"], filename) found += 1 if os.path.exists(filename) and not args["force"]: skipped += 1 continue fin = jar.open(info) fout = open(filename, "wb") fout.write(fin.read()) fin.close() fout.close() extracted += 1 print(" - Found %d block images." % found) print(" - Extracted %d." % extracted) print(" - Skipped %d (Use -f to force overwrite)." % skipped) print("") print("Extracting other textures:") for filename, zipname in files: try: info = jar.getinfo(zipname) filename = os.path.join(args["outdir"], filename) if os.path.exists(filename) and not args["force"]: print(" - Extracting %s ... skipped." % filename) else: fin = jar.open(info) fout = open(filename, "wb") fout.write(fin.read()) fin.close() fout.close() print(" - Extracting %s ... extracted." % filename) except KeyError: print(" - Extracting %s ... not found!" % filename) if not has_imagemagick(): print("") print("Warning: imagemagick is not installed (command 'convert' not found).") print("Install imagemagick to enable automatic texture fixes (to prevent libpng warnings).") else: for filename in glob.glob(os.path.join(args["outdir"], "blocks", "hardened_clay*.png")): if os.path.exists(filename): subprocess.check_call(["convert", "-strip", filename, filename]) filename = os.path.join(args["outdir"], "blocks", "red_sand.png") if os.path.exists(filename): subprocess.check_call(["convert", "-strip", filename, filename]) filename = os.path.join(args["outdir"], "blocks", "glass_pane_top_white.png") if os.path.exists(filename): subprocess.check_call(["convert", "-strip", filename, "-type", "TrueColorMatte", "-define", "png:color-type=6", filename])
mapcrafter/mapcrafter
src/tools/mapcrafter_textures.py
Python
gpl-3.0
6,484
(function($){ $.fn.MKNotification = function(mknOptions){ var mkn = $.extend({ 'MKMessage' : 'Default Message!', 'MKDelay' : 'None', 'MKIcon' : 'None', 'MKSound' : 'None' },mknOptions); var docHeight = $(document).height(); return this.each(function(index, element){ if(mkn.MKIcon=="None"){ var MKNotificationIcon = ""; }else{ var MKNotificationIcon = '<div id="MKNotificationIcon"><img src="'+mkn.MKIcon+'"></div>'; } if(mkn.MKSound!="None"){ function MKSound(){ var audioElement = document.createElement('audio'); audioElement.setAttribute('src', mkn.MKSound); audioElement.setAttribute('autoplay', 'autoplay'); $.get(); audioElement.addEventListener("load", function() { audioElement.play(); }, true); } } if(mkn.MKDelay=="None"){ var MKNotificationShow = $('body').append('<div id="MKNotification"><div class="MKNotification"><div id="MKNotificationText">'+MKNotificationIcon+mkn.MKMessage+'</div></div></div>'); $('body').find("#MKNotification").hide().slideDown(200); MKSound(); }else { var MKNotificationShow = $('body').append('<div id="MKNotification"><div class="MKNotification"><div id="MKNotificationText">'+MKNotificationIcon+mkn.MKMessage+'</div></div></div>'); $('body').find("#MKNotification").hide().slideDown(200); MKSound(); setTimeout(function(){ $('body').find("#MKNotification").slideUp(200, function() { $(this).remove(); } ); }, mkn.MKDelay); } }); } })(jQuery);
mustafakucuk/MKNotification
MKNotification.js
JavaScript
gpl-3.0
1,750
#include "tabuRealloc.h" #define REALLOC_AUTHOR "TEYPAZ" #define REALLOC_IDENTIFIER "S14" int main(int argc, char * argv[]) { reallocTimer timer; std::ifstream file_data; std::ifstream file_solution; std::ofstream file_result; //SRandom(0); if (argc == 1) { timer.activate_for_time_sec(300); file_data.open("model_a1_1.txt"); file_solution.open("assignment_a1_1.txt"); file_result.open("solution_a1_1"); } else { for (int i = 0; i < argc; ++i) { if (std::string(argv[i]) == "-t") { //std::cout << argv[i + 1]<<"\n"; timer.activate_for_time_sec(atof(argv[i + 1])-0.5); } else if (std::string(argv[i]) == "-p") { //std::cout << argv[i + 1]<<"\n"; file_data.open(argv[i + 1]); } else if (std::string(argv[i]) == "-i") { //std::cout << argv[i + 1]<<"\n"; file_solution.open(argv[i + 1]); } else if (std::string(argv[i]) == "-o") { //std::cout << argv[i + 1]<<"\n"; file_result.open(argv[i + 1]); } else if (std::string(argv[i]) == "-s") { //SRandom(atoi(argv[i + 1])); } else if (std::string(argv[i]) == "-name") { std::cout << REALLOC_IDENTIFIER << std::endl; } /*else if (std::string(argv[i]) == "-class") { nb_classes = atoi(argv[i + 1]); //std::cout << "nb_classes" <<nb_classes<<"\n"; } else if (std::string(argv[i]) == "-update") { update = atoi(argv[i + 1]); //std::cout << "coeff" <<coeff<<"\n"; }*/ } } if (file_solution.is_open() && file_data.is_open()) { tabuReallocInstance temp(timer); temp.loadFile(file_data); temp.loadInitialAffectation(file_solution); temp.search(file_result); file_result.close(); } return 0; }
nicoteyp/ROADEF2012-S14
src/tabuReallocMain.cpp
C++
gpl-3.0
1,695
/* MegaMek - Copyright (C) 2004,2005 Ben Mazur (bmazur@sev.org) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. */ /* * Created on Sep 25, 2004 * */ package megamek.common.weapons; import megamek.common.TechConstants; /** * @author Jay Lawson */ public class CLNL55Weapon extends NavalLaserWeapon { /** * */ private static final long serialVersionUID = 8756042527483383101L; /** * */ public CLNL55Weapon() { super(); techLevel.put(3071, TechConstants.T_CLAN_ADVANCED); this.name = "Naval Laser 55 (Clan)"; this.setInternalName(this.name); this.addLookupName("CLNL55"); this.heat = 85; this.damage = 5; this.shortRange = 13; this.mediumRange = 26; this.longRange = 39; this.extremeRange = 52; this.tonnage = 1100.0f; this.bv = 1386; this.cost = 1250000; this.shortAV = 5.5; this.medAV = 5.5; this.longAV = 5.5; this.extAV = 5.5; this.maxRange = RANGE_EXT; introDate = 2820; techLevel.put(2820, techLevel.get(3071)); availRating = new int[] { RATING_X, RATING_D, RATING_C }; techRating = RATING_D; } }
chvink/kilomek
megamek/src/megamek/common/weapons/CLNL55Weapon.java
Java
gpl-3.0
1,706
/* * This file is part of SQLDatabaseAPI (2012). * * SQLDatabaseAPI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SQLDatabaseAPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SQLDatabaseAPI. If not, see <http://www.gnu.org/licenses/>. * * Last modified: 29.12.12 15:35 */ package com.p000ison.dev.sqlapi; /** * This class represents a column. Known implementations are {@link FieldColumn} (Used to store {@link com.p000ison.dev.sqlapi.annotation.DatabaseColumn}s) * and {@link MethodColumn} (Used to store {@link com.p000ison.dev.sqlapi.annotation.DatabaseColumnSetter}s. */ public abstract class Column { protected Column() { } /** * Gets the class of the java object which represents this column * * @return The type of this column */ public abstract Class<?> getType(); /** * Gets the name of the column * * @return The name of the column */ public abstract String getName(); /** * Gets the position of the column. This can be any value above or equal 0 or -1 if the order does not matter. * * @return The position of the column in the table */ public abstract int getPosition(); /** * Gets a optional default value for this column or a empty string * * @return A optional default value */ public abstract String getDefaultValue(); /** * Gets the lenght of this column like { 5, 10 } or a empty array if there is no lenght. * * @return The lenght of the column or a empty array. */ public abstract int[] getLength(); /** * Whether this column should autoincrement * * @return Weather this column should autoincrement */ public abstract boolean isAutoIncrementing(); /** * Whether this column can be null * * @return Whether this column can be null */ public abstract boolean isNotNull(); /** * Whether this column is unique * * @return Whether this column is unique */ public abstract boolean isUnique(); /** * Sets a value for the column in the {@link TableObject}. * * @param tableObject The table object to modify * @param object The object to set the column to */ public abstract void setValue(TableObject tableObject, Object object); /** * Gets the value for the column in the {@link TableObject}. * * @param tableObject The table object * @return The value */ public abstract Object getValue(TableObject tableObject); /** * Checks if the type is serializable so we can store it in a blob * * @return Weather this type is serializable */ public boolean isSerializable() { return RegisteredTable.isSerializable(getType()); } public abstract boolean isID(); public abstract boolean isSaveInputAfterLoading(); }
maxammann/SAM
src/main/java/com/p000ison/dev/sqlapi/Column.java
Java
gpl-3.0
3,360
from database import Database import argparse class Analyzer(): ignores = ['id', 'time', 'browser_fingerprint', 'computer_fingerprint_1', "fonts"] db = Database('uniquemachine') cols = db.run_sql("SHOW COLUMNS FROM features") def __init__(self): pass def check_imgs_difference_by_str(self, str_1, str_2): """ check the differences of two gpu rendering result strs vars: str_1, str_2 return: the differences """ imgs_1 = str_1.split(',') imgs_2 = str_2.split(',') length = len(imgs_1) if len(imgs_2) != length: return "different number of imgs" imgs_1 = sorted(imgs_1, key=lambda img: int(img.split('_')[0])) imgs_2 = sorted(imgs_2, key=lambda img: int(img.split('_')[0])) res = {} for i in range(length): img_1 = imgs_1[i].split('_')[2] img_2 = imgs_2[i].split('_')[2] if img_1 != img_2: res[i] = (img_1, img_2) return res def check_fonts_difference_by_str(self, str_1, str_2): """ check the differences of two font lists vars: str_1, str_2 return: the differences """ if str_1 == None or str_2 == None: return ([], []) fonts_1 = str_1.split('_') fonts_2 = str_2.split('_') f1 = [] f2 = [] for f in fonts_1: if f not in fonts_2: f1.append(f) for f in fonts_2: if f not in fonts_1: f2.append(f) return (f1, f2) def output_diff(self, keys, values): length = len(keys) for i in range(length): print '\t'+ str(keys[i]) + ': \t' + str(values[i]) def check_difference_by_id(self, base_id, entry_id, detail): """ check the difference of two entries based on the ids vars: id1, id2, print details or not return: the array of differences """ base_entry = self.db.get_entry_by_id('features', base_id) compare_entry = self.db.get_entry_by_id('features', entry_id) length = len(base_entry) res = {} for i in range(length): if self.cols[i][0] in self.ignores: continue if base_entry[i] != compare_entry[i]: if self.cols[i][0] == 'gpuimgs': diff = self.check_imgs_difference_by_str(base_entry[i], compare_entry[i]) if len(diff) == 0: continue res[self.cols[i][0]] = diff if (detail): print self.cols[i][0] self.output_diff(diff.keys(), diff.values()) elif self.cols[i][0] == 'flashFonts': diff = self.check_fonts_difference_by_str(base_entry[i], compare_entry[i]) res[self.cols[i][0]] = diff if detail == True: print self.cols[i][0] self.output_diff([base_id, entry_id], diff) else: res[self.cols[i][0]] = [base_entry[i], compare_entry[i]] if detail == True: print self.cols[i][0] self.output_diff([base_id, entry_id], [base_entry[i], compare_entry[i]]) return res def cal_gpuimgs_distance(self, diff): return (1, "video==================================") def cal_flashFonts_distance(self, diff): return (1, len(diff[0]) + len(diff[1])) def cal_agent_distance(self, diff): return (1, "agent") def cal_distance(self, diff): dis = 0 way = "" for feature in diff: if feature == "gpuimgs": gpuimgs_change = self.cal_gpuimgs_distance(diff[feature]) dis += gpuimgs_change[0] way += gpuimgs_change[1] elif feature == "agent": agent_change = self.cal_agent_distance(diff[feature]) dis += agent_change[0] way += agent_change[1] elif feature == "flashFonts": flashFonts_change = self.cal_flashFonts_distance(diff[feature]) dis += flashFonts_change[0] way += str(flashFonts_change[1]) + " fonts ====================" elif feature == "label": dis += 0 way += diff[feature][1] else: dis += 1 way += feature way += '~~' return (dis, way) def check_difference_by_group(self, firefox_version, base_group, compare_group, detail): """ check the difference of two groups """ sql_str = "SELECT id FROM features WHERE agent like '%" + str(firefox_version) + "%' and label like '%" + base_group + "%'" base_id = self.db.run_sql(sql_str)[0][0] sql_str = "SELECT id FROM features WHERE agent like '%" + str(firefox_version) + "%' and label like '%" + compare_group + "%'" compare_id = self.db.run_sql(sql_str)[0][0] diff = self.check_difference_by_id(base_id, compare_id, detail) return diff def cal_all_distances(self, aim, detail): """ calculate the distance between aim and all other entries """ sql_str = "SELECT id FROM features" all_ids = self.db.run_sql(sql_str) length = len(all_ids) distances = [] if aim == 0: for i in range(1, length): distances.append(self.cal_all_distances(all_ids[i][0], detail)) else: for i in range(1, length): dis = self.cal_distance(self.check_difference_by_id(aim, all_ids[i][0], detail)) if dis[0] != 0: distances.append((all_ids[i][0], dis)) return distances def check_change(self): """ check if there is any changes for same cookie/ip (We can decide it later) """ sql_str = "SELECT DISTINCT(label) FROM features" all_cookies = self.db.run_sql(sql_str) num_cookies = len(all_cookies) for cookie in all_cookies: sql_str = "SELECT IP FROM features WHERE label='" + cookie[0] + "'" records = self.db.run_sql(sql_str) if len(records) > 10: print len(records) print records[0] def check_unique(self): for i in range(1, 10): print self.db.run_sql('select count(browser_fingerprint) from ( select browser_fingerprint from features GROUP BY browser_fingerprint HAVING count(*) = ' + str(i) + ' ) AS only_once'); def main(): parser = argparse.ArgumentParser() parser.add_argument("-c", "--change", action = "store_true", help = "Check if there is any change for a single computer") parser.add_argument("-g", "--group", nargs = '*', action="store", help="Input the key word of two groups") parser.add_argument("-v", "--firefox_version", type=int, action="store", help = "Input the firefox version") parser.add_argument("-a", "--all", type=int, action = "store", help = "Compare all data pairs in database") parser.add_argument("-d", "--detail", action = "store_true", help = "Compare all data pairs in database") parser.add_argument("-i", "--id", type=int, nargs = '*', action = "store", help = "Compare all data pairs in database") args = parser.parse_args() analyzer = Analyzer() analyzer.check_unique() if args.change: analyzer.check_change() elif args.all != None : distance = analyzer.cal_all_distances(args.all, args.detail) if args.all == 0: for i in distance: string = "" for j in i: string += str(j[0]) + '\t' print string else: for i in distance: print i elif args.id != None: ids = args.id diff = analyzer.check_difference_by_id(ids[0], ids[1], args.detail) distance = analyzer.cal_distance(diff) print distance else: groups = args.group firefox_version = args.firefox_version if firefox_version == None: firefox_version = 0 if groups == None: print "Please use -h to see the usage. Key words needed here" return 0 diff = analyzer.check_difference_by_group(firefox_version, groups[0], groups[1], args.detail) distance = analyzer.cal_distance(diff) print distance if __name__ == "__main__": main()
Song-Li/dynamic_fingerprinting
research/analyze/analyze.py
Python
gpl-3.0
8,676
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Brian Coca <bcoca@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = ''' module: systemd author: - "Ansible Core Team" version_added: "2.2" short_description: Manage services. description: - Controls systemd services on remote hosts. options: name: required: true description: - Name of the service. aliases: ['unit', 'service'] state: required: false default: null choices: [ 'started', 'stopped', 'restarted', 'reloaded' ] description: - C(started)/C(stopped) are idempotent actions that will not run commands unless necessary. C(restarted) will always bounce the service. C(reloaded) will always reload. enabled: required: false choices: [ "yes", "no" ] default: null description: - Whether the service should start on boot. B(At least one of state and enabled are required.) masked: required: false choices: [ "yes", "no" ] default: null description: - Whether the unit should be masked or not, a masked unit is impossible to start. daemon_reload: required: false default: no choices: [ "yes", "no" ] description: - run daemon-reload before doing any other operations, to make sure systemd has read any changes. aliases: ['daemon-reload'] user: required: false default: no choices: [ "yes", "no" ] description: - run systemctl talking to the service manager of the calling user, rather than the service manager of the system. notes: - One option other than name is required. requirements: - A system managed by systemd ''' EXAMPLES = ''' # Example action to start service httpd, if not running - systemd: state=started name=httpd # Example action to stop service cron on debian, if running - systemd: name=cron state=stopped # Example action to restart service cron on centos, in all cases, also issue daemon-reload to pick up config changes - systemd: state: restarted daemon_reload: yes name: crond # Example action to reload service httpd, in all cases - systemd: name: httpd state: reloaded # Example action to enable service httpd and ensure it is not masked - systemd: name: httpd enabled: yes masked: no # Example action to enable a timer for dnf-automatic - systemd: name: dnf-automatic.timer state: started enabled: True ''' RETURN = ''' status: description: A dictionary with the key=value pairs returned from `systemctl show` returned: success type: complex sample: { "ActiveEnterTimestamp": "Sun 2016-05-15 18:28:49 EDT", "ActiveEnterTimestampMonotonic": "8135942", "ActiveExitTimestampMonotonic": "0", "ActiveState": "active", "After": "auditd.service systemd-user-sessions.service time-sync.target systemd-journald.socket basic.target system.slice", "AllowIsolate": "no", "Before": "shutdown.target multi-user.target", "BlockIOAccounting": "no", "BlockIOWeight": "1000", "CPUAccounting": "no", "CPUSchedulingPolicy": "0", "CPUSchedulingPriority": "0", "CPUSchedulingResetOnFork": "no", "CPUShares": "1024", "CanIsolate": "no", "CanReload": "yes", "CanStart": "yes", "CanStop": "yes", "CapabilityBoundingSet": "18446744073709551615", "ConditionResult": "yes", "ConditionTimestamp": "Sun 2016-05-15 18:28:49 EDT", "ConditionTimestampMonotonic": "7902742", "Conflicts": "shutdown.target", "ControlGroup": "/system.slice/crond.service", "ControlPID": "0", "DefaultDependencies": "yes", "Delegate": "no", "Description": "Command Scheduler", "DevicePolicy": "auto", "EnvironmentFile": "/etc/sysconfig/crond (ignore_errors=no)", "ExecMainCode": "0", "ExecMainExitTimestampMonotonic": "0", "ExecMainPID": "595", "ExecMainStartTimestamp": "Sun 2016-05-15 18:28:49 EDT", "ExecMainStartTimestampMonotonic": "8134990", "ExecMainStatus": "0", "ExecReload": "{ path=/bin/kill ; argv[]=/bin/kill -HUP $MAINPID ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", "ExecStart": "{ path=/usr/sbin/crond ; argv[]=/usr/sbin/crond -n $CRONDARGS ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", "FragmentPath": "/usr/lib/systemd/system/crond.service", "GuessMainPID": "yes", "IOScheduling": "0", "Id": "crond.service", "IgnoreOnIsolate": "no", "IgnoreOnSnapshot": "no", "IgnoreSIGPIPE": "yes", "InactiveEnterTimestampMonotonic": "0", "InactiveExitTimestamp": "Sun 2016-05-15 18:28:49 EDT", "InactiveExitTimestampMonotonic": "8135942", "JobTimeoutUSec": "0", "KillMode": "process", "KillSignal": "15", "LimitAS": "18446744073709551615", "LimitCORE": "18446744073709551615", "LimitCPU": "18446744073709551615", "LimitDATA": "18446744073709551615", "LimitFSIZE": "18446744073709551615", "LimitLOCKS": "18446744073709551615", "LimitMEMLOCK": "65536", "LimitMSGQUEUE": "819200", "LimitNICE": "0", "LimitNOFILE": "4096", "LimitNPROC": "3902", "LimitRSS": "18446744073709551615", "LimitRTPRIO": "0", "LimitRTTIME": "18446744073709551615", "LimitSIGPENDING": "3902", "LimitSTACK": "18446744073709551615", "LoadState": "loaded", "MainPID": "595", "MemoryAccounting": "no", "MemoryLimit": "18446744073709551615", "MountFlags": "0", "Names": "crond.service", "NeedDaemonReload": "no", "Nice": "0", "NoNewPrivileges": "no", "NonBlocking": "no", "NotifyAccess": "none", "OOMScoreAdjust": "0", "OnFailureIsolate": "no", "PermissionsStartOnly": "no", "PrivateNetwork": "no", "PrivateTmp": "no", "RefuseManualStart": "no", "RefuseManualStop": "no", "RemainAfterExit": "no", "Requires": "basic.target", "Restart": "no", "RestartUSec": "100ms", "Result": "success", "RootDirectoryStartOnly": "no", "SameProcessGroup": "no", "SecureBits": "0", "SendSIGHUP": "no", "SendSIGKILL": "yes", "Slice": "system.slice", "StandardError": "inherit", "StandardInput": "null", "StandardOutput": "journal", "StartLimitAction": "none", "StartLimitBurst": "5", "StartLimitInterval": "10000000", "StatusErrno": "0", "StopWhenUnneeded": "no", "SubState": "running", "SyslogLevelPrefix": "yes", "SyslogPriority": "30", "TTYReset": "no", "TTYVHangup": "no", "TTYVTDisallocate": "no", "TimeoutStartUSec": "1min 30s", "TimeoutStopUSec": "1min 30s", "TimerSlackNSec": "50000", "Transient": "no", "Type": "simple", "UMask": "0022", "UnitFileState": "enabled", "WantedBy": "multi-user.target", "Wants": "system.slice", "WatchdogTimestampMonotonic": "0", "WatchdogUSec": "0", } ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.service import sysv_exists, sysv_is_enabled, fail_if_missing from ansible.module_utils._text import to_native # =========================================== # Main control flow def main(): # initialize module = AnsibleModule( argument_spec = dict( name = dict(required=True, type='str', aliases=['unit', 'service']), state = dict(choices=[ 'started', 'stopped', 'restarted', 'reloaded'], type='str'), enabled = dict(type='bool'), masked = dict(type='bool'), daemon_reload= dict(type='bool', default=False, aliases=['daemon-reload']), user= dict(type='bool', default=False), ), supports_check_mode=True, required_one_of=[['state', 'enabled', 'masked', 'daemon_reload']], ) systemctl = module.get_bin_path('systemctl') if module.params['user']: systemctl = systemctl + " --user" unit = module.params['name'] rc = 0 out = err = '' result = { 'name': unit, 'changed': False, 'status': {}, 'warnings': [], } # Run daemon-reload first, if requested if module.params['daemon_reload']: (rc, out, err) = module.run_command("%s daemon-reload" % (systemctl)) if rc != 0: module.fail_json(msg='failure %d during daemon-reload: %s' % (rc, err)) # check service data (rc, out, err) = module.run_command("%s show '%s'" % (systemctl, unit)) if rc != 0: module.fail_json(msg='failure %d running systemctl show for %r: %s' % (rc, unit, err)) found = False is_initd = sysv_exists(unit) is_systemd = False # load return of systemctl show into dictionary for easy access and return multival = [] if out: k = None for line in to_native(out).split('\n'): # systemd can have multiline values delimited with {} if line.strip(): if k is None: if '=' in line: k,v = line.split('=', 1) if v.lstrip().startswith('{'): if not v.rstrip().endswith('}'): multival.append(line) continue result['status'][k] = v.strip() k = None else: if line.rstrip().endswith('}'): result['status'][k] = '\n'.join(multival).strip() multival = [] k = None else: multival.append(line) is_systemd = 'LoadState' in result['status'] and result['status']['LoadState'] != 'not-found' # Check for loading error if is_systemd and 'LoadError' in result['status']: module.fail_json(msg="Error loading unit file '%s': %s" % (unit, result['status']['LoadError'])) # Does service exist? found = is_systemd or is_initd if is_initd and not is_systemd: result['warnings'].append('The service (%s) is actually an init script but the system is managed by systemd' % unit) # mask/unmask the service, if requested, can operate on services before they are installed if module.params['masked'] is not None: # state is not masked unless systemd affirms otherwise masked = ('LoadState' in result['status'] and result['status']['LoadState'] == 'masked') if masked != module.params['masked']: result['changed'] = True if module.params['masked']: action = 'mask' else: action = 'unmask' if not module.check_mode: (rc, out, err) = module.run_command("%s %s '%s'" % (systemctl, action, unit)) if rc != 0: # some versions of system CAN mask/unmask non existing services, we only fail on missing if they don't fail_if_missing(module, found, unit, "cannot %s" % (action)) module.fail_json(msg="Unable to %s service %s: %s" % (action, unit, err)) # Enable/disable service startup at boot if requested if module.params['enabled'] is not None: if module.params['enabled']: action = 'enable' else: action = 'disable' fail_if_missing(module, found, unit, "cannot %s" % (action)) # do we need to enable the service? enabled = False (rc, out, err) = module.run_command("%s is-enabled '%s'" % (systemctl, unit)) # check systemctl result or if it is a init script if rc == 0: enabled = True elif rc == 1: # if both init script and unit file exist stdout should have enabled/disabled, otherwise use rc entries if is_initd and (not out.startswith('disabled') or sysv_is_enabled(unit)): enabled = True # default to current state result['enabled'] = enabled # Change enable/disable if needed if enabled != module.params['enabled']: result['changed'] = True if not module.check_mode: (rc, out, err) = module.run_command("%s %s '%s'" % (systemctl, action, unit)) if rc != 0: module.fail_json(msg="Unable to %s service %s: %s" % (action, unit, out + err)) result['enabled'] = not enabled # set service state if requested if module.params['state'] is not None: fail_if_missing(module, found, unit, "cannot check nor set state") # default to desired state result['state'] = module.params['state'] # What is current service state? if 'ActiveState' in result['status']: action = None if module.params['state'] == 'started': if result['status']['ActiveState'] != 'active': action = 'start' elif module.params['state'] == 'stopped': if result['status']['ActiveState'] == 'active': action = 'stop' else: action = module.params['state'][:-2] # remove 'ed' from restarted/reloaded result['state'] = 'started' if action: result['changed'] = True if not module.check_mode: (rc, out, err) = module.run_command("%s %s '%s'" % (systemctl, action, unit)) if rc != 0: module.fail_json(msg="Unable to %s service %s: %s" % (action, unit, err)) else: # this should not happen? module.fail_json(msg="Service is in unknown state", status=result['status']) module.exit_json(**result) if __name__ == '__main__': main()
jtyr/ansible-modules-core
system/systemd.py
Python
gpl-3.0
15,567
// Mantid Repository : https://github.com/mantidproject/mantid // // Copyright &copy; 2018 ISIS Rutherford Appleton Laboratory UKRI, // NScD Oak Ridge National Laboratory, European Spallation Source // & Institut Laue - Langevin // SPDX - License - Identifier: GPL - 3.0 + //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #include "MantidAlgorithms/ConvertTableToMatrixWorkspace.h" #include "MantidAPI/Axis.h" #include "MantidAPI/ITableWorkspace.h" #include "MantidAPI/MatrixWorkspace.h" #include "MantidDataObjects/Workspace2D.h" #include "MantidDataObjects/WorkspaceCreation.h" #include "MantidKernel/MandatoryValidator.h" #include "MantidKernel/Unit.h" #include "MantidKernel/UnitFactory.h" namespace Mantid { namespace Algorithms { // Register the algorithm into the AlgorithmFactory DECLARE_ALGORITHM(ConvertTableToMatrixWorkspace) using namespace Kernel; using namespace API; using namespace HistogramData; using namespace DataObjects; void ConvertTableToMatrixWorkspace::init() { declareProperty(make_unique<WorkspaceProperty<API::ITableWorkspace>>( "InputWorkspace", "", Direction::Input), "An input TableWorkspace."); declareProperty(make_unique<WorkspaceProperty<>>("OutputWorkspace", "", Direction::Output), "An output Workspace2D."); declareProperty("ColumnX", "", boost::make_shared<MandatoryValidator<std::string>>(), "The column name for the X vector."); declareProperty("ColumnY", "", boost::make_shared<MandatoryValidator<std::string>>(), "The column name for the Y vector."); declareProperty("ColumnE", "", "The column name for the E vector (optional)."); } void ConvertTableToMatrixWorkspace::exec() { ITableWorkspace_const_sptr inputWorkspace = getProperty("InputWorkspace"); std::string columnX = getProperty("ColumnX"); std::string columnY = getProperty("ColumnY"); std::string columnE = getProperty("ColumnE"); size_t nrows = inputWorkspace->rowCount(); if (nrows == 0) { throw std::runtime_error("The input table is empty"); } auto X = inputWorkspace->getColumn(columnX)->numeric_fill<>(); auto Y = inputWorkspace->getColumn(columnY)->numeric_fill<>(); MatrixWorkspace_sptr outputWorkspace = create<Workspace2D>(1, Points(nrows)); outputWorkspace->mutableX(0).assign(X.begin(), X.end()); outputWorkspace->mutableY(0).assign(Y.begin(), Y.end()); if (!columnE.empty()) { outputWorkspace->mutableE(0) = inputWorkspace->getColumn(columnE)->numeric_fill<>(); } auto labelX = boost::dynamic_pointer_cast<Units::Label>( UnitFactory::Instance().create("Label")); labelX->setLabel(columnX); outputWorkspace->getAxis(0)->unit() = labelX; outputWorkspace->setYUnitLabel(columnY); setProperty("OutputWorkspace", outputWorkspace); } } // namespace Algorithms } // namespace Mantid
mganeva/mantid
Framework/Algorithms/src/ConvertTableToMatrixWorkspace.cpp
C++
gpl-3.0
3,092
#!./python_link # -*- coding: utf-8 -*- ################################################################################ # DChars-FE Copyright (C) 2008 Xavier Faure # Contact: faure dot epistulam dot mihi dot scripsisti at orange dot fr # # This file is part of DChars-FE. # DChars-FE is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # DChars-FE is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with DChars-FE. If not, see <http://www.gnu.org/licenses/>. ################################################################################ """ ❏DChars-FE❏ config_ini.py """ import configparser, os, codecs CONFIG_INI = None #/////////////////////////////////////////////////////////////////////////////// def read_configuration_file(): """ function read_configuration_file() read the config.ini and return the result. """ DATA = configparser.ConfigParser() # about the following line : why not simply DATA.read( "dchars-fr", "config.ini") ? # -> once installed, DChars have to know the exact path to config.ini, # hence the following line : config_ini_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), "config.ini" ) # something's wrong with configparser : instead of simply writing # DATA.read( open(config_ini_filename, "r", encoding="utf-8") ) # we have to use this strange hack : DATA.readfp( codecs.open(config_ini_filename, "r", "utf-8") ) return DATA
suizokukan/dchars-fe
config_ini.py
Python
gpl-3.0
1,966
<?php namespace Starteed\Resources; use Starteed\BaseResource; /** * @property bool $is_keep_it_all * @property bool $is_all_or_nothing * @property string $label */ class FundingResource extends BaseResource { /** * @param array $data */ public function __construct(array $data) { $this->setData($data); } }
StarteedGroup/crowdfunding
src/Resources/FundingResource.php
PHP
gpl-3.0
352
# -*- coding: utf-8 -*- #----------------------------------------------------------------------------- # OpenModes - An eigenmode solver for open electromagnetic resonantors # Copyright (C) 2013 David Powell # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #----------------------------------------------------------------------------- import setuptools from distutils.util import get_platform import os.path as osp import os from pkg_resources import parse_version try: import numpy except ImportError: numpy_installed = False else: numpy_installed = True if not numpy_installed or (parse_version(numpy.__version__) < parse_version('1.10.0')): raise ValueError("Numpy 1.10.0 or greater required") from numpy.distutils.core import Extension, setup import platform if platform.system() == 'Darwin': os.environ["CC"] = "gcc-7" os.environ["CXX"] = "gcc-7" # Ideally would like to perform static linking under mingw32 to avoid # packaging a whole bunch of dlls. However, static linking is not supported # for the openmp libraries. ccompiler_dependent_options = { 'mingw32': { # 'extra_link_args' : ['-static'] } } # The following options are required to enable openmp to be used in the fortran # code, which is entirely compiler dependent fcompiler_dependent_options = { # gnu gfortran (including under mingw) 'gnu95': { # -O3 is most desireable, but generate NaNs under mingw32 'extra_f90_compile_args': ["-g", "-fimplicit-none", "-fopenmp", "-O3"], 'libraries': ["gomp"] }, 'intel': { # Currently ifort gives NaNs in impedance matrix derivative # on -O2, but not on -O3. To be investigated! #'extra_f90_compile_args': ['/debug', '-openmp', '-O3', '/fpe:0', '/fp:precise']#, '/traceback'], 'extra_f90_compile_args': ['-openmp', '-O2', '/fpe:0', '/fp:fast=2']#, '/traceback'], #'extra_link_args' : ['-openmp'] #'extra_f77_compile_args' : ['-openmp', '-O3'], #'extra_compile_args' : ['-openmp', '-O3', '-static'], #'extra_link_args' : ['-nodefaultlib:msvcrt'] } } # Intel fortran compiler goes by several names depending on the version # and target platform. Here the settings are all the same fcompiler_dependent_options['intelem'] = fcompiler_dependent_options['intel'] fcompiler_dependent_options['intelvem'] = fcompiler_dependent_options['intel'] core = Extension(name='openmodes.core', sources=[osp.join('src', 'core.pyf'), osp.join('src', 'common.f90'), osp.join('src', 'rwg.f90')], ) dunavant = Extension(name='openmodes.dunavant', sources=[osp.join('src', 'dunavant.pyf'), osp.join('src', 'dunavant.f90')]) from numpy.distutils.command.build_ext import build_ext class compiler_dependent_build_ext(build_ext): """A build extension which allows compiler-dependent options for compilation, linking etc. Options can depend on either the C or FORTRAN compiler which is actually used (as distinct from the default compilers, which are much easier to detect) Based on http://stackoverflow.com/a/5192738/482420 """ def build_extensions(self): ccompiler = self.compiler.compiler_type fcompiler = self._f77_compiler.compiler_type # add the compiler dependent options to each extension for extension in self.extensions: try: modification = ccompiler_dependent_options[ccompiler] for key, val in modification.items(): getattr(extension, key).extend(val) except (KeyError, AttributeError): pass try: modification = fcompiler_dependent_options[fcompiler] for key, val in modification.items(): getattr(extension, key).extend(val) except (KeyError, AttributeError): pass build_ext.build_extensions(self) # Find library files which must be included, which should be placed in the # appropriate subdirectory of the redist directory. This must be done manually, # as this code cannot detect which compiler will be used. redist_path = osp.join("redist", get_platform()) redist_data = [] if osp.exists(redist_path): redist_data.append(redist_path) try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except(IOError, ImportError): long_description = open('README.md').read() # run the script to find the version exec(open(osp.join("openmodes", "version.py")).read()) setup(name='OpenModes', description="An eigenmode solver for open electromagnetic resonantors", author="David Powell", author_email='DavidAnthonyPowell@gmail.com', license='GPLv3+', url='http://davidpowell.github.io/OpenModes', packages=setuptools.find_packages(), package_data={'openmodes': [osp.join("geometry", "*.geo"), osp.join("external", "three.js", "*"), osp.join("templates", "*"), osp.join("static", "*")]}, ext_modules=[dunavant, core], version=__version__, install_requires=['numpy >= 1.10.0', 'scipy >= 0.18.0', 'matplotlib', 'jinja2', 'six', 'ipywidgets', 'meshio', 'dill'], long_description=long_description, long_description_content_type="text/markdown", platforms="Windows, Linux", classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Science/Research', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Fortran', 'Topic :: Scientific/Engineering' ], cmdclass={'build_ext': compiler_dependent_build_ext}, # Include any required library files data_files=[('openmodes', redist_data+["RELEASE-VERSION"])] )
DavidPowell/OpenModes
setup.py
Python
gpl-3.0
7,161
# -*- coding: utf-8 -*- from time import time from module.common.json_layer import json_loads from module.plugins.Account import Account class MyfastfileCom(Account): __name__ = "MyfastfileCom" __type__ = "account" __version__ = "0.02" __description__ = """Myfastfile.com account plugin""" __license__ = "GPLv3" __authors__ = [("stickell", "l.stickell@yahoo.it")] def loadAccountInfo(self, user, req): if 'days_left' in self.json_data: validuntil = int(time() + self.json_data['days_left'] * 24 * 60 * 60) return {"premium": True, "validuntil": validuntil, "trafficleft": -1} else: self.logError(_("Unable to get account information")) def login(self, user, data, req): # Password to use is the API-Password written in http://myfastfile.com/myaccount html = req.load("http://myfastfile.com/api.php", get={"user": user, "pass": data['password']}) self.logDebug("JSON data: " + html) self.json_data = json_loads(html) if self.json_data['status'] != 'ok': self.logError(_('Invalid login. The password to use is the API-Password you find in your "My Account" page')) self.wrongPassword()
sebdelsol/pyload
module/plugins/accounts/MyfastfileCom.py
Python
gpl-3.0
1,284
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Strings for component 'qbehaviour_immediatefeedback', language 'fi', branch 'MOODLE_22_STABLE' * * @package qbehaviour_immediatefeedback * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $string['notcomplete'] = 'Kesken'; $string['pluginname'] = 'Välitön palaute';
danielbonetto/twig_MVC
lang/fi/qbehaviour_immediatefeedback.php
PHP
gpl-3.0
1,104
/* * Copyright 2014 REI Systems, Inc. * * This file is part of GovDashboard. * * GovDashboard is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GovDashboard is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GovDashboard. If not, see <http://www.gnu.org/licenses/>. */ (function(global,$,undefined) { if ( typeof $ === 'undefined' ) { throw new Error('Ext requires jQuery'); } if ( typeof global.GD === 'undefined' ) { throw new Error('Ext requires GD'); } var GD = global.GD; var DashboardSection = GD.Section.extend({ routes: ['/cp/dashboard'], name: 'dashboard', title: 'Dashboards', init: function ( options ) { this._super(options); }, getDefaultRoute: function () { return this.routes[0]; }, dispatch: function ( request ) { this._super(request); var _this = this; if ( !this.dispatched ) { $.each(this.routes,function(i,route){ var routeMatcher = new RegExp(route.replace(/:[^\s/]+/g, '([\\w-]+)')); var match = request.match(routeMatcher); if ( match ) { _this.setActive(); _this.dispatched = true; if ( request == _this.routes[0] ) { _this.renderIndex(); } return false; } }); } }, renderIndex: function () { this.messaging = new GD.MessagingView('#gd-admin-messages'); this.layoutHeader.find('.gd-section-header-left').append('<h1>Dashboard Management</h1>'); var View = new GD.DashboardListView(null, this.layoutBody, { 'section':this }); View.render(); var _this = this; GD.DashboardFactory.getDashboardList(GovdashAdmin.getActiveDatasourceName(), function ( data ) { View.loadData(data); }, function(jqXHR, textStatus, errorThrown) { _this.messaging.addErrors(jqXHR.responseText); _this.messaging.displayMessages(); $("html, body").animate({ scrollTop: 0 }, "slow"); }); } }); // add to global space global.GD.DashboardSection = DashboardSection; })(typeof window === 'undefined' ? this : window, jQuery);
REI-Systems/GovDashboard-Community
webapp/sites/all/modules/custom/dashboard/admin/js/DashboardSection.js
JavaScript
gpl-3.0
2,933
/* MicroBuild Copyright (C) 2016 TwinDrills This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "PCH.h" #include "App/Builder/Tasks/AccelerateTask.h" #include "Core/Platform/Process.h" namespace MicroBuild { AccelerateTask::AccelerateTask(ProjectFile& projectFile, std::vector<std::shared_ptr<BuildTask>>& tasks, Toolchain* toolchain, Accelerator* accelerator) : BuildTask(BuildStage::Compile, true, true, false) , m_toolchain(toolchain) , m_accelerator(accelerator) , m_tasks(tasks) , m_projectFile(projectFile) { m_subTaskCount = (int)m_tasks.size() + 1; } bool AccelerateTask::Execute() { int jobIndex = 0, totalJobs = 0; GetTaskProgress(jobIndex, totalJobs); TaskLog(LogSeverity::SilentInfo, 0, "Distributing %i tasks ...\n", m_tasks.size()); Platform::Path batchPath = m_projectFile.Get_Project_IntermediateDirectory().AppendFragment(Strings::Format("%s.sndbs.bat", m_projectFile.Get_Project_Name().c_str()), true); std::vector<BuildAction> actions; for (auto& task : m_tasks) { actions.push_back(task->GetAction()); } if (!m_accelerator->RunActions(m_toolchain, this, m_projectFile, actions)) { return false; } return true; } BuildAction AccelerateTask::GetAction() { assert(false); BuildAction action; return action; } }; // namespace MicroBuild
TwinDrills/MicroBuild
Source/MicroBuild/Source/App/Builder/Tasks/AccelerateTask.cpp
C++
gpl-3.0
1,869
<?php class ControllerToolBackup extends Controller { public function index() { $this->load->language('tool/backup'); $this->document->setTitle($this->language->get('heading_title')); $data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], true) ); $data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('tool/backup', 'user_token=' . $this->session->data['user_token'], true) ); $data['user_token'] = $this->session->data['user_token']; $this->load->model('tool/backup'); $ignore = array( DB_PREFIX . 'user', DB_PREFIX . 'user_group' ); $data['tables'] = array(); $results = $this->model_tool_backup->getTables(); foreach ($results as $result) { if (!in_array($result, $ignore)) { $data['tables'][] = $result; } } $data['header'] = $this->load->controller('common/header'); $data['column_left'] = $this->load->controller('common/column_left'); $data['footer'] = $this->load->controller('common/footer'); $this->response->setOutput($this->load->view('tool/backup', $data)); } public function history() { $this->load->language('tool/backup'); $data['histories'] = array(); $files = glob(DIR_STORAGE . 'backup/*.sql'); foreach ($files as $file) { $size = filesize($file); $i = 0; $suffix = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' ); while (($size / 1024) > 1) { $size = $size / 1024; $i++; } $data['histories'][] = array( 'filename' => basename($file), 'size' => round(substr($size, 0, strpos($size, '.') + 4), 2) . $suffix[$i], 'date_added' => date($this->language->get('datetime_format'), filemtime($file)), 'download' => $this->url->link('tool/backup/download', 'user_token=' . $this->session->data['user_token'] . '&filename=' . urlencode(basename($file)), true), ); } $this->response->setOutput($this->load->view('tool/backup_history', $data)); } public function backup() { $this->load->language('tool/backup'); $json = array(); if (isset($this->request->get['filename'])) { $filename = basename(html_entity_decode($this->request->get['filename'], ENT_QUOTES, 'UTF-8')); } else { $filename = date('Y-m-d H.i.s') . '.sql'; } if (isset($this->request->get['table'])) { $table = $this->request->get['table']; } else { $table = ''; } if (isset($this->request->post['backup'])) { $backup = $this->request->post['backup']; } else { $backup = array(); } if (isset($this->request->get['page'])) { $page = $this->request->get['page']; } else { $page = 1; } if (!$this->user->hasPermission('modify', 'tool/backup')) { $json['error'] = $this->language->get('error_permission'); } $this->load->model('tool/backup'); $allowed = $this->model_tool_backup->getTables(); if (!in_array($table, $allowed)) { $json['error'] = sprintf($this->language->get('error_table'), $table); } if (!$json) { $output = ''; if ($page == 1) { $output .= 'TRUNCATE TABLE `' . $this->db->escape($table) . '`;' . "\n\n"; } $record_total = $this->model_tool_backup->getTotalRecords($table); $results = $this->model_tool_backup->getRecords($table, ($page - 1) * 200, 200); foreach ($results as $result) { $fields = ''; foreach (array_keys($result) as $value) { $fields .= '`' . $value . '`, '; } $values = ''; foreach (array_values($result) as $value) { $value = str_replace(array("\x00", "\x0a", "\x0d", "\x1a"), array('\0', '\n', '\r', '\Z'), $value); $value = str_replace(array("\n", "\r", "\t"), array('\n', '\r', '\t'), $value); $value = str_replace('\\', '\\\\', $value); $value = str_replace('\'', '\\\'', $value); $value = str_replace('\\\n', '\n', $value); $value = str_replace('\\\r', '\r', $value); $value = str_replace('\\\t', '\t', $value); $values .= '\'' . $value . '\', '; } $output .= 'INSERT INTO `' . $table . '` (' . preg_replace('/, $/', '', $fields) . ') VALUES (' . preg_replace('/, $/', '', $values) . ');' . "\n"; } $position = array_search($table, $backup); if (($page * 200) >= $record_total) { $output .= "\n"; if (isset($backup[$position + 1])) { $table = $backup[$position + 1]; } else { $table = ''; } } if ($position) { $json['progress'] = round(($position / count($backup)) * 100); } else { $json['progress'] = 0; } $handle = fopen(DIR_STORAGE . 'backup/' . $filename, 'a'); fwrite($handle, $output); fclose($handle); if (!$table) { $json['success'] = $this->language->get('text_success'); } elseif (($page * 200) >= $record_total) { $json['text'] = sprintf($this->language->get('text_backup'), $table, ($page - 1) * 200, $record_total); $json['next'] = str_replace('&amp;', '&', $this->url->link('tool/backup/backup', 'user_token=' . $this->session->data['user_token'] . '&filename=' . urlencode($filename) . '&table=' . $table . '&page=1', true)); } else { $json['text'] = sprintf($this->language->get('text_backup'), $table, ($page - 1) * 200, $page * 200); $json['next'] = str_replace('&amp;', '&', $this->url->link('tool/backup/backup', 'user_token=' . $this->session->data['user_token'] . '&filename=' . urlencode($filename) . '&table=' . $table . '&page=' . ($page + 1), true)); } } $this->response->addHeader('Content-Type: application/json'); $this->response->setOutput(json_encode($json)); } public function restore() { $this->load->language('tool/backup'); $json = array(); if (isset($this->request->get['filename'])) { $filename = basename(html_entity_decode($this->request->get['filename'], ENT_QUOTES, 'UTF-8')); } else { $filename = ''; } if (isset($this->request->get['position'])) { $position = $this->request->get['position']; } else { $position = 0; } if (!$this->user->hasPermission('modify', 'tool/backup')) { $json['error'] = $this->language->get('error_permission'); } $file = DIR_STORAGE . 'backup/' . $filename; if (!is_file($file)) { $json['error'] = $this->language->get('error_file'); } if (!$json) { // We set $i so we can batch execute the queries rather than do them all at once. $i = 0; $start = false; $handle = fopen($file, 'r'); fseek($handle, $position, SEEK_SET); while (!feof($handle) && ($i < 100)) { $position = ftell($handle); $line = fgets($handle, 1000000); if (substr($line, 0, 14) == 'TRUNCATE TABLE' || substr($line, 0, 11) == 'INSERT INTO') { $sql = ''; $start = true; } if ($i > 0 && (substr($line, 0, 24) == 'TRUNCATE TABLE `oc_user`' || substr($line, 0, 30) == 'TRUNCATE TABLE `oc_user_group`')) { fseek($handle, $position, SEEK_SET); break; } if ($start) { $sql .= $line; } if ($start && substr($line, -2) == ";\n") { $this->db->query(substr($sql, 0, strlen($sql) -2)); $start = false; } $i++; } $position = ftell($handle); $size = filesize($file); if ($position) { $json['progress'] = round(($position / $size) * 100); } else { $json['progress'] = 0; } if ($position && !feof($handle)) { $json['text'] = sprintf($this->language->get('text_restore'), $position, $size); $json['next'] = str_replace('&amp;', '&', $this->url->link('tool/backup/restore', 'user_token=' . $this->session->data['user_token'] . '&filename=' . urlencode($filename) . '&position=' . $position, true)); fclose($handle); } else { fclose($handle); $json['success'] = $this->language->get('text_success'); $this->cache->delete('*'); } } $this->response->addHeader('Content-Type: application/json'); $this->response->setOutput(json_encode($json)); } public function upload() { $this->load->language('tool/backup'); $json = array(); // Check user has permission if (!$this->user->hasPermission('modify', 'tool/backup')) { $json['error'] = $this->language->get('error_permission'); } if (empty($this->request->files['upload']['name']) || !is_file($this->request->files['upload']['tmp_name'])) { $json['error'] = $this->language->get('error_upload'); } if (!$json) { // Sanitize the filename $filename = basename(html_entity_decode($this->request->files['upload']['name'], ENT_QUOTES, 'UTF-8')); if ((utf8_strlen($filename) < 3) || (utf8_strlen($filename) > 128)) { $json['error'] = $this->language->get('error_filename'); } // Allowed file extension types if (strtolower(substr(strrchr($filename, '.'), 1)) != 'sql') { $json['error'] = $this->language->get('error_filetype'); } } if (!$json) { $json['success'] = $this->language->get('text_success'); move_uploaded_file($this->request->files['upload']['tmp_name'], DIR_STORAGE . 'backup/' . $filename); } $this->response->addHeader('Content-Type: application/json'); $this->response->setOutput(json_encode($json)); } public function download() { $this->load->language('tool/backup'); $json = array(); if (isset($this->request->get['filename'])) { $filename = basename(html_entity_decode($this->request->get['filename'], ENT_QUOTES, 'UTF-8')); } else { $filename = ''; } // Check user has permission if (!$this->user->hasPermission('modify', 'tool/backup')) { $this->response->redirect($this->url->link('error/permission', '', true)); } $file = DIR_STORAGE . 'backup/' . $filename; if (!is_file($file)) { $this->response->redirect($this->url->link('error/not_found', '', true)); } if (!headers_sent()) { header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $filename . '"'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); if (ob_get_level()) { ob_end_clean(); } readfile($file, 'rb'); exit(); } else { exit('Error: Headers already sent out!'); } } public function delete() { $this->load->language('tool/backup'); $json = array(); if (isset($this->request->get['filename'])) { $filename = basename(html_entity_decode($this->request->get['filename'], ENT_QUOTES, 'UTF-8')); } else { $filename = ''; } // Check user has permission if (!$this->user->hasPermission('modify', 'tool/backup')) { $json['error'] = $this->language->get('error_permission'); } $file = DIR_STORAGE . 'backup/' . $filename; if (!is_file($file)) { $json['error'] = $this->language->get('error_file'); } if (!$json) { $json['success'] = $this->language->get('text_success'); unlink($file); } $this->response->addHeader('Content-Type: application/json'); $this->response->setOutput(json_encode($json)); } }
Codek365/chtd
upload/admin/controller/tool/backup.php
PHP
gpl-3.0
11,095
/*************************************************************************** * SpellbookGump.cs * Copyright (c) 2015 UltimaXNA Development Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * ***************************************************************************/ #region usings using UltimaXNA.Core.Input; using UltimaXNA.Core.UI; using UltimaXNA.Ultima.Data; using UltimaXNA.Ultima.UI.Controls; using UltimaXNA.Ultima.World; using UltimaXNA.Ultima.World.Entities.Items.Containers; #endregion namespace UltimaXNA.Ultima.UI.WorldGumps { class SpellbookGump : Gump { // ================================================================================ // Private variables // ================================================================================ SpellBook m_Spellbook; HtmlGumpling[] m_CircleHeaders; HtmlGumpling[] m_Indexes; // ================================================================================ // Private services // ================================================================================ private WorldModel m_World; // ================================================================================ // Ctor, Update, Dispose // ================================================================================ public SpellbookGump(SpellBook entity, int itemID) : base(entity.Serial, 0) { m_World = ServiceRegistry.GetService<WorldModel>(); m_Spellbook = entity; m_Spellbook.OnEntityUpdated += OnEntityUpdate; IsMoveable = true; if (m_Spellbook.BookType != SpellBookTypes.Unknown) { CreateMageryGumplings(); } else { // display a default spellbook graphic, based on the default spellbook type for this item ID. // right now, I'm just using a magery background, but really the background should change based // on the item id. AddControl(new GumpPic(this, 0, 0, 0x08AC, 0)); // other options? necro? spellweaving? } } public override void Update(double totalMS, double frameMS) { base.Update(totalMS, frameMS); } public override void Dispose() { m_Spellbook.OnEntityUpdated -= OnEntityUpdate; if (m_PageCornerLeft != null) { m_PageCornerLeft.MouseClickEvent -= PageCorner_MouseClickEvent; m_PageCornerLeft.MouseDoubleClickEvent -= PageCorner_MouseDoubleClickEvent; } if (m_PageCornerRight != null) { m_PageCornerRight.MouseClickEvent -= PageCorner_MouseClickEvent; m_PageCornerRight.MouseDoubleClickEvent -= PageCorner_MouseDoubleClickEvent; } base.Dispose(); } // ================================================================================ // OnEntityUpdate - called when spellbook entity is updated by server. // ================================================================================ private void OnEntityUpdate() { if (m_Spellbook.BookType == SpellBookTypes.Magic) CreateMageryGumplings(); } // ================================================================================ // Child control creation // The spellbook is laid out as such: // 1. A list of all spells in the book. Clicking on a spell will turn to that spell's page. // 2. One page per spell in the book. Icon, runes, reagents, etc. // ================================================================================ private GumpPic m_PageCornerLeft; private GumpPic m_PageCornerRight; private int m_MaxPage = 0; private bool m_RenderedSpellInfoPage = false; private void CreateMageryGumplings() { ClearControls(); AddControl(new GumpPic(this, 0, 0, 0x08AC, 0)); // spellbook background AddControl(m_PageCornerLeft = new GumpPic(this, 50, 8, 0x08BB, 0)); // page turn left m_PageCornerLeft.GumpLocalID = 0; m_PageCornerLeft.MouseClickEvent += PageCorner_MouseClickEvent; m_PageCornerLeft.MouseDoubleClickEvent += PageCorner_MouseDoubleClickEvent; AddControl(m_PageCornerRight = new GumpPic(this, 321, 8, 0x08BC, 0)); // page turn right m_PageCornerRight.GumpLocalID = 1; m_PageCornerRight.MouseClickEvent += PageCorner_MouseClickEvent; m_PageCornerRight.MouseDoubleClickEvent += PageCorner_MouseDoubleClickEvent; for (int i = 0; i < 4; i++) // spell circles 1 - 4 { AddControl(new GumpPic(this, 60 + i * 35, 174, 0x08B1 + i, 0)); LastControl.GumpLocalID = i; LastControl.MouseClickEvent += SpellCircle_MouseClickEvent; // unsubscribe from these? } for (int i = 0; i < 4; i++) // spell circles 5 - 8 { AddControl(new GumpPic(this, 226 + i * 34, 174, 0x08B5 + i, 0)); LastControl.GumpLocalID = i + 4; LastControl.MouseClickEvent += SpellCircle_MouseClickEvent; // unsubscribe from these? } // indexes are on pages 1 - 4. Spells are on pages 5+. m_CircleHeaders = new HtmlGumpling[8]; for (int i = 0; i < 8; i++) { m_CircleHeaders[i] = (HtmlGumpling)AddControl( new HtmlGumpling(this, 64 + (i % 2) * 148, 10, 130, 200, 0, 0, string.Format("<span color='#004' style='font-family=uni0;'><center>{0}</center></span>", Magery.CircleNames[i])), 1 + (i / 2)); } m_Indexes = new HtmlGumpling[8]; for (int i = 0; i < 8; i++) { m_Indexes[i] = (HtmlGumpling)AddControl( new HtmlGumpling(this, 64 + (i % 2) * 156, 28, 130, 200, 0, 0, string.Empty), 1 + (i / 2)); } // add indexes and spell pages. m_MaxPage = 4; int currentSpellPage = 5; bool isRightPage = false; for (int spellCircle = 0; spellCircle < 8; spellCircle++) { for (int spellIndex = 1; spellIndex <= 8; spellIndex++) { if (m_Spellbook.HasSpell(spellCircle, spellIndex)) { m_Indexes[spellCircle].Text += string.Format("<a href='page={1}' color='#532' hovercolor='#800' activecolor='#611' style='font-family=uni0; text-decoration=none;'>{0}</a><br/>", Magery.GetSpell(spellCircle * 8 + spellIndex).Name, currentSpellPage); if (isRightPage) { currentSpellPage++; isRightPage = false; } else { m_MaxPage += 1; isRightPage = true; } } } } SetActivePage(1); } private void CreateSpellPage(int page, bool rightPage, int circle, SpellDefinition spell) { // header: "NTH CIRCLE" AddControl(new HtmlGumpling(this, 64 + (rightPage ? 148 : 0), 10, 130, 200, 0, 0, string.Format("<span color='#004' style='font-family=uni0;'><center>{0}</center></span>", Magery.CircleNames[circle])), page); // icon and spell name AddControl(new HtmlGumpling(this, 56 + (rightPage ? 156 : 0), 38, 130, 44, 0, 0, string.Format("<a href='spellicon={0}'><gumpimg src='{1}'/></a>", spell.ID, spell.GumpIconID - 0x1298)), page); AddControl(new HtmlGumpling(this, 104 + (rightPage ? 156 : 0), 38, 88, 40, 0, 0, string.Format( "<a href='spell={0}' color='#542' hovercolor='#875' activecolor='#420' style='font-family=uni0; text-decoration=none;'>{1}</a>", spell.ID, spell.Name)), page); // reagents. AddControl(new HtmlGumpling(this, 56 + (rightPage ? 156 : 0), 84, 146, 106, 0, 0, string.Format( "<span color='#400' style='font-family=uni0;'>Reagents:</span><br/><span style='font-family=ascii6;'>{0}</span>", spell.CreateReagentListString(", "))), page); } public override void OnHtmlInputEvent(string href, MouseEvent e) { if (e == MouseEvent.DoubleClick) { string[] hrefs = href.Split('='); if (hrefs.Length != 2) return; else if (hrefs[0] == "page") { int page; if (int.TryParse(hrefs[1], out page)) m_World.Interaction.CastSpell(page-4); } else if (hrefs[0] == "spell") { int spell; if (int.TryParse(hrefs[1], out spell)) m_World.Interaction.CastSpell(spell); } else if (hrefs[0] == "spellicon") { int spell; if (int.TryParse(hrefs[1], out spell)) m_World.Interaction.CastSpell(spell); } } else if (e == MouseEvent.Click) { string[] hrefs = href.Split('='); if (hrefs.Length != 2) return; if (hrefs[0] == "page") { int page; if (int.TryParse(hrefs[1], out page)) SetActivePage(page); } } else if (e == MouseEvent.DragBegin) { string[] hrefs = href.Split('='); if (hrefs.Length != 2) return; if (hrefs[0] == "spellicon") { int spellIndex; if (!int.TryParse(hrefs[1], out spellIndex)) return; SpellDefinition spell = Magery.GetSpell(spellIndex); if (spell.ID == spellIndex) { InputManager input = ServiceRegistry.GetService<InputManager>(); UseSpellButtonGump gump = new UseSpellButtonGump(spell); UserInterface.AddControl(gump, input.MousePosition.X - 22, input.MousePosition.Y - 22); UserInterface.AttemptDragControl(gump, input.MousePosition, true); } } } } private void SpellCircle_MouseClickEvent(AControl sender, int x, int y, MouseButton button) { if (button != MouseButton.Left) return; SetActivePage(sender.GumpLocalID / 2 + 1); } private void PageCorner_MouseClickEvent(AControl sender, int x, int y, MouseButton button) { if (button != MouseButton.Left) return; if (sender.GumpLocalID == 0) { SetActivePage(ActivePage - 1); } else { SetActivePage(ActivePage + 1); } } private void PageCorner_MouseDoubleClickEvent(AControl sender, int x, int y, MouseButton button) { if (button != MouseButton.Left) return; if (sender.GumpLocalID == 0) { SetActivePage(1); } else { SetActivePage(m_MaxPage); } } private void SetActivePage(int page) { if (page < 1) page = 1; if (page > m_MaxPage) page = m_MaxPage; if (page > 4 && m_RenderedSpellInfoPage == false) { int currentSpellPage = 5; bool isRightPage = false; for (int spellCircle = 0; spellCircle < 8; spellCircle++) { for (int spellIndex = 1; spellIndex <= 8; spellIndex++) { int spellIndexAll = spellCircle * 8 + spellIndex; if (m_Spellbook.HasSpell(spellCircle, spellIndex)) { CreateSpellPage(currentSpellPage, isRightPage, spellCircle, Magery.GetSpell(spellIndexAll)); if (isRightPage) { currentSpellPage++; isRightPage = false; } else { m_MaxPage += 1; isRightPage = true; } } } } m_RenderedSpellInfoPage = true; } ActivePage = page; // hide the page corners if we're at the first or final page. m_PageCornerLeft.Page = (ActivePage != 1) ? 0 : int.MaxValue; m_PageCornerRight.Page = (ActivePage != m_MaxPage) ? 0 : int.MaxValue; } } }
azmanomer/UltimaXNA
dev/Ultima/UI/WorldGumps/SpellbookGump.cs
C#
gpl-3.0
14,126
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. [assembly: System.Reflection.AssemblyCultureAttribute("en-US")] public class enUS { }
BlastarIndia/roslyn
Src/Compilers/Test/Resources/Core/SymbolsTests/Versioning/EN_US.cs
C#
gpl-3.0
275
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from buildbot.db import builders from buildbot.test.fake import fakedb from buildbot.test.fake import fakemaster from buildbot.test.util import connector_component from buildbot.test.util import interfaces from buildbot.test.util import validation from twisted.internet import defer from twisted.trial import unittest class Tests(interfaces.InterfaceTests): # common sample data builder_row = [ fakedb.Builder(id=7, name="some:builder"), ] # tests def test_signature_findBuilderId(self): @self.assertArgSpecMatches(self.db.builders.findBuilderId) def findBuilderId(self, name): pass def test_signature_addBuilderMaster(self): @self.assertArgSpecMatches(self.db.builders.addBuilderMaster) def addBuilderMaster(self, builderid=None, masterid=None): pass def test_signature_removeBuilderMaster(self): @self.assertArgSpecMatches(self.db.builders.removeBuilderMaster) def removeBuilderMaster(self, builderid=None, masterid=None): pass def test_signature_getBuilder(self): @self.assertArgSpecMatches(self.db.builders.getBuilder) def getBuilder(self, builderid): pass def test_signature_getBuilders(self): @self.assertArgSpecMatches(self.db.builders.getBuilders) def getBuilders(self, masterid=None): pass @defer.inlineCallbacks def test_findBuilderId_new(self): id = yield self.db.builders.findBuilderId('some:builder') builderdict = yield self.db.builders.getBuilder(id) self.assertEqual(builderdict, dict(id=id, name='some:builder', masterids=[])) @defer.inlineCallbacks def test_findBuilderId_exists(self): yield self.insertTestData([ fakedb.Builder(id=7, name='some:builder'), ]) id = yield self.db.builders.findBuilderId('some:builder') self.assertEqual(id, 7) @defer.inlineCallbacks def test_addBuilderMaster(self): yield self.insertTestData([ fakedb.Builder(id=7), fakedb.Master(id=9, name='abc'), fakedb.Master(id=10, name='def'), fakedb.BuilderMaster(builderid=7, masterid=10), ]) yield self.db.builders.addBuilderMaster(builderid=7, masterid=9) builderdict = yield self.db.builders.getBuilder(7) validation.verifyDbDict(self, 'builderdict', builderdict) self.assertEqual(builderdict, dict(id=7, name='some:builder', masterids=[9, 10])) @defer.inlineCallbacks def test_addBuilderMaster_already_present(self): yield self.insertTestData([ fakedb.Builder(id=7), fakedb.Master(id=9, name='abc'), fakedb.Master(id=10, name='def'), fakedb.BuilderMaster(builderid=7, masterid=9), ]) yield self.db.builders.addBuilderMaster(builderid=7, masterid=9) builderdict = yield self.db.builders.getBuilder(7) validation.verifyDbDict(self, 'builderdict', builderdict) self.assertEqual(builderdict, dict(id=7, name='some:builder', masterids=[9])) @defer.inlineCallbacks def test_removeBuilderMaster(self): yield self.insertTestData([ fakedb.Builder(id=7), fakedb.Master(id=9, name='some:master'), fakedb.Master(id=10, name='other:master'), fakedb.BuilderMaster(builderid=7, masterid=9), fakedb.BuilderMaster(builderid=7, masterid=10), ]) yield self.db.builders.removeBuilderMaster(builderid=7, masterid=9) builderdict = yield self.db.builders.getBuilder(7) validation.verifyDbDict(self, 'builderdict', builderdict) self.assertEqual(builderdict, dict(id=7, name='some:builder', masterids=[10])) @defer.inlineCallbacks def test_getBuilder_no_masters(self): yield self.insertTestData([ fakedb.Builder(id=7, name='some:builder'), ]) builderdict = yield self.db.builders.getBuilder(7) validation.verifyDbDict(self, 'builderdict', builderdict) self.assertEqual(builderdict, dict(id=7, name='some:builder', masterids=[])) @defer.inlineCallbacks def test_getBuilder_with_masters(self): yield self.insertTestData([ fakedb.Builder(id=7, name='some:builder'), fakedb.Master(id=3, name='m1'), fakedb.Master(id=4, name='m2'), fakedb.BuilderMaster(builderid=7, masterid=3), fakedb.BuilderMaster(builderid=7, masterid=4), ]) builderdict = yield self.db.builders.getBuilder(7) validation.verifyDbDict(self, 'builderdict', builderdict) self.assertEqual(builderdict, dict(id=7, name='some:builder', masterids=[3, 4])) @defer.inlineCallbacks def test_getBuilder_missing(self): builderdict = yield self.db.builders.getBuilder(7) self.assertEqual(builderdict, None) @defer.inlineCallbacks def test_getBuilders(self): yield self.insertTestData([ fakedb.Builder(id=7, name='some:builder'), fakedb.Builder(id=8, name='other:builder'), fakedb.Builder(id=9, name='third:builder'), fakedb.Master(id=3, name='m1'), fakedb.Master(id=4, name='m2'), fakedb.BuilderMaster(builderid=7, masterid=3), fakedb.BuilderMaster(builderid=8, masterid=3), fakedb.BuilderMaster(builderid=8, masterid=4), ]) builderlist = yield self.db.builders.getBuilders() for builderdict in builderlist: validation.verifyDbDict(self, 'builderdict', builderdict) self.assertEqual(sorted(builderlist), sorted([ dict(id=7, name='some:builder', masterids=[3]), dict(id=8, name='other:builder', masterids=[3, 4]), dict(id=9, name='third:builder', masterids=[]), ])) @defer.inlineCallbacks def test_getBuilders_masterid(self): yield self.insertTestData([ fakedb.Builder(id=7, name='some:builder'), fakedb.Builder(id=8, name='other:builder'), fakedb.Builder(id=9, name='third:builder'), fakedb.Master(id=3, name='m1'), fakedb.Master(id=4, name='m2'), fakedb.BuilderMaster(builderid=7, masterid=3), fakedb.BuilderMaster(builderid=8, masterid=3), fakedb.BuilderMaster(builderid=8, masterid=4), ]) builderlist = yield self.db.builders.getBuilders(masterid=3) for builderdict in builderlist: validation.verifyDbDict(self, 'builderdict', builderdict) self.assertEqual(sorted(builderlist), sorted([ dict(id=7, name='some:builder', masterids=[3]), dict(id=8, name='other:builder', masterids=[3, 4]), ])) @defer.inlineCallbacks def test_getBuilders_empty(self): builderlist = yield self.db.builders.getBuilders() self.assertEqual(sorted(builderlist), []) class RealTests(Tests): # tests that only "real" implementations will pass pass class TestFakeDB(unittest.TestCase, Tests): def setUp(self): self.master = fakemaster.make_master() self.db = fakedb.FakeDBConnector(self.master, self) self.db.checkForeignKeys = True self.insertTestData = self.db.insertTestData class TestRealDB(unittest.TestCase, connector_component.ConnectorComponentMixin, RealTests): def setUp(self): d = self.setUpConnectorComponent( table_names=['builders', 'masters', 'builder_masters']) @d.addCallback def finish_setup(_): self.db.builders = builders.BuildersConnectorComponent(self.db) return d def tearDown(self): return self.tearDownConnectorComponent()
zozo123/buildbot
master/buildbot/test/unit/test_db_builders.py
Python
gpl-3.0
8,680
/* * This file is part of Wi-Fi Reminders. * * Wi-Fi Reminders is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Wi-Fi Reminders is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Wi-Fi Reminders. If not, see <http://www.gnu.org/licenses/>. */ package ru.glesik.wifireminders; import android.os.Bundle; import android.preference.PreferenceActivity; public class SettingsActivity extends PreferenceActivity { @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); } }
glesik/wifireminders
app/src/main/java/ru/glesik/wifireminders/SettingsActivity.java
Java
gpl-3.0
1,084
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace CSCore.CoreAudioAPI { [ComImport] [Guid("641DD20B-4D41-49CC-ABA3-174B9477BB08")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [SuppressUnmanagedCodeSecurity] public interface IAudioSessionNotification { [PreserveSig] int OnSessionCreated([In] IntPtr newSession); //newSession is a pointer to an IAudioSessionControl interface } }
techdude101/code
C Sharp/cscore-e2822dc89eca17ec28d8e22e91ebb61ebff5cbef/CSCore/CoreAudioAPI/IAudioSessionNotification.cs
C#
gpl-3.0
544
<?php session_start(); header("Content-Type: image/png"); header("Content-Disposition: attachment; filename=mapa_UNICEF.png"); $image_name = $_SESSION["mapserver_img"]; $image = imagecreatefrompng($image_name); imagePng($image); ?>
umaic/sidi
consulta/unicef_mapserver_download_img.php
PHP
gpl-3.0
236
apex.region('emp').widget().interactiveGrid('getToolbar'); /** * Call this method when the size of the widget element changes. This can happen if the browser window * changes for example. This will resize the current view. * Note: Most of the time it is not necessary to call this method as Interactive Grid detects when its * size changes. */ apex.region('emp').widget().interactiveGrid('resize'); /** * Cause the Interactive Grid to get fresh data from the server. * A warning is given if the model has any outstanding changes and the user can choose to allow the refresh or not. * * @param {Object} [pOptions] tbd/todo */ apex.region('emp').widget().interactiveGrid('refresh'); apex.region('emp').refresh(); /** * Put focus in the cell (or field etc.) given by pRecordId and pColumn. This is used to focus rows or cells * that have errors. This will switch to the "editable" view. * This delegates to the view. Not all views will support going to a cell. * * @param {String} [pModelInstanceId] model instance id. only needed if using multiple models such as in master * detail and the model has not already been set correctly by the master. * @param {String} pRecordId the record id of the row to go to. * @param {String} [pColumn] column in the record row to go to. */ apex.region('emp').widget().interactiveGrid('gotoCell'); /** * Returns the actions context for this Interactive Grid instance * @return {apex.actions} the actions context * @example * apex.region("emp").widget().interactiveGrid("getActions").invoke("save"); */ apex.region('emp').widget().interactiveGrid('getActions'); /** * Returns the toolbar widget element. * * @return {jQuery} jQuery object of the interactive grid toolbar or null if there is no toolbar */ apex.region('emp').widget().interactiveGrid('getToolbar'); /** * Return the underlying data model records corresponding to the current selection in the current view. * Use the apex.model API to manipulate these records. Make sure you are using the model for the current * view for example: apex.region(<static-id>).widget().interactiveGrid("getCurrentView").model * * Note: Depending on the view and the submitSelectedRows option the selected records returned could * span multiple pages. To get just the records that are selected in the current page requires * using view widget specific methods. * * @return {Array} array of records from the model corresponding to the selected rows/records * Returns empty array if there is no selection. Returns null if the current view doesn't support * selection. */ apex.region('emp').widget().interactiveGrid('getSelectedRecords'); /** * Set the current selection to the records specified. Only applies for views that support selection. * * Note that the records or record ids given may not yet exist in the model or may not be visible in the view. * * @param [array] pRecords an array of model records or an array of model record ids as returned by model * getRecordId. If this is an empty array then the selection is cleared. */ apex.region('emp').widget().interactiveGrid('setSelectedRecords'); /** * Return the Interactive Grid view interface for the given view id or if not view id is given return a * map of all the view interfaces. * * @param {string} [pViewId] Id of the view to get. For example "grid" or "chart". * @return {object} View interface. */ apex.region('emp').widget().interactiveGrid('getViews'); apex.region('emp').widget().interactiveGrid('getCurrentView'); apex.region('emp').widget().interactiveGrid('getCurrentViewId'); /** * Sets focus to the search field if present, and if not delegates to the current view's focus handling. */ apex.region('emp').widget().interactiveGrid('focus');
mgoricki/orclapex-ig-cheat-sheet
ig_methods.js
JavaScript
gpl-3.0
3,779
/* -*- c++ -*- */ /* * Copyright 2004 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * GNU Radio is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /* * This is actually the same as gr_local_signhandler, but with a different name. * We don't have a common library to put this in, so... */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <usrp_local_sighandler.h> #include <stdexcept> #include <stdio.h> usrp_local_sighandler::usrp_local_sighandler (int signum, void (*new_handler)(int)) : d_signum (signum) { #ifdef HAVE_SIGACTION struct sigaction new_action; memset (&new_action, 0, sizeof (new_action)); new_action.sa_handler = new_handler; sigemptyset (&new_action.sa_mask); new_action.sa_flags = 0; if (sigaction (d_signum, &new_action, &d_old_action) < 0){ perror ("sigaction (install new)"); throw std::runtime_error ("sigaction"); } #endif } usrp_local_sighandler::~usrp_local_sighandler () { #ifdef HAVE_SIGACTION if (sigaction (d_signum, &d_old_action, 0) < 0){ perror ("sigaction (restore old)"); throw std::runtime_error ("sigaction"); } #endif } void usrp_local_sighandler::throw_signal(int signum) throw(usrp_signal) { throw usrp_signal (signum); } /* * Semi-hideous way to may a signal number into a signal name */ #define SIGNAME(x) case x: return #x std::string usrp_signal::name () const { char tmp[128]; switch (signal ()){ #ifdef SIGHUP SIGNAME (SIGHUP); #endif #ifdef SIGINT SIGNAME (SIGINT); #endif #ifdef SIGQUIT SIGNAME (SIGQUIT); #endif #ifdef SIGILL SIGNAME (SIGILL); #endif #ifdef SIGTRAP SIGNAME (SIGTRAP); #endif #ifdef SIGABRT SIGNAME (SIGABRT); #endif #ifdef SIGBUS SIGNAME (SIGBUS); #endif #ifdef SIGFPE SIGNAME (SIGFPE); #endif #ifdef SIGKILL SIGNAME (SIGKILL); #endif #ifdef SIGUSR1 SIGNAME (SIGUSR1); #endif #ifdef SIGSEGV SIGNAME (SIGSEGV); #endif #ifdef SIGUSR2 SIGNAME (SIGUSR2); #endif #ifdef SIGPIPE SIGNAME (SIGPIPE); #endif #ifdef SIGALRM SIGNAME (SIGALRM); #endif #ifdef SIGTERM SIGNAME (SIGTERM); #endif #ifdef SIGSTKFLT SIGNAME (SIGSTKFLT); #endif #ifdef SIGCHLD SIGNAME (SIGCHLD); #endif #ifdef SIGCONT SIGNAME (SIGCONT); #endif #ifdef SIGSTOP SIGNAME (SIGSTOP); #endif #ifdef SIGTSTP SIGNAME (SIGTSTP); #endif #ifdef SIGTTIN SIGNAME (SIGTTIN); #endif #ifdef SIGTTOU SIGNAME (SIGTTOU); #endif #ifdef SIGURG SIGNAME (SIGURG); #endif #ifdef SIGXCPU SIGNAME (SIGXCPU); #endif #ifdef SIGXFSZ SIGNAME (SIGXFSZ); #endif #ifdef SIGVTALRM SIGNAME (SIGVTALRM); #endif #ifdef SIGPROF SIGNAME (SIGPROF); #endif #ifdef SIGWINCH SIGNAME (SIGWINCH); #endif #ifdef SIGIO SIGNAME (SIGIO); #endif #ifdef SIGPWR SIGNAME (SIGPWR); #endif #ifdef SIGSYS SIGNAME (SIGSYS); #endif default: #if defined (HAVE_SNPRINTF) #if defined (SIGRTMIN) && defined (SIGRTMAX) if (signal () >= SIGRTMIN && signal () <= SIGRTMAX){ snprintf (tmp, sizeof (tmp), "SIGRTMIN + %d", signal ()); return tmp; } #endif snprintf (tmp, sizeof (tmp), "SIGNAL %d", signal ()); return tmp; #else return "Unknown signal"; #endif } }
mojca/gecko
lib/sis3150_calls/loader/usrp_local_sighandler.cc
C++
gpl-3.0
3,851
# -*- coding: utf-8 -*- import os import pipeline_item class Serialize(pipeline_item.pipeline_stage): def stage(self, pipeline_value): storage_path = "%s/%s" % (self.pipeline_storage_prefix, self.attributes['toFile']) if self.pipeline_storage_prefix is None: storage_path = self.attributes['toFile'] self.storage[storage_path] = str(pipeline_value) return pipeline_value
Br3nda/docvert
core/pipeline_type/serialize.py
Python
gpl-3.0
422
package com.baeldung.dao; import com.baeldung.aop.annotations.Loggable; import com.baeldung.model.Foo; import org.springframework.stereotype.Repository; @Repository public class FooDao { public String findById(Long id) { return "Bazz"; } @Loggable public Foo create(Long id, String name) { return new Foo(id, name); } public Foo merge(Foo foo) { return foo; } }
Niky4000/UsefulUtils
projects/tutorials-master/tutorials-master/spring-mvc-java/src/main/java/com/baeldung/dao/FooDao.java
Java
gpl-3.0
419
#ifndef _COMPILE_WORKER_HPP_ #define _COMPILE_WORKER_HPP_ #include <QThread> #include <kar/kar.hpp> #include <pcompiler/output.hpp> #include <pcompiler/progress.hpp> class KovanSerial; class CompileWorker : public QThread, public Compiler::Progress { Q_OBJECT public: CompileWorker(const kiss::KarPtr &archive, KovanSerial *proto, QObject *parent = 0); void run(); const Compiler::OutputList &output() const; void setUserRoot(const QString &userRoot); const QString &userRoot() const; void progress(double fraction); void cleanup(); private: Compiler::OutputList compile(); static QString tempPath(); kiss::KarPtr m_archive; KovanSerial *m_proto; Compiler::OutputList m_output; QString m_userRoot; QString m_tempDir; }; #endif
kipr/computer
include/compile_worker.hpp
C++
gpl-3.0
760
# This file is part of HamsiManager. # # Copyright (c) 2010 - 2015 Murat Demir <mopened@gmail.com> # # Hamsi Manager is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Hamsi Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with HamsiManager; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from Core import Universals as uni import FileUtils as fu from Databases import sqlite, getDefaultConnection, correctForSql, getAmendedSQLInsertOrUpdateQueries tableName = "bookmarksOfDirectories" tableVersion = 2 allForFetch = None def fetchAll(): global allForFetch if allForFetch is None: con = getDefaultConnection() cur = con.cursor() cur.execute("SELECT * FROM " + tableName) allForFetch = cur.fetchall() return allForFetch def fetch(_id): con = getDefaultConnection() cur = con.cursor() cur.execute("SELECT * FROM " + tableName + " where id=" + str(int(_id))) return cur.fetchall() def checkValues(_bookmark, _value, _type): if len(_bookmark) == 0 or len(_value) == 0: return False return True def insert(_bookmark, _value, _type=""): global allForFetch if checkValues(_bookmark, _value, _type): allForFetch = None con = getDefaultConnection() cur = con.cursor() sqlQueries = getAmendedSQLInsertOrUpdateQueries(tableName, {"bookmark": "'" + correctForSql(_bookmark) + "'", "value": "'" + correctForSql(_value) + "'", "type": "'" + correctForSql(_type) + "'"}, ["value"]) cur.execute(sqlQueries[0]) cur.execute(sqlQueries[1]) con.commit() cur.execute("SELECT last_insert_rowid();") return cur.fetchall()[0][0] return None def update(_id, _bookmark, _value, _type=""): global allForFetch if checkValues(_bookmark, _value, _type): allForFetch = None con = getDefaultConnection() cur = con.cursor() cur.execute(str( "update " + tableName + " set bookmark='" + correctForSql(_bookmark) + "', value='" + correctForSql( _value) + "', type='" + correctForSql(_type) + "' where id=" + str(int(_id)))) con.commit() def delete(_id): global allForFetch allForFetch = None con = getDefaultConnection() cur = con.cursor() cur.execute("delete from " + tableName + " where id=" + str(int(_id))) con.commit() def getTableCreateQuery(): return "CREATE TABLE IF NOT EXISTS " + tableName + " ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,'bookmark' TEXT,'value' TEXT,'type' TEXT)" def getDeleteTableQuery(): return "DELETE FROM " + tableName def getDefaultsQueries(): sqlQueries = [] sqlQueries += getAmendedSQLInsertOrUpdateQueries(tableName, {"bookmark": "'Home'", "value": "'" + fu.userDirectoryPath + "'", "type": "''"}, ["value"]) if uni.isWindows: sqlQueries += getAmendedSQLInsertOrUpdateQueries(tableName, {"bookmark": "'C:\\'", "value": "'C:\\'", "type": "''"}, ["value"]) else: sqlQueries += getAmendedSQLInsertOrUpdateQueries(tableName, {"bookmark": "'MNT'", "value": "'/mnt'", "type": "''"}, ["value"]) sqlQueries += getAmendedSQLInsertOrUpdateQueries(tableName, {"bookmark": "'MEDIA'", "value": "'/media'", "type": "''"}, ["value"]) return sqlQueries def checkUpdates(_oldVersion): if _oldVersion < 2: con = getDefaultConnection() cur = con.cursor() cur.execute(str("DROP TABLE " + tableName + ";")) con.commit() cur.execute(getTableCreateQuery()) con.commit() for sqlCommand in getDefaultsQueries(): cur = con.cursor() cur.execute(str(sqlCommand)) con.commit()
supermurat/hamsi-manager
Databases/BookmarksOfDirectories.py
Python
gpl-3.0
4,852
from iHunterModel.models import DomainObject, Organization from django.db import models # class for specifying different types of EduOrgs. like school, colleges, universities etc. class EducationalOrganizationType(DomainObject): name = models.CharField(max_length=255, null=False, blank=False) description = models.TextField() def __str__(self): return self.name class EducationalOrganization(Organization): # Relationship. nullable is true. category = models.ForeignKey(EducationalOrganizationType, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name
kumarsandeep91/Russet.iHunter.Model
iHunterModel/models/EducationalOrganization.py
Python
gpl-3.0
634
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace SurfaceGaming.Models { public class SettingKeyValue { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Key] public Guid Id { get; set; } public string Key { get; set; } public string Value { get; set; } public bool IsRemoved { get; set; } } }
arnvanhoutte/SurfaceGaming
SurfaceGaming/Models/SettingKeyValue.cs
C#
gpl-3.0
433
/* * Copyright (c) 2013, Robert Rueger <rueger@itp.uni-frankfurt.de> * * This file is part of hVMC. * * hVMC is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * hVMC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with hVMC. If not, see <http://www.gnu.org/licenses/>. */ #include "mccresults.hpp" #include <iostream> #include <fstream> #include <boost/archive/text_oarchive.hpp> #include <boost/serialization/vector.hpp> #include "serialization_eigen.hpp" using namespace std; namespace fs = boost::filesystem; namespace ar = boost::archive; void MCCResults::write_to_files( const fs::path& dir ) const { if ( E ) { ofstream E_txtfile( ( dir / "sim_res_E.txt" ).string() ); E_txtfile << E->mean << " " << E->sigma << endl; ofstream E_datfile( ( dir / "sim_res_E.dat" ).string() ); ar::text_oarchive E_archive( E_datfile ); E_archive << E.get(); } if ( Deltak ) { ofstream Dk_txtfile( ( dir / "sim_res_Dk.txt" ).string() ); Dk_txtfile << Deltak->transpose() << endl; ofstream Dk_datfile( ( dir / "sim_res_Dk.dat" ).string() ); ar::text_oarchive Dk_archive( Dk_datfile ); Dk_archive << Deltak.get(); } if ( Deltak_Deltakprime ) { ofstream DkDkp_file( ( dir / "sim_res_DkDkp.txt" ).string() ); DkDkp_file << Deltak_Deltakprime.get() << endl; ofstream DkDkp_datfile( ( dir / "sim_res_DkDkp.dat" ).string() ); ar::text_oarchive DkDkp_archive( DkDkp_datfile ); DkDkp_archive << Deltak_Deltakprime.get(); } if ( Deltak_E ) { ofstream DkE_txtfile( ( dir / "sim_res_DkE.txt" ).string() ); DkE_txtfile << Deltak_E->transpose() << endl; ofstream DkE_datfile( ( dir / "sim_res_DkE.dat" ).string() ); ar::text_oarchive DkE_archive( DkE_datfile ); DkE_archive << Deltak_E.get(); } if ( dblocc ) { ofstream dblocc_txtfile( ( dir / "sim_res_dblocc.txt" ).string() ); dblocc_txtfile << dblocc->mean << " " << dblocc->sigma << endl; ofstream dblocc_datfile( ( dir / "sim_res_dblocc.dat" ).string() ); ar::text_oarchive dblocc_archive( dblocc_datfile ); dblocc_archive << dblocc.get(); } if ( nncorr ) { ofstream nncorr_txtfile( ( dir / "sim_res_nncorr.txt" ).string() ); nncorr_txtfile << nncorr.get() << endl; ofstream nncorr_datfile( ( dir / "sim_res_nncorr.dat" ).string() ); ar::text_oarchive nncorr_archive( nncorr_datfile ); nncorr_archive << nncorr.get(); } if ( sscorr ) { ofstream sscorr_txtfile( ( dir / "sim_res_sscorr.txt" ).string() ); sscorr_txtfile << sscorr.get() << endl; ofstream sscorr_datfile( ( dir / "sim_res_sscorr.dat" ).string() ); ar::text_oarchive sscorr_archive( sscorr_datfile ); sscorr_archive << sscorr.get(); } if ( pconfs ) { ofstream pconfs_txtfile( ( dir / "sim_res_pconfs.txt" ).string() ); for ( auto it = pconfs.get().begin(); it != pconfs.get().end(); ++it ) { pconfs_txtfile << it->transpose() << endl; } ofstream pconfs_datfile( ( dir / "sim_res_pconfs.dat" ).string() ); ar::text_oarchive pconfs_archive( pconfs_datfile ); pconfs_archive << pconfs.get(); } } std::ostream& operator<<( std::ostream& out, const MCCResults& res ) { if ( res.E ) { out << endl << " E = " << res.E->mean << endl << "sigma_E = " << res.E->sigma << endl; } if ( res.Deltak ) { out << endl << "Delta_k = " << endl << res.Deltak->transpose() << endl; } if ( res.Deltak_Deltakprime ) { out << endl << "DkDkp = " << endl << res.Deltak_Deltakprime.get() << endl; } if ( res.Deltak_E ) { out << endl << "Dk_E = " << endl << res.Deltak_E->transpose() << endl; } if ( res.dblocc ) { out << endl << " dblocc = " << res.dblocc->mean << endl << "sigma_dblocc = " << res.dblocc->sigma << endl; } if ( res.nncorr ) { out << endl << "nncorr = " << endl << res.nncorr.get() << endl; } if ( res.sscorr ) { out << endl << "sscorr = " << endl << res.sscorr.get() << endl; } if ( res.pconfs ) { cout << endl << "pconfs = " << endl; for ( auto it = res.pconfs.get().begin(); it != res.pconfs.get().end(); ++it ) { cout << it->transpose() << endl; } } out << endl; return out; }
robertrueger/hVMC
mccresults.cpp
C++
gpl-3.0
4,788
package com.taobao.api.request; import java.util.Map; import com.taobao.api.ApiRuleException; import com.taobao.api.TaobaoRequest; import com.taobao.api.internal.util.TaobaoHashMap; import com.taobao.api.response.TbkShopCouponGetResponse; /** * TOP API: taobao.tbk.shop.coupon.get request * * @author auto create * @since 1.0, 2014-11-02 16:51:12 */ public class TbkShopCouponGetRequest implements TaobaoRequest<TbkShopCouponGetResponse> { private Map<String, String> headerMap = new TaobaoHashMap(); /** * 店铺Id */ private Long shopId; private Long timestamp; private TaobaoHashMap udfParams; // add user-defined text parameters @Override public void check() throws ApiRuleException { } @Override public String getApiMethodName() { return "taobao.tbk.shop.coupon.get"; } @Override public Map<String, String> getHeaderMap() { return headerMap; } @Override public Class<TbkShopCouponGetResponse> getResponseClass() { return TbkShopCouponGetResponse.class; } public Long getShopId() { return this.shopId; } @Override public Map<String, String> getTextParams() { TaobaoHashMap txtParams = new TaobaoHashMap(); txtParams.put("shop_id", this.shopId); if (this.udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } @Override public Long getTimestamp() { return this.timestamp; } @Override public void putOtherTextParam(String key, String value) { if (this.udfParams == null) { this.udfParams = new TaobaoHashMap(); } this.udfParams.put(key, value); } public void setShopId(Long shopId) { this.shopId = shopId; } @Override public void setTimestamp(Long timestamp) { this.timestamp = timestamp; } }
kuiwang/my-dev
src/main/java/com/taobao/api/request/TbkShopCouponGetRequest.java
Java
gpl-3.0
1,926
#include "RNGMarsaglia.h" namespace Kernal { RNGMarsaglia::RNGMarsaglia() { SeedTime(); } RNGMarsaglia::RNGMarsaglia(const RNGMarsaglia& other) { stateZ = other.stateZ; stateW = other.stateW; } RNGMarsaglia& RNGMarsaglia::operator=(const RNGMarsaglia& rhs) { stateZ = rhs.stateZ; stateW = rhs.stateW; return *this; } Kernal::uint32 RNGMarsaglia::Rand() { stateZ = 36969 * (stateZ & 65535) + (stateZ >> 16); stateW = 18000 * (stateW & 65535) + (stateW >> 16); return (stateZ << 16) + stateW; } void RNGMarsaglia::Seed(Kernal::uint32 seed) { stateZ = seed >> 16; stateW = seed & UINT16_MAX; // % TWO_TO_32 } } //namespace Kernal
virac/Slicer
src/Kernal/RNGMarsaglia.cpp
C++
gpl-3.0
676
// Compiled by ClojureScript 1.9.293 {:static-fns true, :optimize-constants true} goog.provide('thi.ng.dstruct.streams'); goog.require('cljs.core'); goog.require('thi.ng.xerror.core'); /** * @interface */ thi.ng.dstruct.streams.IInputStream = function(){}; thi.ng.dstruct.streams.read_utf8_line = (function thi$ng$dstruct$streams$read_utf8_line(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IInputStream$read_utf8_line$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IInputStream$read_utf8_line$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.read_utf8_line[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.read_utf8_line["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IInputStream.read-utf8-line",_); } } } }); thi.ng.dstruct.streams.read_uint8 = (function thi$ng$dstruct$streams$read_uint8(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IInputStream$read_uint8$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IInputStream$read_uint8$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.read_uint8[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.read_uint8["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IInputStream.read-uint8",_); } } } }); thi.ng.dstruct.streams.read_uint16_le = (function thi$ng$dstruct$streams$read_uint16_le(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IInputStream$read_uint16_le$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IInputStream$read_uint16_le$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.read_uint16_le[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.read_uint16_le["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IInputStream.read-uint16-le",_); } } } }); thi.ng.dstruct.streams.read_uint16_be = (function thi$ng$dstruct$streams$read_uint16_be(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IInputStream$read_uint16_be$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IInputStream$read_uint16_be$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.read_uint16_be[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.read_uint16_be["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IInputStream.read-uint16-be",_); } } } }); thi.ng.dstruct.streams.read_uint32_le = (function thi$ng$dstruct$streams$read_uint32_le(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IInputStream$read_uint32_le$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IInputStream$read_uint32_le$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.read_uint32_le[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.read_uint32_le["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IInputStream.read-uint32-le",_); } } } }); thi.ng.dstruct.streams.read_uint32_be = (function thi$ng$dstruct$streams$read_uint32_be(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IInputStream$read_uint32_be$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IInputStream$read_uint32_be$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.read_uint32_be[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.read_uint32_be["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IInputStream.read-uint32-be",_); } } } }); thi.ng.dstruct.streams.read_float_le = (function thi$ng$dstruct$streams$read_float_le(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IInputStream$read_float_le$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IInputStream$read_float_le$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.read_float_le[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.read_float_le["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IInputStream.read-float-le",_); } } } }); thi.ng.dstruct.streams.read_float_be = (function thi$ng$dstruct$streams$read_float_be(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IInputStream$read_float_be$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IInputStream$read_float_be$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.read_float_be[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.read_float_be["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IInputStream.read-float-be",_); } } } }); thi.ng.dstruct.streams.read_double_le = (function thi$ng$dstruct$streams$read_double_le(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IInputStream$read_double_le$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IInputStream$read_double_le$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.read_double_le[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.read_double_le["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IInputStream.read-double-le",_); } } } }); thi.ng.dstruct.streams.read_double_be = (function thi$ng$dstruct$streams$read_double_be(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IInputStream$read_double_be$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IInputStream$read_double_be$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.read_double_be[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.read_double_be["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IInputStream.read-double-be",_); } } } }); thi.ng.dstruct.streams.read_vec2f_le = (function thi$ng$dstruct$streams$read_vec2f_le(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IInputStream$read_vec2f_le$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IInputStream$read_vec2f_le$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.read_vec2f_le[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.read_vec2f_le["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IInputStream.read-vec2f-le",_); } } } }); thi.ng.dstruct.streams.read_vec2f_be = (function thi$ng$dstruct$streams$read_vec2f_be(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IInputStream$read_vec2f_be$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IInputStream$read_vec2f_be$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.read_vec2f_be[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.read_vec2f_be["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IInputStream.read-vec2f-be",_); } } } }); thi.ng.dstruct.streams.read_vec3f_le = (function thi$ng$dstruct$streams$read_vec3f_le(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IInputStream$read_vec3f_le$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IInputStream$read_vec3f_le$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.read_vec3f_le[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.read_vec3f_le["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IInputStream.read-vec3f-le",_); } } } }); thi.ng.dstruct.streams.read_vec3f_be = (function thi$ng$dstruct$streams$read_vec3f_be(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IInputStream$read_vec3f_be$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IInputStream$read_vec3f_be$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.read_vec3f_be[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.read_vec3f_be["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IInputStream.read-vec3f-be",_); } } } }); /** * @interface */ thi.ng.dstruct.streams.IOutputStream = function(){}; thi.ng.dstruct.streams.write_utf8_bytes = (function thi$ng$dstruct$streams$write_utf8_bytes(_,str){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IOutputStream$write_utf8_bytes$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IOutputStream$write_utf8_bytes$arity$2(_,str); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.write_utf8_bytes[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,str) : m__8103__auto__.call(null,_,str)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.write_utf8_bytes["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,str) : m__8103__auto____$1.call(null,_,str)); } else { throw cljs.core.missing_protocol("IOutputStream.write-utf8-bytes",_); } } } }); thi.ng.dstruct.streams.write_uint8 = (function thi$ng$dstruct$streams$write_uint8(_,x){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IOutputStream$write_uint8$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IOutputStream$write_uint8$arity$2(_,x); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.write_uint8[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto__.call(null,_,x)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.write_uint8["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto____$1.call(null,_,x)); } else { throw cljs.core.missing_protocol("IOutputStream.write-uint8",_); } } } }); thi.ng.dstruct.streams.write_uint16_le = (function thi$ng$dstruct$streams$write_uint16_le(_,x){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IOutputStream$write_uint16_le$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IOutputStream$write_uint16_le$arity$2(_,x); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.write_uint16_le[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto__.call(null,_,x)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.write_uint16_le["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto____$1.call(null,_,x)); } else { throw cljs.core.missing_protocol("IOutputStream.write-uint16-le",_); } } } }); thi.ng.dstruct.streams.write_uint16_be = (function thi$ng$dstruct$streams$write_uint16_be(_,x){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IOutputStream$write_uint16_be$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IOutputStream$write_uint16_be$arity$2(_,x); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.write_uint16_be[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto__.call(null,_,x)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.write_uint16_be["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto____$1.call(null,_,x)); } else { throw cljs.core.missing_protocol("IOutputStream.write-uint16-be",_); } } } }); thi.ng.dstruct.streams.write_uint32_le = (function thi$ng$dstruct$streams$write_uint32_le(_,x){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IOutputStream$write_uint32_le$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IOutputStream$write_uint32_le$arity$2(_,x); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.write_uint32_le[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto__.call(null,_,x)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.write_uint32_le["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto____$1.call(null,_,x)); } else { throw cljs.core.missing_protocol("IOutputStream.write-uint32-le",_); } } } }); thi.ng.dstruct.streams.write_uint32_be = (function thi$ng$dstruct$streams$write_uint32_be(_,x){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IOutputStream$write_uint32_be$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IOutputStream$write_uint32_be$arity$2(_,x); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.write_uint32_be[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto__.call(null,_,x)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.write_uint32_be["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto____$1.call(null,_,x)); } else { throw cljs.core.missing_protocol("IOutputStream.write-uint32-be",_); } } } }); thi.ng.dstruct.streams.write_float_le = (function thi$ng$dstruct$streams$write_float_le(_,x){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IOutputStream$write_float_le$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IOutputStream$write_float_le$arity$2(_,x); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.write_float_le[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto__.call(null,_,x)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.write_float_le["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto____$1.call(null,_,x)); } else { throw cljs.core.missing_protocol("IOutputStream.write-float-le",_); } } } }); thi.ng.dstruct.streams.write_float_be = (function thi$ng$dstruct$streams$write_float_be(_,x){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IOutputStream$write_float_be$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IOutputStream$write_float_be$arity$2(_,x); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.write_float_be[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto__.call(null,_,x)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.write_float_be["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto____$1.call(null,_,x)); } else { throw cljs.core.missing_protocol("IOutputStream.write-float-be",_); } } } }); thi.ng.dstruct.streams.write_double_le = (function thi$ng$dstruct$streams$write_double_le(_,x){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IOutputStream$write_double_le$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IOutputStream$write_double_le$arity$2(_,x); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.write_double_le[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto__.call(null,_,x)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.write_double_le["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto____$1.call(null,_,x)); } else { throw cljs.core.missing_protocol("IOutputStream.write-double-le",_); } } } }); thi.ng.dstruct.streams.write_double_be = (function thi$ng$dstruct$streams$write_double_be(_,x){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IOutputStream$write_double_be$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IOutputStream$write_double_be$arity$2(_,x); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.write_double_be[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto__.call(null,_,x)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.write_double_be["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto____$1.call(null,_,x)); } else { throw cljs.core.missing_protocol("IOutputStream.write-double-be",_); } } } }); thi.ng.dstruct.streams.write_vec2f_le = (function thi$ng$dstruct$streams$write_vec2f_le(_,v){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IOutputStream$write_vec2f_le$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IOutputStream$write_vec2f_le$arity$2(_,v); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.write_vec2f_le[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,v) : m__8103__auto__.call(null,_,v)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.write_vec2f_le["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,v) : m__8103__auto____$1.call(null,_,v)); } else { throw cljs.core.missing_protocol("IOutputStream.write-vec2f-le",_); } } } }); thi.ng.dstruct.streams.write_vec2f_be = (function thi$ng$dstruct$streams$write_vec2f_be(_,v){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IOutputStream$write_vec2f_be$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IOutputStream$write_vec2f_be$arity$2(_,v); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.write_vec2f_be[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,v) : m__8103__auto__.call(null,_,v)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.write_vec2f_be["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,v) : m__8103__auto____$1.call(null,_,v)); } else { throw cljs.core.missing_protocol("IOutputStream.write-vec2f-be",_); } } } }); thi.ng.dstruct.streams.write_vec3f_le = (function thi$ng$dstruct$streams$write_vec3f_le(_,v){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IOutputStream$write_vec3f_le$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IOutputStream$write_vec3f_le$arity$2(_,v); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.write_vec3f_le[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,v) : m__8103__auto__.call(null,_,v)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.write_vec3f_le["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,v) : m__8103__auto____$1.call(null,_,v)); } else { throw cljs.core.missing_protocol("IOutputStream.write-vec3f-le",_); } } } }); thi.ng.dstruct.streams.write_vec3f_be = (function thi$ng$dstruct$streams$write_vec3f_be(_,v){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IOutputStream$write_vec3f_be$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IOutputStream$write_vec3f_be$arity$2(_,v); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.write_vec3f_be[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,v) : m__8103__auto__.call(null,_,v)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.write_vec3f_be["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,v) : m__8103__auto____$1.call(null,_,v)); } else { throw cljs.core.missing_protocol("IOutputStream.write-vec3f-be",_); } } } }); /** * @interface */ thi.ng.dstruct.streams.IStreamPosition = function(){}; thi.ng.dstruct.streams.skip = (function thi$ng$dstruct$streams$skip(_,x){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IStreamPosition$skip$arity$2 == null)))){ return _.thi$ng$dstruct$streams$IStreamPosition$skip$arity$2(_,x); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.skip[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto__.call(null,_,x)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.skip["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$2(_,x) : m__8103__auto____$1.call(null,_,x)); } else { throw cljs.core.missing_protocol("IStreamPosition.skip",_); } } } }); thi.ng.dstruct.streams.get_position = (function thi$ng$dstruct$streams$get_position(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IStreamPosition$get_position$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IStreamPosition$get_position$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.get_position[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.get_position["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IStreamPosition.get-position",_); } } } }); /** * @interface */ thi.ng.dstruct.streams.IBuffer = function(){}; thi.ng.dstruct.streams.get_byte_buffer = (function thi$ng$dstruct$streams$get_byte_buffer(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IBuffer$get_byte_buffer$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IBuffer$get_byte_buffer$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.get_byte_buffer[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.get_byte_buffer["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IBuffer.get-byte-buffer",_); } } } }); thi.ng.dstruct.streams.get_float_buffer = (function thi$ng$dstruct$streams$get_float_buffer(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IBuffer$get_float_buffer$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IBuffer$get_float_buffer$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.get_float_buffer[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.get_float_buffer["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IBuffer.get-float-buffer",_); } } } }); thi.ng.dstruct.streams.get_double_buffer = (function thi$ng$dstruct$streams$get_double_buffer(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IBuffer$get_double_buffer$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IBuffer$get_double_buffer$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.get_double_buffer[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.get_double_buffer["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IBuffer.get-double-buffer",_); } } } }); thi.ng.dstruct.streams.get_short_buffer = (function thi$ng$dstruct$streams$get_short_buffer(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IBuffer$get_short_buffer$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IBuffer$get_short_buffer$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.get_short_buffer[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.get_short_buffer["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IBuffer.get-short-buffer",_); } } } }); thi.ng.dstruct.streams.get_int_buffer = (function thi$ng$dstruct$streams$get_int_buffer(_){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IBuffer$get_int_buffer$arity$1 == null)))){ return _.thi$ng$dstruct$streams$IBuffer$get_int_buffer$arity$1(_); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.get_int_buffer[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto__.call(null,_)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.get_int_buffer["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$1(_) : m__8103__auto____$1.call(null,_)); } else { throw cljs.core.missing_protocol("IBuffer.get-int-buffer",_); } } } }); /** * @interface */ thi.ng.dstruct.streams.IIntoBuffer = function(){}; thi.ng.dstruct.streams.into_byte_buffer = (function thi$ng$dstruct$streams$into_byte_buffer(_,dest,stride,idx){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IIntoBuffer$into_byte_buffer$arity$4 == null)))){ return _.thi$ng$dstruct$streams$IIntoBuffer$into_byte_buffer$arity$4(_,dest,stride,idx); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.into_byte_buffer[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$4 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$4(_,dest,stride,idx) : m__8103__auto__.call(null,_,dest,stride,idx)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.into_byte_buffer["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$4 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$4(_,dest,stride,idx) : m__8103__auto____$1.call(null,_,dest,stride,idx)); } else { throw cljs.core.missing_protocol("IIntoBuffer.into-byte-buffer",_); } } } }); thi.ng.dstruct.streams.into_float_buffer = (function thi$ng$dstruct$streams$into_float_buffer(_,dest,stride,idx){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IIntoBuffer$into_float_buffer$arity$4 == null)))){ return _.thi$ng$dstruct$streams$IIntoBuffer$into_float_buffer$arity$4(_,dest,stride,idx); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.into_float_buffer[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$4 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$4(_,dest,stride,idx) : m__8103__auto__.call(null,_,dest,stride,idx)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.into_float_buffer["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$4 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$4(_,dest,stride,idx) : m__8103__auto____$1.call(null,_,dest,stride,idx)); } else { throw cljs.core.missing_protocol("IIntoBuffer.into-float-buffer",_); } } } }); thi.ng.dstruct.streams.into_double_buffer = (function thi$ng$dstruct$streams$into_double_buffer(_,dest,stride,idx){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IIntoBuffer$into_double_buffer$arity$4 == null)))){ return _.thi$ng$dstruct$streams$IIntoBuffer$into_double_buffer$arity$4(_,dest,stride,idx); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.into_double_buffer[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$4 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$4(_,dest,stride,idx) : m__8103__auto__.call(null,_,dest,stride,idx)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.into_double_buffer["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$4 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$4(_,dest,stride,idx) : m__8103__auto____$1.call(null,_,dest,stride,idx)); } else { throw cljs.core.missing_protocol("IIntoBuffer.into-double-buffer",_); } } } }); thi.ng.dstruct.streams.into_short_buffer = (function thi$ng$dstruct$streams$into_short_buffer(_,dest,stride,idx){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IIntoBuffer$into_short_buffer$arity$4 == null)))){ return _.thi$ng$dstruct$streams$IIntoBuffer$into_short_buffer$arity$4(_,dest,stride,idx); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.into_short_buffer[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$4 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$4(_,dest,stride,idx) : m__8103__auto__.call(null,_,dest,stride,idx)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.into_short_buffer["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$4 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$4(_,dest,stride,idx) : m__8103__auto____$1.call(null,_,dest,stride,idx)); } else { throw cljs.core.missing_protocol("IIntoBuffer.into-short-buffer",_); } } } }); thi.ng.dstruct.streams.into_int_buffer = (function thi$ng$dstruct$streams$into_int_buffer(_,dest,stride,idx){ if((!((_ == null))) && (!((_.thi$ng$dstruct$streams$IIntoBuffer$into_int_buffer$arity$4 == null)))){ return _.thi$ng$dstruct$streams$IIntoBuffer$into_int_buffer$arity$4(_,dest,stride,idx); } else { var x__8102__auto__ = (((_ == null))?null:_); var m__8103__auto__ = (thi.ng.dstruct.streams.into_int_buffer[goog.typeOf(x__8102__auto__)]); if(!((m__8103__auto__ == null))){ return (m__8103__auto__.cljs$core$IFn$_invoke$arity$4 ? m__8103__auto__.cljs$core$IFn$_invoke$arity$4(_,dest,stride,idx) : m__8103__auto__.call(null,_,dest,stride,idx)); } else { var m__8103__auto____$1 = (thi.ng.dstruct.streams.into_int_buffer["_"]); if(!((m__8103__auto____$1 == null))){ return (m__8103__auto____$1.cljs$core$IFn$_invoke$arity$4 ? m__8103__auto____$1.cljs$core$IFn$_invoke$arity$4(_,dest,stride,idx) : m__8103__auto____$1.call(null,_,dest,stride,idx)); } else { throw cljs.core.missing_protocol("IIntoBuffer.into-int-buffer",_); } } } }); thi.ng.dstruct.streams.utf8_str = (function thi$ng$dstruct$streams$utf8_str(str){ var G__14532 = encodeURIComponent(str); return unescape(G__14532); }); /** * @constructor * @implements {thi.ng.dstruct.streams.IStreamPosition} * @implements {thi.ng.dstruct.streams.IBuffer} * @implements {thi.ng.dstruct.streams.IInputStream} */ thi.ng.dstruct.streams.InputStreamWrapper = (function (buf,dv,pos){ this.buf = buf; this.dv = dv; this.pos = pos; }) thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IInputStream$ = cljs.core.PROTOCOL_SENTINEL; thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IInputStream$read_double_be$arity$1 = (function (_){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2(___$1,(8)) : thi.ng.dstruct.streams.ensure_readable.call(null,___$1,(8))); var x = self__.dv.getFloat64(self__.pos); self__.pos = (self__.pos + (8)); return x; }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IInputStream$read_vec3f_le$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [thi.ng.dstruct.streams.read_float_le(___$1),thi.ng.dstruct.streams.read_float_le(___$1),thi.ng.dstruct.streams.read_float_le(___$1)], null); }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IInputStream$read_uint32_be$arity$1 = (function (_){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2(___$1,(4)) : thi.ng.dstruct.streams.ensure_readable.call(null,___$1,(4))); var x = self__.dv.getUint32(self__.pos); self__.pos = (self__.pos + (4)); return x; }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IInputStream$read_uint8$arity$1 = (function (_){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2(___$1,(1)) : thi.ng.dstruct.streams.ensure_readable.call(null,___$1,(1))); var x = self__.dv.getUint8(self__.pos); self__.pos = (self__.pos + (1)); return x; }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IInputStream$read_vec3f_be$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [thi.ng.dstruct.streams.read_float_be(___$1),thi.ng.dstruct.streams.read_float_be(___$1),thi.ng.dstruct.streams.read_float_be(___$1)], null); }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IInputStream$read_uint32_le$arity$1 = (function (_){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2(___$1,(4)) : thi.ng.dstruct.streams.ensure_readable.call(null,___$1,(4))); var x = self__.dv.getUint32(self__.pos,true); self__.pos = (self__.pos + (4)); return x; }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IInputStream$read_vec2f_le$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [thi.ng.dstruct.streams.read_float_le(___$1),thi.ng.dstruct.streams.read_float_le(___$1)], null); }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IInputStream$read_vec2f_be$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [thi.ng.dstruct.streams.read_float_be(___$1),thi.ng.dstruct.streams.read_float_be(___$1)], null); }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IInputStream$read_double_le$arity$1 = (function (_){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2(___$1,(8)) : thi.ng.dstruct.streams.ensure_readable.call(null,___$1,(8))); var x = self__.dv.getFloat64(self__.pos,true); self__.pos = (self__.pos + (8)); return x; }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IInputStream$read_uint16_be$arity$1 = (function (_){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2(___$1,(2)) : thi.ng.dstruct.streams.ensure_readable.call(null,___$1,(2))); var x = self__.dv.getUint16(self__.pos); self__.pos = (self__.pos + (2)); return x; }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IInputStream$read_uint16_le$arity$1 = (function (_){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2(___$1,(2)) : thi.ng.dstruct.streams.ensure_readable.call(null,___$1,(2))); var x = self__.dv.getUint16(self__.pos,true); self__.pos = (self__.pos + (2)); return x; }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IInputStream$read_float_le$arity$1 = (function (_){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2(___$1,(4)) : thi.ng.dstruct.streams.ensure_readable.call(null,___$1,(4))); var x = self__.dv.getFloat32(self__.pos,true); self__.pos = (self__.pos + (4)); return x; }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IInputStream$read_float_be$arity$1 = (function (_){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2(___$1,(4)) : thi.ng.dstruct.streams.ensure_readable.call(null,___$1,(4))); var x = self__.dv.getFloat32(self__.pos); self__.pos = (self__.pos + (4)); return x; }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IStreamPosition$ = cljs.core.PROTOCOL_SENTINEL; thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IStreamPosition$skip$arity$2 = (function (_,x){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_readable.cljs$core$IFn$_invoke$arity$2(___$1,x) : thi.ng.dstruct.streams.ensure_readable.call(null,___$1,x)); self__.pos = (self__.pos + x); return ___$1; }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IStreamPosition$get_position$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.pos; }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IBuffer$ = cljs.core.PROTOCOL_SENTINEL; thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IBuffer$get_byte_buffer$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return (new Uint8Array(self__.buf)); }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IBuffer$get_float_buffer$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return (new Float32Array(self__.buf)); }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IBuffer$get_double_buffer$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return (new Float64Array(self__.buf)); }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IBuffer$get_short_buffer$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return (new Uint16Array(self__.buf)); }); thi.ng.dstruct.streams.InputStreamWrapper.prototype.thi$ng$dstruct$streams$IBuffer$get_int_buffer$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return (new Uint32Array(self__.buf)); }); thi.ng.dstruct.streams.InputStreamWrapper.getBasis = (function (){ return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.with_meta(cljs.core.cst$sym$buf,new cljs.core.PersistentArrayMap(null, 1, [cljs.core.cst$kw$tag,cljs.core.cst$sym$js_SLASH_ArrayBuffer], null)),cljs.core.with_meta(cljs.core.cst$sym$dv,new cljs.core.PersistentArrayMap(null, 1, [cljs.core.cst$kw$tag,cljs.core.cst$sym$js_SLASH_DataView], null)),cljs.core.with_meta(cljs.core.cst$sym$pos,new cljs.core.PersistentArrayMap(null, 1, [cljs.core.cst$kw$mutable,true], null))], null); }); thi.ng.dstruct.streams.InputStreamWrapper.cljs$lang$type = true; thi.ng.dstruct.streams.InputStreamWrapper.cljs$lang$ctorStr = "thi.ng.dstruct.streams/InputStreamWrapper"; thi.ng.dstruct.streams.InputStreamWrapper.cljs$lang$ctorPrWriter = (function (this__8041__auto__,writer__8042__auto__,opt__8043__auto__){ return cljs.core._write(writer__8042__auto__,"thi.ng.dstruct.streams/InputStreamWrapper"); }); thi.ng.dstruct.streams.__GT_InputStreamWrapper = (function thi$ng$dstruct$streams$__GT_InputStreamWrapper(buf,dv,pos){ return (new thi.ng.dstruct.streams.InputStreamWrapper(buf,dv,pos)); }); /** * @constructor * @implements {thi.ng.dstruct.streams.IStreamPosition} * @implements {thi.ng.dstruct.streams.IBuffer} * @implements {thi.ng.dstruct.streams.IOutputStream} */ thi.ng.dstruct.streams.OutputStreamWrapper = (function (buf,dv,pos){ this.buf = buf; this.dv = dv; this.pos = pos; }) thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$ = cljs.core.PROTOCOL_SENTINEL; thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$write_utf8_bytes$arity$2 = (function (_,str){ var self__ = this; var ___$1 = this; var utf8_14535 = thi.ng.dstruct.streams.utf8_str(str); var len_14536 = cljs.core.count(utf8_14535); var G__14533_14537 = ___$1; var G__14534_14538 = cljs.core.count(utf8_14535); (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(G__14533_14537,G__14534_14538) : thi.ng.dstruct.streams.ensure_size.call(null,G__14533_14537,G__14534_14538)); var i_14539 = (0); var p_14540 = self__.pos; while(true){ if((i_14539 < len_14536)){ self__.dv.setUint8(p_14540,utf8_14535.charCodeAt(i_14539)); var G__14541 = (i_14539 + (1)); var G__14542 = (p_14540 + (1)); i_14539 = G__14541; p_14540 = G__14542; continue; } else { self__.pos = p_14540; } break; } return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$write_uint16_be$arity$2 = (function (_,x){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(___$1,(2)) : thi.ng.dstruct.streams.ensure_size.call(null,___$1,(2))); self__.dv.setUint16(self__.pos,x); self__.pos = (self__.pos + (2)); return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$write_uint16_le$arity$2 = (function (_,x){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(___$1,(2)) : thi.ng.dstruct.streams.ensure_size.call(null,___$1,(2))); self__.dv.setUint16(self__.pos,x,true); self__.pos = (self__.pos + (2)); return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$write_uint32_be$arity$2 = (function (_,x){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(___$1,(4)) : thi.ng.dstruct.streams.ensure_size.call(null,___$1,(4))); self__.dv.setUint32(self__.pos,x); self__.pos = (self__.pos + (4)); return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$write_vec3f_le$arity$2 = (function (_,v){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(___$1,(12)) : thi.ng.dstruct.streams.ensure_size.call(null,___$1,(12))); self__.dv.setFloat32(self__.pos,cljs.core.first(v),true); self__.dv.setFloat32((self__.pos + (4)),cljs.core.nth.cljs$core$IFn$_invoke$arity$2(v,(1)),true); self__.dv.setFloat32((self__.pos + (8)),cljs.core.nth.cljs$core$IFn$_invoke$arity$2(v,(2)),true); self__.pos = (self__.pos + (12)); return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$write_vec3f_be$arity$2 = (function (_,v){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(___$1,(12)) : thi.ng.dstruct.streams.ensure_size.call(null,___$1,(12))); self__.dv.setFloat32(self__.pos,cljs.core.first(v)); self__.dv.setFloat32((self__.pos + (4)),cljs.core.nth.cljs$core$IFn$_invoke$arity$2(v,(1))); self__.dv.setFloat32((self__.pos + (8)),cljs.core.nth.cljs$core$IFn$_invoke$arity$2(v,(2))); self__.pos = (self__.pos + (12)); return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$write_double_be$arity$2 = (function (_,x){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(___$1,(8)) : thi.ng.dstruct.streams.ensure_size.call(null,___$1,(8))); self__.dv.setFloat64(self__.pos,x); self__.pos = (self__.pos + (8)); return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$write_uint8$arity$2 = (function (_,x){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(___$1,(1)) : thi.ng.dstruct.streams.ensure_size.call(null,___$1,(1))); self__.dv.setUint8(self__.pos,x); self__.pos = (self__.pos + (1)); return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$write_float_be$arity$2 = (function (_,x){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(___$1,(4)) : thi.ng.dstruct.streams.ensure_size.call(null,___$1,(4))); self__.dv.setFloat32(self__.pos,x); self__.pos = (self__.pos + (4)); return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$write_float_le$arity$2 = (function (_,x){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(___$1,(4)) : thi.ng.dstruct.streams.ensure_size.call(null,___$1,(4))); self__.dv.setFloat32(self__.pos,x,true); self__.pos = (self__.pos + (4)); return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$write_uint32_le$arity$2 = (function (_,x){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(___$1,(4)) : thi.ng.dstruct.streams.ensure_size.call(null,___$1,(4))); self__.dv.setUint32(self__.pos,x,true); self__.pos = (self__.pos + (4)); return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$write_vec2f_be$arity$2 = (function (_,v){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(___$1,(8)) : thi.ng.dstruct.streams.ensure_size.call(null,___$1,(8))); self__.dv.setFloat32(self__.pos,cljs.core.first(v)); self__.dv.setFloat32((self__.pos + (4)),cljs.core.nth.cljs$core$IFn$_invoke$arity$2(v,(1))); self__.pos = (self__.pos + (8)); return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$write_double_le$arity$2 = (function (_,x){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(___$1,(8)) : thi.ng.dstruct.streams.ensure_size.call(null,___$1,(8))); self__.dv.setFloat64(self__.pos,x,true); self__.pos = (self__.pos + (8)); return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IOutputStream$write_vec2f_le$arity$2 = (function (_,v){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(___$1,(8)) : thi.ng.dstruct.streams.ensure_size.call(null,___$1,(8))); self__.dv.setFloat32(self__.pos,cljs.core.first(v),true); self__.dv.setFloat32((self__.pos + (4)),cljs.core.nth.cljs$core$IFn$_invoke$arity$2(v,(1)),true); self__.pos = (self__.pos + (8)); return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IStreamPosition$ = cljs.core.PROTOCOL_SENTINEL; thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IStreamPosition$skip$arity$2 = (function (_,x){ var self__ = this; var ___$1 = this; (thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2 ? thi.ng.dstruct.streams.ensure_size.cljs$core$IFn$_invoke$arity$2(___$1,x) : thi.ng.dstruct.streams.ensure_size.call(null,___$1,x)); self__.pos = (self__.pos + x); return ___$1; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IStreamPosition$get_position$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return self__.pos; }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IBuffer$ = cljs.core.PROTOCOL_SENTINEL; thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IBuffer$get_byte_buffer$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return (new Uint8Array(self__.buf,(0),self__.pos)); }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IBuffer$get_float_buffer$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return (new Float32Array(self__.buf,(0),(self__.pos >>> (2)))); }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IBuffer$get_double_buffer$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return (new Float64Array(self__.buf,(0),(self__.pos >>> (3)))); }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IBuffer$get_short_buffer$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return (new Uint16Array(self__.buf,(0),(self__.pos >>> (1)))); }); thi.ng.dstruct.streams.OutputStreamWrapper.prototype.thi$ng$dstruct$streams$IBuffer$get_int_buffer$arity$1 = (function (_){ var self__ = this; var ___$1 = this; return (new Uint32Array(self__.buf,(0),(self__.pos >>> (2)))); }); thi.ng.dstruct.streams.OutputStreamWrapper.getBasis = (function (){ return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.with_meta(cljs.core.cst$sym$buf,new cljs.core.PersistentArrayMap(null, 2, [cljs.core.cst$kw$tag,cljs.core.cst$sym$js_SLASH_ArrayBuffer,cljs.core.cst$kw$mutable,true], null)),cljs.core.with_meta(cljs.core.cst$sym$dv,new cljs.core.PersistentArrayMap(null, 2, [cljs.core.cst$kw$tag,cljs.core.cst$sym$js_SLASH_DataView,cljs.core.cst$kw$mutable,true], null)),cljs.core.with_meta(cljs.core.cst$sym$pos,new cljs.core.PersistentArrayMap(null, 1, [cljs.core.cst$kw$mutable,true], null))], null); }); thi.ng.dstruct.streams.OutputStreamWrapper.cljs$lang$type = true; thi.ng.dstruct.streams.OutputStreamWrapper.cljs$lang$ctorStr = "thi.ng.dstruct.streams/OutputStreamWrapper"; thi.ng.dstruct.streams.OutputStreamWrapper.cljs$lang$ctorPrWriter = (function (this__8041__auto__,writer__8042__auto__,opt__8043__auto__){ return cljs.core._write(writer__8042__auto__,"thi.ng.dstruct.streams/OutputStreamWrapper"); }); thi.ng.dstruct.streams.__GT_OutputStreamWrapper = (function thi$ng$dstruct$streams$__GT_OutputStreamWrapper(buf,dv,pos){ return (new thi.ng.dstruct.streams.OutputStreamWrapper(buf,dv,pos)); }); thi.ng.dstruct.streams.ensure_readable = (function thi$ng$dstruct$streams$ensure_readable(in$,size){ if(((in$.pos + size) > in$.buf.byteLength)){ throw (new Error([cljs.core.str("EOF overrun, current pos: "),cljs.core.str(in$.pos),cljs.core.str(", requested read length: "),cljs.core.str(size),cljs.core.str(", but length: "),cljs.core.str(in$.buf.byteLength)].join(''))); } else { return null; } }); thi.ng.dstruct.streams.ensure_size = (function thi$ng$dstruct$streams$ensure_size(out,size){ var len = out.buf.byteLength; if(((out.pos + size) > len)){ var buf_SINGLEQUOTE_ = (new ArrayBuffer((len + (16384)))); (new Uint8Array(buf_SINGLEQUOTE_)).set((new Uint8Array(out.buf,(0),out.pos))); out.buf = buf_SINGLEQUOTE_; return out.dv = (new DataView(buf_SINGLEQUOTE_)); } else { return null; } }); /** * Takes an input or outputstream and optional mime type, returns * contents as data url wrapped in a volatile. The volatile's value is * initially nil and will only become realized after the function * returned. */ thi.ng.dstruct.streams.as_data_url = (function thi$ng$dstruct$streams$as_data_url(var_args){ var args14543 = []; var len__8605__auto___14546 = arguments.length; var i__8606__auto___14547 = (0); while(true){ if((i__8606__auto___14547 < len__8605__auto___14546)){ args14543.push((arguments[i__8606__auto___14547])); var G__14548 = (i__8606__auto___14547 + (1)); i__8606__auto___14547 = G__14548; continue; } else { } break; } var G__14545 = args14543.length; switch (G__14545) { case 1: return thi.ng.dstruct.streams.as_data_url.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return thi.ng.dstruct.streams.as_data_url.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; default: throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(args14543.length)].join(''))); } }); thi.ng.dstruct.streams.as_data_url.cljs$core$IFn$_invoke$arity$1 = (function (stream){ return thi.ng.dstruct.streams.as_data_url.cljs$core$IFn$_invoke$arity$2(stream,"application/octet-stream"); }); thi.ng.dstruct.streams.as_data_url.cljs$core$IFn$_invoke$arity$2 = (function (stream,mime){ var fr = (new FileReader()); var uri = cljs.core.volatile_BANG_(null); fr.onload = ((function (fr,uri){ return (function (e){ return cljs.core.vreset_BANG_(uri,e.target.result); });})(fr,uri)) ; fr.readAsDataURL((new Blob([thi.ng.dstruct.streams.get_byte_buffer(stream)],({"type": mime})))); return uri; }); thi.ng.dstruct.streams.as_data_url.cljs$lang$maxFixedArity = 2; /** * Takes an input or outputstream, callback fn and optional mime * type, calls fn with data url string, returns nil. */ thi.ng.dstruct.streams.as_data_url_async = (function thi$ng$dstruct$streams$as_data_url_async(var_args){ var args14551 = []; var len__8605__auto___14555 = arguments.length; var i__8606__auto___14556 = (0); while(true){ if((i__8606__auto___14556 < len__8605__auto___14555)){ args14551.push((arguments[i__8606__auto___14556])); var G__14557 = (i__8606__auto___14556 + (1)); i__8606__auto___14556 = G__14557; continue; } else { } break; } var G__14553 = args14551.length; switch (G__14553) { case 2: return thi.ng.dstruct.streams.as_data_url_async.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; case 3: return thi.ng.dstruct.streams.as_data_url_async.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(args14551.length)].join(''))); } }); thi.ng.dstruct.streams.as_data_url_async.cljs$core$IFn$_invoke$arity$2 = (function (stream,cb){ return thi.ng.dstruct.streams.as_data_url_async.cljs$core$IFn$_invoke$arity$3(stream,cb,"application/octet-stream"); }); thi.ng.dstruct.streams.as_data_url_async.cljs$core$IFn$_invoke$arity$3 = (function (stream,cb,mime){ var fr = (new FileReader()); fr.onload = ((function (fr){ return (function (p1__14550_SHARP_){ var G__14554 = p1__14550_SHARP_.target.result; return (cb.cljs$core$IFn$_invoke$arity$1 ? cb.cljs$core$IFn$_invoke$arity$1(G__14554) : cb.call(null,G__14554)); });})(fr)) ; fr.readAsDataURL((new Blob([thi.ng.dstruct.streams.get_byte_buffer(stream)],({"type": mime})))); return null; }); thi.ng.dstruct.streams.as_data_url_async.cljs$lang$maxFixedArity = 3; thi.ng.dstruct.streams.input_stream = (function thi$ng$dstruct$streams$input_stream(var_args){ var args14559 = []; var len__8605__auto___14562 = arguments.length; var i__8606__auto___14563 = (0); while(true){ if((i__8606__auto___14563 < len__8605__auto___14562)){ args14559.push((arguments[i__8606__auto___14563])); var G__14564 = (i__8606__auto___14563 + (1)); i__8606__auto___14563 = G__14564; continue; } else { } break; } var G__14561 = args14559.length; switch (G__14561) { case 1: return thi.ng.dstruct.streams.input_stream.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return thi.ng.dstruct.streams.input_stream.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; default: throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(args14559.length)].join(''))); } }); thi.ng.dstruct.streams.input_stream.cljs$core$IFn$_invoke$arity$1 = (function (buf){ return thi.ng.dstruct.streams.input_stream.cljs$core$IFn$_invoke$arity$2(buf,(0)); }); thi.ng.dstruct.streams.input_stream.cljs$core$IFn$_invoke$arity$2 = (function (buf,pos){ return (new thi.ng.dstruct.streams.InputStreamWrapper(buf,(new DataView(buf)),pos)); }); thi.ng.dstruct.streams.input_stream.cljs$lang$maxFixedArity = 2; thi.ng.dstruct.streams.output_stream = (function thi$ng$dstruct$streams$output_stream(var_args){ var args14566 = []; var len__8605__auto___14569 = arguments.length; var i__8606__auto___14570 = (0); while(true){ if((i__8606__auto___14570 < len__8605__auto___14569)){ args14566.push((arguments[i__8606__auto___14570])); var G__14571 = (i__8606__auto___14570 + (1)); i__8606__auto___14570 = G__14571; continue; } else { } break; } var G__14568 = args14566.length; switch (G__14568) { case 0: return thi.ng.dstruct.streams.output_stream.cljs$core$IFn$_invoke$arity$0(); break; case 1: return thi.ng.dstruct.streams.output_stream.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 2: return thi.ng.dstruct.streams.output_stream.cljs$core$IFn$_invoke$arity$2((arguments[(0)]),(arguments[(1)])); break; default: throw (new Error([cljs.core.str("Invalid arity: "),cljs.core.str(args14566.length)].join(''))); } }); thi.ng.dstruct.streams.output_stream.cljs$core$IFn$_invoke$arity$0 = (function (){ return thi.ng.dstruct.streams.output_stream.cljs$core$IFn$_invoke$arity$1((4096)); }); thi.ng.dstruct.streams.output_stream.cljs$core$IFn$_invoke$arity$1 = (function (size){ return thi.ng.dstruct.streams.output_stream.cljs$core$IFn$_invoke$arity$2((new ArrayBuffer(size)),(0)); }); thi.ng.dstruct.streams.output_stream.cljs$core$IFn$_invoke$arity$2 = (function (buf,pos){ return (new thi.ng.dstruct.streams.OutputStreamWrapper(buf,(new DataView(buf)),pos)); }); thi.ng.dstruct.streams.output_stream.cljs$lang$maxFixedArity = 2;
scientific-coder/Mazes
target/main.out/thi/ng/dstruct/streams.js
JavaScript
gpl-3.0
66,698
package com.srlupdater.updater.injection.analyzers; import com.srlupdater.updater.injection.generic.AbstractAnalyzer; import com.srlupdater.updater.injection.generic.Hook; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import java.util.ListIterator; public class ItemAnalyzer extends AbstractAnalyzer { @Override protected boolean canRun(ClassNode node) { if (!node.superName.equals(classNodes.get("Renderable").name) || classNodes.containsKey("Item")) return false; ListIterator<MethodNode> mnli = node.methods.listIterator(); while (mnli.hasNext()) { MethodNode mn = mnli.next(); if (mn.name.equals("<init>")) { if (mn.instructions.get(3).getOpcode() == Opcodes.RETURN) return true; } } return false; } @Override protected Hook analyse(ClassNode node) { Hook hook = new Hook("Item",node.name); classNodes.put("Item",node); return hook; } }
NKNScripts/Updater
src/com/srlupdater/updater/injection/analyzers/ItemAnalyzer.java
Java
gpl-3.0
1,089