code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
# promise-tracker-client WebApp Client that works with https://github.com/jfresco/promise-tracker-api
mjlescano/promise-tracker-client
README.md
Markdown
gpl-2.0
102
package com.coffee.finder.util.locationmanager; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.location.*; import android.net.Uri; import android.util.Log; import android.view.Menu; import com.coffee.finder.HomeActivity; import com.coffee.finder.R; import com.coffee.finder.util.networkmanager.CustomNetworkManager; import java.io.IOException; import java.util.List; import java.util.Locale; /** * Created by Josh on 10/02/2015. */ public class CurrentLocationManager { public static CurrentLocationManager instance; private LocationManager locationManager; private LocationListener locationListener; private Context ctx; private boolean isListeningForGeolocationUpdates = false; private CurrentLocationManager(Context ctx) { this.ctx = ctx; } public static void init(Context ctx) { if (instance != null) { Log.d("CurrentLocationManager", "CurrentLocationManager already initialised, not attempting to reinitialise"); return; } instance = new CurrentLocationManager(ctx); Log.d("CurrentLocationManager", "CurrentLocationManager initialised"); instance.setupLocationUpdates(); } public boolean isGeoLocationUpdating() { return isListeningForGeolocationUpdates; } public boolean hasValidLocationListener() { return locationListener != null; } public LocationListener getCurrentLocationListener() { return locationListener; } public void directToPhone(String phoneNumber) { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber)); ctx.startActivity(intent); } public void directToGoogleMaps(String destination) { String currentLocation = CurrentLocationListener.latitude+","+CurrentLocationListener.longitude; Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr=" + currentLocation + "&daddr=" + destination)); ctx.startActivity(intent); } public void updateLocationText() { Menu optionsMenu = ((HomeActivity)ctx).getSplitActionBarMenu(); double lat = CurrentLocationListener.latitude; double lng = CurrentLocationListener.longitude; String addressString = ""; //If the split action bar hasn't initialised, don't attempt to update it. if (optionsMenu == null) return; Log.d("CurrentLocationManager", "Updating Location Text"); final LocationManager manager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE); //If GPS is not enabled, add that to the message if (!manager.isProviderEnabled( LocationManager.GPS_PROVIDER) ) { addressString = "GPS Disabled"; } //If we can't access the internet, add that to the message as well else if (!CustomNetworkManager.get().getIsMobileDataEnabled() && !CustomNetworkManager.get().getIsWifiConnected()) { if (!addressString.equals("")) addressString += ", "; addressString += "Internet Not Connected"; } //If GPS is disabled or we can't access the internet, don't attempt to display address data else { Geocoder geocoder = new Geocoder(ctx, Locale.getDefault()); //Get the nearest street address for the user and add that to the message try { List<Address> addresses = geocoder.getFromLocation(lat, lng, 1); if (addresses.size() != 0) addressString += addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getAddressLine(1); Log.d("CurrentLocationManager", addressString); } catch (IOException e) { e.printStackTrace(); } } Log.d("CurrentLocationManager", "User status output: "+addressString); optionsMenu.findItem(R.id.action_bar_status_text).setTitle(addressString); } public void setupLocationUpdates() { if (locationManager != null) { Log.d("CurrentLocationManager", "Location already updating..."); return; } //Listening for geolocation updates also lets us know when GPS is enabled or disabled Log.d("CurrentLocationManager", "Setting up location updates"); locationManager = (LocationManager)ctx.getSystemService(Context.LOCATION_SERVICE); locationListener = new CurrentLocationListener(); locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 300000, 50, locationListener); isListeningForGeolocationUpdates = true; //Display a warning message if GPS is disabled if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Log.d("CurrentLocationManager", "GPS is not enabled"); AlertDialog.Builder dialogue = new AlertDialog.Builder(ctx); dialogue.setTitle("Error"); dialogue.setMessage("GPS is not enabled. Enable GPS before attempting to make a search."); dialogue.setPositiveButton("Continue", null); dialogue.show(); return; } //Attempt to get last known location from old GPS data, if anything exists. Log.d("CurrentLocationManager", "Requesting last known location"); requestLastKnownLocation(); } public void requestLastKnownLocation() { Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (lastKnownLocation != null) { locationListener.onLocationChanged(lastKnownLocation); } } public void stopLocationUpdates() { Log.d("CurrentLocationManager", "Stopping location updates..."); if (locationListener != null) locationManager.removeUpdates(locationListener); locationListener = null; locationManager = null; isListeningForGeolocationUpdates = false; } public static CurrentLocationManager get() { if (instance == null) throw new RuntimeException("Please initialise FoursquareHelper first."); return instance; } public void setupLocationUpdatedEvent(LocationEvent event) { if (locationListener != null) ((CurrentLocationListener)locationListener).setLocationUpdatedEvent(event); } }
jbright927/CoffeeFinder
src/com/coffee/finder/util/locationmanager/CurrentLocationManager.java
Java
gpl-2.0
6,496
<?php class JConfig { public $offline = '0'; public $offline_message = 'This site is down for maintenance.<br /> Please check back again soon.'; public $display_offline_message = '1'; public $offline_image = 'images/maintenance.jpg'; public $sitename = 'Astro Isha'; public $editor = 'none'; public $captcha = 'recaptcha'; public $list_limit = '20'; public $access = '1'; public $debug = '0'; public $debug_lang = '0'; public $dbtype = 'mysqli'; public $host = 'localhost'; public $user = 'root'; public $password = 'desai1985'; public $db = 'jyotishividya'; public $dbprefix = 'jv_'; public $live_site = ''; public $secret = 'o9TGynnHQQTK56DS'; public $gzip = '0'; public $error_reporting = 'default'; public $helpurl = 'http://help.joomla.org/proxy/index.php?option=com_help&keyref=Help{major}{minor}:{keyref}'; public $ftp_host = '127.0.0.1'; public $ftp_port = '21'; public $ftp_user = 'zoro123'; public $ftp_pass = 'DenaDena1985'; public $ftp_root = ''; public $ftp_enable = '0'; public $offset = 'UTC'; public $mailonline = '1'; public $mailer = 'mail'; public $mailfrom = 'admin@astroisha.com'; public $fromname = 'Astro Isha'; public $sendmail = '/usr/sbin/sendmail'; public $smtpauth = '0'; public $smtpuser = ''; public $smtppass = ''; public $smtphost = 'localhost'; public $smtpsecure = 'none'; public $smtpport = '25'; public $caching = '0'; public $cache_handler = 'file'; public $cachetime = '15'; public $MetaDesc = 'Comprehensive Guide to Vedic Astrology'; public $MetaKeys = 'vedic astrology, astrology, 27 nakshatras, 9 grahas, shani, mangal, 12 bhavas, 12 rashis,'; public $MetaTitle = '1'; public $MetaAuthor = '0'; public $MetaVersion = '0'; public $robots = ''; public $sef = '1'; public $sef_rewrite = '1'; public $sef_suffix = '1'; public $unicodeslugs = '0'; public $feed_limit = '10'; public $log_path = '/opt/lampp/htdocs/jvidya/logs'; public $tmp_path = '/opt/lampp/htdocs/jvidya/tmp'; public $lifetime = '15'; public $session_handler = 'database'; public $MetaRights = ''; public $sitename_pagetitles = '1'; public $force_ssl = '0'; public $frontediting = '0'; public $feed_email = 'author'; public $cookie_domain = ''; public $cookie_path = ''; public $asset_id = '1'; public $proxy_enable = '0'; public $proxy_host = ''; public $proxy_port = ''; public $proxy_user = ''; public $proxy_pass = ''; }
luffy22/jvidya
configuration.php
PHP
gpl-2.0
2,400
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <title>Source code</title> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <div class="sourceContainer"> <pre><span class="sourceLineNo">001</span>/* ===========================================================<a name="line.1"></a> <span class="sourceLineNo">002</span> * JFreeChart : a free chart library for the Java(tm) platform<a name="line.2"></a> <span class="sourceLineNo">003</span> * ===========================================================<a name="line.3"></a> <span class="sourceLineNo">004</span> *<a name="line.4"></a> <span class="sourceLineNo">005</span> * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors.<a name="line.5"></a> <span class="sourceLineNo">006</span> *<a name="line.6"></a> <span class="sourceLineNo">007</span> * Project Info: http://www.jfree.org/jfreechart/index.html<a name="line.7"></a> <span class="sourceLineNo">008</span> *<a name="line.8"></a> <span class="sourceLineNo">009</span> * This library is free software; you can redistribute it and/or modify it<a name="line.9"></a> <span class="sourceLineNo">010</span> * under the terms of the GNU Lesser General Public License as published by<a name="line.10"></a> <span class="sourceLineNo">011</span> * the Free Software Foundation; either version 2.1 of the License, or<a name="line.11"></a> <span class="sourceLineNo">012</span> * (at your option) any later version.<a name="line.12"></a> <span class="sourceLineNo">013</span> *<a name="line.13"></a> <span class="sourceLineNo">014</span> * This library is distributed in the hope that it will be useful, but<a name="line.14"></a> <span class="sourceLineNo">015</span> * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY<a name="line.15"></a> <span class="sourceLineNo">016</span> * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public<a name="line.16"></a> <span class="sourceLineNo">017</span> * License for more details.<a name="line.17"></a> <span class="sourceLineNo">018</span> *<a name="line.18"></a> <span class="sourceLineNo">019</span> * You should have received a copy of the GNU Lesser General Public<a name="line.19"></a> <span class="sourceLineNo">020</span> * License along with this library; if not, write to the Free Software<a name="line.20"></a> <span class="sourceLineNo">021</span> * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,<a name="line.21"></a> <span class="sourceLineNo">022</span> * USA.<a name="line.22"></a> <span class="sourceLineNo">023</span> *<a name="line.23"></a> <span class="sourceLineNo">024</span> * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. <a name="line.24"></a> <span class="sourceLineNo">025</span> * Other names may be trademarks of their respective owners.]<a name="line.25"></a> <span class="sourceLineNo">026</span> *<a name="line.26"></a> <span class="sourceLineNo">027</span> * ---------------------------------<a name="line.27"></a> <span class="sourceLineNo">028</span> * IntervalXYItemLabelGenerator.java<a name="line.28"></a> <span class="sourceLineNo">029</span> * ---------------------------------<a name="line.29"></a> <span class="sourceLineNo">030</span> * (C) Copyright 2008, by Object Refinery Limited.<a name="line.30"></a> <span class="sourceLineNo">031</span> *<a name="line.31"></a> <span class="sourceLineNo">032</span> * Original Author: David Gilbert (for Object Refinery Limited);<a name="line.32"></a> <span class="sourceLineNo">033</span> * Contributor(s): -;<a name="line.33"></a> <span class="sourceLineNo">034</span> *<a name="line.34"></a> <span class="sourceLineNo">035</span> * Changes<a name="line.35"></a> <span class="sourceLineNo">036</span> * -------<a name="line.36"></a> <span class="sourceLineNo">037</span> * 26-May-2008 : Version 1 (DG);<a name="line.37"></a> <span class="sourceLineNo">038</span> *<a name="line.38"></a> <span class="sourceLineNo">039</span> */<a name="line.39"></a> <span class="sourceLineNo">040</span><a name="line.40"></a> <span class="sourceLineNo">041</span>package org.jfree.chart.labels;<a name="line.41"></a> <span class="sourceLineNo">042</span><a name="line.42"></a> <span class="sourceLineNo">043</span>import java.io.Serializable;<a name="line.43"></a> <span class="sourceLineNo">044</span>import java.text.DateFormat;<a name="line.44"></a> <span class="sourceLineNo">045</span>import java.text.MessageFormat;<a name="line.45"></a> <span class="sourceLineNo">046</span>import java.text.NumberFormat;<a name="line.46"></a> <span class="sourceLineNo">047</span>import java.util.Date;<a name="line.47"></a> <span class="sourceLineNo">048</span><a name="line.48"></a> <span class="sourceLineNo">049</span>import org.jfree.data.xy.IntervalXYDataset;<a name="line.49"></a> <span class="sourceLineNo">050</span>import org.jfree.data.xy.XYDataset;<a name="line.50"></a> <span class="sourceLineNo">051</span>import org.jfree.util.PublicCloneable;<a name="line.51"></a> <span class="sourceLineNo">052</span><a name="line.52"></a> <span class="sourceLineNo">053</span>/**<a name="line.53"></a> <span class="sourceLineNo">054</span> * An item label generator for datasets that implement the<a name="line.54"></a> <span class="sourceLineNo">055</span> * {@link IntervalXYDataset} interface.<a name="line.55"></a> <span class="sourceLineNo">056</span> *<a name="line.56"></a> <span class="sourceLineNo">057</span> * @since 1.0.10<a name="line.57"></a> <span class="sourceLineNo">058</span> */<a name="line.58"></a> <span class="sourceLineNo">059</span>public class IntervalXYItemLabelGenerator extends AbstractXYItemLabelGenerator<a name="line.59"></a> <span class="sourceLineNo">060</span> implements XYItemLabelGenerator, Cloneable, PublicCloneable,<a name="line.60"></a> <span class="sourceLineNo">061</span> Serializable {<a name="line.61"></a> <span class="sourceLineNo">062</span><a name="line.62"></a> <span class="sourceLineNo">063</span> /** The default item label format. */<a name="line.63"></a> <span class="sourceLineNo">064</span> public static final String DEFAULT_ITEM_LABEL_FORMAT = "{5} - {6}";<a name="line.64"></a> <span class="sourceLineNo">065</span><a name="line.65"></a> <span class="sourceLineNo">066</span> /**<a name="line.66"></a> <span class="sourceLineNo">067</span> * Creates an item label generator using default number formatters.<a name="line.67"></a> <span class="sourceLineNo">068</span> */<a name="line.68"></a> <span class="sourceLineNo">069</span> public IntervalXYItemLabelGenerator() {<a name="line.69"></a> <span class="sourceLineNo">070</span> this(DEFAULT_ITEM_LABEL_FORMAT, NumberFormat.getNumberInstance(),<a name="line.70"></a> <span class="sourceLineNo">071</span> NumberFormat.getNumberInstance());<a name="line.71"></a> <span class="sourceLineNo">072</span> }<a name="line.72"></a> <span class="sourceLineNo">073</span><a name="line.73"></a> <span class="sourceLineNo">074</span> /**<a name="line.74"></a> <span class="sourceLineNo">075</span> * Creates an item label generator using the specified number formatters.<a name="line.75"></a> <span class="sourceLineNo">076</span> *<a name="line.76"></a> <span class="sourceLineNo">077</span> * @param formatString the item label format string (&lt;code&gt;null&lt;/code&gt; not<a name="line.77"></a> <span class="sourceLineNo">078</span> * permitted).<a name="line.78"></a> <span class="sourceLineNo">079</span> * @param xFormat the format object for the x values (&lt;code&gt;null&lt;/code&gt;<a name="line.79"></a> <span class="sourceLineNo">080</span> * not permitted).<a name="line.80"></a> <span class="sourceLineNo">081</span> * @param yFormat the format object for the y values (&lt;code&gt;null&lt;/code&gt;<a name="line.81"></a> <span class="sourceLineNo">082</span> * not permitted).<a name="line.82"></a> <span class="sourceLineNo">083</span> */<a name="line.83"></a> <span class="sourceLineNo">084</span> public IntervalXYItemLabelGenerator(String formatString,<a name="line.84"></a> <span class="sourceLineNo">085</span> NumberFormat xFormat, NumberFormat yFormat) {<a name="line.85"></a> <span class="sourceLineNo">086</span><a name="line.86"></a> <span class="sourceLineNo">087</span> super(formatString, xFormat, yFormat);<a name="line.87"></a> <span class="sourceLineNo">088</span> }<a name="line.88"></a> <span class="sourceLineNo">089</span><a name="line.89"></a> <span class="sourceLineNo">090</span> /**<a name="line.90"></a> <span class="sourceLineNo">091</span> * Creates an item label generator using the specified formatters.<a name="line.91"></a> <span class="sourceLineNo">092</span> *<a name="line.92"></a> <span class="sourceLineNo">093</span> * @param formatString the item label format string (&lt;code&gt;null&lt;/code&gt;<a name="line.93"></a> <span class="sourceLineNo">094</span> * not permitted).<a name="line.94"></a> <span class="sourceLineNo">095</span> * @param xFormat the format object for the x values (&lt;code&gt;null&lt;/code&gt;<a name="line.95"></a> <span class="sourceLineNo">096</span> * not permitted).<a name="line.96"></a> <span class="sourceLineNo">097</span> * @param yFormat the format object for the y values (&lt;code&gt;null&lt;/code&gt;<a name="line.97"></a> <span class="sourceLineNo">098</span> * not permitted).<a name="line.98"></a> <span class="sourceLineNo">099</span> */<a name="line.99"></a> <span class="sourceLineNo">100</span> public IntervalXYItemLabelGenerator(String formatString,<a name="line.100"></a> <span class="sourceLineNo">101</span> DateFormat xFormat, NumberFormat yFormat) {<a name="line.101"></a> <span class="sourceLineNo">102</span><a name="line.102"></a> <span class="sourceLineNo">103</span> super(formatString, xFormat, yFormat);<a name="line.103"></a> <span class="sourceLineNo">104</span> }<a name="line.104"></a> <span class="sourceLineNo">105</span><a name="line.105"></a> <span class="sourceLineNo">106</span> /**<a name="line.106"></a> <span class="sourceLineNo">107</span> * Creates an item label generator using the specified formatters (a<a name="line.107"></a> <span class="sourceLineNo">108</span> * number formatter for the x-values and a date formatter for the<a name="line.108"></a> <span class="sourceLineNo">109</span> * y-values).<a name="line.109"></a> <span class="sourceLineNo">110</span> *<a name="line.110"></a> <span class="sourceLineNo">111</span> * @param formatString the item label format string (&lt;code&gt;null&lt;/code&gt;<a name="line.111"></a> <span class="sourceLineNo">112</span> * not permitted).<a name="line.112"></a> <span class="sourceLineNo">113</span> * @param xFormat the format object for the x values (&lt;code&gt;null&lt;/code&gt;<a name="line.113"></a> <span class="sourceLineNo">114</span> * permitted).<a name="line.114"></a> <span class="sourceLineNo">115</span> * @param yFormat the format object for the y values (&lt;code&gt;null&lt;/code&gt;<a name="line.115"></a> <span class="sourceLineNo">116</span> * not permitted).<a name="line.116"></a> <span class="sourceLineNo">117</span> */<a name="line.117"></a> <span class="sourceLineNo">118</span> public IntervalXYItemLabelGenerator(String formatString,<a name="line.118"></a> <span class="sourceLineNo">119</span> NumberFormat xFormat, DateFormat yFormat) {<a name="line.119"></a> <span class="sourceLineNo">120</span><a name="line.120"></a> <span class="sourceLineNo">121</span> super(formatString, xFormat, yFormat);<a name="line.121"></a> <span class="sourceLineNo">122</span> }<a name="line.122"></a> <span class="sourceLineNo">123</span><a name="line.123"></a> <span class="sourceLineNo">124</span> /**<a name="line.124"></a> <span class="sourceLineNo">125</span> * Creates a label generator using the specified date formatters.<a name="line.125"></a> <span class="sourceLineNo">126</span> *<a name="line.126"></a> <span class="sourceLineNo">127</span> * @param formatString the label format string (&lt;code&gt;null&lt;/code&gt; not<a name="line.127"></a> <span class="sourceLineNo">128</span> * permitted).<a name="line.128"></a> <span class="sourceLineNo">129</span> * @param xFormat the format object for the x values (&lt;code&gt;null&lt;/code&gt;<a name="line.129"></a> <span class="sourceLineNo">130</span> * not permitted).<a name="line.130"></a> <span class="sourceLineNo">131</span> * @param yFormat the format object for the y values (&lt;code&gt;null&lt;/code&gt;<a name="line.131"></a> <span class="sourceLineNo">132</span> * not permitted).<a name="line.132"></a> <span class="sourceLineNo">133</span> */<a name="line.133"></a> <span class="sourceLineNo">134</span> public IntervalXYItemLabelGenerator(String formatString,<a name="line.134"></a> <span class="sourceLineNo">135</span> DateFormat xFormat, DateFormat yFormat) {<a name="line.135"></a> <span class="sourceLineNo">136</span><a name="line.136"></a> <span class="sourceLineNo">137</span> super(formatString, xFormat, yFormat);<a name="line.137"></a> <span class="sourceLineNo">138</span> }<a name="line.138"></a> <span class="sourceLineNo">139</span><a name="line.139"></a> <span class="sourceLineNo">140</span> /**<a name="line.140"></a> <span class="sourceLineNo">141</span> * Creates the array of items that can be passed to the<a name="line.141"></a> <span class="sourceLineNo">142</span> * {@link MessageFormat} class for creating labels.<a name="line.142"></a> <span class="sourceLineNo">143</span> *<a name="line.143"></a> <span class="sourceLineNo">144</span> * @param dataset the dataset (&lt;code&gt;null&lt;/code&gt; not permitted).<a name="line.144"></a> <span class="sourceLineNo">145</span> * @param series the series (zero-based index).<a name="line.145"></a> <span class="sourceLineNo">146</span> * @param item the item (zero-based index).<a name="line.146"></a> <span class="sourceLineNo">147</span> *<a name="line.147"></a> <span class="sourceLineNo">148</span> * @return An array of seven items from the dataset formatted as<a name="line.148"></a> <span class="sourceLineNo">149</span> * &lt;code&gt;String&lt;/code&gt; objects (never &lt;code&gt;null&lt;/code&gt;).<a name="line.149"></a> <span class="sourceLineNo">150</span> */<a name="line.150"></a> <span class="sourceLineNo">151</span> protected Object[] createItemArray(XYDataset dataset, int series,<a name="line.151"></a> <span class="sourceLineNo">152</span> int item) {<a name="line.152"></a> <span class="sourceLineNo">153</span><a name="line.153"></a> <span class="sourceLineNo">154</span> IntervalXYDataset intervalDataset = null;<a name="line.154"></a> <span class="sourceLineNo">155</span> if (dataset instanceof IntervalXYDataset) {<a name="line.155"></a> <span class="sourceLineNo">156</span> intervalDataset = (IntervalXYDataset) dataset;<a name="line.156"></a> <span class="sourceLineNo">157</span> }<a name="line.157"></a> <span class="sourceLineNo">158</span> Object[] result = new Object[7];<a name="line.158"></a> <span class="sourceLineNo">159</span> result[0] = dataset.getSeriesKey(series).toString();<a name="line.159"></a> <span class="sourceLineNo">160</span><a name="line.160"></a> <span class="sourceLineNo">161</span> double x = dataset.getXValue(series, item);<a name="line.161"></a> <span class="sourceLineNo">162</span> double xs = x;<a name="line.162"></a> <span class="sourceLineNo">163</span> double xe = x;<a name="line.163"></a> <span class="sourceLineNo">164</span> double y = dataset.getYValue(series, item);<a name="line.164"></a> <span class="sourceLineNo">165</span> double ys = y;<a name="line.165"></a> <span class="sourceLineNo">166</span> double ye = y;<a name="line.166"></a> <span class="sourceLineNo">167</span> if (intervalDataset != null) {<a name="line.167"></a> <span class="sourceLineNo">168</span> xs = intervalDataset.getStartXValue(series, item);<a name="line.168"></a> <span class="sourceLineNo">169</span> xe = intervalDataset.getEndXValue(series, item);<a name="line.169"></a> <span class="sourceLineNo">170</span> ys = intervalDataset.getStartYValue(series, item);<a name="line.170"></a> <span class="sourceLineNo">171</span> ye = intervalDataset.getEndYValue(series, item);<a name="line.171"></a> <span class="sourceLineNo">172</span> }<a name="line.172"></a> <span class="sourceLineNo">173</span><a name="line.173"></a> <span class="sourceLineNo">174</span> DateFormat xdf = getXDateFormat();<a name="line.174"></a> <span class="sourceLineNo">175</span> if (xdf != null) {<a name="line.175"></a> <span class="sourceLineNo">176</span> result[1] = xdf.format(new Date((long) x));<a name="line.176"></a> <span class="sourceLineNo">177</span> result[2] = xdf.format(new Date((long) xs));<a name="line.177"></a> <span class="sourceLineNo">178</span> result[3] = xdf.format(new Date((long) xe));<a name="line.178"></a> <span class="sourceLineNo">179</span> }<a name="line.179"></a> <span class="sourceLineNo">180</span> else {<a name="line.180"></a> <span class="sourceLineNo">181</span> NumberFormat xnf = getXFormat();<a name="line.181"></a> <span class="sourceLineNo">182</span> result[1] = xnf.format(x);<a name="line.182"></a> <span class="sourceLineNo">183</span> result[2] = xnf.format(xs);<a name="line.183"></a> <span class="sourceLineNo">184</span> result[3] = xnf.format(xe);<a name="line.184"></a> <span class="sourceLineNo">185</span> }<a name="line.185"></a> <span class="sourceLineNo">186</span><a name="line.186"></a> <span class="sourceLineNo">187</span> NumberFormat ynf = getYFormat();<a name="line.187"></a> <span class="sourceLineNo">188</span> DateFormat ydf = getYDateFormat();<a name="line.188"></a> <span class="sourceLineNo">189</span> if (Double.isNaN(y) &amp;&amp; dataset.getY(series, item) == null) {<a name="line.189"></a> <span class="sourceLineNo">190</span> result[4] = getNullYString();<a name="line.190"></a> <span class="sourceLineNo">191</span> }<a name="line.191"></a> <span class="sourceLineNo">192</span> else {<a name="line.192"></a> <span class="sourceLineNo">193</span> if (ydf != null) {<a name="line.193"></a> <span class="sourceLineNo">194</span> result[4] = ydf.format(new Date((long) y));<a name="line.194"></a> <span class="sourceLineNo">195</span> }<a name="line.195"></a> <span class="sourceLineNo">196</span> else {<a name="line.196"></a> <span class="sourceLineNo">197</span> result[4] = ynf.format(y);<a name="line.197"></a> <span class="sourceLineNo">198</span> }<a name="line.198"></a> <span class="sourceLineNo">199</span> }<a name="line.199"></a> <span class="sourceLineNo">200</span> if (Double.isNaN(ys)<a name="line.200"></a> <span class="sourceLineNo">201</span> &amp;&amp; intervalDataset.getStartY(series, item) == null) {<a name="line.201"></a> <span class="sourceLineNo">202</span> result[5] = getNullYString();<a name="line.202"></a> <span class="sourceLineNo">203</span> }<a name="line.203"></a> <span class="sourceLineNo">204</span> else {<a name="line.204"></a> <span class="sourceLineNo">205</span> if (ydf != null) {<a name="line.205"></a> <span class="sourceLineNo">206</span> result[5] = ydf.format(new Date((long) ys));<a name="line.206"></a> <span class="sourceLineNo">207</span> }<a name="line.207"></a> <span class="sourceLineNo">208</span> else {<a name="line.208"></a> <span class="sourceLineNo">209</span> result[5] = ynf.format(ys);<a name="line.209"></a> <span class="sourceLineNo">210</span> }<a name="line.210"></a> <span class="sourceLineNo">211</span> }<a name="line.211"></a> <span class="sourceLineNo">212</span> if (Double.isNaN(ye)<a name="line.212"></a> <span class="sourceLineNo">213</span> &amp;&amp; intervalDataset.getEndY(series, item) == null) {<a name="line.213"></a> <span class="sourceLineNo">214</span> result[6] = getNullYString();<a name="line.214"></a> <span class="sourceLineNo">215</span> }<a name="line.215"></a> <span class="sourceLineNo">216</span> else {<a name="line.216"></a> <span class="sourceLineNo">217</span> if (ydf != null) {<a name="line.217"></a> <span class="sourceLineNo">218</span> result[6] = ydf.format(new Date((long) ye));<a name="line.218"></a> <span class="sourceLineNo">219</span> }<a name="line.219"></a> <span class="sourceLineNo">220</span> else {<a name="line.220"></a> <span class="sourceLineNo">221</span> result[6] = ynf.format(ye);<a name="line.221"></a> <span class="sourceLineNo">222</span> }<a name="line.222"></a> <span class="sourceLineNo">223</span> }<a name="line.223"></a> <span class="sourceLineNo">224</span> return result;<a name="line.224"></a> <span class="sourceLineNo">225</span> }<a name="line.225"></a> <span class="sourceLineNo">226</span><a name="line.226"></a> <span class="sourceLineNo">227</span> /**<a name="line.227"></a> <span class="sourceLineNo">228</span> * Generates the item label text for an item in a dataset.<a name="line.228"></a> <span class="sourceLineNo">229</span> *<a name="line.229"></a> <span class="sourceLineNo">230</span> * @param dataset the dataset (&lt;code&gt;null&lt;/code&gt; not permitted).<a name="line.230"></a> <span class="sourceLineNo">231</span> * @param series the series index (zero-based).<a name="line.231"></a> <span class="sourceLineNo">232</span> * @param item the item index (zero-based).<a name="line.232"></a> <span class="sourceLineNo">233</span> *<a name="line.233"></a> <span class="sourceLineNo">234</span> * @return The label text (possibly &lt;code&gt;null&lt;/code&gt;).<a name="line.234"></a> <span class="sourceLineNo">235</span> */<a name="line.235"></a> <span class="sourceLineNo">236</span> public String generateLabel(XYDataset dataset, int series, int item) {<a name="line.236"></a> <span class="sourceLineNo">237</span> return generateLabelString(dataset, series, item);<a name="line.237"></a> <span class="sourceLineNo">238</span> }<a name="line.238"></a> <span class="sourceLineNo">239</span><a name="line.239"></a> <span class="sourceLineNo">240</span> /**<a name="line.240"></a> <span class="sourceLineNo">241</span> * Returns an independent copy of the generator.<a name="line.241"></a> <span class="sourceLineNo">242</span> *<a name="line.242"></a> <span class="sourceLineNo">243</span> * @return A clone.<a name="line.243"></a> <span class="sourceLineNo">244</span> *<a name="line.244"></a> <span class="sourceLineNo">245</span> * @throws CloneNotSupportedException if cloning is not supported.<a name="line.245"></a> <span class="sourceLineNo">246</span> */<a name="line.246"></a> <span class="sourceLineNo">247</span> public Object clone() throws CloneNotSupportedException {<a name="line.247"></a> <span class="sourceLineNo">248</span> return super.clone();<a name="line.248"></a> <span class="sourceLineNo">249</span> }<a name="line.249"></a> <span class="sourceLineNo">250</span><a name="line.250"></a> <span class="sourceLineNo">251</span> /**<a name="line.251"></a> <span class="sourceLineNo">252</span> * Tests this object for equality with an arbitrary object.<a name="line.252"></a> <span class="sourceLineNo">253</span> *<a name="line.253"></a> <span class="sourceLineNo">254</span> * @param obj the other object (&lt;code&gt;null&lt;/code&gt; permitted).<a name="line.254"></a> <span class="sourceLineNo">255</span> *<a name="line.255"></a> <span class="sourceLineNo">256</span> * @return A boolean.<a name="line.256"></a> <span class="sourceLineNo">257</span> */<a name="line.257"></a> <span class="sourceLineNo">258</span> public boolean equals(Object obj) {<a name="line.258"></a> <span class="sourceLineNo">259</span> if (obj == this) {<a name="line.259"></a> <span class="sourceLineNo">260</span> return true;<a name="line.260"></a> <span class="sourceLineNo">261</span> }<a name="line.261"></a> <span class="sourceLineNo">262</span> if (!(obj instanceof IntervalXYItemLabelGenerator)) {<a name="line.262"></a> <span class="sourceLineNo">263</span> return false;<a name="line.263"></a> <span class="sourceLineNo">264</span> }<a name="line.264"></a> <span class="sourceLineNo">265</span> return super.equals(obj);<a name="line.265"></a> <span class="sourceLineNo">266</span> }<a name="line.266"></a> <span class="sourceLineNo">267</span><a name="line.267"></a> <span class="sourceLineNo">268</span>}<a name="line.268"></a> </pre> </div> </body> </html>
Mr-Steve/LTSpice_Library_Manager
libs/jfreechart-1.0.16/javadoc/src-html/org/jfree/chart/labels/IntervalXYItemLabelGenerator.html
HTML
gpl-2.0
25,793
mui.init(); var postInfo = { 'page': 1 }; var activityUl = document.getElementById("activityUl"); var addActivityList = function(data) { var li = document.createElement('li'); li.className = "mui-table-view-cell"; data.explain = imgTools.getDtlContent(data.explain); li.innerHTML = template('activity_item_script', data); mui(li.getElementsByClassName('activity-li-middle'))[0].innerHTML = data.explain; return li; } mui.plusReady(function() { mui('.mui-scroll').pullToRefresh({ up: { auto: true, callback: function() { var pullObj = this; activity.getActivityList(postInfo, function(res) { if(res.data) { for(i in res.data) { var li = addActivityList(res.data[i]); activityUl.appendChild(li); } res.data.length < 10 ? pullObj.endPullUpToRefresh(true) : pullObj.endPullUpToRefresh(false); } else { pullObj.endPullUpToRefresh(true); } }) postInfo.page++; } }, down: { callback: function() { var pullObj = this; postInfo.page = 1; activityUl.innerHTML = ""; activity.getActivityList(postInfo, function(res) { if(res.data) { for(i in res.data) { var li = addActivityList(res.data[i]); activityUl.appendChild(li); } pullObj.endPullDownToRefresh(); res.data.length < 10 ? pullObj.endPullUpToRefresh(true) : pullObj.endPullUpToRefresh(false); } else { pullObj.endPullDownToRefresh(); pullObj.endPullUpToRefresh(true); } }) } } }) mui('.mui-table-view').on('tap', '.activity-buttom', function() { var type = this.id; switch(type) { case 'endBtn': mui.toast('活动已经结束!'); break; case 'joinBtn': break; case 'cancelBtn': break; } }) })
243756501/zcx-social.zjc
activity/view/js/activity-main.js
JavaScript
gpl-2.0
1,952
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <HTML> <HEAD> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <META name="GENERATOR" content="hevea 1.10"> <LINK rel="stylesheet" type="text/css" href="cascmd_fr.css"> <TITLE>Le vecteur en 3-d : vecteur</TITLE> </HEAD> <BODY > <A HREF="cascmd_fr1018.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A> <A HREF="cascmd_fr1020.html"><IMG SRC="next_motif.gif" ALT="Next"></A> <HR> <H3 CLASS="subsection"><A NAME="htoc1195">11.5.5</A>  Le vecteur en 3-d : <TT>vecteur</TT></H3><P><A NAME="@default1988"></A> <A NAME="sec:vecteur3"></A> <B>Voir aussi :</B> <A HREF="cascmd_fr910.html#sec:vecteur2">10.9.6</A> pour la géométrie plane.<BR> Pour travailler avec les composantes d’un vecteur de ℝ<SUP><I>n</I></SUP>, il faut utiliser des listes.<BR> <TT>vecteur</TT>, en géométrie 3-d, a comme arguments soit : </P><UL CLASS="itemize"><LI CLASS="li-itemize"> une liste représentant les coordonnées d’un point <I>A</I>.<BR> <TT>vecteur</TT> définit et dessine le vecteur <I>OA</I> où <I>O</I> est l’origine du repère. </LI><LI CLASS="li-itemize">deux points <I>A</I>,<I>B</I> ou deux listes représentant les coordonnées de ces points.<BR> <TT>vecteur</TT> définit et dessine le vecteur <I>AB</I> </LI><LI CLASS="li-itemize">un point <I>A</I> (ou une liste représentant les coordonnées de ce point) et un vecteur <I>V</I> (définition récursive).<BR> <TT>vecteur</TT> définit et dessine le vecteur <I>AB</I> tel que <I>AB</I>=<I>V</I>. </LI></UL><P> On tape : </P><DIV CLASS="center"><TT>vecteur([1,2,3])</TT></DIV><P> On obtient : </P><DIV CLASS="center"><TT>Le tracé du vecteur d’origine [0,0,0] et d’extrémité [1,2,3]</TT></DIV><P> On tape : </P><DIV CLASS="center"><TT>vecteur(point([-1,0,0]),point([0,1,2]))</TT></DIV><P> Ou on tape : </P><DIV CLASS="center"><TT>vecteur([-1,0,0],[0,1,2])</TT></DIV><P> On obtient : </P><DIV CLASS="center"><TT>Le tracé du vecteur d’origine [-1,0,0] et d’extrémité [0,1,2]</TT></DIV><P> On tape : </P><DIV CLASS="center"><TT>V:=vecteur([-1,0,0],[0,1,2])</TT></DIV><P> On tape : </P><DIV CLASS="center"><TT>vecteur(point([-1,2,0]),V)</TT></DIV><P> Ou on tape : </P><DIV CLASS="center"><TT>vecteur([-1,2,0],V)</TT></DIV><P> On obtient : </P><DIV CLASS="center"><TT>Le tracé du vecteur d’origine [-1,2,0] et d’extrémité [0,3,2]</TT></DIV><P> <B>Remarque</B><BR> En calcul formel, on travaille sur la liste des coordonnées des vecteurs que l’on obtient avec la commande <TT>coordonnees</TT> (cf <A HREF="cascmd_fr1048.html#sec:coordonnees3">11.12.4</A>).</P><HR> <A HREF="cascmd_fr1018.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A> <A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A> <A HREF="cascmd_fr1020.html"><IMG SRC="next_motif.gif" ALT="Next"></A> </BODY> </HTML>
hiplayer/giac
giac/giac-1.2.3/doc/fr/cascmd_fr/cascmd_fr1019.html
HTML
gpl-2.0
2,980
using System; using GalaSoft.MvvmLight; namespace CSGO_Demos_Manager.Models { public class Suspect : ObservableObject { #region Properties /// <summary> /// 64bit SteamID of the user /// </summary> private string _steamId; /// <summary> /// This represents whether the profile is visible or not, and if it is visible, why you are allowed to see it. /// Note that because this WebAPI does not use authentication, there are only two possible values returned: /// 1 - the profile is not visible to you (Private, Friends Only, etc) /// 3 - the profile is "Public", and the data is visible. /// Mike Blaszczak's post on Steam forums says, "The community visibility state this API returns is different than the privacy state. /// It's the effective visibility state from the account making the request to the account being viewed given the requesting account's relationship to the viewed account." /// </summary> private int _communityVisibilityState; /// <summary> /// If set, indicates the user has a community profile configured (will be set to '1') /// </summary> private int _profileState; /// <summary> /// The player's persona name (display name) /// </summary> private string _nickname; /// <summary> /// The last time the user was online, in unix time. /// </summary> private int _lastLogOff = 0; /// <summary> /// The full URL of the player's Steam Community profile. /// </summary> private string _profileUrl; /// <summary> /// The full URL of the player's 184x184px avatar. /// If the user hasn't configured an avatar, this will be the default ? avatar. /// </summary> private string _avatarUrl; /// <summary> /// The user's current status. /// 0 - Offline, 1 - Online, 2 - Busy, 3 - Away, 4 - Snooze, 5 - looking to trade, 6 - looking to play. /// If the player's profile is private, this will always be "0", except is the user has set his status to looking to trade or looking to play, /// because a bug makes those status appear even if the profile is private. /// </summary> private int _currentStatus; /// <summary> /// Indicates whether or not the player is banned from Steam Community. /// </summary> private bool _communityBanned; /// <summary> /// Indicates whether or not the player has VAC bans on record. /// </summary> private bool _vacBanned; /// <summary> /// The player's ban status in the economy. /// If the player has no bans on record the string will be "none", if the player is on probation it will say "probation", etc. /// </summary> private string _economyBan; /// <summary> /// VAC ban count (only if at least one ban) /// </summary> private int _banCount; /// <summary> /// Days count since last ban (only if at least one ban) /// </summary> private int _daySinceLastBanCount; /// <summary> /// Game ban count /// </summary> private int _gameBanCount; #endregion #region Accessors public string SteamId { get { return _steamId; } set { Set(() => SteamId, ref _steamId, value); } } public string Nickname { get { return _nickname; } set { Set(() => Nickname, ref _nickname, value); } } public string AvatarUrl { get { return _avatarUrl; } set { Set(() => AvatarUrl, ref _avatarUrl, value); } } public int CurrentStatus { get { return _currentStatus; } set { Set(() => CurrentStatus, ref _currentStatus, value); } } public int CommunityVisibilityState { get { return _communityVisibilityState; } set { Set(() => CommunityVisibilityState, ref _communityVisibilityState, value); } } public string PublicProfile { get { switch(_communityVisibilityState) { case 1: return "Private"; case 3: return "Public"; default: return "Unknow"; } } } public string LastLogOffDate { get { DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); dt = dt.AddSeconds(_lastLogOff).ToLocalTime(); return string.Format("{0:d/M/yyyy HH:mm:ss}", dt); } } public int LastLogOff { get { return _lastLogOff; } set { Set(() => LastLogOff, ref _lastLogOff, value); } } public int ProfileState { get { return _profileState; } set { Set(() => ProfileState, ref _profileState, value); } } public string ProfileStateString => _profileState == 0 ? "No" : "Yes"; public string ProfileUrl { get { return _profileUrl; } set { Set(() => ProfileUrl, ref _profileUrl, value); } } public bool CommunityBanned { get { return _communityBanned; } set { Set(() => CommunityBanned, ref _communityBanned, value); } } public bool VacBanned { get { return _vacBanned; } set { Set(() => VacBanned, ref _vacBanned, value); } } public int BanCount { get { return _banCount; } set { Set(() => BanCount, ref _banCount, value); } } public int GameBanCount { get { return _gameBanCount; } set { Set(() => GameBanCount, ref _gameBanCount, value); } } public int DaySinceLastBanCount { get { return _daySinceLastBanCount; } set { Set(() => DaySinceLastBanCount, ref _daySinceLastBanCount, value); } } public string EconomyBan { get { return _economyBan; } set { Set(() => EconomyBan, ref _economyBan, value); } } public string CurrentStatusString { get { switch(_currentStatus) { case 0: return "Offline"; case 1: return "Online"; case 2: return "Busy"; case 3: return "Away"; case 4: return "Snooze"; case 5: return "Looking to trade"; case 6: return "Looking to play"; default: return "Unknow"; } } } #endregion } }
LoveDuckie/CSGO-Demos-Manager
src/Models/Suspect.cs
C#
gpl-2.0
5,758
/******************************************************************************** ** Form generated from reading UI file 'catalogocontable.ui' ** ** Created: Thu Apr 21 08:48:21 2011 ** by: Qt User Interface Compiler version 4.7.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_CATALOGOCONTABLE_H #define UI_CATALOGOCONTABLE_H #include <QtCore/QLocale> #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QDialog> #include <QtGui/QGridLayout> #include <QtGui/QGroupBox> #include <QtGui/QHeaderView> #include <QtGui/QLineEdit> #include <QtGui/QPushButton> #include <QtGui/QTextEdit> #include <QtGui/QToolButton> #include <QtGui/QTreeWidget> #include <QtGui/QVBoxLayout> QT_BEGIN_NAMESPACE class Ui_CatalogoContable { public: QGridLayout *gridLayout; QTreeWidget *Catalogo; QGroupBox *groupBox; QVBoxLayout *verticalLayout; QLineEdit *codigoCuenta; QGroupBox *groupBox_2; QVBoxLayout *verticalLayout_2; QLineEdit *debe; QGroupBox *groupBox_3; QVBoxLayout *verticalLayout_3; QLineEdit *haber; QGroupBox *groupBox_5; QVBoxLayout *verticalLayout_4; QLineEdit *saldoDeudor; QGroupBox *groupBox_6; QVBoxLayout *verticalLayout_5; QLineEdit *saldoAcreedor; QGroupBox *groupBox_4; QVBoxLayout *verticalLayout_6; QTextEdit *textEdit; QPushButton *crearRubro; QPushButton *crearCuenta; QPushButton *crearEspecifico; QPushButton *transaccion; QToolButton *pushButton_3; QToolButton *btmSeleccionar; QToolButton *botonBuscar; void setupUi(QDialog *CatalogoContable) { if (CatalogoContable->objectName().isEmpty()) CatalogoContable->setObjectName(QString::fromUtf8("CatalogoContable")); CatalogoContable->resize(900, 590); gridLayout = new QGridLayout(CatalogoContable); gridLayout->setObjectName(QString::fromUtf8("gridLayout")); Catalogo = new QTreeWidget(CatalogoContable); Catalogo->setObjectName(QString::fromUtf8("Catalogo")); Catalogo->setMaximumSize(QSize(580, 680)); Catalogo->setLocale(QLocale(QLocale::Spanish, QLocale::ElSalvador)); Catalogo->setAlternatingRowColors(true); gridLayout->addWidget(Catalogo, 1, 0, 5, 4); groupBox = new QGroupBox(CatalogoContable); groupBox->setObjectName(QString::fromUtf8("groupBox")); verticalLayout = new QVBoxLayout(groupBox); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); codigoCuenta = new QLineEdit(groupBox); codigoCuenta->setObjectName(QString::fromUtf8("codigoCuenta")); codigoCuenta->setReadOnly(true); verticalLayout->addWidget(codigoCuenta); gridLayout->addWidget(groupBox, 1, 4, 1, 5); groupBox_2 = new QGroupBox(CatalogoContable); groupBox_2->setObjectName(QString::fromUtf8("groupBox_2")); groupBox_2->setStyleSheet(QString::fromUtf8("")); verticalLayout_2 = new QVBoxLayout(groupBox_2); verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2")); debe = new QLineEdit(groupBox_2); debe->setObjectName(QString::fromUtf8("debe")); debe->setLayoutDirection(Qt::RightToLeft); debe->setReadOnly(true); verticalLayout_2->addWidget(debe); gridLayout->addWidget(groupBox_2, 2, 4, 1, 2); groupBox_3 = new QGroupBox(CatalogoContable); groupBox_3->setObjectName(QString::fromUtf8("groupBox_3")); verticalLayout_3 = new QVBoxLayout(groupBox_3); verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3")); haber = new QLineEdit(groupBox_3); haber->setObjectName(QString::fromUtf8("haber")); haber->setLayoutDirection(Qt::RightToLeft); haber->setReadOnly(true); verticalLayout_3->addWidget(haber); gridLayout->addWidget(groupBox_3, 2, 6, 1, 3); groupBox_5 = new QGroupBox(CatalogoContable); groupBox_5->setObjectName(QString::fromUtf8("groupBox_5")); verticalLayout_4 = new QVBoxLayout(groupBox_5); verticalLayout_4->setObjectName(QString::fromUtf8("verticalLayout_4")); saldoDeudor = new QLineEdit(groupBox_5); saldoDeudor->setObjectName(QString::fromUtf8("saldoDeudor")); QFont font; font.setFamily(QString::fromUtf8("MS Shell Dlg 2")); font.setPointSize(9); font.setBold(true); font.setItalic(false); font.setWeight(75); saldoDeudor->setFont(font); saldoDeudor->setLayoutDirection(Qt::RightToLeft); saldoDeudor->setReadOnly(true); verticalLayout_4->addWidget(saldoDeudor); gridLayout->addWidget(groupBox_5, 3, 4, 1, 2); groupBox_6 = new QGroupBox(CatalogoContable); groupBox_6->setObjectName(QString::fromUtf8("groupBox_6")); verticalLayout_5 = new QVBoxLayout(groupBox_6); verticalLayout_5->setObjectName(QString::fromUtf8("verticalLayout_5")); saldoAcreedor = new QLineEdit(groupBox_6); saldoAcreedor->setObjectName(QString::fromUtf8("saldoAcreedor")); QFont font1; font1.setBold(true); font1.setItalic(false); font1.setWeight(75); saldoAcreedor->setFont(font1); saldoAcreedor->setLayoutDirection(Qt::RightToLeft); saldoAcreedor->setReadOnly(true); verticalLayout_5->addWidget(saldoAcreedor); gridLayout->addWidget(groupBox_6, 3, 6, 1, 3); groupBox_4 = new QGroupBox(CatalogoContable); groupBox_4->setObjectName(QString::fromUtf8("groupBox_4")); verticalLayout_6 = new QVBoxLayout(groupBox_4); verticalLayout_6->setObjectName(QString::fromUtf8("verticalLayout_6")); textEdit = new QTextEdit(groupBox_4); textEdit->setObjectName(QString::fromUtf8("textEdit")); textEdit->setReadOnly(true); verticalLayout_6->addWidget(textEdit); gridLayout->addWidget(groupBox_4, 4, 4, 1, 5); crearRubro = new QPushButton(CatalogoContable); crearRubro->setObjectName(QString::fromUtf8("crearRubro")); gridLayout->addWidget(crearRubro, 6, 0, 1, 1); crearCuenta = new QPushButton(CatalogoContable); crearCuenta->setObjectName(QString::fromUtf8("crearCuenta")); gridLayout->addWidget(crearCuenta, 6, 1, 1, 1); crearEspecifico = new QPushButton(CatalogoContable); crearEspecifico->setObjectName(QString::fromUtf8("crearEspecifico")); gridLayout->addWidget(crearEspecifico, 6, 2, 1, 1); transaccion = new QPushButton(CatalogoContable); transaccion->setObjectName(QString::fromUtf8("transaccion")); gridLayout->addWidget(transaccion, 6, 3, 1, 1); pushButton_3 = new QToolButton(CatalogoContable); pushButton_3->setObjectName(QString::fromUtf8("pushButton_3")); QIcon icon; icon.addFile(QString::fromUtf8(":/iconos/exit.png"), QSize(), QIcon::Normal, QIcon::Off); pushButton_3->setIcon(icon); pushButton_3->setIconSize(QSize(34, 34)); gridLayout->addWidget(pushButton_3, 0, 8, 1, 1); btmSeleccionar = new QToolButton(CatalogoContable); btmSeleccionar->setObjectName(QString::fromUtf8("btmSeleccionar")); QIcon icon1; icon1.addFile(QString::fromUtf8(":/iconos/button_ok.png"), QSize(), QIcon::Normal, QIcon::Off); btmSeleccionar->setIcon(icon1); btmSeleccionar->setIconSize(QSize(34, 34)); gridLayout->addWidget(btmSeleccionar, 0, 7, 1, 1); botonBuscar = new QToolButton(CatalogoContable); botonBuscar->setObjectName(QString::fromUtf8("botonBuscar")); QIcon icon2; icon2.addFile(QString::fromUtf8(":/Iconos/iconos/buscar.png"), QSize(), QIcon::Normal, QIcon::Off); botonBuscar->setIcon(icon2); botonBuscar->setIconSize(QSize(34, 34)); gridLayout->addWidget(botonBuscar, 0, 6, 1, 1); retranslateUi(CatalogoContable); QMetaObject::connectSlotsByName(CatalogoContable); } // setupUi void retranslateUi(QDialog *CatalogoContable) { CatalogoContable->setWindowTitle(QApplication::translate("CatalogoContable", "Catalogo Contable", 0, QApplication::UnicodeUTF8)); QTreeWidgetItem *___qtreewidgetitem = Catalogo->headerItem(); ___qtreewidgetitem->setText(1, QApplication::translate("CatalogoContable", "Catalogo de Cuentas", 0, QApplication::UnicodeUTF8)); ___qtreewidgetitem->setText(0, QApplication::translate("CatalogoContable", "Codigo", 0, QApplication::UnicodeUTF8)); groupBox->setTitle(QApplication::translate("CatalogoContable", "Nombre de la Cuenta", 0, QApplication::UnicodeUTF8)); groupBox_2->setTitle(QApplication::translate("CatalogoContable", "Debe", 0, QApplication::UnicodeUTF8)); groupBox_3->setTitle(QApplication::translate("CatalogoContable", "Haber", 0, QApplication::UnicodeUTF8)); groupBox_5->setTitle(QApplication::translate("CatalogoContable", "Saldo Deudor", 0, QApplication::UnicodeUTF8)); groupBox_6->setTitle(QApplication::translate("CatalogoContable", "Saldo Acreedor", 0, QApplication::UnicodeUTF8)); groupBox_4->setTitle(QApplication::translate("CatalogoContable", "Descripci\303\263n", 0, QApplication::UnicodeUTF8)); crearRubro->setText(QApplication::translate("CatalogoContable", "Crear Rubro", 0, QApplication::UnicodeUTF8)); crearCuenta->setText(QApplication::translate("CatalogoContable", "Crear Cuenta", 0, QApplication::UnicodeUTF8)); crearEspecifico->setText(QApplication::translate("CatalogoContable", "Crear Especifico", 0, QApplication::UnicodeUTF8)); transaccion->setText(QApplication::translate("CatalogoContable", "Crear Transaccion", 0, QApplication::UnicodeUTF8)); pushButton_3->setText(QApplication::translate("CatalogoContable", "...", 0, QApplication::UnicodeUTF8)); btmSeleccionar->setText(QString()); botonBuscar->setText(QApplication::translate("CatalogoContable", "...", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class CatalogoContable: public Ui_CatalogoContable {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_CATALOGOCONTABLE_H
bagonzalez/SI-BCUES
bin/SIBCUES-GUI/ui_catalogocontable.h
C
gpl-2.0
10,442
/** * @file * Right to left menu and navigational styles. */ /** * @file * Styles for a hierarchical menu as generated by theme_menu_tree(). */ @media -sass-debug-info{filename{font-family:file\:\/\/\/Applications\/mampstack-5\.4\.40-0\/apache2\/htdocs\/drupalcl\/sites\/all\/themes\/omega\/omega\/sass\/modules\/system\/menus\/_menutree\.theme-rtl\.scss}line{font-family:\000036}} .menu { text-align: right; /* Menu Item Hierarchy Modifiers */ } @media -sass-debug-info{filename{font-family:file\:\/\/\/Applications\/mampstack-5\.4\.40-0\/apache2\/htdocs\/drupalcl\/sites\/all\/themes\/omega\/omega\/sass\/modules\/system\/menus\/_menutree\.theme-rtl\.scss}line{font-family:\0000310}} .menu .collapsed { list-style-image: url('../../../images/misc/menu-collapsed-rtl.png?1432693563'); } /** * @file * Inline links as generated by theme_links(). */ @media -sass-debug-info{filename{font-family:file\:\/\/\/Applications\/mampstack-5\.4\.40-0\/apache2\/htdocs\/drupalcl\/sites\/all\/themes\/omega\/omega\/sass\/modules\/system\/menus\/_links\.theme-rtl\.scss}line{font-family:\000037}} ul.inline li { float: right; margin-right: 0; margin-left: 1em; }
DrupalChile/drupalcl
sites/all/themes/omega/omega/css/modules/system/system.menus.theme-rtl.css
CSS
gpl-2.0
1,176
#!/usr/bin/env python from setuptools import setup, find_packages from os import path # www.pythonhosted.org/setuptools/setuptools.html setup( name="lines", version="1.4.0", description="Program for plotting powder diffraction patterns and background subtraction", author="Stef Smeets", author_email="s.smeets@esciencecenter.nl", license="GPL", url="https://github.com/stefsmeets/lines", classifiers=[ 'Programming Language :: Python :: 2.7', ], packages=["lines", "zeolite_database"], install_requires=[ "matplotlib<3.0", "numpy>=1.10", "scipy>=0.16", ], package_data={ "": ["LICENCE", "readme.md", "setup.py"], "zeolite_database": ["*.cif"], }, entry_points={ 'console_scripts': [ 'lines = lines.lines:main', 'cif2xy = lines.cif2xy:main', ] } )
stefsmeets/lines
setup.py
Python
gpl-2.0
911
<?php namespace OAuth; interface Exception {} class LogicException extends \LogicException implements Exception {} class InvalidArgumentException extends \InvalidArgumentException implements Exception {} class UnexpectedValueException extends \UnexpectedValueException implements Exception {} class OutOfRangeException extends \OutOfRangeException implements Exception {} class BadMethodCallException extends \BadMethodCallException implements Exception {} class RuntimeException extends \LoggingExceptions\RuntimeException implements Exception {} class AuthenticationException extends RuntimeException {} class AuthorizationException extends RuntimeException {} ?>
performics/ga-cli-api
src/OAuth/Exception.class.php
PHP
gpl-2.0
665
<?php /** * * Auto Groups extension for the phpBB Forum Software package. * * @copyright (c) 2015 phpBB Limited <https://www.phpbb.com> * @license GNU General Public License, version 2 (GPL-2.0) * */ namespace phpbb\autogroups\conditions\type; /** * Auto Groups conditions type helper class */ class helper { /** @var \phpbb\db\driver\driver_interface */ protected $db; /** @var \phpbb\notification\manager */ protected $notification_manager; /** @var string */ protected $phpbb_root_path; /** @var string */ protected $php_ext; /** * Constructor * * @param \phpbb\db\driver\driver_interface $db Database object * @param \phpbb\notification\manager $notification_manager Notification manager * @param string $phpbb_root_path phpBB root path * @param string $php_ext phpEx * * @access public */ public function __construct(\phpbb\db\driver\driver_interface $db, \phpbb\notification\manager $notification_manager, $phpbb_root_path, $php_ext) { $this->db = $db; $this->notification_manager = $notification_manager; $this->phpbb_root_path = $phpbb_root_path; $this->php_ext = $php_ext; } /** * Get user's group ids * * @param array $user_id_ary An array of user ids to check * @return array An array of usergroup ids each user belongs to * @access public */ public function get_users_groups($user_id_ary) { $group_id_ary = array(); $sql = 'SELECT user_id, group_id FROM ' . USER_GROUP_TABLE . ' WHERE ' . $this->db->sql_in_set('user_id', $user_id_ary, false, true); $result = $this->db->sql_query($sql); while ($row = $this->db->sql_fetchrow($result)) { $group_id_ary[$row['user_id']][] = $row['group_id']; } $this->db->sql_freeresult($result); return $group_id_ary; } /** * Get users that should not have their default status changed * * @return array An array of user ids * @access public */ public function get_default_exempt_users() { $user_id_ary = array(); // Get users whose default group is autogroup_default_exempt $sql_array = array( 'SELECT' => 'u.user_id', 'FROM' => array( USERS_TABLE => 'u', ), 'LEFT_JOIN' => array( array( 'FROM' => array(GROUPS_TABLE => 'g'), 'ON' => 'g.group_id = u.group_id', ), ), 'WHERE' => 'g.autogroup_default_exempt = 1', ); $sql = $this->db->sql_build_query('SELECT', $sql_array); $result = $this->db->sql_query($sql); while ($row = $this->db->sql_fetchrow($result)) { $user_id_ary[] = $row['user_id']; } $this->db->sql_freeresult($result); return $user_id_ary; } /** * Prepare user ids for querying * * @param mixed $user_ids User id(s) expected as int or array * @return array An array of user id(s) * @access public */ public function prepare_users_for_query($user_ids) { if (!is_array($user_ids)) { $user_ids = array($user_ids); } // Cast each array value to integer $user_ids = array_map('intval', $user_ids); return $user_ids; } /** * Send notifications * * @param string $type Type of notification to send (group_added|group_removed) * @param array $user_id_ary Array of user(s) to notify * @param int $group_id The usergroup identifier * @return void * @access public */ public function send_notifications($type, $user_id_ary, $group_id) { if (!function_exists('get_group_name')) { include $this->phpbb_root_path . 'includes/functions_user.' . $this->php_ext; } $this->notification_manager->add_notifications("phpbb.autogroups.notification.type.$type", array( 'user_ids' => $user_id_ary, 'group_id' => $group_id, 'group_name' => get_group_name($group_id), )); } }
VSEphpbb/autogroups
conditions/type/helper.php
PHP
gpl-2.0
3,779
package mbs2.pr20.bean; import javax.annotation.Resource; import javax.ejb.Local; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.ejb.TransactionManagement; import javax.transaction.UserTransaction; import mbs2.pr20.CreditCard; import static javax.ejb.TransactionManagementType.BEAN; @Stateless(name="Payment20Bean") @Local(PaymentLocal.class) @Remote(Payment.class) @TransactionManagement(BEAN) public class PaymentBean implements Payment { @Resource private UserTransaction tx; public boolean processCreditCard(CreditCard card) { try { tx.begin(); if (somethingWentWrong()) { tx.rollback(); return false; } tx.commit(); return true; } catch (Exception ex) { return false; } } private boolean somethingWentWrong() { return Math.random() > 0.5; } }
mbranko/mbs2
src/mbs2/pr20/bean/PaymentBean.java
Java
gpl-2.0
858
/* * kernel/sched/core.c * * Kernel scheduler and related syscalls * * Copyright (C) 1991-2002 Linus Torvalds * * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and * make semaphores SMP safe * 1998-11-19 Implemented schedule_timeout() and related stuff * by Andrea Arcangeli * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar: * hybrid priority-list and round-robin design with * an array-switch method of distributing timeslices * and per-CPU runqueues. Cleanups and useful suggestions * by Davide Libenzi, preemptible kernel bits by Robert Love. * 2003-09-03 Interactivity tuning by Con Kolivas. * 2004-04-02 Scheduler domains code by Nick Piggin * 2007-04-15 Work begun on replacing all interactivity tuning with a * fair scheduling design by Con Kolivas. * 2007-05-05 Load balancing (smp-nice) and other improvements * by Peter Williams * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins, * Thomas Gleixner, Mike Kravetz */ #include <linux/mm.h> #include <linux/module.h> #include <linux/nmi.h> #include <linux/init.h> #include <linux/uaccess.h> #include <linux/highmem.h> #include <asm/mmu_context.h> #include <linux/interrupt.h> #include <linux/capability.h> #include <linux/completion.h> #include <linux/kernel_stat.h> #include <linux/debug_locks.h> #include <linux/perf_event.h> #include <linux/security.h> #include <linux/notifier.h> #include <linux/profile.h> #include <linux/freezer.h> #include <linux/vmalloc.h> #include <linux/blkdev.h> #include <linux/delay.h> #include <linux/pid_namespace.h> #include <linux/smp.h> #include <linux/threads.h> #include <linux/timer.h> #include <linux/rcupdate.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/percpu.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/sysctl.h> #include <linux/syscalls.h> #include <linux/times.h> #include <linux/tsacct_kern.h> #include <linux/kprobes.h> #include <linux/delayacct.h> #include <linux/unistd.h> #include <linux/pagemap.h> #include <linux/hrtimer.h> #include <linux/tick.h> #include <linux/debugfs.h> #include <linux/ctype.h> #include <linux/ftrace.h> #include <linux/slab.h> #include <linux/init_task.h> #include <linux/binfmts.h> #include <asm/switch_to.h> #include <asm/tlb.h> #include <asm/irq_regs.h> #include <asm/mutex.h> #ifdef CONFIG_PARAVIRT #include <asm/paravirt.h> #endif #include "sched.h" #include "../workqueue_sched.h" #define CREATE_TRACE_POINTS #include <trace/events/sched.h> ATOMIC_NOTIFIER_HEAD(migration_notifier_head); void start_bandwidth_timer(struct hrtimer *period_timer, ktime_t period) { unsigned long delta; ktime_t soft, hard, now; for (;;) { if (hrtimer_active(period_timer)) break; now = hrtimer_cb_get_time(period_timer); hrtimer_forward(period_timer, now, period); soft = hrtimer_get_softexpires(period_timer); hard = hrtimer_get_expires(period_timer); delta = ktime_to_ns(ktime_sub(hard, soft)); __hrtimer_start_range_ns(period_timer, soft, delta, HRTIMER_MODE_ABS_PINNED, 0); } } DEFINE_MUTEX(sched_domains_mutex); DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues); #ifdef CONFIG_INTELLI_PLUG DEFINE_PER_CPU_SHARED_ALIGNED(struct nr_stats_s, runqueue_stats); #endif static void update_rq_clock_task(struct rq *rq, s64 delta); void update_rq_clock(struct rq *rq) { s64 delta; if (rq->skip_clock_update > 0) return; delta = sched_clock_cpu(cpu_of(rq)) - rq->clock; rq->clock += delta; update_rq_clock_task(rq, delta); } /* * Debugging: various feature bits */ #define SCHED_FEAT(name, enabled) \ (1UL << __SCHED_FEAT_##name) * enabled | const_debug unsigned int sysctl_sched_features = #include "features.h" 0; #undef SCHED_FEAT #ifdef CONFIG_SCHED_DEBUG #define SCHED_FEAT(name, enabled) \ #name , static __read_mostly char *sched_feat_names[] = { #include "features.h" NULL }; #undef SCHED_FEAT static int sched_feat_show(struct seq_file *m, void *v) { int i; for (i = 0; i < __SCHED_FEAT_NR; i++) { if (!(sysctl_sched_features & (1UL << i))) seq_puts(m, "NO_"); seq_printf(m, "%s ", sched_feat_names[i]); } seq_puts(m, "\n"); return 0; } #ifdef HAVE_JUMP_LABEL #define jump_label_key__true STATIC_KEY_INIT_TRUE #define jump_label_key__false STATIC_KEY_INIT_FALSE #define SCHED_FEAT(name, enabled) \ jump_label_key__##enabled , struct static_key sched_feat_keys[__SCHED_FEAT_NR] = { #include "features.h" }; #undef SCHED_FEAT static void sched_feat_disable(int i) { if (static_key_enabled(&sched_feat_keys[i])) static_key_slow_dec(&sched_feat_keys[i]); } static void sched_feat_enable(int i) { if (!static_key_enabled(&sched_feat_keys[i])) static_key_slow_inc(&sched_feat_keys[i]); } #else static void sched_feat_disable(int i) { }; static void sched_feat_enable(int i) { }; #endif /* HAVE_JUMP_LABEL */ static ssize_t sched_feat_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { char buf[64]; char *cmp; int neg = 0; int i; if (cnt > 63) cnt = 63; if (copy_from_user(&buf, ubuf, cnt)) return -EFAULT; buf[cnt] = 0; cmp = strstrip(buf); if (strncmp(cmp, "NO_", 3) == 0) { neg = 1; cmp += 3; } for (i = 0; i < __SCHED_FEAT_NR; i++) { if (strcmp(cmp, sched_feat_names[i]) == 0) { if (neg) { sysctl_sched_features &= ~(1UL << i); sched_feat_disable(i); } else { sysctl_sched_features |= (1UL << i); sched_feat_enable(i); } break; } } if (i == __SCHED_FEAT_NR) return -EINVAL; *ppos += cnt; return cnt; } static int sched_feat_open(struct inode *inode, struct file *filp) { return single_open(filp, sched_feat_show, NULL); } static const struct file_operations sched_feat_fops = { .open = sched_feat_open, .write = sched_feat_write, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static __init int sched_init_debug(void) { debugfs_create_file("sched_features", 0644, NULL, NULL, &sched_feat_fops); return 0; } late_initcall(sched_init_debug); #endif /* CONFIG_SCHED_DEBUG */ /* * Number of tasks to iterate in a single balance run. * Limited because this is done with IRQs disabled. */ const_debug unsigned int sysctl_sched_nr_migrate = 32; /* * period over which we average the RT time consumption, measured * in ms. * * default: 1s */ const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC; /* * period over which we measure -rt task cpu usage in us. * default: 1s */ unsigned int sysctl_sched_rt_period = 1000000; __read_mostly int scheduler_running; /* * part of the period that we allow rt tasks to run in us. * default: 0.95s */ int sysctl_sched_rt_runtime = 950000; /* * __task_rq_lock - lock the rq @p resides on. */ static inline struct rq *__task_rq_lock(struct task_struct *p) __acquires(rq->lock) { struct rq *rq; lockdep_assert_held(&p->pi_lock); for (;;) { rq = task_rq(p); raw_spin_lock(&rq->lock); if (likely(rq == task_rq(p))) return rq; raw_spin_unlock(&rq->lock); } } /* * task_rq_lock - lock p->pi_lock and lock the rq @p resides on. */ static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags) __acquires(p->pi_lock) __acquires(rq->lock) { struct rq *rq; for (;;) { raw_spin_lock_irqsave(&p->pi_lock, *flags); rq = task_rq(p); raw_spin_lock(&rq->lock); if (likely(rq == task_rq(p))) return rq; raw_spin_unlock(&rq->lock); raw_spin_unlock_irqrestore(&p->pi_lock, *flags); } } static void __task_rq_unlock(struct rq *rq) __releases(rq->lock) { raw_spin_unlock(&rq->lock); } static inline void task_rq_unlock(struct rq *rq, struct task_struct *p, unsigned long *flags) __releases(rq->lock) __releases(p->pi_lock) { raw_spin_unlock(&rq->lock); raw_spin_unlock_irqrestore(&p->pi_lock, *flags); } /* * this_rq_lock - lock this runqueue and disable interrupts. */ static struct rq *this_rq_lock(void) __acquires(rq->lock) { struct rq *rq; local_irq_disable(); rq = this_rq(); raw_spin_lock(&rq->lock); return rq; } #ifdef CONFIG_SCHED_HRTICK /* * Use HR-timers to deliver accurate preemption points. * * Its all a bit involved since we cannot program an hrt while holding the * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a * reschedule event. * * When we get rescheduled we reprogram the hrtick_timer outside of the * rq->lock. */ static void hrtick_clear(struct rq *rq) { if (hrtimer_active(&rq->hrtick_timer)) hrtimer_cancel(&rq->hrtick_timer); } /* * High-resolution timer tick. * Runs from hardirq context with interrupts disabled. */ static enum hrtimer_restart hrtick(struct hrtimer *timer) { struct rq *rq = container_of(timer, struct rq, hrtick_timer); WARN_ON_ONCE(cpu_of(rq) != smp_processor_id()); raw_spin_lock(&rq->lock); update_rq_clock(rq); rq->curr->sched_class->task_tick(rq, rq->curr, 1); raw_spin_unlock(&rq->lock); return HRTIMER_NORESTART; } #ifdef CONFIG_SMP /* * called from hardirq (IPI) context */ static void __hrtick_start(void *arg) { struct rq *rq = arg; struct hrtimer *timer = &rq->hrtick_timer; ktime_t soft, hard; unsigned long delta; soft = hrtimer_get_softexpires(timer); hard = hrtimer_get_expires(timer); delta = ktime_to_ns(ktime_sub(hard, soft)); raw_spin_lock(&rq->lock); __hrtimer_start_range_ns(timer, soft, delta, HRTIMER_MODE_ABS, 0); rq->hrtick_csd_pending = 0; raw_spin_unlock(&rq->lock); } /* * Called to set the hrtick timer state. * * called with rq->lock held and irqs disabled */ void hrtick_start(struct rq *rq, u64 delay) { struct hrtimer *timer = &rq->hrtick_timer; ktime_t time = ktime_add_ns(timer->base->get_time(), delay); hrtimer_set_expires(timer, time); if (rq == this_rq()) { __hrtimer_start_range_ns(timer, ns_to_ktime(delay), 0, HRTIMER_MODE_REL_PINNED, 0); } else if (!rq->hrtick_csd_pending) { __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0); rq->hrtick_csd_pending = 1; } } static int hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu) { int cpu = (int)(long)hcpu; switch (action) { case CPU_UP_CANCELED: case CPU_UP_CANCELED_FROZEN: case CPU_DOWN_PREPARE: case CPU_DOWN_PREPARE_FROZEN: case CPU_DEAD: case CPU_DEAD_FROZEN: hrtick_clear(cpu_rq(cpu)); return NOTIFY_OK; } return NOTIFY_DONE; } static __init void init_hrtick(void) { hotcpu_notifier(hotplug_hrtick, 0); } #else /* * Called to set the hrtick timer state. * * called with rq->lock held and irqs disabled */ void hrtick_start(struct rq *rq, u64 delay) { __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0, HRTIMER_MODE_REL_PINNED, 0); } static inline void init_hrtick(void) { } #endif /* CONFIG_SMP */ static void init_rq_hrtick(struct rq *rq) { #ifdef CONFIG_SMP rq->hrtick_csd_pending = 0; rq->hrtick_csd.flags = 0; rq->hrtick_csd.func = __hrtick_start; rq->hrtick_csd.info = rq; #endif hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); rq->hrtick_timer.function = hrtick; } #else /* CONFIG_SCHED_HRTICK */ static inline void hrtick_clear(struct rq *rq) { } static inline void init_rq_hrtick(struct rq *rq) { } static inline void init_hrtick(void) { } #endif /* CONFIG_SCHED_HRTICK */ /* * resched_task - mark a task 'to be rescheduled now'. * * On UP this means the setting of the need_resched flag, on SMP it * might also involve a cross-CPU call to trigger the scheduler on * the target CPU. */ #ifdef CONFIG_SMP #ifndef tsk_is_polling #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG) #endif /* * * cmpxchg based fetch_or, macro so it works for different integer types * */ #define fetch_or(ptr, val) \ ({ typeof(*(ptr)) __old, __val = *(ptr); \ for (;;) { \ __old = cmpxchg((ptr), __val, __val | (val)); \ if (__old == __val) \ break; \ __val = __old; \ } \ __old; \ }) #ifdef TIF_POLLING_NRFLAG /* * * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG, * * this avoids any races wrt polling state changes and thereby avoids * * spurious IPIs. * */ static bool set_nr_and_not_polling(struct task_struct *p) { struct thread_info *ti = task_thread_info(p); return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG); } #else static bool set_nr_and_not_polling(struct task_struct *p) { set_tsk_need_resched(p); return true; } #endif void resched_task(struct task_struct *p) { int cpu; assert_raw_spin_locked(&task_rq(p)->lock); if (test_tsk_need_resched(p)) return; cpu = task_cpu(p); if (cpu == smp_processor_id()) { set_tsk_need_resched(p); return; } if (set_nr_and_not_polling(p)) smp_send_reschedule(cpu); } void resched_cpu(int cpu) { struct rq *rq = cpu_rq(cpu); unsigned long flags; if (!raw_spin_trylock_irqsave(&rq->lock, flags)) return; resched_task(cpu_curr(cpu)); raw_spin_unlock_irqrestore(&rq->lock, flags); } #ifdef CONFIG_NO_HZ /* * In the semi idle case, use the nearest busy cpu for migrating timers * from an idle cpu. This is good for power-savings. * * We don't do similar optimization for completely idle system, as * selecting an idle cpu will add more delays to the timers than intended * (as that cpu's timer base may not be uptodate wrt jiffies etc). */ int get_nohz_timer_target(void) { int cpu = smp_processor_id(); int i; struct sched_domain *sd; rcu_read_lock(); for_each_domain(cpu, sd) { for_each_cpu(i, sched_domain_span(sd)) { if (!idle_cpu(i)) { cpu = i; goto unlock; } } } unlock: rcu_read_unlock(); return cpu; } /* * When add_timer_on() enqueues a timer into the timer wheel of an * idle CPU then this timer might expire before the next timer event * which is scheduled to wake up that CPU. In case of a completely * idle system the next event might even be infinite time into the * future. wake_up_idle_cpu() ensures that the CPU is woken up and * leaves the inner idle loop so the newly added timer is taken into * account when the CPU goes back to idle and evaluates the timer * wheel for the next timer event. */ void wake_up_idle_cpu(int cpu) { struct rq *rq = cpu_rq(cpu); if (cpu == smp_processor_id()) return; if (set_nr_and_not_polling(rq->idle)) smp_send_reschedule(cpu); } static inline bool got_nohz_idle_kick(void) { int cpu = smp_processor_id(); return idle_cpu(cpu) && test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)); } #else /* CONFIG_NO_HZ */ static inline bool got_nohz_idle_kick(void) { return false; } #endif /* CONFIG_NO_HZ */ void sched_avg_update(struct rq *rq) { s64 period = sched_avg_period(); while ((s64)(rq->clock - rq->age_stamp) > period) { /* * Inline assembly required to prevent the compiler * optimising this loop into a divmod call. * See __iter_div_u64_rem() for another example of this. */ asm("" : "+rm" (rq->age_stamp)); rq->age_stamp += period; rq->rt_avg /= 2; } } #else /* !CONFIG_SMP */ void resched_task(struct task_struct *p) { assert_raw_spin_locked(&task_rq(p)->lock); set_tsk_need_resched(p); } #endif /* CONFIG_SMP */ #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \ (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH))) /* * Iterate task_group tree rooted at *from, calling @down when first entering a * node and @up when leaving it for the final time. * * Caller must hold rcu_lock or sufficient equivalent. */ int walk_tg_tree_from(struct task_group *from, tg_visitor down, tg_visitor up, void *data) { struct task_group *parent, *child; int ret; parent = from; down: ret = (*down)(parent, data); if (ret) goto out; list_for_each_entry_rcu(child, &parent->children, siblings) { parent = child; goto down; up: continue; } ret = (*up)(parent, data); if (ret || parent == from) goto out; child = parent; parent = parent->parent; if (parent) goto up; out: return ret; } int tg_nop(struct task_group *tg, void *data) { return 0; } #endif static void set_load_weight(struct task_struct *p) { int prio = p->static_prio - MAX_RT_PRIO; struct load_weight *load = &p->se.load; /* * SCHED_IDLE tasks get minimal weight: */ if (p->policy == SCHED_IDLE) { load->weight = scale_load(WEIGHT_IDLEPRIO); load->inv_weight = WMULT_IDLEPRIO; return; } load->weight = scale_load(prio_to_weight[prio]); load->inv_weight = prio_to_wmult[prio]; } static void enqueue_task(struct rq *rq, struct task_struct *p, int flags) { update_rq_clock(rq); sched_info_queued(p); p->sched_class->enqueue_task(rq, p, flags); } static void dequeue_task(struct rq *rq, struct task_struct *p, int flags) { update_rq_clock(rq); sched_info_dequeued(p); p->sched_class->dequeue_task(rq, p, flags); } void activate_task(struct rq *rq, struct task_struct *p, int flags) { if (task_contributes_to_load(p)) rq->nr_uninterruptible--; enqueue_task(rq, p, flags); } void deactivate_task(struct rq *rq, struct task_struct *p, int flags) { if (task_contributes_to_load(p)) rq->nr_uninterruptible++; dequeue_task(rq, p, flags); } #ifdef CONFIG_IRQ_TIME_ACCOUNTING /* * There are no locks covering percpu hardirq/softirq time. * They are only modified in account_system_vtime, on corresponding CPU * with interrupts disabled. So, writes are safe. * They are read and saved off onto struct rq in update_rq_clock(). * This may result in other CPU reading this CPU's irq time and can * race with irq/account_system_vtime on this CPU. We would either get old * or new value with a side effect of accounting a slice of irq time to wrong * task when irq is in progress while we read rq->clock. That is a worthy * compromise in place of having locks on each irq in account_system_time. */ static DEFINE_PER_CPU(u64, cpu_hardirq_time); static DEFINE_PER_CPU(u64, cpu_softirq_time); static DEFINE_PER_CPU(u64, irq_start_time); static int sched_clock_irqtime; void enable_sched_clock_irqtime(void) { sched_clock_irqtime = 1; } void disable_sched_clock_irqtime(void) { sched_clock_irqtime = 0; } #ifndef CONFIG_64BIT static DEFINE_PER_CPU(seqcount_t, irq_time_seq); static inline void irq_time_write_begin(void) { __this_cpu_inc(irq_time_seq.sequence); smp_wmb(); } static inline void irq_time_write_end(void) { smp_wmb(); __this_cpu_inc(irq_time_seq.sequence); } static inline u64 irq_time_read(int cpu) { u64 irq_time; unsigned seq; do { seq = read_seqcount_begin(&per_cpu(irq_time_seq, cpu)); irq_time = per_cpu(cpu_softirq_time, cpu) + per_cpu(cpu_hardirq_time, cpu); } while (read_seqcount_retry(&per_cpu(irq_time_seq, cpu), seq)); return irq_time; } #else /* CONFIG_64BIT */ static inline void irq_time_write_begin(void) { } static inline void irq_time_write_end(void) { } static inline u64 irq_time_read(int cpu) { return per_cpu(cpu_softirq_time, cpu) + per_cpu(cpu_hardirq_time, cpu); } #endif /* CONFIG_64BIT */ /* * Called before incrementing preempt_count on {soft,}irq_enter * and before decrementing preempt_count on {soft,}irq_exit. */ void account_system_vtime(struct task_struct *curr) { unsigned long flags; s64 delta; int cpu; if (!sched_clock_irqtime) return; local_irq_save(flags); cpu = smp_processor_id(); delta = sched_clock_cpu(cpu) - __this_cpu_read(irq_start_time); __this_cpu_add(irq_start_time, delta); irq_time_write_begin(); /* * We do not account for softirq time from ksoftirqd here. * We want to continue accounting softirq time to ksoftirqd thread * in that case, so as not to confuse scheduler with a special task * that do not consume any time, but still wants to run. */ if (hardirq_count()) __this_cpu_add(cpu_hardirq_time, delta); else if (in_serving_softirq() && curr != this_cpu_ksoftirqd()) __this_cpu_add(cpu_softirq_time, delta); irq_time_write_end(); local_irq_restore(flags); } EXPORT_SYMBOL_GPL(account_system_vtime); #endif /* CONFIG_IRQ_TIME_ACCOUNTING */ #ifdef CONFIG_PARAVIRT static inline u64 steal_ticks(u64 steal) { if (unlikely(steal > NSEC_PER_SEC)) return div_u64(steal, TICK_NSEC); return __iter_div_u64_rem(steal, TICK_NSEC, &steal); } #endif static void update_rq_clock_task(struct rq *rq, s64 delta) { /* * In theory, the compile should just see 0 here, and optimize out the call * to sched_rt_avg_update. But I don't trust it... */ #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING) s64 steal = 0, irq_delta = 0; #endif #ifdef CONFIG_IRQ_TIME_ACCOUNTING irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time; /* * Since irq_time is only updated on {soft,}irq_exit, we might run into * this case when a previous update_rq_clock() happened inside a * {soft,}irq region. * * When this happens, we stop ->clock_task and only update the * prev_irq_time stamp to account for the part that fit, so that a next * update will consume the rest. This ensures ->clock_task is * monotonic. * * It does however cause some slight miss-attribution of {soft,}irq * time, a more accurate solution would be to update the irq_time using * the current rq->clock timestamp, except that would require using * atomic ops. */ if (irq_delta > delta) irq_delta = delta; rq->prev_irq_time += irq_delta; delta -= irq_delta; #endif #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING if (static_key_false((&paravirt_steal_rq_enabled))) { u64 st; steal = paravirt_steal_clock(cpu_of(rq)); steal -= rq->prev_steal_time_rq; if (unlikely(steal > delta)) steal = delta; st = steal_ticks(steal); steal = st * TICK_NSEC; rq->prev_steal_time_rq += steal; delta -= steal; } #endif rq->clock_task += delta; #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING) if ((irq_delta + steal) && sched_feat(NONTASK_POWER)) sched_rt_avg_update(rq, irq_delta + steal); #endif } #ifdef CONFIG_IRQ_TIME_ACCOUNTING static int irqtime_account_hi_update(void) { u64 *cpustat = kcpustat_this_cpu->cpustat; unsigned long flags; u64 latest_ns; int ret = 0; local_irq_save(flags); latest_ns = this_cpu_read(cpu_hardirq_time); if (nsecs_to_cputime64(latest_ns) > cpustat[CPUTIME_IRQ]) ret = 1; local_irq_restore(flags); return ret; } static int irqtime_account_si_update(void) { u64 *cpustat = kcpustat_this_cpu->cpustat; unsigned long flags; u64 latest_ns; int ret = 0; local_irq_save(flags); latest_ns = this_cpu_read(cpu_softirq_time); if (nsecs_to_cputime64(latest_ns) > cpustat[CPUTIME_SOFTIRQ]) ret = 1; local_irq_restore(flags); return ret; } #else /* CONFIG_IRQ_TIME_ACCOUNTING */ #define sched_clock_irqtime (0) #endif void sched_set_stop_task(int cpu, struct task_struct *stop) { struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 }; struct task_struct *old_stop = cpu_rq(cpu)->stop; if (stop) { /* * Make it appear like a SCHED_FIFO task, its something * userspace knows about and won't get confused about. * * Also, it will make PI more or less work without too * much confusion -- but then, stop work should not * rely on PI working anyway. */ sched_setscheduler_nocheck(stop, SCHED_FIFO, &param); stop->sched_class = &stop_sched_class; } cpu_rq(cpu)->stop = stop; if (old_stop) { /* * Reset it back to a normal scheduling class so that * it can die in pieces. */ old_stop->sched_class = &rt_sched_class; } } /* * __normal_prio - return the priority that is based on the static prio */ static inline int __normal_prio(struct task_struct *p) { return p->static_prio; } /* * Calculate the expected normal priority: i.e. priority * without taking RT-inheritance into account. Might be * boosted by interactivity modifiers. Changes upon fork, * setprio syscalls, and whenever the interactivity * estimator recalculates. */ static inline int normal_prio(struct task_struct *p) { int prio; if (task_has_rt_policy(p)) prio = MAX_RT_PRIO-1 - p->rt_priority; else prio = __normal_prio(p); return prio; } /* * Calculate the current priority, i.e. the priority * taken into account by the scheduler. This value might * be boosted by RT tasks, or might be boosted by * interactivity modifiers. Will be RT if the task got * RT-boosted. If not then it returns p->normal_prio. */ static int effective_prio(struct task_struct *p) { p->normal_prio = normal_prio(p); /* * If we are RT tasks or we were boosted to RT priority, * keep the priority unchanged. Otherwise, update priority * to the normal priority: */ if (!rt_prio(p->prio)) return p->normal_prio; return p->prio; } /** * task_curr - is this task currently executing on a CPU? * @p: the task in question. */ inline int task_curr(const struct task_struct *p) { return cpu_curr(task_cpu(p)) == p; } static inline void check_class_changed(struct rq *rq, struct task_struct *p, const struct sched_class *prev_class, int oldprio) { if (prev_class != p->sched_class) { if (prev_class->switched_from) prev_class->switched_from(rq, p); p->sched_class->switched_to(rq, p); } else if (oldprio != p->prio) p->sched_class->prio_changed(rq, p, oldprio); } void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags) { const struct sched_class *class; if (p->sched_class == rq->curr->sched_class) { rq->curr->sched_class->check_preempt_curr(rq, p, flags); } else { for_each_class(class) { if (class == rq->curr->sched_class) break; if (class == p->sched_class) { resched_task(rq->curr); break; } } } /* * A queue event has occurred, and we're going to schedule. In * this case, we can save a useless back to back clock update. */ if (rq->curr->on_rq && test_tsk_need_resched(rq->curr)) rq->skip_clock_update = 1; } #ifdef CONFIG_SMP void set_task_cpu(struct task_struct *p, unsigned int new_cpu) { #ifdef CONFIG_SCHED_DEBUG /* * We should never call set_task_cpu() on a blocked task, * ttwu() will sort out the placement. */ WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING && !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE)); #ifdef CONFIG_LOCKDEP /* * The caller should hold either p->pi_lock or rq->lock, when changing * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks. * * sched_move_task() holds both and thus holding either pins the cgroup, * see task_group(). * * Furthermore, all task_rq users should acquire both locks, see * task_rq_lock(). */ WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) || lockdep_is_held(&task_rq(p)->lock))); #endif #endif trace_sched_migrate_task(p, new_cpu); if (task_cpu(p) != new_cpu) { p->se.nr_migrations++; perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, NULL, 0); } __set_task_cpu(p, new_cpu); } struct migration_arg { struct task_struct *task; int dest_cpu; }; static int migration_cpu_stop(void *data); /* * wait_task_inactive - wait for a thread to unschedule. * * If @match_state is nonzero, it's the @p->state value just checked and * not expected to change. If it changes, i.e. @p might have woken up, * then return zero. When we succeed in waiting for @p to be off its CPU, * we return a positive number (its total switch count). If a second call * a short while later returns the same number, the caller can be sure that * @p has remained unscheduled the whole time. * * The caller must ensure that the task *will* unschedule sometime soon, * else this function might spin for a *long* time. This function can't * be called with interrupts off, or it may introduce deadlock with * smp_call_function() if an IPI is sent by the same process we are * waiting to become inactive. */ unsigned long wait_task_inactive(struct task_struct *p, long match_state) { unsigned long flags; int running, on_rq; unsigned long ncsw; struct rq *rq; for (;;) { /* * We do the initial early heuristics without holding * any task-queue locks at all. We'll only try to get * the runqueue lock when things look like they will * work out! */ rq = task_rq(p); /* * If the task is actively running on another CPU * still, just relax and busy-wait without holding * any locks. * * NOTE! Since we don't hold any locks, it's not * even sure that "rq" stays as the right runqueue! * But we don't care, since "task_running()" will * return false if the runqueue has changed and p * is actually now running somewhere else! */ while (task_running(rq, p)) { if (match_state && unlikely(p->state != match_state)) return 0; cpu_relax(); } /* * Ok, time to look more closely! We need the rq * lock now, to be *sure*. If we're wrong, we'll * just go back and repeat. */ rq = task_rq_lock(p, &flags); trace_sched_wait_task(p); running = task_running(rq, p); on_rq = p->on_rq; ncsw = 0; if (!match_state || p->state == match_state) ncsw = p->nvcsw | LONG_MIN; /* sets MSB */ task_rq_unlock(rq, p, &flags); /* * If it changed from the expected state, bail out now. */ if (unlikely(!ncsw)) break; /* * Was it really running after all now that we * checked with the proper locks actually held? * * Oops. Go back and try again.. */ if (unlikely(running)) { cpu_relax(); continue; } /* * It's not enough that it's not actively running, * it must be off the runqueue _entirely_, and not * preempted! * * So if it was still runnable (but just not actively * running right now), it's preempted, and we should * yield - it could be a while. */ if (unlikely(on_rq)) { ktime_t to = ktime_set(0, NSEC_PER_MSEC); set_current_state(TASK_UNINTERRUPTIBLE); schedule_hrtimeout(&to, HRTIMER_MODE_REL); continue; } /* * Ahh, all good. It wasn't running, and it wasn't * runnable, which means that it will never become * running in the future either. We're all done! */ break; } return ncsw; } /*** * kick_process - kick a running thread to enter/exit the kernel * @p: the to-be-kicked thread * * Cause a process which is running on another CPU to enter * kernel-mode, without any delay. (to get signals handled.) * * NOTE: this function doesn't have to take the runqueue lock, * because all it wants to ensure is that the remote task enters * the kernel. If the IPI races and the task has been migrated * to another CPU then no harm is done and the purpose has been * achieved as well. */ void kick_process(struct task_struct *p) { int cpu; preempt_disable(); cpu = task_cpu(p); if ((cpu != smp_processor_id()) && task_curr(p)) smp_send_reschedule(cpu); preempt_enable(); } EXPORT_SYMBOL_GPL(kick_process); #endif /* CONFIG_SMP */ #ifdef CONFIG_SMP /* * ->cpus_allowed is protected by both rq->lock and p->pi_lock */ static int select_fallback_rq(int cpu, struct task_struct *p) { const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(cpu)); enum { cpuset, possible, fail } state = cpuset; int dest_cpu; /* Look for allowed, online CPU in same node. */ for_each_cpu(dest_cpu, nodemask) { if (!cpu_online(dest_cpu)) continue; if (!cpu_active(dest_cpu)) continue; if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p))) return dest_cpu; } for (;;) { /* Any allowed, online CPU? */ for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) { if (!cpu_online(dest_cpu)) continue; if (!cpu_active(dest_cpu)) continue; goto out; } switch (state) { case cpuset: /* No more Mr. Nice Guy. */ cpuset_cpus_allowed_fallback(p); state = possible; break; case possible: do_set_cpus_allowed(p, cpu_possible_mask); state = fail; break; case fail: BUG(); break; } } out: if (state != cpuset) { /* * Don't tell them about moving exiting tasks or * kernel threads (both mm NULL), since they never * leave kernel. */ if (p->mm && printk_ratelimit()) { printk_deferred("process %d (%s) no longer affine to cpu%d\n", task_pid_nr(p), p->comm, cpu); } } return dest_cpu; } /* * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable. */ static inline int select_task_rq(struct task_struct *p, int sd_flags, int wake_flags) { int cpu = p->sched_class->select_task_rq(p, sd_flags, wake_flags); /* * In order not to call set_task_cpu() on a blocking task we need * to rely on ttwu() to place the task on a valid ->cpus_allowed * cpu. * * Since this is common to all placement strategies, this lives here. * * [ this allows ->select_task() to simply return task_cpu(p) and * not worry about this generic constraint ] */ if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) || !cpu_online(cpu))) cpu = select_fallback_rq(task_cpu(p), p); return cpu; } static void update_avg(u64 *avg, u64 sample) { s64 diff = sample - *avg; *avg += diff >> 3; } #endif static void ttwu_stat(struct task_struct *p, int cpu, int wake_flags) { #ifdef CONFIG_SCHEDSTATS struct rq *rq = this_rq(); #ifdef CONFIG_SMP int this_cpu = smp_processor_id(); if (cpu == this_cpu) { schedstat_inc(rq, ttwu_local); schedstat_inc(p, se.statistics.nr_wakeups_local); } else { struct sched_domain *sd; schedstat_inc(p, se.statistics.nr_wakeups_remote); rcu_read_lock(); for_each_domain(this_cpu, sd) { if (cpumask_test_cpu(cpu, sched_domain_span(sd))) { schedstat_inc(sd, ttwu_wake_remote); break; } } rcu_read_unlock(); } if (wake_flags & WF_MIGRATED) schedstat_inc(p, se.statistics.nr_wakeups_migrate); #endif /* CONFIG_SMP */ schedstat_inc(rq, ttwu_count); schedstat_inc(p, se.statistics.nr_wakeups); if (wake_flags & WF_SYNC) schedstat_inc(p, se.statistics.nr_wakeups_sync); #endif /* CONFIG_SCHEDSTATS */ } static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags) { activate_task(rq, p, en_flags); p->on_rq = 1; /* if a worker is waking up, notify workqueue */ if (p->flags & PF_WQ_WORKER) wq_worker_waking_up(p, cpu_of(rq)); } /* * Mark the task runnable and perform wakeup-preemption. */ static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags) { trace_sched_wakeup(p, true); check_preempt_curr(rq, p, wake_flags); p->state = TASK_RUNNING; #ifdef CONFIG_SMP if (p->sched_class->task_woken) p->sched_class->task_woken(rq, p); if (rq->idle_stamp) { u64 delta = rq->clock - rq->idle_stamp; u64 max = 2*sysctl_sched_migration_cost; update_avg(&rq->avg_idle, delta); if (rq->avg_idle > max) rq->avg_idle = max; rq->idle_stamp = 0; } #endif } static void ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags) { #ifdef CONFIG_SMP if (p->sched_contributes_to_load) rq->nr_uninterruptible--; #endif ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING); ttwu_do_wakeup(rq, p, wake_flags); } /* * Called in case the task @p isn't fully descheduled from its runqueue, * in this case we must do a remote wakeup. Its a 'light' wakeup though, * since all we need to do is flip p->state to TASK_RUNNING, since * the task is still ->on_rq. */ static int ttwu_remote(struct task_struct *p, int wake_flags) { struct rq *rq; int ret = 0; rq = __task_rq_lock(p); if (p->on_rq) { ttwu_do_wakeup(rq, p, wake_flags); ret = 1; } __task_rq_unlock(rq); return ret; } #ifdef CONFIG_SMP static void sched_ttwu_pending(void) { struct rq *rq = this_rq(); struct llist_node *llist = llist_del_all(&rq->wake_list); struct task_struct *p; raw_spin_lock(&rq->lock); while (llist) { p = llist_entry(llist, struct task_struct, wake_entry); llist = llist_next(llist); ttwu_do_activate(rq, p, 0); } raw_spin_unlock(&rq->lock); } void scheduler_ipi(void) { if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick()) return; /* * Not all reschedule IPI handlers call irq_enter/irq_exit, since * traditionally all their work was done from the interrupt return * path. Now that we actually do some work, we need to make sure * we do call them. * * Some archs already do call them, luckily irq_enter/exit nest * properly. * * Arguably we should visit all archs and update all handlers, * however a fair share of IPIs are still resched only so this would * somewhat pessimize the simple resched case. */ irq_enter(); sched_ttwu_pending(); /* * Check if someone kicked us for doing the nohz idle load balance. */ if (unlikely(got_nohz_idle_kick() && !need_resched())) { this_rq()->idle_balance = 1; raise_softirq_irqoff(SCHED_SOFTIRQ); } irq_exit(); } static void ttwu_queue_remote(struct task_struct *p, int cpu) { if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) smp_send_reschedule(cpu); } #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW static int ttwu_activate_remote(struct task_struct *p, int wake_flags) { struct rq *rq; int ret = 0; rq = __task_rq_lock(p); if (p->on_cpu) { ttwu_activate(rq, p, ENQUEUE_WAKEUP); ttwu_do_wakeup(rq, p, wake_flags); ret = 1; } __task_rq_unlock(rq); return ret; } #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */ bool cpus_share_cache(int this_cpu, int that_cpu) { return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu); } #endif /* CONFIG_SMP */ static void ttwu_queue(struct task_struct *p, int cpu) { struct rq *rq = cpu_rq(cpu); #if defined(CONFIG_SMP) if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) { sched_clock_cpu(cpu); /* sync clocks x-cpu */ ttwu_queue_remote(p, cpu); return; } #endif raw_spin_lock(&rq->lock); ttwu_do_activate(rq, p, 0); raw_spin_unlock(&rq->lock); } /** * try_to_wake_up - wake up a thread * @p: the thread to be awakened * @state: the mask of task states that can be woken * @wake_flags: wake modifier flags (WF_*) * * Put it on the run-queue if it's not already there. The "current" * thread is always on the run-queue (except when the actual * re-schedule is in progress), and as such you're allowed to do * the simpler "current->state = TASK_RUNNING" to mark yourself * runnable without the overhead of this. * * Returns %true if @p was woken up, %false if it was already running * or @state didn't match @p's state. */ static int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) { unsigned long flags; int cpu, src_cpu, success = 0; smp_wmb(); raw_spin_lock_irqsave(&p->pi_lock, flags); src_cpu = task_cpu(p); cpu = src_cpu; if (!(p->state & state)) goto out; success = 1; /* we're going to change ->state */ if (p->on_rq && ttwu_remote(p, wake_flags)) goto stat; #ifdef CONFIG_SMP /* * If the owning (remote) cpu is still in the middle of schedule() with * this task as prev, wait until its done referencing the task. */ while (p->on_cpu) { #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW /* * In case the architecture enables interrupts in * context_switch(), we cannot busy wait, since that * would lead to deadlocks when an interrupt hits and * tries to wake up @prev. So bail and do a complete * remote wakeup. */ if (ttwu_activate_remote(p, wake_flags)) goto stat; #else cpu_relax(); #endif } /* * Pairs with the smp_wmb() in finish_lock_switch(). */ smp_rmb(); p->sched_contributes_to_load = !!task_contributes_to_load(p); p->state = TASK_WAKING; if (p->sched_class->task_waking) p->sched_class->task_waking(p); cpu = select_task_rq(p, SD_BALANCE_WAKE, wake_flags); if (src_cpu != cpu) { wake_flags |= WF_MIGRATED; set_task_cpu(p, cpu); } #endif /* CONFIG_SMP */ ttwu_queue(p, cpu); stat: ttwu_stat(p, cpu, wake_flags); out: raw_spin_unlock_irqrestore(&p->pi_lock, flags); if (src_cpu != cpu && task_notify_on_migrate(p)) atomic_notifier_call_chain(&migration_notifier_head, cpu, (void *)src_cpu); return success; } /** * try_to_wake_up_local - try to wake up a local task with rq lock held * @p: the thread to be awakened * * Put @p on the run-queue if it's not already there. The caller must * ensure that this_rq() is locked, @p is bound to this_rq() and not * the current task. */ static void try_to_wake_up_local(struct task_struct *p) { struct rq *rq = task_rq(p); if (WARN_ON_ONCE(rq != this_rq()) || WARN_ON_ONCE(p == current)) return; lockdep_assert_held(&rq->lock); if (!raw_spin_trylock(&p->pi_lock)) { raw_spin_unlock(&rq->lock); raw_spin_lock(&p->pi_lock); raw_spin_lock(&rq->lock); } if (!(p->state & TASK_NORMAL)) goto out; if (!p->on_rq) ttwu_activate(rq, p, ENQUEUE_WAKEUP); ttwu_do_wakeup(rq, p, 0); ttwu_stat(p, smp_processor_id(), 0); out: raw_spin_unlock(&p->pi_lock); } /** * wake_up_process - Wake up a specific process * @p: The process to be woken up. * * Attempt to wake up the nominated process and move it to the set of runnable * processes. Returns 1 if the process was woken up, 0 if it was already * running. * * It may be assumed that this function implies a write memory barrier before * changing the task state if and only if any tasks are woken up. */ int wake_up_process(struct task_struct *p) { WARN_ON(task_is_stopped_or_traced(p)); return try_to_wake_up(p, TASK_NORMAL, 0); } EXPORT_SYMBOL(wake_up_process); int wake_up_state(struct task_struct *p, unsigned int state) { return try_to_wake_up(p, state, 0); } /* * Perform scheduler related setup for a newly forked process p. * p is forked by current. * * __sched_fork() is basic setup used by init_idle() too: */ static void __sched_fork(struct task_struct *p) { p->on_rq = 0; p->se.on_rq = 0; p->se.exec_start = 0; p->se.sum_exec_runtime = 0; p->se.prev_sum_exec_runtime = 0; p->se.nr_migrations = 0; p->se.vruntime = 0; INIT_LIST_HEAD(&p->se.group_node); #ifdef CONFIG_SCHEDSTATS memset(&p->se.statistics, 0, sizeof(p->se.statistics)); #endif INIT_LIST_HEAD(&p->rt.run_list); #ifdef CONFIG_PREEMPT_NOTIFIERS INIT_HLIST_HEAD(&p->preempt_notifiers); #endif } /* * fork()/clone()-time setup: */ void sched_fork(struct task_struct *p) { unsigned long flags; int cpu = get_cpu(); __sched_fork(p); /* * We mark the process as running here. This guarantees that * nobody will actually run it, and a signal or other external * event cannot wake it up and insert it on the runqueue either. */ p->state = TASK_RUNNING; /* * Make sure we do not leak PI boosting priority to the child. */ p->prio = current->normal_prio; /* * Revert to default priority/policy on fork if requested. */ if (unlikely(p->sched_reset_on_fork)) { if (task_has_rt_policy(p)) { p->policy = SCHED_NORMAL; p->static_prio = NICE_TO_PRIO(0); p->rt_priority = 0; } else if (PRIO_TO_NICE(p->static_prio) < 0) p->static_prio = NICE_TO_PRIO(0); p->prio = p->normal_prio = __normal_prio(p); set_load_weight(p); /* * We don't need the reset flag anymore after the fork. It has * fulfilled its duty: */ p->sched_reset_on_fork = 0; } if (!rt_prio(p->prio)) p->sched_class = &fair_sched_class; if (p->sched_class->task_fork) p->sched_class->task_fork(p); /* * The child is not yet in the pid-hash so no cgroup attach races, * and the cgroup is pinned to this child due to cgroup_fork() * is ran before sched_fork(). * * Silence PROVE_RCU. */ raw_spin_lock_irqsave(&p->pi_lock, flags); set_task_cpu(p, cpu); raw_spin_unlock_irqrestore(&p->pi_lock, flags); #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT) if (likely(sched_info_on())) memset(&p->sched_info, 0, sizeof(p->sched_info)); #endif #if defined(CONFIG_SMP) p->on_cpu = 0; #endif #ifdef CONFIG_PREEMPT_COUNT /* Want to start with kernel preemption disabled. */ task_thread_info(p)->preempt_count = 1; #endif #ifdef CONFIG_SMP plist_node_init(&p->pushable_tasks, MAX_PRIO); #endif put_cpu(); } /* * wake_up_new_task - wake up a newly created task for the first time. * * This function will do some initial scheduler statistics housekeeping * that must be done for every newly created context, then puts the task * on the runqueue and wakes it. */ void wake_up_new_task(struct task_struct *p) { unsigned long flags; struct rq *rq; raw_spin_lock_irqsave(&p->pi_lock, flags); #ifdef CONFIG_SMP /* * Fork balancing, do it here and not earlier because: * - cpus_allowed can change in the fork path * - any previously selected cpu might disappear through hotplug */ set_task_cpu(p, select_task_rq(p, SD_BALANCE_FORK, 0)); #endif rq = __task_rq_lock(p); activate_task(rq, p, 0); p->on_rq = 1; trace_sched_wakeup_new(p, true); check_preempt_curr(rq, p, WF_FORK); #ifdef CONFIG_SMP if (p->sched_class->task_woken) p->sched_class->task_woken(rq, p); #endif task_rq_unlock(rq, p, &flags); } #ifdef CONFIG_PREEMPT_NOTIFIERS /** * preempt_notifier_register - tell me when current is being preempted & rescheduled * @notifier: notifier struct to register */ void preempt_notifier_register(struct preempt_notifier *notifier) { hlist_add_head(&notifier->link, &current->preempt_notifiers); } EXPORT_SYMBOL_GPL(preempt_notifier_register); /** * preempt_notifier_unregister - no longer interested in preemption notifications * @notifier: notifier struct to unregister * * This is safe to call from within a preemption notifier. */ void preempt_notifier_unregister(struct preempt_notifier *notifier) { hlist_del(&notifier->link); } EXPORT_SYMBOL_GPL(preempt_notifier_unregister); static void fire_sched_in_preempt_notifiers(struct task_struct *curr) { struct preempt_notifier *notifier; struct hlist_node *node; hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link) notifier->ops->sched_in(notifier, raw_smp_processor_id()); } static void fire_sched_out_preempt_notifiers(struct task_struct *curr, struct task_struct *next) { struct preempt_notifier *notifier; struct hlist_node *node; hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link) notifier->ops->sched_out(notifier, next); } #else /* !CONFIG_PREEMPT_NOTIFIERS */ static void fire_sched_in_preempt_notifiers(struct task_struct *curr) { } static void fire_sched_out_preempt_notifiers(struct task_struct *curr, struct task_struct *next) { } #endif /* CONFIG_PREEMPT_NOTIFIERS */ /** * prepare_task_switch - prepare to switch tasks * @rq: the runqueue preparing to switch * @prev: the current task that is being switched out * @next: the task we are going to switch to. * * This is called with the rq lock held and interrupts off. It must * be paired with a subsequent finish_task_switch after the context * switch. * * prepare_task_switch sets up locking and calls architecture specific * hooks. */ static inline void prepare_task_switch(struct rq *rq, struct task_struct *prev, struct task_struct *next) { sched_info_switch(prev, next); perf_event_task_sched_out(prev, next); fire_sched_out_preempt_notifiers(prev, next); prepare_lock_switch(rq, next); prepare_arch_switch(next); trace_sched_switch(prev, next); } /** * finish_task_switch - clean up after a task-switch * @rq: runqueue associated with task-switch * @prev: the thread we just switched away from. * * finish_task_switch must be called after the context switch, paired * with a prepare_task_switch call before the context switch. * finish_task_switch will reconcile locking set up by prepare_task_switch, * and do any other architecture-specific cleanup actions. * * Note that we may have delayed dropping an mm in context_switch(). If * so, we finish that here outside of the runqueue lock. (Doing it * with the lock held can cause deadlocks; see schedule() for * details.) */ static void finish_task_switch(struct rq *rq, struct task_struct *prev) __releases(rq->lock) { struct mm_struct *mm = rq->prev_mm; long prev_state; rq->prev_mm = NULL; /* * A task struct has one reference for the use as "current". * If a task dies, then it sets TASK_DEAD in tsk->state and calls * schedule one last time. The schedule call will never return, and * the scheduled task must drop that reference. * The test for TASK_DEAD must occur while the runqueue locks are * still held, otherwise prev could be scheduled on another cpu, die * there before we look at prev->state, and then the reference would * be dropped twice. * Manfred Spraul <manfred@colorfullife.com> */ prev_state = prev->state; finish_arch_switch(prev); #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW local_irq_disable(); #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */ perf_event_task_sched_in(prev, current); #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW local_irq_enable(); #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */ finish_lock_switch(rq, prev); finish_arch_post_lock_switch(); fire_sched_in_preempt_notifiers(current); if (mm) mmdrop(mm); if (unlikely(prev_state == TASK_DEAD)) { /* * Remove function-return probe instances associated with this * task and put them back on the free list. */ kprobe_flush_task(prev); put_task_struct(prev); } } #ifdef CONFIG_SMP /* assumes rq->lock is held */ static inline void pre_schedule(struct rq *rq, struct task_struct *prev) { if (prev->sched_class->pre_schedule) prev->sched_class->pre_schedule(rq, prev); } /* rq->lock is NOT held, but preemption is disabled */ static inline void post_schedule(struct rq *rq) { if (rq->post_schedule) { unsigned long flags; raw_spin_lock_irqsave(&rq->lock, flags); if (rq->curr->sched_class->post_schedule) rq->curr->sched_class->post_schedule(rq); raw_spin_unlock_irqrestore(&rq->lock, flags); rq->post_schedule = 0; } } #else static inline void pre_schedule(struct rq *rq, struct task_struct *p) { } static inline void post_schedule(struct rq *rq) { } #endif /** * schedule_tail - first thing a freshly forked thread must call. * @prev: the thread we just switched away from. */ asmlinkage void schedule_tail(struct task_struct *prev) __releases(rq->lock) { struct rq *rq = this_rq(); finish_task_switch(rq, prev); /* * FIXME: do we need to worry about rq being invalidated by the * task_switch? */ post_schedule(rq); #ifdef __ARCH_WANT_UNLOCKED_CTXSW /* In this case, finish_task_switch does not reenable preemption */ preempt_enable(); #endif if (current->set_child_tid) put_user(task_pid_vnr(current), current->set_child_tid); } /* * context_switch - switch to the new MM and the new * thread's register state. */ static inline void context_switch(struct rq *rq, struct task_struct *prev, struct task_struct *next) { struct mm_struct *mm, *oldmm; prepare_task_switch(rq, prev, next); mm = next->mm; oldmm = prev->active_mm; /* * For paravirt, this is coupled with an exit in switch_to to * combine the page table reload and the switch backend into * one hypercall. */ arch_start_context_switch(prev); if (!mm) { next->active_mm = oldmm; atomic_inc(&oldmm->mm_count); enter_lazy_tlb(oldmm, next); } else switch_mm(oldmm, mm, next); if (!prev->mm) { prev->active_mm = NULL; rq->prev_mm = oldmm; } /* * Since the runqueue lock will be released by the next * task (which is an invalid locking op but in the case * of the scheduler it's an obvious special-case), so we * do an early lockdep release here: */ #ifndef __ARCH_WANT_UNLOCKED_CTXSW spin_release(&rq->lock.dep_map, 1, _THIS_IP_); #endif /* Here we just switch the register state and the stack. */ switch_to(prev, next, prev); barrier(); /* * this_rq must be evaluated again because prev may have moved * CPUs since it called schedule(), thus the 'rq' on its stack * frame will be invalid. */ finish_task_switch(this_rq(), prev); } /* * nr_running, nr_uninterruptible and nr_context_switches: * * externally visible scheduler statistics: current number of runnable * threads, current number of uninterruptible-sleeping threads, total * number of context switches performed since bootup. */ unsigned long nr_running(void) { unsigned long i, sum = 0; for_each_online_cpu(i) sum += cpu_rq(i)->nr_running; return sum; } unsigned long nr_uninterruptible(void) { unsigned long i, sum = 0; for_each_possible_cpu(i) sum += cpu_rq(i)->nr_uninterruptible; /* * Since we read the counters lockless, it might be slightly * inaccurate. Do not allow it to go below zero though: */ if (unlikely((long)sum < 0)) sum = 0; return sum; } unsigned long long nr_context_switches(void) { int i; unsigned long long sum = 0; for_each_possible_cpu(i) sum += cpu_rq(i)->nr_switches; return sum; } unsigned long nr_iowait(void) { unsigned long i, sum = 0; for_each_possible_cpu(i) sum += atomic_read(&cpu_rq(i)->nr_iowait); return sum; } unsigned long nr_iowait_cpu(int cpu) { struct rq *this = cpu_rq(cpu); return atomic_read(&this->nr_iowait); } unsigned long this_cpu_load(void) { struct rq *this = this_rq(); return this->cpu_load[0]; } #ifdef CONFIG_INTELLI_PLUG unsigned long avg_nr_running(void) { unsigned long i, sum = 0; unsigned int seqcnt, ave_nr_running; for_each_online_cpu(i) { struct nr_stats_s *stats = &per_cpu(runqueue_stats, i); struct rq *q = cpu_rq(i); /* * Update average to avoid reading stalled value if there were * no run-queue changes for a long time. On the other hand if * the changes are happening right now, just read current value * directly. */ seqcnt = read_seqcount_begin(&stats->ave_seqcnt); ave_nr_running = do_avg_nr_running(q); if (read_seqcount_retry(&stats->ave_seqcnt, seqcnt)) { read_seqcount_begin(&stats->ave_seqcnt); ave_nr_running = stats->ave_nr_running; } sum += ave_nr_running; } return sum; } EXPORT_SYMBOL(avg_nr_running); unsigned long avg_cpu_nr_running(unsigned int cpu) { unsigned int seqcnt, ave_nr_running; struct nr_stats_s *stats = &per_cpu(runqueue_stats, cpu); struct rq *q = cpu_rq(cpu); /* * Update average to avoid reading stalled value if there were * no run-queue changes for a long time. On the other hand if * the changes are happening right now, just read current value * directly. */ seqcnt = read_seqcount_begin(&stats->ave_seqcnt); ave_nr_running = do_avg_nr_running(q); if (read_seqcount_retry(&stats->ave_seqcnt, seqcnt)) { read_seqcount_begin(&stats->ave_seqcnt); ave_nr_running = stats->ave_nr_running; } return ave_nr_running; } EXPORT_SYMBOL(avg_cpu_nr_running); #endif /* * Global load-average calculations * * We take a distributed and async approach to calculating the global load-avg * in order to minimize overhead. * * The global load average is an exponentially decaying average of nr_running + * nr_uninterruptible. * * Once every LOAD_FREQ: * * nr_active = 0; * for_each_possible_cpu(cpu) * nr_active += cpu_of(cpu)->nr_running + cpu_of(cpu)->nr_uninterruptible; * * avenrun[n] = avenrun[0] * exp_n + nr_active * (1 - exp_n) * * Due to a number of reasons the above turns in the mess below: * * - for_each_possible_cpu() is prohibitively expensive on machines with * serious number of cpus, therefore we need to take a distributed approach * to calculating nr_active. * * \Sum_i x_i(t) = \Sum_i x_i(t) - x_i(t_0) | x_i(t_0) := 0 * = \Sum_i { \Sum_j=1 x_i(t_j) - x_i(t_j-1) } * * So assuming nr_active := 0 when we start out -- true per definition, we * can simply take per-cpu deltas and fold those into a global accumulate * to obtain the same result. See calc_load_fold_active(). * * Furthermore, in order to avoid synchronizing all per-cpu delta folding * across the machine, we assume 10 ticks is sufficient time for every * cpu to have completed this task. * * This places an upper-bound on the IRQ-off latency of the machine. Then * again, being late doesn't loose the delta, just wrecks the sample. * * - cpu_rq()->nr_uninterruptible isn't accurately tracked per-cpu because * this would add another cross-cpu cacheline miss and atomic operation * to the wakeup path. Instead we increment on whatever cpu the task ran * when it went into uninterruptible state and decrement on whatever cpu * did the wakeup. This means that only the sum of nr_uninterruptible over * all cpus yields the correct result. * * This covers the NO_HZ=n code, for extra head-aches, see the comment below. */ /* Variables and functions for calc_load */ static atomic_long_t calc_load_tasks; static unsigned long calc_load_update; unsigned long avenrun[3]; EXPORT_SYMBOL(avenrun); /* should be removed */ /** * get_avenrun - get the load average array * @loads: pointer to dest load array * @offset: offset to add * @shift: shift count to shift the result left * * These values are estimates at best, so no need for locking. */ void get_avenrun(unsigned long *loads, unsigned long offset, int shift) { loads[0] = (avenrun[0] + offset) << shift; loads[1] = (avenrun[1] + offset) << shift; loads[2] = (avenrun[2] + offset) << shift; } static long calc_load_fold_active(struct rq *this_rq) { long nr_active, delta = 0; nr_active = this_rq->nr_running; nr_active += (long) this_rq->nr_uninterruptible; if (nr_active != this_rq->calc_load_active) { delta = nr_active - this_rq->calc_load_active; this_rq->calc_load_active = nr_active; } return delta; } /* * a1 = a0 * e + a * (1 - e) */ static unsigned long calc_load(unsigned long load, unsigned long exp, unsigned long active) { load *= exp; load += active * (FIXED_1 - exp); load += 1UL << (FSHIFT - 1); return load >> FSHIFT; } #ifdef CONFIG_NO_HZ /* * Handle NO_HZ for the global load-average. * * Since the above described distributed algorithm to compute the global * load-average relies on per-cpu sampling from the tick, it is affected by * NO_HZ. * * The basic idea is to fold the nr_active delta into a global idle-delta upon * entering NO_HZ state such that we can include this as an 'extra' cpu delta * when we read the global state. * * Obviously reality has to ruin such a delightfully simple scheme: * * - When we go NO_HZ idle during the window, we can negate our sample * contribution, causing under-accounting. * * We avoid this by keeping two idle-delta counters and flipping them * when the window starts, thus separating old and new NO_HZ load. * * The only trick is the slight shift in index flip for read vs write. * * 0s 5s 10s 15s * +10 +10 +10 +10 * |-|-----------|-|-----------|-|-----------|-| * r:0 0 1 1 0 0 1 1 0 * w:0 1 1 0 0 1 1 0 0 * * This ensures we'll fold the old idle contribution in this window while * accumlating the new one. * * - When we wake up from NO_HZ idle during the window, we push up our * contribution, since we effectively move our sample point to a known * busy state. * * This is solved by pushing the window forward, and thus skipping the * sample, for this cpu (effectively using the idle-delta for this cpu which * was in effect at the time the window opened). This also solves the issue * of having to deal with a cpu having been in NOHZ idle for multiple * LOAD_FREQ intervals. * * When making the ILB scale, we should try to pull this in as well. */ static atomic_long_t calc_load_idle[2]; static int calc_load_idx; static inline int calc_load_write_idx(void) { int idx = calc_load_idx; /* * See calc_global_nohz(), if we observe the new index, we also * need to observe the new update time. */ smp_rmb(); /* * If the folding window started, make sure we start writing in the * next idle-delta. */ if (!time_before(jiffies, calc_load_update)) idx++; return idx & 1; } static inline int calc_load_read_idx(void) { return calc_load_idx & 1; } void calc_load_enter_idle(void) { struct rq *this_rq = this_rq(); long delta; /* * We're going into NOHZ mode, if there's any pending delta, fold it * into the pending idle delta. */ delta = calc_load_fold_active(this_rq); if (delta) { int idx = calc_load_write_idx(); atomic_long_add(delta, &calc_load_idle[idx]); } } void calc_load_exit_idle(void) { struct rq *this_rq = this_rq(); /* * If we're still before the sample window, we're done. */ if (time_before(jiffies, this_rq->calc_load_update)) return; /* * We woke inside or after the sample window, this means we're already * accounted through the nohz accounting, so skip the entire deal and * sync up for the next window. */ this_rq->calc_load_update = calc_load_update; if (time_before(jiffies, this_rq->calc_load_update + 10)) this_rq->calc_load_update += LOAD_FREQ; } static long calc_load_fold_idle(void) { int idx = calc_load_read_idx(); long delta = 0; if (atomic_long_read(&calc_load_idle[idx])) delta = atomic_long_xchg(&calc_load_idle[idx], 0); return delta; } /** * fixed_power_int - compute: x^n, in O(log n) time * * @x: base of the power * @frac_bits: fractional bits of @x * @n: power to raise @x to. * * By exploiting the relation between the definition of the natural power * function: x^n := x*x*...*x (x multiplied by itself for n times), and * the binary encoding of numbers used by computers: n := \Sum n_i * 2^i, * (where: n_i \elem {0, 1}, the binary vector representing n), * we find: x^n := x^(\Sum n_i * 2^i) := \Prod x^(n_i * 2^i), which is * of course trivially computable in O(log_2 n), the length of our binary * vector. */ static unsigned long fixed_power_int(unsigned long x, unsigned int frac_bits, unsigned int n) { unsigned long result = 1UL << frac_bits; if (n) for (;;) { if (n & 1) { result *= x; result += 1UL << (frac_bits - 1); result >>= frac_bits; } n >>= 1; if (!n) break; x *= x; x += 1UL << (frac_bits - 1); x >>= frac_bits; } return result; } /* * a1 = a0 * e + a * (1 - e) * * a2 = a1 * e + a * (1 - e) * = (a0 * e + a * (1 - e)) * e + a * (1 - e) * = a0 * e^2 + a * (1 - e) * (1 + e) * * a3 = a2 * e + a * (1 - e) * = (a0 * e^2 + a * (1 - e) * (1 + e)) * e + a * (1 - e) * = a0 * e^3 + a * (1 - e) * (1 + e + e^2) * * ... * * an = a0 * e^n + a * (1 - e) * (1 + e + ... + e^n-1) [1] * = a0 * e^n + a * (1 - e) * (1 - e^n)/(1 - e) * = a0 * e^n + a * (1 - e^n) * * [1] application of the geometric series: * * n 1 - x^(n+1) * S_n := \Sum x^i = ------------- * i=0 1 - x */ static unsigned long calc_load_n(unsigned long load, unsigned long exp, unsigned long active, unsigned int n) { return calc_load(load, fixed_power_int(exp, FSHIFT, n), active); } /* * NO_HZ can leave us missing all per-cpu ticks calling * calc_load_account_active(), but since an idle CPU folds its delta into * calc_load_tasks_idle per calc_load_account_idle(), all we need to do is fold * in the pending idle delta if our idle period crossed a load cycle boundary. * * Once we've updated the global active value, we need to apply the exponential * weights adjusted to the number of cycles missed. */ static void calc_global_nohz(void) { long delta, active, n; if (!time_before(jiffies, calc_load_update + 10)) { /* * Catch-up, fold however many we are behind still */ delta = jiffies - calc_load_update - 10; n = 1 + (delta / LOAD_FREQ); active = atomic_long_read(&calc_load_tasks); active = active > 0 ? active * FIXED_1 : 0; avenrun[0] = calc_load_n(avenrun[0], EXP_1, active, n); avenrun[1] = calc_load_n(avenrun[1], EXP_5, active, n); avenrun[2] = calc_load_n(avenrun[2], EXP_15, active, n); calc_load_update += n * LOAD_FREQ; } /* * Flip the idle index... * * Make sure we first write the new time then flip the index, so that * calc_load_write_idx() will see the new time when it reads the new * index, this avoids a double flip messing things up. */ smp_wmb(); calc_load_idx++; } #else /* !CONFIG_NO_HZ */ static inline long calc_load_fold_idle(void) { return 0; } static inline void calc_global_nohz(void) { } #endif /* CONFIG_NO_HZ */ /* * calc_load - update the avenrun load estimates 10 ticks after the * CPUs have updated calc_load_tasks. */ void calc_global_load(unsigned long ticks) { long active, delta; if (time_before(jiffies, calc_load_update + 10)) return; /* * Fold the 'old' idle-delta to include all NO_HZ cpus. */ delta = calc_load_fold_idle(); if (delta) atomic_long_add(delta, &calc_load_tasks); active = atomic_long_read(&calc_load_tasks); active = active > 0 ? active * FIXED_1 : 0; avenrun[0] = calc_load(avenrun[0], EXP_1, active); avenrun[1] = calc_load(avenrun[1], EXP_5, active); avenrun[2] = calc_load(avenrun[2], EXP_15, active); calc_load_update += LOAD_FREQ; /* * In case we idled for multiple LOAD_FREQ intervals, catch up in bulk. */ calc_global_nohz(); } /* * Called from update_cpu_load() to periodically update this CPU's * active count. */ static void calc_load_account_active(struct rq *this_rq) { long delta; if (time_before(jiffies, this_rq->calc_load_update)) return; delta = calc_load_fold_active(this_rq); if (delta) atomic_long_add(delta, &calc_load_tasks); this_rq->calc_load_update += LOAD_FREQ; } /* * End of global load-average stuff */ /* * The exact cpuload at various idx values, calculated at every tick would be * load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load * * If a cpu misses updates for n-1 ticks (as it was idle) and update gets called * on nth tick when cpu may be busy, then we have: * load = ((2^idx - 1) / 2^idx)^(n-1) * load * load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load * * decay_load_missed() below does efficient calculation of * load = ((2^idx - 1) / 2^idx)^(n-1) * load * avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load * * The calculation is approximated on a 128 point scale. * degrade_zero_ticks is the number of ticks after which load at any * particular idx is approximated to be zero. * degrade_factor is a precomputed table, a row for each load idx. * Each column corresponds to degradation factor for a power of two ticks, * based on 128 point scale. * Example: * row 2, col 3 (=12) says that the degradation at load idx 2 after * 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8). * * With this power of 2 load factors, we can degrade the load n times * by looking at 1 bits in n and doing as many mult/shift instead of * n mult/shifts needed by the exact degradation. */ #define DEGRADE_SHIFT 7 static const unsigned char degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128}; static const unsigned char degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = { {0, 0, 0, 0, 0, 0, 0, 0}, {64, 32, 8, 0, 0, 0, 0, 0}, {96, 72, 40, 12, 1, 0, 0}, {112, 98, 75, 43, 15, 1, 0}, {120, 112, 98, 76, 45, 16, 2} }; /* * Update cpu_load for any missed ticks, due to tickless idle. The backlog * would be when CPU is idle and so we just decay the old load without * adding any new load. */ static unsigned long decay_load_missed(unsigned long load, unsigned long missed_updates, int idx) { int j = 0; if (!missed_updates) return load; if (missed_updates >= degrade_zero_ticks[idx]) return 0; if (idx == 1) return load >> missed_updates; while (missed_updates) { if (missed_updates % 2) load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT; missed_updates >>= 1; j++; } return load; } /* * Update rq->cpu_load[] statistics. This function is usually called every * scheduler tick (TICK_NSEC). With tickless idle this will not be called * every tick. We fix it up based on jiffies. */ static void __update_cpu_load(struct rq *this_rq, unsigned long this_load, unsigned long pending_updates) { int i, scale; this_rq->nr_load_updates++; /* Update our load: */ this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */ for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) { unsigned long old_load, new_load; /* scale is effectively 1 << i now, and >> i divides by scale */ old_load = this_rq->cpu_load[i]; old_load = decay_load_missed(old_load, pending_updates - 1, i); new_load = this_load; /* * Round up the averaging division if load is increasing. This * prevents us from getting stuck on 9 if the load is 10, for * example. */ if (new_load > old_load) new_load += scale - 1; this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i; } sched_avg_update(this_rq); } #ifdef CONFIG_NO_HZ /* * There is no sane way to deal with nohz on smp when using jiffies because the * cpu doing the jiffies update might drift wrt the cpu doing the jiffy reading * causing off-by-one errors in observed deltas; {0,2} instead of {1,1}. * * Therefore we cannot use the delta approach from the regular tick since that * would seriously skew the load calculation. However we'll make do for those * updates happening while idle (nohz_idle_balance) or coming out of idle * (tick_nohz_idle_exit). * * This means we might still be one tick off for nohz periods. */ /* * Called from nohz_idle_balance() to update the load ratings before doing the * idle balance. */ void update_idle_cpu_load(struct rq *this_rq) { unsigned long curr_jiffies = ACCESS_ONCE(jiffies); unsigned long load = this_rq->load.weight; unsigned long pending_updates; /* * bail if there's load or we're actually up-to-date. */ if (load || curr_jiffies == this_rq->last_load_update_tick) return; pending_updates = curr_jiffies - this_rq->last_load_update_tick; this_rq->last_load_update_tick = curr_jiffies; __update_cpu_load(this_rq, load, pending_updates); } /* * Called from tick_nohz_idle_exit() -- try and fix up the ticks we missed. */ void update_cpu_load_nohz(void) { struct rq *this_rq = this_rq(); unsigned long curr_jiffies = ACCESS_ONCE(jiffies); unsigned long pending_updates; if (curr_jiffies == this_rq->last_load_update_tick) return; raw_spin_lock(&this_rq->lock); pending_updates = curr_jiffies - this_rq->last_load_update_tick; if (pending_updates) { this_rq->last_load_update_tick = curr_jiffies; /* * We were idle, this means load 0, the current load might be * !0 due to remote wakeups and the sort. */ __update_cpu_load(this_rq, 0, pending_updates); } raw_spin_unlock(&this_rq->lock); } #endif /* CONFIG_NO_HZ */ /* * Called from scheduler_tick() */ static void update_cpu_load_active(struct rq *this_rq) { /* * See the mess around update_idle_cpu_load() / update_cpu_load_nohz(). */ this_rq->last_load_update_tick = jiffies; __update_cpu_load(this_rq, this_rq->load.weight, 1); calc_load_account_active(this_rq); } #ifdef CONFIG_SMP /* * sched_exec - execve() is a valuable balancing opportunity, because at * this point the task has the smallest effective memory and cache footprint. */ void sched_exec(void) { struct task_struct *p = current; unsigned long flags; int dest_cpu; raw_spin_lock_irqsave(&p->pi_lock, flags); dest_cpu = p->sched_class->select_task_rq(p, SD_BALANCE_EXEC, 0); if (dest_cpu == smp_processor_id()) goto unlock; if (likely(cpu_active(dest_cpu))) { struct migration_arg arg = { p, dest_cpu }; raw_spin_unlock_irqrestore(&p->pi_lock, flags); stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg); return; } unlock: raw_spin_unlock_irqrestore(&p->pi_lock, flags); } #endif DEFINE_PER_CPU(struct kernel_stat, kstat); DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat); EXPORT_PER_CPU_SYMBOL(kstat); EXPORT_PER_CPU_SYMBOL(kernel_cpustat); /* * Return any ns on the sched_clock that have not yet been accounted in * @p in case that task is currently running. * * Called with task_rq_lock() held on @rq. */ static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq) { u64 ns = 0; if (task_current(rq, p)) { update_rq_clock(rq); ns = rq->clock_task - p->se.exec_start; if ((s64)ns < 0) ns = 0; } return ns; } unsigned long long task_delta_exec(struct task_struct *p) { unsigned long flags; struct rq *rq; u64 ns = 0; rq = task_rq_lock(p, &flags); ns = do_task_delta_exec(p, rq); task_rq_unlock(rq, p, &flags); return ns; } /* * Return accounted runtime for the task. * In case the task is currently running, return the runtime plus current's * pending runtime that have not been accounted yet. */ unsigned long long task_sched_runtime(struct task_struct *p) { unsigned long flags; struct rq *rq; u64 ns = 0; rq = task_rq_lock(p, &flags); ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq); task_rq_unlock(rq, p, &flags); return ns; } #ifdef CONFIG_CGROUP_CPUACCT struct cgroup_subsys cpuacct_subsys; struct cpuacct root_cpuacct; #endif static inline void task_group_account_field(struct task_struct *p, int index, u64 tmp) { #ifdef CONFIG_CGROUP_CPUACCT struct kernel_cpustat *kcpustat; struct cpuacct *ca; #endif /* * Since all updates are sure to touch the root cgroup, we * get ourselves ahead and touch it first. If the root cgroup * is the only cgroup, then nothing else should be necessary. * */ __get_cpu_var(kernel_cpustat).cpustat[index] += tmp; #ifdef CONFIG_CGROUP_CPUACCT if (unlikely(!cpuacct_subsys.active)) return; rcu_read_lock(); ca = task_ca(p); while (ca && (ca != &root_cpuacct)) { kcpustat = this_cpu_ptr(ca->cpustat); kcpustat->cpustat[index] += tmp; ca = parent_ca(ca); } rcu_read_unlock(); #endif } /* * Account user cpu time to a process. * @p: the process that the cpu time gets accounted to * @cputime: the cpu time spent in user space since the last update * @cputime_scaled: cputime scaled by cpu frequency */ void account_user_time(struct task_struct *p, cputime_t cputime, cputime_t cputime_scaled) { int index; /* Add user time to process. */ p->utime += cputime; p->utimescaled += cputime_scaled; account_group_user_time(p, cputime); index = (TASK_NICE(p) > 0) ? CPUTIME_NICE : CPUTIME_USER; /* Add user time to cpustat. */ task_group_account_field(p, index, (__force u64) cputime); /* Account for user time used */ acct_update_integrals(p); } /* * Account guest cpu time to a process. * @p: the process that the cpu time gets accounted to * @cputime: the cpu time spent in virtual machine since the last update * @cputime_scaled: cputime scaled by cpu frequency */ static void account_guest_time(struct task_struct *p, cputime_t cputime, cputime_t cputime_scaled) { u64 *cpustat = kcpustat_this_cpu->cpustat; /* Add guest time to process. */ p->utime += cputime; p->utimescaled += cputime_scaled; account_group_user_time(p, cputime); p->gtime += cputime; /* Add guest time to cpustat. */ if (TASK_NICE(p) > 0) { cpustat[CPUTIME_NICE] += (__force u64) cputime; cpustat[CPUTIME_GUEST_NICE] += (__force u64) cputime; } else { cpustat[CPUTIME_USER] += (__force u64) cputime; cpustat[CPUTIME_GUEST] += (__force u64) cputime; } } /* * Account system cpu time to a process and desired cpustat field * @p: the process that the cpu time gets accounted to * @cputime: the cpu time spent in kernel space since the last update * @cputime_scaled: cputime scaled by cpu frequency * @target_cputime64: pointer to cpustat field that has to be updated */ static inline void __account_system_time(struct task_struct *p, cputime_t cputime, cputime_t cputime_scaled, int index) { /* Add system time to process. */ p->stime += cputime; p->stimescaled += cputime_scaled; account_group_system_time(p, cputime); /* Add system time to cpustat. */ task_group_account_field(p, index, (__force u64) cputime); /* Account for system time used */ acct_update_integrals(p); } /* * Account system cpu time to a process. * @p: the process that the cpu time gets accounted to * @hardirq_offset: the offset to subtract from hardirq_count() * @cputime: the cpu time spent in kernel space since the last update * @cputime_scaled: cputime scaled by cpu frequency */ void account_system_time(struct task_struct *p, int hardirq_offset, cputime_t cputime, cputime_t cputime_scaled) { int index; if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) { account_guest_time(p, cputime, cputime_scaled); return; } if (hardirq_count() - hardirq_offset) index = CPUTIME_IRQ; else if (in_serving_softirq()) index = CPUTIME_SOFTIRQ; else index = CPUTIME_SYSTEM; __account_system_time(p, cputime, cputime_scaled, index); } /* * Account for involuntary wait time. * @cputime: the cpu time spent in involuntary wait */ void account_steal_time(cputime_t cputime) { u64 *cpustat = kcpustat_this_cpu->cpustat; cpustat[CPUTIME_STEAL] += (__force u64) cputime; } /* * Account for idle time. * @cputime: the cpu time spent in idle wait */ void account_idle_time(cputime_t cputime) { u64 *cpustat = kcpustat_this_cpu->cpustat; struct rq *rq = this_rq(); if (atomic_read(&rq->nr_iowait) > 0) cpustat[CPUTIME_IOWAIT] += (__force u64) cputime; else cpustat[CPUTIME_IDLE] += (__force u64) cputime; } static __always_inline bool steal_account_process_tick(void) { #ifdef CONFIG_PARAVIRT if (static_key_false(&paravirt_steal_enabled)) { u64 steal, st = 0; steal = paravirt_steal_clock(smp_processor_id()); steal -= this_rq()->prev_steal_time; st = steal_ticks(steal); this_rq()->prev_steal_time += st * TICK_NSEC; account_steal_time(st); return st; } #endif return false; } #ifndef CONFIG_VIRT_CPU_ACCOUNTING #ifdef CONFIG_IRQ_TIME_ACCOUNTING /* * Account a tick to a process and cpustat * @p: the process that the cpu time gets accounted to * @user_tick: is the tick from userspace * @rq: the pointer to rq * * Tick demultiplexing follows the order * - pending hardirq update * - pending softirq update * - user_time * - idle_time * - system time * - check for guest_time * - else account as system_time * * Check for hardirq is done both for system and user time as there is * no timer going off while we are on hardirq and hence we may never get an * opportunity to update it solely in system time. * p->stime and friends are only updated on system time and not on irq * softirq as those do not count in task exec_runtime any more. */ static void irqtime_account_process_tick(struct task_struct *p, int user_tick, struct rq *rq) { cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy); u64 *cpustat = kcpustat_this_cpu->cpustat; if (steal_account_process_tick()) return; if (irqtime_account_hi_update()) { cpustat[CPUTIME_IRQ] += (__force u64) cputime_one_jiffy; } else if (irqtime_account_si_update()) { cpustat[CPUTIME_SOFTIRQ] += (__force u64) cputime_one_jiffy; } else if (this_cpu_ksoftirqd() == p) { /* * ksoftirqd time do not get accounted in cpu_softirq_time. * So, we have to handle it separately here. * Also, p->stime needs to be updated for ksoftirqd. */ __account_system_time(p, cputime_one_jiffy, one_jiffy_scaled, CPUTIME_SOFTIRQ); } else if (user_tick) { account_user_time(p, cputime_one_jiffy, one_jiffy_scaled); } else if (p == rq->idle) { account_idle_time(cputime_one_jiffy); } else if (p->flags & PF_VCPU) { /* System time or guest time */ account_guest_time(p, cputime_one_jiffy, one_jiffy_scaled); } else { __account_system_time(p, cputime_one_jiffy, one_jiffy_scaled, CPUTIME_SYSTEM); } } static void irqtime_account_idle_ticks(int ticks) { int i; struct rq *rq = this_rq(); for (i = 0; i < ticks; i++) irqtime_account_process_tick(current, 0, rq); } #else /* CONFIG_IRQ_TIME_ACCOUNTING */ static void irqtime_account_idle_ticks(int ticks) {} static void irqtime_account_process_tick(struct task_struct *p, int user_tick, struct rq *rq) {} #endif /* CONFIG_IRQ_TIME_ACCOUNTING */ /* * Account a single tick of cpu time. * @p: the process that the cpu time gets accounted to * @user_tick: indicates if the tick is a user or a system tick */ void account_process_tick(struct task_struct *p, int user_tick) { cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy); struct rq *rq = this_rq(); if (sched_clock_irqtime) { irqtime_account_process_tick(p, user_tick, rq); return; } if (steal_account_process_tick()) return; if (user_tick) account_user_time(p, cputime_one_jiffy, one_jiffy_scaled); else if ((p != rq->idle) || (irq_count() != HARDIRQ_OFFSET)) account_system_time(p, HARDIRQ_OFFSET, cputime_one_jiffy, one_jiffy_scaled); else account_idle_time(cputime_one_jiffy); } /* * Account multiple ticks of steal time. * @p: the process from which the cpu time has been stolen * @ticks: number of stolen ticks */ void account_steal_ticks(unsigned long ticks) { account_steal_time(jiffies_to_cputime(ticks)); } /* * Account multiple ticks of idle time. * @ticks: number of stolen ticks */ void account_idle_ticks(unsigned long ticks) { if (sched_clock_irqtime) { irqtime_account_idle_ticks(ticks); return; } account_idle_time(jiffies_to_cputime(ticks)); } #endif /* * Use precise platform statistics if available: */ #ifdef CONFIG_VIRT_CPU_ACCOUNTING void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st) { *ut = p->utime; *st = p->stime; } void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st) { struct task_cputime cputime; thread_group_cputime(p, &cputime); *ut = cputime.utime; *st = cputime.stime; } #else #ifndef nsecs_to_cputime # define nsecs_to_cputime(__nsecs) nsecs_to_jiffies(__nsecs) #endif static cputime_t scale_utime(cputime_t utime, cputime_t rtime, cputime_t total) { u64 temp = (__force u64) rtime; temp *= (__force u64) utime; if (sizeof(cputime_t) == 4) temp = div_u64(temp, (__force u32) total); else temp = div64_u64(temp, (__force u64) total); return (__force cputime_t) temp; } void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st) { cputime_t rtime, utime = p->utime, total = utime + p->stime; /* * Use CFS's precise accounting: */ rtime = nsecs_to_cputime(p->se.sum_exec_runtime); if (total) utime = scale_utime(utime, rtime, total); else utime = rtime; /* * Compare with previous values, to keep monotonicity: */ p->prev_utime = max(p->prev_utime, utime); p->prev_stime = max(p->prev_stime, rtime - p->prev_utime); *ut = p->prev_utime; *st = p->prev_stime; } /* * Must be called with siglock held. */ void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st) { struct signal_struct *sig = p->signal; struct task_cputime cputime; cputime_t rtime, utime, total; thread_group_cputime(p, &cputime); total = cputime.utime + cputime.stime; rtime = nsecs_to_cputime(cputime.sum_exec_runtime); if (total) utime = scale_utime(cputime.utime, rtime, total); else utime = rtime; sig->prev_utime = max(sig->prev_utime, utime); sig->prev_stime = max(sig->prev_stime, rtime - sig->prev_utime); *ut = sig->prev_utime; *st = sig->prev_stime; } #endif /* * This function gets called by the timer code, with HZ frequency. * We call it with interrupts disabled. */ void scheduler_tick(void) { int cpu = smp_processor_id(); struct rq *rq = cpu_rq(cpu); struct task_struct *curr = rq->curr; sched_clock_tick(); raw_spin_lock(&rq->lock); update_rq_clock(rq); update_cpu_load_active(rq); curr->sched_class->task_tick(rq, curr, 0); raw_spin_unlock(&rq->lock); perf_event_task_tick(); #ifdef CONFIG_SMP rq->idle_balance = idle_cpu(cpu); trigger_load_balance(rq, cpu); #endif } notrace unsigned long get_parent_ip(unsigned long addr) { if (in_lock_functions(addr)) { addr = CALLER_ADDR2; if (in_lock_functions(addr)) addr = CALLER_ADDR3; } return addr; } #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \ defined(CONFIG_PREEMPT_TRACER)) void __kprobes add_preempt_count(int val) { #ifdef CONFIG_DEBUG_PREEMPT /* * Underflow? */ if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0))) return; #endif preempt_count() += val; #ifdef CONFIG_DEBUG_PREEMPT /* * Spinlock count overflowing soon? */ DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK - 10); #endif if (preempt_count() == val) trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1)); } EXPORT_SYMBOL(add_preempt_count); void __kprobes sub_preempt_count(int val) { #ifdef CONFIG_DEBUG_PREEMPT /* * Underflow? */ if (DEBUG_LOCKS_WARN_ON(val > preempt_count())) return; /* * Is the spinlock portion underflowing? */ if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK))) return; #endif if (preempt_count() == val) trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1)); preempt_count() -= val; } EXPORT_SYMBOL(sub_preempt_count); #endif /* * Print scheduling while atomic bug: */ static noinline void __schedule_bug(struct task_struct *prev) { if (oops_in_progress) return; printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n", prev->comm, prev->pid, preempt_count()); debug_show_held_locks(prev); print_modules(); if (irqs_disabled()) print_irqtrace_events(prev); dump_stack(); } /* * Various schedule()-time debugging checks and statistics: */ static inline void schedule_debug(struct task_struct *prev) { /* * Test if we are atomic. Since do_exit() needs to call into * schedule() atomically, we ignore that path for now. * Otherwise, whine if we are scheduling when we should not be. */ if (unlikely(in_atomic_preempt_off() && !prev->exit_state)) __schedule_bug(prev); rcu_sleep_check(); profile_hit(SCHED_PROFILING, __builtin_return_address(0)); schedstat_inc(this_rq(), sched_count); } static void put_prev_task(struct rq *rq, struct task_struct *prev) { if (prev->on_rq || rq->skip_clock_update < 0) update_rq_clock(rq); prev->sched_class->put_prev_task(rq, prev); } /* * Pick up the highest-prio task: */ static inline struct task_struct * pick_next_task(struct rq *rq) { const struct sched_class *class; struct task_struct *p; /* * Optimization: we know that if all tasks are in * the fair class we can call that function directly: */ if (likely(rq->nr_running == rq->cfs.h_nr_running)) { p = fair_sched_class.pick_next_task(rq); if (likely(p)) return p; } for_each_class(class) { p = class->pick_next_task(rq); if (p) return p; } BUG(); /* the idle class will always have a runnable task */ } /* * __schedule() is the main scheduler function. */ static void __sched __schedule(void) { struct task_struct *prev, *next; unsigned long *switch_count; struct rq *rq; int cpu; need_resched: preempt_disable(); cpu = smp_processor_id(); rq = cpu_rq(cpu); rcu_note_context_switch(cpu); prev = rq->curr; schedule_debug(prev); if (sched_feat(HRTICK)) hrtick_clear(rq); raw_spin_lock_irq(&rq->lock); switch_count = &prev->nivcsw; if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) { if (unlikely(signal_pending_state(prev->state, prev))) { prev->state = TASK_RUNNING; } else { deactivate_task(rq, prev, DEQUEUE_SLEEP); prev->on_rq = 0; /* * If a worker went to sleep, notify and ask workqueue * whether it wants to wake up a task to maintain * concurrency. */ if (prev->flags & PF_WQ_WORKER) { struct task_struct *to_wakeup; to_wakeup = wq_worker_sleeping(prev, cpu); if (to_wakeup) try_to_wake_up_local(to_wakeup); } } switch_count = &prev->nvcsw; } pre_schedule(rq, prev); if (unlikely(!rq->nr_running)) idle_balance(cpu, rq); put_prev_task(rq, prev); next = pick_next_task(rq); clear_tsk_need_resched(prev); rq->skip_clock_update = 0; if (likely(prev != next)) { rq->nr_switches++; rq->curr = next; ++*switch_count; context_switch(rq, prev, next); /* unlocks the rq */ /* * The context switch have flipped the stack from under us * and restored the local variables which were saved when * this task called schedule() in the past. prev == current * is still correct, but it can be moved to another cpu/rq. */ cpu = smp_processor_id(); rq = cpu_rq(cpu); } else raw_spin_unlock_irq(&rq->lock); post_schedule(rq); sched_preempt_enable_no_resched(); if (need_resched()) goto need_resched; } static inline void sched_submit_work(struct task_struct *tsk) { if (!tsk->state || tsk_is_pi_blocked(tsk)) return; /* * If we are going to sleep and we have plugged IO queued, * make sure to submit it to avoid deadlocks. */ if (blk_needs_flush_plug(tsk)) blk_schedule_flush_plug(tsk); } asmlinkage void __sched schedule(void) { struct task_struct *tsk = current; sched_submit_work(tsk); __schedule(); } EXPORT_SYMBOL(schedule); /** * schedule_preempt_disabled - called with preemption disabled * * Returns with preemption disabled. Note: preempt_count must be 1 */ void __sched schedule_preempt_disabled(void) { sched_preempt_enable_no_resched(); schedule(); preempt_disable(); } #ifdef CONFIG_MUTEX_SPIN_ON_OWNER static inline bool owner_running(struct mutex *lock, struct task_struct *owner) { if (lock->owner != owner) return false; /* * Ensure we emit the owner->on_cpu, dereference _after_ checking * lock->owner still matches owner, if that fails, owner might * point to free()d memory, if it still matches, the rcu_read_lock() * ensures the memory stays valid. */ barrier(); return owner->on_cpu; } /* * Look out! "owner" is an entirely speculative pointer * access and not reliable. */ int mutex_spin_on_owner(struct mutex *lock, struct task_struct *owner) { rcu_read_lock(); while (owner_running(lock, owner)) { if (need_resched()) break; arch_mutex_cpu_relax(); } rcu_read_unlock(); /* * We break out the loop above on need_resched() and when the * owner changed, which is a sign for heavy contention. Return * success only when lock->owner is NULL. */ return lock->owner == NULL; } /* * Initial check for entering the mutex spinning loop */ int mutex_can_spin_on_owner(struct mutex *lock) { int retval = 1; if (!sched_feat(OWNER_SPIN)) return 0; rcu_read_lock(); if (lock->owner) retval = lock->owner->on_cpu; rcu_read_unlock(); /* * if lock->owner is not set, the mutex owner may have just acquired * it and not set the owner yet or the mutex has been released. */ return retval; } #endif #ifdef CONFIG_PREEMPT /* * this is the entry point to schedule() from in-kernel preemption * off of preempt_enable. Kernel preemptions off return from interrupt * occur there and call schedule directly. */ asmlinkage void __sched notrace preempt_schedule(void) { struct thread_info *ti = current_thread_info(); /* * If there is a non-zero preempt_count or interrupts are disabled, * we do not want to preempt the current task. Just return.. */ if (likely(ti->preempt_count || irqs_disabled())) return; do { add_preempt_count_notrace(PREEMPT_ACTIVE); __schedule(); sub_preempt_count_notrace(PREEMPT_ACTIVE); /* * Check again in case we missed a preemption opportunity * between schedule and now. */ barrier(); } while (need_resched()); } EXPORT_SYMBOL(preempt_schedule); /* * this is the entry point to schedule() from kernel preemption * off of irq context. * Note, that this is called and return with irqs disabled. This will * protect us against recursive calling from irq. */ asmlinkage void __sched preempt_schedule_irq(void) { struct thread_info *ti = current_thread_info(); /* Catch callers which need to be fixed */ BUG_ON(ti->preempt_count || !irqs_disabled()); do { add_preempt_count(PREEMPT_ACTIVE); local_irq_enable(); __schedule(); local_irq_disable(); sub_preempt_count(PREEMPT_ACTIVE); /* * Check again in case we missed a preemption opportunity * between schedule and now. */ barrier(); } while (need_resched()); } #endif /* CONFIG_PREEMPT */ int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags, void *key) { return try_to_wake_up(curr->private, mode, wake_flags); } EXPORT_SYMBOL(default_wake_function); /* * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve * number) then we wake all the non-exclusive tasks and one exclusive task. * * There are circumstances in which we can try to wake a task which has already * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns * zero in this (rare) case, and we handle it by continuing to scan the queue. */ static void __wake_up_common(wait_queue_head_t *q, unsigned int mode, int nr_exclusive, int wake_flags, void *key) { wait_queue_t *curr, *next; list_for_each_entry_safe(curr, next, &q->task_list, task_list) { unsigned flags = curr->flags; if (curr->func(curr, mode, wake_flags, key) && (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive) break; } } /** * __wake_up - wake up threads blocked on a waitqueue. * @q: the waitqueue * @mode: which threads * @nr_exclusive: how many wake-one or wake-many threads to wake up * @key: is directly passed to the wakeup function * * It may be assumed that this function implies a write memory barrier before * changing the task state if and only if any tasks are woken up. */ void __wake_up(wait_queue_head_t *q, unsigned int mode, int nr_exclusive, void *key) { unsigned long flags; spin_lock_irqsave(&q->lock, flags); __wake_up_common(q, mode, nr_exclusive, 0, key); spin_unlock_irqrestore(&q->lock, flags); } EXPORT_SYMBOL(__wake_up); /* * Same as __wake_up but called with the spinlock in wait_queue_head_t held. */ void __wake_up_locked(wait_queue_head_t *q, unsigned int mode, int nr) { __wake_up_common(q, mode, nr, 0, NULL); } EXPORT_SYMBOL_GPL(__wake_up_locked); void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key) { __wake_up_common(q, mode, 1, 0, key); } EXPORT_SYMBOL_GPL(__wake_up_locked_key); /** * __wake_up_sync_key - wake up threads blocked on a waitqueue. * @q: the waitqueue * @mode: which threads * @nr_exclusive: how many wake-one or wake-many threads to wake up * @key: opaque value to be passed to wakeup targets * * The sync wakeup differs that the waker knows that it will schedule * away soon, so while the target thread will be woken up, it will not * be migrated to another CPU - ie. the two threads are 'synchronized' * with each other. This can prevent needless bouncing between CPUs. * * On UP it can prevent extra preemption. * * It may be assumed that this function implies a write memory barrier before * changing the task state if and only if any tasks are woken up. */ void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode, int nr_exclusive, void *key) { unsigned long flags; int wake_flags = WF_SYNC; if (unlikely(!q)) return; if (unlikely(!nr_exclusive)) wake_flags = 0; spin_lock_irqsave(&q->lock, flags); __wake_up_common(q, mode, nr_exclusive, wake_flags, key); spin_unlock_irqrestore(&q->lock, flags); } EXPORT_SYMBOL_GPL(__wake_up_sync_key); /* * __wake_up_sync - see __wake_up_sync_key() */ void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive) { __wake_up_sync_key(q, mode, nr_exclusive, NULL); } EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */ /** * complete: - signals a single thread waiting on this completion * @x: holds the state of this particular completion * * This will wake up a single thread waiting on this completion. Threads will be * awakened in the same order in which they were queued. * * See also complete_all(), wait_for_completion() and related routines. * * It may be assumed that this function implies a write memory barrier before * changing the task state if and only if any tasks are woken up. */ void complete(struct completion *x) { unsigned long flags; spin_lock_irqsave(&x->wait.lock, flags); x->done++; __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL); spin_unlock_irqrestore(&x->wait.lock, flags); } EXPORT_SYMBOL(complete); /** * complete_all: - signals all threads waiting on this completion * @x: holds the state of this particular completion * * This will wake up all threads waiting on this particular completion event. * * It may be assumed that this function implies a write memory barrier before * changing the task state if and only if any tasks are woken up. */ void complete_all(struct completion *x) { unsigned long flags; spin_lock_irqsave(&x->wait.lock, flags); x->done += UINT_MAX/2; __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL); spin_unlock_irqrestore(&x->wait.lock, flags); } EXPORT_SYMBOL(complete_all); static inline long __sched do_wait_for_common(struct completion *x, long timeout, int state, int iowait) { if (!x->done) { DECLARE_WAITQUEUE(wait, current); __add_wait_queue_tail_exclusive(&x->wait, &wait); do { if (signal_pending_state(state, current)) { timeout = -ERESTARTSYS; break; } __set_current_state(state); spin_unlock_irq(&x->wait.lock); if (iowait) timeout = io_schedule_timeout(timeout); else timeout = schedule_timeout(timeout); spin_lock_irq(&x->wait.lock); } while (!x->done && timeout); __remove_wait_queue(&x->wait, &wait); if (!x->done) return timeout; } x->done--; return timeout ?: 1; } static long __sched wait_for_common(struct completion *x, long timeout, int state, int iowait) { might_sleep(); spin_lock_irq(&x->wait.lock); timeout = do_wait_for_common(x, timeout, state, iowait); spin_unlock_irq(&x->wait.lock); return timeout; } /** * wait_for_completion: - waits for completion of a task * @x: holds the state of this particular completion * * This waits to be signaled for completion of a specific task. It is NOT * interruptible and there is no timeout. * * See also similar routines (i.e. wait_for_completion_timeout()) with timeout * and interrupt capability. Also see complete(). */ void __sched wait_for_completion(struct completion *x) { wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE, 0); } EXPORT_SYMBOL(wait_for_completion); /** * wait_for_completion_io: - waits for completion of a task * @x: holds the state of this particular completion * * This waits for completion of a specific task to be signaled. Treats any * sleeping as waiting for IO for the purposes of process accounting. */ void __sched wait_for_completion_io(struct completion *x) { wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE, 1); } EXPORT_SYMBOL(wait_for_completion_io); /** * wait_for_completion_timeout: - waits for completion of a task (w/timeout) * @x: holds the state of this particular completion * @timeout: timeout value in jiffies * * This waits for either a completion of a specific task to be signaled or for a * specified timeout to expire. The timeout is in jiffies. It is not * interruptible. * * The return value is 0 if timed out, and positive (at least 1, or number of * jiffies left till timeout) if completed. */ unsigned long __sched wait_for_completion_timeout(struct completion *x, unsigned long timeout) { return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE, 0); } EXPORT_SYMBOL(wait_for_completion_timeout); /** * wait_for_completion_interruptible: - waits for completion of a task (w/intr) * @x: holds the state of this particular completion * * This waits for completion of a specific task to be signaled. It is * interruptible. * * The return value is -ERESTARTSYS if interrupted, 0 if completed. */ int __sched wait_for_completion_interruptible(struct completion *x) { long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE, 0); if (t == -ERESTARTSYS) return t; return 0; } EXPORT_SYMBOL(wait_for_completion_interruptible); /** * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr)) * @x: holds the state of this particular completion * @timeout: timeout value in jiffies * * This waits for either a completion of a specific task to be signaled or for a * specified timeout to expire. It is interruptible. The timeout is in jiffies. * * The return value is -ERESTARTSYS if interrupted, 0 if timed out, * positive (at least 1, or number of jiffies left till timeout) if completed. */ long __sched wait_for_completion_interruptible_timeout(struct completion *x, unsigned long timeout) { return wait_for_common(x, timeout, TASK_INTERRUPTIBLE, 0); } EXPORT_SYMBOL(wait_for_completion_interruptible_timeout); /** * wait_for_completion_killable: - waits for completion of a task (killable) * @x: holds the state of this particular completion * * This waits to be signaled for completion of a specific task. It can be * interrupted by a kill signal. * * The return value is -ERESTARTSYS if interrupted, 0 if completed. */ int __sched wait_for_completion_killable(struct completion *x) { long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE, 0); if (t == -ERESTARTSYS) return t; return 0; } EXPORT_SYMBOL(wait_for_completion_killable); /** * wait_for_completion_killable_timeout: - waits for completion of a task (w/(to,killable)) * @x: holds the state of this particular completion * @timeout: timeout value in jiffies * * This waits for either a completion of a specific task to be * signaled or for a specified timeout to expire. It can be * interrupted by a kill signal. The timeout is in jiffies. * * The return value is -ERESTARTSYS if interrupted, 0 if timed out, * positive (at least 1, or number of jiffies left till timeout) if completed. */ long __sched wait_for_completion_killable_timeout(struct completion *x, unsigned long timeout) { return wait_for_common(x, timeout, TASK_KILLABLE, 0); } EXPORT_SYMBOL(wait_for_completion_killable_timeout); /** * try_wait_for_completion - try to decrement a completion without blocking * @x: completion structure * * Returns: 0 if a decrement cannot be done without blocking * 1 if a decrement succeeded. * * If a completion is being used as a counting completion, * attempt to decrement the counter without blocking. This * enables us to avoid waiting if the resource the completion * is protecting is not available. */ bool try_wait_for_completion(struct completion *x) { unsigned long flags; int ret = 1; spin_lock_irqsave(&x->wait.lock, flags); if (!x->done) ret = 0; else x->done--; spin_unlock_irqrestore(&x->wait.lock, flags); return ret; } EXPORT_SYMBOL(try_wait_for_completion); /** * completion_done - Test to see if a completion has any waiters * @x: completion structure * * Returns: 0 if there are waiters (wait_for_completion() in progress) * 1 if there are no waiters. * */ bool completion_done(struct completion *x) { unsigned long flags; int ret = 1; spin_lock_irqsave(&x->wait.lock, flags); if (!x->done) ret = 0; spin_unlock_irqrestore(&x->wait.lock, flags); return ret; } EXPORT_SYMBOL(completion_done); static long __sched sleep_on_common(wait_queue_head_t *q, int state, long timeout) { unsigned long flags; wait_queue_t wait; init_waitqueue_entry(&wait, current); __set_current_state(state); spin_lock_irqsave(&q->lock, flags); __add_wait_queue(q, &wait); spin_unlock(&q->lock); timeout = schedule_timeout(timeout); spin_lock_irq(&q->lock); __remove_wait_queue(q, &wait); spin_unlock_irqrestore(&q->lock, flags); return timeout; } void __sched interruptible_sleep_on(wait_queue_head_t *q) { sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT); } EXPORT_SYMBOL(interruptible_sleep_on); long __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout) { return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout); } EXPORT_SYMBOL(interruptible_sleep_on_timeout); void __sched sleep_on(wait_queue_head_t *q) { sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT); } EXPORT_SYMBOL(sleep_on); long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout) { return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout); } EXPORT_SYMBOL(sleep_on_timeout); #ifdef CONFIG_RT_MUTEXES /* * rt_mutex_setprio - set the current priority of a task * @p: task * @prio: prio value (kernel-internal form) * * This function changes the 'effective' priority of a task. It does * not touch ->normal_prio like __setscheduler(). * * Used by the rt_mutex code to implement priority inheritance logic. */ void rt_mutex_setprio(struct task_struct *p, int prio) { int oldprio, on_rq, running; struct rq *rq; const struct sched_class *prev_class; BUG_ON(prio < 0 || prio > MAX_PRIO); rq = __task_rq_lock(p); /* * Idle task boosting is a nono in general. There is one * exception, when PREEMPT_RT and NOHZ is active: * * The idle task calls get_next_timer_interrupt() and holds * the timer wheel base->lock on the CPU and another CPU wants * to access the timer (probably to cancel it). We can safely * ignore the boosting request, as the idle CPU runs this code * with interrupts disabled and will complete the lock * protected section without being interrupted. So there is no * real need to boost. */ if (unlikely(p == rq->idle)) { WARN_ON(p != rq->curr); WARN_ON(p->pi_blocked_on); goto out_unlock; } trace_sched_pi_setprio(p, prio); oldprio = p->prio; prev_class = p->sched_class; on_rq = p->on_rq; running = task_current(rq, p); if (on_rq) dequeue_task(rq, p, 0); if (running) p->sched_class->put_prev_task(rq, p); if (rt_prio(prio)) { p->sched_class = &rt_sched_class; } else { if (rt_prio(oldprio)) p->rt.timeout = 0; p->sched_class = &fair_sched_class; } p->prio = prio; if (running) p->sched_class->set_curr_task(rq); if (on_rq) enqueue_task(rq, p, oldprio < prio ? ENQUEUE_HEAD : 0); check_class_changed(rq, p, prev_class, oldprio); out_unlock: __task_rq_unlock(rq); } #endif void set_user_nice(struct task_struct *p, long nice) { int old_prio, delta, on_rq; unsigned long flags; struct rq *rq; if (TASK_NICE(p) == nice || nice < -20 || nice > 19) return; /* * We have to be careful, if called from sys_setpriority(), * the task might be in the middle of scheduling on another CPU. */ rq = task_rq_lock(p, &flags); /* * The RT priorities are set via sched_setscheduler(), but we still * allow the 'normal' nice value to be set - but as expected * it wont have any effect on scheduling until the task is * SCHED_FIFO/SCHED_RR: */ if (task_has_rt_policy(p)) { p->static_prio = NICE_TO_PRIO(nice); goto out_unlock; } on_rq = p->on_rq; if (on_rq) dequeue_task(rq, p, 0); p->static_prio = NICE_TO_PRIO(nice); set_load_weight(p); old_prio = p->prio; p->prio = effective_prio(p); delta = p->prio - old_prio; if (on_rq) { enqueue_task(rq, p, 0); /* * If the task increased its priority or is running and * lowered its priority, then reschedule its CPU: */ if (delta < 0 || (delta > 0 && task_running(rq, p))) resched_task(rq->curr); } out_unlock: task_rq_unlock(rq, p, &flags); } EXPORT_SYMBOL(set_user_nice); /* * can_nice - check if a task can reduce its nice value * @p: task * @nice: nice value */ int can_nice(const struct task_struct *p, const int nice) { /* convert nice value [19,-20] to rlimit style value [1,40] */ int nice_rlim = 20 - nice; return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) || capable(CAP_SYS_NICE)); } #ifdef __ARCH_WANT_SYS_NICE /* * sys_nice - change the priority of the current process. * @increment: priority increment * * sys_setpriority is a more generic, but much slower function that * does similar things. */ SYSCALL_DEFINE1(nice, int, increment) { long nice, retval; /* * Setpriority might change our priority at the same moment. * We don't have to worry. Conceptually one call occurs first * and we have a single winner. */ if (increment < -40) increment = -40; if (increment > 40) increment = 40; nice = TASK_NICE(current) + increment; if (nice < -20) nice = -20; if (nice > 19) nice = 19; if (increment < 0 && !can_nice(current, nice)) return -EPERM; retval = security_task_setnice(current, nice); if (retval) return retval; set_user_nice(current, nice); return 0; } #endif /** * task_prio - return the priority value of a given task. * @p: the task in question. * * This is the priority value as seen by users in /proc. * RT tasks are offset by -200. Normal tasks are centered * around 0, value goes from -16 to +15. */ int task_prio(const struct task_struct *p) { return p->prio - MAX_RT_PRIO; } /** * task_nice - return the nice value of a given task. * @p: the task in question. */ int task_nice(const struct task_struct *p) { return TASK_NICE(p); } EXPORT_SYMBOL(task_nice); /** * idle_cpu - is a given cpu idle currently? * @cpu: the processor in question. */ int idle_cpu(int cpu) { struct rq *rq = cpu_rq(cpu); if (rq->curr != rq->idle) return 0; if (rq->nr_running) return 0; #ifdef CONFIG_SMP if (!llist_empty(&rq->wake_list)) return 0; #endif return 1; } /** * idle_task - return the idle task for a given cpu. * @cpu: the processor in question. */ struct task_struct *idle_task(int cpu) { return cpu_rq(cpu)->idle; } /** * find_process_by_pid - find a process with a matching PID value. * @pid: the pid in question. */ static struct task_struct *find_process_by_pid(pid_t pid) { return pid ? find_task_by_vpid(pid) : current; } /* Actually do priority change: must hold rq lock. */ static void __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio) { p->policy = policy; p->rt_priority = prio; p->normal_prio = normal_prio(p); /* we are holding p->pi_lock already */ p->prio = rt_mutex_getprio(p); if (rt_prio(p->prio)) p->sched_class = &rt_sched_class; else p->sched_class = &fair_sched_class; set_load_weight(p); } /* * check the target process has a UID that matches the current process's */ static bool check_same_owner(struct task_struct *p) { const struct cred *cred = current_cred(), *pcred; bool match; rcu_read_lock(); pcred = __task_cred(p); if (cred->user->user_ns == pcred->user->user_ns) match = (cred->euid == pcred->euid || cred->euid == pcred->uid); else match = false; rcu_read_unlock(); return match; } static int __sched_setscheduler(struct task_struct *p, int policy, const struct sched_param *param, bool user) { int retval, oldprio, oldpolicy = -1, on_rq, running; unsigned long flags; const struct sched_class *prev_class; struct rq *rq; int reset_on_fork; /* may grab non-irq protected spin_locks */ BUG_ON(in_interrupt()); recheck: /* double check policy once rq lock held */ if (policy < 0) { reset_on_fork = p->sched_reset_on_fork; policy = oldpolicy = p->policy; } else { reset_on_fork = !!(policy & SCHED_RESET_ON_FORK); policy &= ~SCHED_RESET_ON_FORK; if (policy != SCHED_FIFO && policy != SCHED_RR && policy != SCHED_NORMAL && policy != SCHED_BATCH && policy != SCHED_IDLE) return -EINVAL; } /* * Valid priorities for SCHED_FIFO and SCHED_RR are * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL, * SCHED_BATCH and SCHED_IDLE is 0. */ if (param->sched_priority < 0 || (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) || (!p->mm && param->sched_priority > MAX_RT_PRIO-1)) return -EINVAL; if (rt_policy(policy) != (param->sched_priority != 0)) return -EINVAL; /* * Allow unprivileged RT tasks to decrease priority: */ if (user && !capable(CAP_SYS_NICE)) { if (rt_policy(policy)) { unsigned long rlim_rtprio = task_rlimit(p, RLIMIT_RTPRIO); /* can't set/change the rt policy */ if (policy != p->policy && !rlim_rtprio) return -EPERM; /* can't increase priority */ if (param->sched_priority > p->rt_priority && param->sched_priority > rlim_rtprio) return -EPERM; } /* * Treat SCHED_IDLE as nice 20. Only allow a switch to * SCHED_NORMAL if the RLIMIT_NICE would normally permit it. */ if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) { if (!can_nice(p, TASK_NICE(p))) return -EPERM; } /* can't change other user's priorities */ if (!check_same_owner(p)) return -EPERM; /* Normal users shall not reset the sched_reset_on_fork flag */ if (p->sched_reset_on_fork && !reset_on_fork) return -EPERM; } if (user) { retval = security_task_setscheduler(p); if (retval) return retval; } /* * make sure no PI-waiters arrive (or leave) while we are * changing the priority of the task: * * To be able to change p->policy safely, the appropriate * runqueue lock must be held. */ rq = task_rq_lock(p, &flags); /* * Changing the policy of the stop threads its a very bad idea */ if (p == rq->stop) { task_rq_unlock(rq, p, &flags); return -EINVAL; } /* * If not changing anything there's no need to proceed further: */ if (unlikely(policy == p->policy && (!rt_policy(policy) || param->sched_priority == p->rt_priority))) { __task_rq_unlock(rq); raw_spin_unlock_irqrestore(&p->pi_lock, flags); return 0; } #ifdef CONFIG_RT_GROUP_SCHED if (user) { /* * Do not allow realtime tasks into groups that have no runtime * assigned. */ if (rt_bandwidth_enabled() && rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0 && !task_group_is_autogroup(task_group(p))) { task_rq_unlock(rq, p, &flags); return -EPERM; } } #endif /* recheck policy now with rq lock held */ if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) { policy = oldpolicy = -1; task_rq_unlock(rq, p, &flags); goto recheck; } on_rq = p->on_rq; running = task_current(rq, p); if (on_rq) dequeue_task(rq, p, 0); if (running) p->sched_class->put_prev_task(rq, p); p->sched_reset_on_fork = reset_on_fork; oldprio = p->prio; prev_class = p->sched_class; __setscheduler(rq, p, policy, param->sched_priority); if (running) p->sched_class->set_curr_task(rq); if (on_rq) enqueue_task(rq, p, 0); check_class_changed(rq, p, prev_class, oldprio); task_rq_unlock(rq, p, &flags); rt_mutex_adjust_pi(p); return 0; } /** * sched_setscheduler - change the scheduling policy and/or RT priority of a thread. * @p: the task in question. * @policy: new policy. * @param: structure containing the new RT priority. * * NOTE that the task may be already dead. */ int sched_setscheduler(struct task_struct *p, int policy, const struct sched_param *param) { return __sched_setscheduler(p, policy, param, true); } EXPORT_SYMBOL_GPL(sched_setscheduler); /** * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace. * @p: the task in question. * @policy: new policy. * @param: structure containing the new RT priority. * * Just like sched_setscheduler, only don't bother checking if the * current context has permission. For example, this is needed in * stop_machine(): we create temporary high priority worker threads, * but our caller might not have that capability. */ int sched_setscheduler_nocheck(struct task_struct *p, int policy, const struct sched_param *param) { return __sched_setscheduler(p, policy, param, false); } static int do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param) { struct sched_param lparam; struct task_struct *p; int retval; if (!param || pid < 0) return -EINVAL; if (copy_from_user(&lparam, param, sizeof(struct sched_param))) return -EFAULT; rcu_read_lock(); retval = -ESRCH; p = find_process_by_pid(pid); if (p != NULL) retval = sched_setscheduler(p, policy, &lparam); rcu_read_unlock(); return retval; } /** * sys_sched_setscheduler - set/change the scheduler policy and RT priority * @pid: the pid in question. * @policy: new policy. * @param: structure containing the new RT priority. */ SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param) { /* negative values for policy are not valid */ if (policy < 0) return -EINVAL; return do_sched_setscheduler(pid, policy, param); } /** * sys_sched_setparam - set/change the RT priority of a thread * @pid: the pid in question. * @param: structure containing the new RT priority. */ SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param) { return do_sched_setscheduler(pid, -1, param); } /** * sys_sched_getscheduler - get the policy (scheduling class) of a thread * @pid: the pid in question. */ SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid) { struct task_struct *p; int retval; if (pid < 0) return -EINVAL; retval = -ESRCH; rcu_read_lock(); p = find_process_by_pid(pid); if (p) { retval = security_task_getscheduler(p); if (!retval) retval = p->policy | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0); } rcu_read_unlock(); return retval; } /** * sys_sched_getparam - get the RT priority of a thread * @pid: the pid in question. * @param: structure containing the RT priority. */ SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param) { struct sched_param lp; struct task_struct *p; int retval; if (!param || pid < 0) return -EINVAL; rcu_read_lock(); p = find_process_by_pid(pid); retval = -ESRCH; if (!p) goto out_unlock; retval = security_task_getscheduler(p); if (retval) goto out_unlock; lp.sched_priority = p->rt_priority; rcu_read_unlock(); /* * This one might sleep, we cannot do it with a spinlock held ... */ retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0; return retval; out_unlock: rcu_read_unlock(); return retval; } long sched_setaffinity(pid_t pid, const struct cpumask *in_mask) { cpumask_var_t cpus_allowed, new_mask; struct task_struct *p; int retval; get_online_cpus(); rcu_read_lock(); p = find_process_by_pid(pid); if (!p) { rcu_read_unlock(); put_online_cpus(); return -ESRCH; } /* Prevent p going away */ get_task_struct(p); rcu_read_unlock(); if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) { retval = -ENOMEM; goto out_put_task; } if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) { retval = -ENOMEM; goto out_free_cpus_allowed; } retval = -EPERM; if (!check_same_owner(p) && !ns_capable(task_user_ns(p), CAP_SYS_NICE)) goto out_unlock; retval = security_task_setscheduler(p); if (retval) goto out_unlock; cpuset_cpus_allowed(p, cpus_allowed); cpumask_and(new_mask, in_mask, cpus_allowed); again: retval = set_cpus_allowed_ptr(p, new_mask); if (!retval) { cpuset_cpus_allowed(p, cpus_allowed); if (!cpumask_subset(new_mask, cpus_allowed)) { /* * We must have raced with a concurrent cpuset * update. Just reset the cpus_allowed to the * cpuset's cpus_allowed */ cpumask_copy(new_mask, cpus_allowed); goto again; } } out_unlock: free_cpumask_var(new_mask); out_free_cpus_allowed: free_cpumask_var(cpus_allowed); out_put_task: put_task_struct(p); put_online_cpus(); return retval; } static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len, struct cpumask *new_mask) { if (len < cpumask_size()) cpumask_clear(new_mask); else if (len > cpumask_size()) len = cpumask_size(); return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0; } /** * sys_sched_setaffinity - set the cpu affinity of a process * @pid: pid of the process * @len: length in bytes of the bitmask pointed to by user_mask_ptr * @user_mask_ptr: user-space pointer to the new cpu mask */ SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len, unsigned long __user *, user_mask_ptr) { cpumask_var_t new_mask; int retval; if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) return -ENOMEM; retval = get_user_cpu_mask(user_mask_ptr, len, new_mask); if (retval == 0) retval = sched_setaffinity(pid, new_mask); free_cpumask_var(new_mask); return retval; } long sched_getaffinity(pid_t pid, struct cpumask *mask) { struct task_struct *p; unsigned long flags; int retval; get_online_cpus(); rcu_read_lock(); retval = -ESRCH; p = find_process_by_pid(pid); if (!p) goto out_unlock; retval = security_task_getscheduler(p); if (retval) goto out_unlock; raw_spin_lock_irqsave(&p->pi_lock, flags); cpumask_and(mask, &p->cpus_allowed, cpu_online_mask); raw_spin_unlock_irqrestore(&p->pi_lock, flags); out_unlock: rcu_read_unlock(); put_online_cpus(); return retval; } /** * sys_sched_getaffinity - get the cpu affinity of a process * @pid: pid of the process * @len: length in bytes of the bitmask pointed to by user_mask_ptr * @user_mask_ptr: user-space pointer to hold the current cpu mask */ SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len, unsigned long __user *, user_mask_ptr) { int ret; cpumask_var_t mask; if ((len * BITS_PER_BYTE) < nr_cpu_ids) return -EINVAL; if (len & (sizeof(unsigned long)-1)) return -EINVAL; if (!alloc_cpumask_var(&mask, GFP_KERNEL)) return -ENOMEM; ret = sched_getaffinity(pid, mask); if (ret == 0) { size_t retlen = min_t(size_t, len, cpumask_size()); if (copy_to_user(user_mask_ptr, mask, retlen)) ret = -EFAULT; else ret = retlen; } free_cpumask_var(mask); return ret; } /** * sys_sched_yield - yield the current processor to other threads. * * This function yields the current CPU to other tasks. If there are no * other threads running on this CPU then this function will return. */ SYSCALL_DEFINE0(sched_yield) { struct rq *rq = this_rq_lock(); schedstat_inc(rq, yld_count); current->sched_class->yield_task(rq); /* * Since we are going to call schedule() anyway, there's * no need to preempt or enable interrupts: */ __release(rq->lock); spin_release(&rq->lock.dep_map, 1, _THIS_IP_); do_raw_spin_unlock(&rq->lock); sched_preempt_enable_no_resched(); schedule(); return 0; } static inline int should_resched(void) { return need_resched() && !(preempt_count() & PREEMPT_ACTIVE); } static void __cond_resched(void) { add_preempt_count(PREEMPT_ACTIVE); __schedule(); sub_preempt_count(PREEMPT_ACTIVE); } int __sched _cond_resched(void) { if (should_resched()) { __cond_resched(); return 1; } return 0; } EXPORT_SYMBOL(_cond_resched); /* * __cond_resched_lock() - if a reschedule is pending, drop the given lock, * call schedule, and on return reacquire the lock. * * This works OK both with and without CONFIG_PREEMPT. We do strange low-level * operations here to prevent schedule() from being called twice (once via * spin_unlock(), once by hand). */ int __cond_resched_lock(spinlock_t *lock) { int resched = should_resched(); int ret = 0; lockdep_assert_held(lock); if (spin_needbreak(lock) || resched) { spin_unlock(lock); if (resched) __cond_resched(); else cpu_relax(); ret = 1; spin_lock(lock); } return ret; } EXPORT_SYMBOL(__cond_resched_lock); int __sched __cond_resched_softirq(void) { BUG_ON(!in_softirq()); if (should_resched()) { local_bh_enable(); __cond_resched(); local_bh_disable(); return 1; } return 0; } EXPORT_SYMBOL(__cond_resched_softirq); /** * yield - yield the current processor to other threads. * * Do not ever use this function, there's a 99% chance you're doing it wrong. * * The scheduler is at all times free to pick the calling task as the most * eligible task to run, if removing the yield() call from your code breaks * it, its already broken. * * Typical broken usage is: * * while (!event) * yield(); * * where one assumes that yield() will let 'the other' process run that will * make event true. If the current task is a SCHED_FIFO task that will never * happen. Never use yield() as a progress guarantee!! * * If you want to use yield() to wait for something, use wait_event(). * If you want to use yield() to be 'nice' for others, use cond_resched(). * If you still want to use yield(), do not! */ void __sched yield(void) { set_current_state(TASK_RUNNING); sys_sched_yield(); } EXPORT_SYMBOL(yield); /** * yield_to - yield the current processor to another thread in * your thread group, or accelerate that thread toward the * processor it's on. * @p: target task * @preempt: whether task preemption is allowed or not * * It's the caller's job to ensure that the target task struct * can't go away on us before we can do any checks. * * Returns true if we indeed boosted the target task. */ bool __sched yield_to(struct task_struct *p, bool preempt) { struct task_struct *curr = current; struct rq *rq, *p_rq; unsigned long flags; bool yielded = 0; local_irq_save(flags); rq = this_rq(); again: p_rq = task_rq(p); double_rq_lock(rq, p_rq); while (task_rq(p) != p_rq) { double_rq_unlock(rq, p_rq); goto again; } if (!curr->sched_class->yield_to_task) goto out; if (curr->sched_class != p->sched_class) goto out; if (task_running(p_rq, p) || p->state) goto out; yielded = curr->sched_class->yield_to_task(rq, p, preempt); if (yielded) { schedstat_inc(rq, yld_count); /* * Make p's CPU reschedule; pick_next_entity takes care of * fairness. */ if (preempt && rq != p_rq) resched_task(p_rq->curr); } else { /* * We might have set it in task_yield_fair(), but are * not going to schedule(), so don't want to skip * the next update. */ rq->skip_clock_update = 0; } out: double_rq_unlock(rq, p_rq); local_irq_restore(flags); if (yielded) schedule(); return yielded; } EXPORT_SYMBOL_GPL(yield_to); /* * This task is about to go to sleep on IO. Increment rq->nr_iowait so * that process accounting knows that this is a task in IO wait state. */ void __sched io_schedule(void) { struct rq *rq = raw_rq(); delayacct_blkio_start(); atomic_inc(&rq->nr_iowait); blk_flush_plug(current); current->in_iowait = 1; schedule(); current->in_iowait = 0; atomic_dec(&rq->nr_iowait); delayacct_blkio_end(); } EXPORT_SYMBOL(io_schedule); long __sched io_schedule_timeout(long timeout) { struct rq *rq = raw_rq(); long ret; delayacct_blkio_start(); atomic_inc(&rq->nr_iowait); blk_flush_plug(current); current->in_iowait = 1; ret = schedule_timeout(timeout); current->in_iowait = 0; atomic_dec(&rq->nr_iowait); delayacct_blkio_end(); return ret; } EXPORT_SYMBOL(io_schedule_timeout); /** * sys_sched_get_priority_max - return maximum RT priority. * @policy: scheduling class. * * this syscall returns the maximum rt_priority that can be used * by a given scheduling class. */ SYSCALL_DEFINE1(sched_get_priority_max, int, policy) { int ret = -EINVAL; switch (policy) { case SCHED_FIFO: case SCHED_RR: ret = MAX_USER_RT_PRIO-1; break; case SCHED_NORMAL: case SCHED_BATCH: case SCHED_IDLE: ret = 0; break; } return ret; } /** * sys_sched_get_priority_min - return minimum RT priority. * @policy: scheduling class. * * this syscall returns the minimum rt_priority that can be used * by a given scheduling class. */ SYSCALL_DEFINE1(sched_get_priority_min, int, policy) { int ret = -EINVAL; switch (policy) { case SCHED_FIFO: case SCHED_RR: ret = 1; break; case SCHED_NORMAL: case SCHED_BATCH: case SCHED_IDLE: ret = 0; } return ret; } /** * sys_sched_rr_get_interval - return the default timeslice of a process. * @pid: pid of the process. * @interval: userspace pointer to the timeslice value. * * this syscall writes the default timeslice value of a given process * into the user-space timespec buffer. A value of '0' means infinity. */ SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid, struct timespec __user *, interval) { struct task_struct *p; unsigned int time_slice; unsigned long flags; struct rq *rq; int retval; struct timespec t; if (pid < 0) return -EINVAL; retval = -ESRCH; rcu_read_lock(); p = find_process_by_pid(pid); if (!p) goto out_unlock; retval = security_task_getscheduler(p); if (retval) goto out_unlock; rq = task_rq_lock(p, &flags); time_slice = p->sched_class->get_rr_interval(rq, p); task_rq_unlock(rq, p, &flags); rcu_read_unlock(); jiffies_to_timespec(time_slice, &t); retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0; return retval; out_unlock: rcu_read_unlock(); return retval; } static const char stat_nam[] = TASK_STATE_TO_CHAR_STR; void sched_show_task(struct task_struct *p) { unsigned long free = 0; unsigned state; state = p->state ? __ffs(p->state) + 1 : 0; printk(KERN_INFO "%-15.15s %c", p->comm, state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?'); #if BITS_PER_LONG == 32 if (state == TASK_RUNNING) printk(KERN_CONT " running "); else printk(KERN_CONT " %08lx ", thread_saved_pc(p)); #else if (state == TASK_RUNNING) printk(KERN_CONT " running task "); else printk(KERN_CONT " %016lx ", thread_saved_pc(p)); #endif #ifdef CONFIG_DEBUG_STACK_USAGE free = stack_not_used(p); #endif printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free, task_pid_nr(p), task_pid_nr(rcu_dereference(p->real_parent)), (unsigned long)task_thread_info(p)->flags); show_stack(p, NULL); } void show_state_filter(unsigned long state_filter) { struct task_struct *g, *p; #if BITS_PER_LONG == 32 printk(KERN_INFO " task PC stack pid father\n"); #else printk(KERN_INFO " task PC stack pid father\n"); #endif rcu_read_lock(); do_each_thread(g, p) { /* * reset the NMI-timeout, listing all files on a slow * console might take a lot of time: */ touch_nmi_watchdog(); if (!state_filter || (p->state & state_filter)) sched_show_task(p); } while_each_thread(g, p); touch_all_softlockup_watchdogs(); #ifdef CONFIG_SCHED_DEBUG sysrq_sched_debug_show(); #endif rcu_read_unlock(); /* * Only show locks if all tasks are dumped: */ if (!state_filter) debug_show_all_locks(); } void __cpuinit init_idle_bootup_task(struct task_struct *idle) { idle->sched_class = &idle_sched_class; } /** * init_idle - set up an idle thread for a given CPU * @idle: task in question * @cpu: cpu the idle task belongs to * * NOTE: this function does not set the idle thread's NEED_RESCHED * flag, to make booting more robust. */ void __cpuinit init_idle(struct task_struct *idle, int cpu) { struct rq *rq = cpu_rq(cpu); unsigned long flags; raw_spin_lock_irqsave(&rq->lock, flags); __sched_fork(idle); idle->state = TASK_RUNNING; idle->se.exec_start = sched_clock(); do_set_cpus_allowed(idle, cpumask_of(cpu)); /* * We're having a chicken and egg problem, even though we are * holding rq->lock, the cpu isn't yet set to this cpu so the * lockdep check in task_group() will fail. * * Similar case to sched_fork(). / Alternatively we could * use task_rq_lock() here and obtain the other rq->lock. * * Silence PROVE_RCU */ rcu_read_lock(); __set_task_cpu(idle, cpu); rcu_read_unlock(); rq->curr = rq->idle = idle; #if defined(CONFIG_SMP) idle->on_cpu = 1; #endif raw_spin_unlock_irqrestore(&rq->lock, flags); /* Set the preempt count _outside_ the spinlocks! */ task_thread_info(idle)->preempt_count = 0; /* * The idle tasks have their own, simple scheduling class: */ idle->sched_class = &idle_sched_class; ftrace_graph_init_idle_task(idle, cpu); #if defined(CONFIG_SMP) sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu); #endif } #ifdef CONFIG_SMP void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask) { if (p->sched_class && p->sched_class->set_cpus_allowed) p->sched_class->set_cpus_allowed(p, new_mask); cpumask_copy(&p->cpus_allowed, new_mask); p->rt.nr_cpus_allowed = cpumask_weight(new_mask); } /* * This is how migration works: * * 1) we invoke migration_cpu_stop() on the target CPU using * stop_one_cpu(). * 2) stopper starts to run (implicitly forcing the migrated thread * off the CPU) * 3) it checks whether the migrated task is still in the wrong runqueue. * 4) if it's in the wrong runqueue then the migration thread removes * it and puts it into the right queue. * 5) stopper completes and stop_one_cpu() returns and the migration * is done. */ /* * Change a given task's CPU affinity. Migrate the thread to a * proper CPU and schedule it away if the CPU it's executing on * is removed from the allowed bitmask. * * NOTE: the caller must have a valid reference to the task, the * task must not exit() & deallocate itself prematurely. The * call is not atomic; no spinlocks may be held. */ int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask) { unsigned long flags; struct rq *rq; unsigned int dest_cpu; int ret = 0; rq = task_rq_lock(p, &flags); if (cpumask_equal(&p->cpus_allowed, new_mask)) goto out; if (!cpumask_intersects(new_mask, cpu_active_mask)) { ret = -EINVAL; goto out; } if (unlikely((p->flags & PF_THREAD_BOUND) && p != current)) { ret = -EINVAL; goto out; } do_set_cpus_allowed(p, new_mask); /* Can the task run on the task's current CPU? If so, we're done */ if (cpumask_test_cpu(task_cpu(p), new_mask)) goto out; dest_cpu = cpumask_any_and(cpu_active_mask, new_mask); if (p->on_rq) { struct migration_arg arg = { p, dest_cpu }; /* Need help from migration thread: drop lock and wait. */ task_rq_unlock(rq, p, &flags); stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg); tlb_migrate_finish(p->mm); return 0; } out: task_rq_unlock(rq, p, &flags); return ret; } EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr); /* * Move (not current) task off this cpu, onto dest cpu. We're doing * this because either it can't run here any more (set_cpus_allowed() * away from this CPU, or CPU going down), or because we're * attempting to rebalance this task on exec (sched_exec). * * So we race with normal scheduler movements, but that's OK, as long * as the task is no longer on this CPU. * * Returns non-zero if task was successfully migrated. */ static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu) { struct rq *rq_dest, *rq_src; bool moved = false; int ret = 0; if (unlikely(!cpu_active(dest_cpu))) return ret; rq_src = cpu_rq(src_cpu); rq_dest = cpu_rq(dest_cpu); raw_spin_lock(&p->pi_lock); double_rq_lock(rq_src, rq_dest); /* Already moved. */ if (task_cpu(p) != src_cpu) goto done; /* Affinity changed (again). */ if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p))) goto fail; /* * If we're not on a rq, the next wake-up will ensure we're * placed properly. */ if (p->on_rq) { dequeue_task(rq_src, p, 0); set_task_cpu(p, dest_cpu); enqueue_task(rq_dest, p, 0); check_preempt_curr(rq_dest, p, 0); moved = true; } done: ret = 1; fail: double_rq_unlock(rq_src, rq_dest); raw_spin_unlock(&p->pi_lock); if (moved && task_notify_on_migrate(p)) atomic_notifier_call_chain(&migration_notifier_head, dest_cpu, (void *)src_cpu); return ret; } /* * migration_cpu_stop - this will be executed by a highprio stopper thread * and performs thread migration by bumping thread off CPU then * 'pushing' onto another runqueue. */ static int migration_cpu_stop(void *data) { struct migration_arg *arg = data; /* * The original target cpu might have gone down and we might * be on another cpu but it doesn't matter. */ local_irq_disable(); __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu); local_irq_enable(); return 0; } #ifdef CONFIG_HOTPLUG_CPU /* * Ensures that the idle task is using init_mm right before its cpu goes * offline. */ void idle_task_exit(void) { struct mm_struct *mm = current->active_mm; BUG_ON(cpu_online(smp_processor_id())); if (mm != &init_mm) switch_mm(mm, &init_mm, current); mmdrop(mm); } /* * While a dead CPU has no uninterruptible tasks queued at this point, * it might still have a nonzero ->nr_uninterruptible counter, because * for performance reasons the counter is not stricly tracking tasks to * their home CPUs. So we just add the counter to another CPU's counter, * to keep the global sum constant after CPU-down: */ static void migrate_nr_uninterruptible(struct rq *rq_src) { struct rq *rq_dest = cpu_rq(cpumask_any(cpu_active_mask)); rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible; rq_src->nr_uninterruptible = 0; } /* * remove the tasks which were accounted by rq from calc_load_tasks. */ static void calc_global_load_remove(struct rq *rq) { atomic_long_sub(rq->calc_load_active, &calc_load_tasks); rq->calc_load_active = 0; } /* * Migrate all tasks from the rq, sleeping tasks will be migrated by * try_to_wake_up()->select_task_rq(). * * Called with rq->lock held even though we'er in stop_machine() and * there's no concurrency possible, we hold the required locks anyway * because of lock validation efforts. */ static void migrate_tasks(unsigned int dead_cpu) { struct rq *rq = cpu_rq(dead_cpu); struct task_struct *next, *stop = rq->stop; int dest_cpu; /* * Fudge the rq selection such that the below task selection loop * doesn't get stuck on the currently eligible stop task. * * We're currently inside stop_machine() and the rq is either stuck * in the stop_machine_cpu_stop() loop, or we're executing this code, * either way we should never end up calling schedule() until we're * done here. */ rq->stop = NULL; for ( ; ; ) { /* * There's this thread running, bail when that's the only * remaining thread. */ if (rq->nr_running == 1) break; next = pick_next_task(rq); BUG_ON(!next); next->sched_class->put_prev_task(rq, next); /* Find suitable destination for @next, with force if needed. */ dest_cpu = select_fallback_rq(dead_cpu, next); raw_spin_unlock(&rq->lock); __migrate_task(next, dead_cpu, dest_cpu); raw_spin_lock(&rq->lock); } rq->stop = stop; } #endif /* CONFIG_HOTPLUG_CPU */ #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL) static struct ctl_table sd_ctl_dir[] = { { .procname = "sched_domain", .mode = 0555, }, {} }; static struct ctl_table sd_ctl_root[] = { { .procname = "kernel", .mode = 0555, .child = sd_ctl_dir, }, {} }; static struct ctl_table *sd_alloc_ctl_entry(int n) { struct ctl_table *entry = kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL); return entry; } static void sd_free_ctl_entry(struct ctl_table **tablep) { struct ctl_table *entry; /* * In the intermediate directories, both the child directory and * procname are dynamically allocated and could fail but the mode * will always be set. In the lowest directory the names are * static strings and all have proc handlers. */ for (entry = *tablep; entry->mode; entry++) { if (entry->child) sd_free_ctl_entry(&entry->child); if (entry->proc_handler == NULL) kfree(entry->procname); } kfree(*tablep); *tablep = NULL; } static int min_load_idx = 0; static int max_load_idx = CPU_LOAD_IDX_MAX-1; static void set_table_entry(struct ctl_table *entry, const char *procname, void *data, int maxlen, umode_t mode, proc_handler *proc_handler, bool load_idx) { entry->procname = procname; entry->data = data; entry->maxlen = maxlen; entry->mode = mode; entry->proc_handler = proc_handler; if (load_idx) { entry->extra1 = &min_load_idx; entry->extra2 = &max_load_idx; } } static struct ctl_table * sd_alloc_ctl_domain_table(struct sched_domain *sd) { struct ctl_table *table = sd_alloc_ctl_entry(13); if (table == NULL) return NULL; set_table_entry(&table[0], "min_interval", &sd->min_interval, sizeof(long), 0644, proc_doulongvec_minmax, false); set_table_entry(&table[1], "max_interval", &sd->max_interval, sizeof(long), 0644, proc_doulongvec_minmax, false); set_table_entry(&table[2], "busy_idx", &sd->busy_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[3], "idle_idx", &sd->idle_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[5], "wake_idx", &sd->wake_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[7], "busy_factor", &sd->busy_factor, sizeof(int), 0644, proc_dointvec_minmax, false); set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct, sizeof(int), 0644, proc_dointvec_minmax, false); set_table_entry(&table[9], "cache_nice_tries", &sd->cache_nice_tries, sizeof(int), 0644, proc_dointvec_minmax, false); set_table_entry(&table[10], "flags", &sd->flags, sizeof(int), 0644, proc_dointvec_minmax, false); set_table_entry(&table[11], "name", sd->name, CORENAME_MAX_SIZE, 0444, proc_dostring, false); /* &table[12] is terminator */ return table; } static ctl_table *sd_alloc_ctl_cpu_table(int cpu) { struct ctl_table *entry, *table; struct sched_domain *sd; int domain_num = 0, i; char buf[32]; for_each_domain(cpu, sd) domain_num++; entry = table = sd_alloc_ctl_entry(domain_num + 1); if (table == NULL) return NULL; i = 0; for_each_domain(cpu, sd) { snprintf(buf, 32, "domain%d", i); entry->procname = kstrdup(buf, GFP_KERNEL); entry->mode = 0555; entry->child = sd_alloc_ctl_domain_table(sd); entry++; i++; } return table; } static struct ctl_table_header *sd_sysctl_header; static void register_sched_domain_sysctl(void) { int i, cpu_num = num_possible_cpus(); struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1); char buf[32]; WARN_ON(sd_ctl_dir[0].child); sd_ctl_dir[0].child = entry; if (entry == NULL) return; for_each_possible_cpu(i) { snprintf(buf, 32, "cpu%d", i); entry->procname = kstrdup(buf, GFP_KERNEL); entry->mode = 0555; entry->child = sd_alloc_ctl_cpu_table(i); entry++; } WARN_ON(sd_sysctl_header); sd_sysctl_header = register_sysctl_table(sd_ctl_root); } /* may be called multiple times per register */ static void unregister_sched_domain_sysctl(void) { if (sd_sysctl_header) unregister_sysctl_table(sd_sysctl_header); sd_sysctl_header = NULL; if (sd_ctl_dir[0].child) sd_free_ctl_entry(&sd_ctl_dir[0].child); } #else static void register_sched_domain_sysctl(void) { } static void unregister_sched_domain_sysctl(void) { } #endif static void set_rq_online(struct rq *rq) { if (!rq->online) { const struct sched_class *class; cpumask_set_cpu(rq->cpu, rq->rd->online); rq->online = 1; for_each_class(class) { if (class->rq_online) class->rq_online(rq); } } } static void set_rq_offline(struct rq *rq) { if (rq->online) { const struct sched_class *class; for_each_class(class) { if (class->rq_offline) class->rq_offline(rq); } cpumask_clear_cpu(rq->cpu, rq->rd->online); rq->online = 0; } } /* * migration_call - callback that gets triggered when a CPU is added. * Here we can start up the necessary migration thread for the new CPU. */ static int __cpuinit migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu) { int cpu = (long)hcpu; unsigned long flags; struct rq *rq = cpu_rq(cpu); switch (action & ~CPU_TASKS_FROZEN) { case CPU_UP_PREPARE: rq->calc_load_update = calc_load_update; break; case CPU_ONLINE: /* Update our root-domain */ raw_spin_lock_irqsave(&rq->lock, flags); if (rq->rd) { BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span)); set_rq_online(rq); } raw_spin_unlock_irqrestore(&rq->lock, flags); break; #ifdef CONFIG_HOTPLUG_CPU case CPU_DYING: sched_ttwu_pending(); /* Update our root-domain */ raw_spin_lock_irqsave(&rq->lock, flags); if (rq->rd) { BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span)); set_rq_offline(rq); } migrate_tasks(cpu); BUG_ON(rq->nr_running != 1); /* the migration thread */ raw_spin_unlock_irqrestore(&rq->lock, flags); migrate_nr_uninterruptible(rq); calc_global_load_remove(rq); break; #endif } update_max_interval(); return NOTIFY_OK; } /* * Register at high priority so that task migration (migrate_all_tasks) * happens before everything else. This has to be lower priority than * the notifier in the perf_event subsystem, though. */ static struct notifier_block __cpuinitdata migration_notifier = { .notifier_call = migration_call, .priority = CPU_PRI_MIGRATION, }; static int __cpuinit sched_cpu_active(struct notifier_block *nfb, unsigned long action, void *hcpu) { switch (action & ~CPU_TASKS_FROZEN) { case CPU_DOWN_FAILED: set_cpu_active((long)hcpu, true); return NOTIFY_OK; default: return NOTIFY_DONE; } } static int __cpuinit sched_cpu_inactive(struct notifier_block *nfb, unsigned long action, void *hcpu) { switch (action & ~CPU_TASKS_FROZEN) { case CPU_DOWN_PREPARE: set_cpu_active((long)hcpu, false); return NOTIFY_OK; default: return NOTIFY_DONE; } } static int __init migration_init(void) { void *cpu = (void *)(long)smp_processor_id(); int err; /* Initialize migration for the boot CPU */ err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu); BUG_ON(err == NOTIFY_BAD); migration_call(&migration_notifier, CPU_ONLINE, cpu); register_cpu_notifier(&migration_notifier); /* Register cpu active notifiers */ cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE); cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE); return 0; } early_initcall(migration_init); #endif #ifdef CONFIG_SMP static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */ #ifdef CONFIG_SCHED_DEBUG static __read_mostly int sched_domain_debug_enabled; static int __init sched_domain_debug_setup(char *str) { sched_domain_debug_enabled = 1; return 0; } early_param("sched_debug", sched_domain_debug_setup); static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level, struct cpumask *groupmask) { struct sched_group *group = sd->groups; char str[256]; cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd)); cpumask_clear(groupmask); printk(KERN_DEBUG "%*s domain %d: ", level, "", level); if (!(sd->flags & SD_LOAD_BALANCE)) { printk("does not load-balance\n"); if (sd->parent) printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain" " has parent"); return -1; } printk(KERN_CONT "span %s level %s\n", str, sd->name); if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) { printk(KERN_ERR "ERROR: domain->span does not contain " "CPU%d\n", cpu); } if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) { printk(KERN_ERR "ERROR: domain->groups does not contain" " CPU%d\n", cpu); } printk(KERN_DEBUG "%*s groups:", level + 1, ""); do { if (!group) { printk("\n"); printk(KERN_ERR "ERROR: group is NULL\n"); break; } if (!group->sgp->power) { printk(KERN_CONT "\n"); printk(KERN_ERR "ERROR: domain->cpu_power not " "set\n"); break; } if (!cpumask_weight(sched_group_cpus(group))) { printk(KERN_CONT "\n"); printk(KERN_ERR "ERROR: empty group\n"); break; } if (cpumask_intersects(groupmask, sched_group_cpus(group))) { printk(KERN_CONT "\n"); printk(KERN_ERR "ERROR: repeated CPUs\n"); break; } cpumask_or(groupmask, groupmask, sched_group_cpus(group)); cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group)); printk(KERN_CONT " %s", str); if (group->sgp->power != SCHED_POWER_SCALE) { printk(KERN_CONT " (cpu_power = %d)", group->sgp->power); } group = group->next; } while (group != sd->groups); printk(KERN_CONT "\n"); if (!cpumask_equal(sched_domain_span(sd), groupmask)) printk(KERN_ERR "ERROR: groups don't span domain->span\n"); if (sd->parent && !cpumask_subset(groupmask, sched_domain_span(sd->parent))) printk(KERN_ERR "ERROR: parent span is not a superset " "of domain->span\n"); return 0; } static void sched_domain_debug(struct sched_domain *sd, int cpu) { int level = 0; if (!sched_domain_debug_enabled) return; if (!sd) { printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu); return; } printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu); for (;;) { if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask)) break; level++; sd = sd->parent; if (!sd) break; } } #else /* !CONFIG_SCHED_DEBUG */ # define sched_domain_debug(sd, cpu) do { } while (0) #endif /* CONFIG_SCHED_DEBUG */ static int sd_degenerate(struct sched_domain *sd) { if (cpumask_weight(sched_domain_span(sd)) == 1) return 1; /* Following flags need at least 2 groups */ if (sd->flags & (SD_LOAD_BALANCE | SD_BALANCE_NEWIDLE | SD_BALANCE_FORK | SD_BALANCE_EXEC | SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)) { if (sd->groups != sd->groups->next) return 0; } /* Following flags don't use groups */ if (sd->flags & (SD_WAKE_AFFINE)) return 0; return 1; } static int sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent) { unsigned long cflags = sd->flags, pflags = parent->flags; if (sd_degenerate(parent)) return 1; if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent))) return 0; /* Flags needing groups don't count if only 1 group in parent */ if (parent->groups == parent->groups->next) { pflags &= ~(SD_LOAD_BALANCE | SD_BALANCE_NEWIDLE | SD_BALANCE_FORK | SD_BALANCE_EXEC | SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES); if (nr_node_ids == 1) pflags &= ~SD_SERIALIZE; } if (~cflags & pflags) return 0; return 1; } static void free_rootdomain(struct rcu_head *rcu) { struct root_domain *rd = container_of(rcu, struct root_domain, rcu); cpupri_cleanup(&rd->cpupri); free_cpumask_var(rd->rto_mask); free_cpumask_var(rd->online); free_cpumask_var(rd->span); kfree(rd); } static void rq_attach_root(struct rq *rq, struct root_domain *rd) { struct root_domain *old_rd = NULL; unsigned long flags; raw_spin_lock_irqsave(&rq->lock, flags); if (rq->rd) { old_rd = rq->rd; if (cpumask_test_cpu(rq->cpu, old_rd->online)) set_rq_offline(rq); cpumask_clear_cpu(rq->cpu, old_rd->span); /* * If we dont want to free the old_rt yet then * set old_rd to NULL to skip the freeing later * in this function: */ if (!atomic_dec_and_test(&old_rd->refcount)) old_rd = NULL; } atomic_inc(&rd->refcount); rq->rd = rd; cpumask_set_cpu(rq->cpu, rd->span); if (cpumask_test_cpu(rq->cpu, cpu_active_mask)) set_rq_online(rq); raw_spin_unlock_irqrestore(&rq->lock, flags); if (old_rd) call_rcu_sched(&old_rd->rcu, free_rootdomain); } static int init_rootdomain(struct root_domain *rd) { memset(rd, 0, sizeof(*rd)); if (!alloc_cpumask_var(&rd->span, GFP_KERNEL)) goto out; if (!alloc_cpumask_var(&rd->online, GFP_KERNEL)) goto free_span; if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL)) goto free_online; if (cpupri_init(&rd->cpupri) != 0) goto free_rto_mask; return 0; free_rto_mask: free_cpumask_var(rd->rto_mask); free_online: free_cpumask_var(rd->online); free_span: free_cpumask_var(rd->span); out: return -ENOMEM; } /* * By default the system creates a single root-domain with all cpus as * members (mimicking the global state we have today). */ struct root_domain def_root_domain; static void init_defrootdomain(void) { init_rootdomain(&def_root_domain); atomic_set(&def_root_domain.refcount, 1); } static struct root_domain *alloc_rootdomain(void) { struct root_domain *rd; rd = kmalloc(sizeof(*rd), GFP_KERNEL); if (!rd) return NULL; if (init_rootdomain(rd) != 0) { kfree(rd); return NULL; } return rd; } static void free_sched_groups(struct sched_group *sg, int free_sgp) { struct sched_group *tmp, *first; if (!sg) return; first = sg; do { tmp = sg->next; if (free_sgp && atomic_dec_and_test(&sg->sgp->ref)) kfree(sg->sgp); kfree(sg); sg = tmp; } while (sg != first); } static void free_sched_domain(struct rcu_head *rcu) { struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu); /* * If its an overlapping domain it has private groups, iterate and * nuke them all. */ if (sd->flags & SD_OVERLAP) { free_sched_groups(sd->groups, 1); } else if (atomic_dec_and_test(&sd->groups->ref)) { kfree(sd->groups->sgp); kfree(sd->groups); } kfree(sd); } static void destroy_sched_domain(struct sched_domain *sd, int cpu) { call_rcu(&sd->rcu, free_sched_domain); } static void destroy_sched_domains(struct sched_domain *sd, int cpu) { for (; sd; sd = sd->parent) destroy_sched_domain(sd, cpu); } /* * Keep a special pointer to the highest sched_domain that has * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this * allows us to avoid some pointer chasing select_idle_sibling(). * * Also keep a unique ID per domain (we use the first cpu number in * the cpumask of the domain), this allows us to quickly tell if * two cpus are in the same cache domain, see cpus_share_cache(). */ DEFINE_PER_CPU(struct sched_domain *, sd_llc); DEFINE_PER_CPU(int, sd_llc_id); static void update_top_cache_domain(int cpu) { struct sched_domain *sd; int id = cpu; sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES); if (sd) id = cpumask_first(sched_domain_span(sd)); rcu_assign_pointer(per_cpu(sd_llc, cpu), sd); per_cpu(sd_llc_id, cpu) = id; } /* * Attach the domain 'sd' to 'cpu' as its base domain. Callers must * hold the hotplug lock. */ static void cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu) { struct rq *rq = cpu_rq(cpu); struct sched_domain *tmp; unsigned long next_balance = rq->next_balance; /* Remove the sched domains which do not contribute to scheduling. */ for (tmp = sd; tmp; ) { struct sched_domain *parent = tmp->parent; if (!parent) break; if (sd_parent_degenerate(tmp, parent)) { tmp->parent = parent->parent; if (parent->parent) parent->parent->child = tmp; destroy_sched_domain(parent, cpu); } else tmp = tmp->parent; } if (sd && sd_degenerate(sd)) { tmp = sd; sd = sd->parent; destroy_sched_domain(tmp, cpu); if (sd) sd->child = NULL; } for (tmp = sd; tmp; ) { unsigned long interval; interval = msecs_to_jiffies(tmp->balance_interval); if (time_after(next_balance, tmp->last_balance + interval)) next_balance = tmp->last_balance + interval; tmp = tmp->parent; } rq->next_balance = next_balance; sched_domain_debug(sd, cpu); rq_attach_root(rq, rd); tmp = rq->sd; rcu_assign_pointer(rq->sd, sd); destroy_sched_domains(tmp, cpu); update_top_cache_domain(cpu); } /* cpus with isolated domains */ static cpumask_var_t cpu_isolated_map; /* Setup the mask of cpus configured for isolated domains */ static int __init isolated_cpu_setup(char *str) { alloc_bootmem_cpumask_var(&cpu_isolated_map); cpulist_parse(str, cpu_isolated_map); return 1; } __setup("isolcpus=", isolated_cpu_setup); #ifdef CONFIG_NUMA /** * find_next_best_node - find the next node to include in a sched_domain * @node: node whose sched_domain we're building * @used_nodes: nodes already in the sched_domain * * Find the next node to include in a given scheduling domain. Simply * finds the closest node not already in the @used_nodes map. * * Should use nodemask_t. */ static int find_next_best_node(int node, nodemask_t *used_nodes) { int i, n, val, min_val, best_node = -1; min_val = INT_MAX; for (i = 0; i < nr_node_ids; i++) { /* Start at @node */ n = (node + i) % nr_node_ids; if (!nr_cpus_node(n)) continue; /* Skip already used nodes */ if (node_isset(n, *used_nodes)) continue; /* Simple min distance search */ val = node_distance(node, n); if (val < min_val) { min_val = val; best_node = n; } } if (best_node != -1) node_set(best_node, *used_nodes); return best_node; } /** * sched_domain_node_span - get a cpumask for a node's sched_domain * @node: node whose cpumask we're constructing * @span: resulting cpumask * * Given a node, construct a good cpumask for its sched_domain to span. It * should be one that prevents unnecessary balancing, but also spreads tasks * out optimally. */ static void sched_domain_node_span(int node, struct cpumask *span) { nodemask_t used_nodes; int i; cpumask_clear(span); nodes_clear(used_nodes); cpumask_or(span, span, cpumask_of_node(node)); node_set(node, used_nodes); for (i = 1; i < SD_NODES_PER_DOMAIN; i++) { int next_node = find_next_best_node(node, &used_nodes); if (next_node < 0) break; cpumask_or(span, span, cpumask_of_node(next_node)); } } static const struct cpumask *cpu_node_mask(int cpu) { lockdep_assert_held(&sched_domains_mutex); sched_domain_node_span(cpu_to_node(cpu), sched_domains_tmpmask); return sched_domains_tmpmask; } static const struct cpumask *cpu_allnodes_mask(int cpu) { return cpu_possible_mask; } #endif /* CONFIG_NUMA */ static const struct cpumask *cpu_cpu_mask(int cpu) { return cpumask_of_node(cpu_to_node(cpu)); } int sched_smt_power_savings = 0, sched_mc_power_savings = 0; struct sd_data { struct sched_domain **__percpu sd; struct sched_group **__percpu sg; struct sched_group_power **__percpu sgp; }; struct s_data { struct sched_domain ** __percpu sd; struct root_domain *rd; }; enum s_alloc { sa_rootdomain, sa_sd, sa_sd_storage, sa_none, }; struct sched_domain_topology_level; typedef struct sched_domain *(*sched_domain_init_f)(struct sched_domain_topology_level *tl, int cpu); typedef const struct cpumask *(*sched_domain_mask_f)(int cpu); #define SDTL_OVERLAP 0x01 struct sched_domain_topology_level { sched_domain_init_f init; sched_domain_mask_f mask; int flags; struct sd_data data; }; static int build_overlap_sched_groups(struct sched_domain *sd, int cpu) { struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg; const struct cpumask *span = sched_domain_span(sd); struct cpumask *covered = sched_domains_tmpmask; struct sd_data *sdd = sd->private; struct sched_domain *child; int i; cpumask_clear(covered); for_each_cpu(i, span) { struct cpumask *sg_span; if (cpumask_test_cpu(i, covered)) continue; sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(), GFP_KERNEL, cpu_to_node(cpu)); if (!sg) goto fail; sg_span = sched_group_cpus(sg); child = *per_cpu_ptr(sdd->sd, i); if (child->child) { child = child->child; cpumask_copy(sg_span, sched_domain_span(child)); } else cpumask_set_cpu(i, sg_span); cpumask_or(covered, covered, sg_span); sg->sgp = *per_cpu_ptr(sdd->sgp, cpumask_first(sg_span)); atomic_inc(&sg->sgp->ref); if (cpumask_test_cpu(cpu, sg_span)) groups = sg; if (!first) first = sg; if (last) last->next = sg; last = sg; last->next = first; } sd->groups = groups; return 0; fail: free_sched_groups(first, 0); return -ENOMEM; } static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg) { struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu); struct sched_domain *child = sd->child; if (child) cpu = cpumask_first(sched_domain_span(child)); if (sg) { *sg = *per_cpu_ptr(sdd->sg, cpu); (*sg)->sgp = *per_cpu_ptr(sdd->sgp, cpu); atomic_set(&(*sg)->sgp->ref, 1); /* for claim_allocations */ } return cpu; } /* * build_sched_groups will build a circular linked list of the groups * covered by the given span, and will set each group's ->cpumask correctly, * and ->cpu_power to 0. * * Assumes the sched_domain tree is fully constructed */ static int build_sched_groups(struct sched_domain *sd, int cpu) { struct sched_group *first = NULL, *last = NULL; struct sd_data *sdd = sd->private; const struct cpumask *span = sched_domain_span(sd); struct cpumask *covered; int i; get_group(cpu, sdd, &sd->groups); atomic_inc(&sd->groups->ref); if (cpu != cpumask_first(sched_domain_span(sd))) return 0; lockdep_assert_held(&sched_domains_mutex); covered = sched_domains_tmpmask; cpumask_clear(covered); for_each_cpu(i, span) { struct sched_group *sg; int group = get_group(i, sdd, &sg); int j; if (cpumask_test_cpu(i, covered)) continue; cpumask_clear(sched_group_cpus(sg)); sg->sgp->power = 0; for_each_cpu(j, span) { if (get_group(j, sdd, NULL) != group) continue; cpumask_set_cpu(j, covered); cpumask_set_cpu(j, sched_group_cpus(sg)); } if (!first) first = sg; if (last) last->next = sg; last = sg; } last->next = first; return 0; } /* * Initialize sched groups cpu_power. * * cpu_power indicates the capacity of sched group, which is used while * distributing the load between different sched groups in a sched domain. * Typically cpu_power for all the groups in a sched domain will be same unless * there are asymmetries in the topology. If there are asymmetries, group * having more cpu_power will pickup more load compared to the group having * less cpu_power. */ static void init_sched_groups_power(int cpu, struct sched_domain *sd) { struct sched_group *sg = sd->groups; WARN_ON(!sd || !sg); do { sg->group_weight = cpumask_weight(sched_group_cpus(sg)); sg = sg->next; } while (sg != sd->groups); if (cpu != group_first_cpu(sg)) return; update_group_power(sd, cpu); atomic_set(&sg->sgp->nr_busy_cpus, sg->group_weight); } int __weak arch_sd_sibling_asym_packing(void) { return 0*SD_ASYM_PACKING; } /* * Initializers for schedule domains * Non-inlined to reduce accumulated stack pressure in build_sched_domains() */ #ifdef CONFIG_SCHED_DEBUG # define SD_INIT_NAME(sd, type) sd->name = #type #else # define SD_INIT_NAME(sd, type) do { } while (0) #endif #define SD_INIT_FUNC(type) \ static noinline struct sched_domain * \ sd_init_##type(struct sched_domain_topology_level *tl, int cpu) \ { \ struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu); \ *sd = SD_##type##_INIT; \ SD_INIT_NAME(sd, type); \ sd->private = &tl->data; \ return sd; \ } SD_INIT_FUNC(CPU) #ifdef CONFIG_NUMA SD_INIT_FUNC(ALLNODES) SD_INIT_FUNC(NODE) #endif #ifdef CONFIG_SCHED_SMT SD_INIT_FUNC(SIBLING) #endif #ifdef CONFIG_SCHED_MC SD_INIT_FUNC(MC) #endif #ifdef CONFIG_SCHED_BOOK SD_INIT_FUNC(BOOK) #endif static int default_relax_domain_level = -1; int sched_domain_level_max; static int __init setup_relax_domain_level(char *str) { if (kstrtoint(str, 0, &default_relax_domain_level)) pr_warn("Unable to set relax_domain_level\n"); return 1; } __setup("relax_domain_level=", setup_relax_domain_level); static void set_domain_attribute(struct sched_domain *sd, struct sched_domain_attr *attr) { int request; if (!attr || attr->relax_domain_level < 0) { if (default_relax_domain_level < 0) return; else request = default_relax_domain_level; } else request = attr->relax_domain_level; if (request < sd->level) { /* turn off idle balance on this domain */ sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE); } else { /* turn on idle balance on this domain */ sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE); } } static void __sdt_free(const struct cpumask *cpu_map); static int __sdt_alloc(const struct cpumask *cpu_map); static void __free_domain_allocs(struct s_data *d, enum s_alloc what, const struct cpumask *cpu_map) { switch (what) { case sa_rootdomain: if (!atomic_read(&d->rd->refcount)) free_rootdomain(&d->rd->rcu); /* fall through */ case sa_sd: free_percpu(d->sd); /* fall through */ case sa_sd_storage: __sdt_free(cpu_map); /* fall through */ case sa_none: break; } } static enum s_alloc __visit_domain_allocation_hell(struct s_data *d, const struct cpumask *cpu_map) { memset(d, 0, sizeof(*d)); if (__sdt_alloc(cpu_map)) return sa_sd_storage; d->sd = alloc_percpu(struct sched_domain *); if (!d->sd) return sa_sd_storage; d->rd = alloc_rootdomain(); if (!d->rd) return sa_sd; return sa_rootdomain; } /* * NULL the sd_data elements we've used to build the sched_domain and * sched_group structure so that the subsequent __free_domain_allocs() * will not free the data we're using. */ static void claim_allocations(int cpu, struct sched_domain *sd) { struct sd_data *sdd = sd->private; WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd); *per_cpu_ptr(sdd->sd, cpu) = NULL; if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref)) *per_cpu_ptr(sdd->sg, cpu) = NULL; if (atomic_read(&(*per_cpu_ptr(sdd->sgp, cpu))->ref)) *per_cpu_ptr(sdd->sgp, cpu) = NULL; } #ifdef CONFIG_SCHED_SMT static const struct cpumask *cpu_smt_mask(int cpu) { return topology_thread_cpumask(cpu); } #endif /* * Topology list, bottom-up. */ static struct sched_domain_topology_level default_topology[] = { #ifdef CONFIG_SCHED_SMT { sd_init_SIBLING, cpu_smt_mask, }, #endif #ifdef CONFIG_SCHED_MC { sd_init_MC, cpu_coregroup_mask, }, #endif #ifdef CONFIG_SCHED_BOOK { sd_init_BOOK, cpu_book_mask, }, #endif { sd_init_CPU, cpu_cpu_mask, }, #ifdef CONFIG_NUMA { sd_init_NODE, cpu_node_mask, SDTL_OVERLAP, }, { sd_init_ALLNODES, cpu_allnodes_mask, }, #endif { NULL, }, }; static struct sched_domain_topology_level *sched_domain_topology = default_topology; static int __sdt_alloc(const struct cpumask *cpu_map) { struct sched_domain_topology_level *tl; int j; for (tl = sched_domain_topology; tl->init; tl++) { struct sd_data *sdd = &tl->data; sdd->sd = alloc_percpu(struct sched_domain *); if (!sdd->sd) return -ENOMEM; sdd->sg = alloc_percpu(struct sched_group *); if (!sdd->sg) return -ENOMEM; sdd->sgp = alloc_percpu(struct sched_group_power *); if (!sdd->sgp) return -ENOMEM; for_each_cpu(j, cpu_map) { struct sched_domain *sd; struct sched_group *sg; struct sched_group_power *sgp; sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(), GFP_KERNEL, cpu_to_node(j)); if (!sd) return -ENOMEM; *per_cpu_ptr(sdd->sd, j) = sd; sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(), GFP_KERNEL, cpu_to_node(j)); if (!sg) return -ENOMEM; sg->next = sg; *per_cpu_ptr(sdd->sg, j) = sg; sgp = kzalloc_node(sizeof(struct sched_group_power), GFP_KERNEL, cpu_to_node(j)); if (!sgp) return -ENOMEM; *per_cpu_ptr(sdd->sgp, j) = sgp; } } return 0; } static void __sdt_free(const struct cpumask *cpu_map) { struct sched_domain_topology_level *tl; int j; for (tl = sched_domain_topology; tl->init; tl++) { struct sd_data *sdd = &tl->data; for_each_cpu(j, cpu_map) { struct sched_domain *sd; if (sdd->sd) { sd = *per_cpu_ptr(sdd->sd, j); if (sd && (sd->flags & SD_OVERLAP)) free_sched_groups(sd->groups, 0); kfree(*per_cpu_ptr(sdd->sd, j)); } if (sdd->sg) kfree(*per_cpu_ptr(sdd->sg, j)); if (sdd->sgp) kfree(*per_cpu_ptr(sdd->sgp, j)); } free_percpu(sdd->sd); sdd->sd = NULL; free_percpu(sdd->sg); sdd->sg = NULL; free_percpu(sdd->sgp); sdd->sgp = NULL; } } struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl, struct s_data *d, const struct cpumask *cpu_map, struct sched_domain_attr *attr, struct sched_domain *child, int cpu) { struct sched_domain *sd = tl->init(tl, cpu); if (!sd) return child; cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu)); if (child) { sd->level = child->level + 1; sched_domain_level_max = max(sched_domain_level_max, sd->level); child->parent = sd; } sd->child = child; set_domain_attribute(sd, attr); return sd; } /* * Build sched domains for a given set of cpus and attach the sched domains * to the individual cpus */ static int build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *attr) { enum s_alloc alloc_state = sa_none; struct sched_domain *sd; struct s_data d; int i, ret = -ENOMEM; alloc_state = __visit_domain_allocation_hell(&d, cpu_map); if (alloc_state != sa_rootdomain) goto error; /* Set up domains for cpus specified by the cpu_map. */ for_each_cpu(i, cpu_map) { struct sched_domain_topology_level *tl; sd = NULL; for (tl = sched_domain_topology; tl->init; tl++) { sd = build_sched_domain(tl, &d, cpu_map, attr, sd, i); if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP)) sd->flags |= SD_OVERLAP; if (cpumask_equal(cpu_map, sched_domain_span(sd))) break; } while (sd->child) sd = sd->child; *per_cpu_ptr(d.sd, i) = sd; } /* Build the groups for the domains */ for_each_cpu(i, cpu_map) { for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) { sd->span_weight = cpumask_weight(sched_domain_span(sd)); if (sd->flags & SD_OVERLAP) { if (build_overlap_sched_groups(sd, i)) goto error; } else { if (build_sched_groups(sd, i)) goto error; } } } /* Calculate CPU power for physical packages and nodes */ for (i = nr_cpumask_bits-1; i >= 0; i--) { if (!cpumask_test_cpu(i, cpu_map)) continue; for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) { claim_allocations(i, sd); init_sched_groups_power(i, sd); } } /* Attach the domains */ rcu_read_lock(); for_each_cpu(i, cpu_map) { sd = *per_cpu_ptr(d.sd, i); cpu_attach_domain(sd, d.rd, i); } rcu_read_unlock(); ret = 0; error: __free_domain_allocs(&d, alloc_state, cpu_map); return ret; } static cpumask_var_t *doms_cur; /* current sched domains */ static int ndoms_cur; /* number of sched domains in 'doms_cur' */ static struct sched_domain_attr *dattr_cur; /* attribues of custom domains in 'doms_cur' */ /* * Special case: If a kmalloc of a doms_cur partition (array of * cpumask) fails, then fallback to a single sched domain, * as determined by the single cpumask fallback_doms. */ static cpumask_var_t fallback_doms; /* * arch_update_cpu_topology lets virtualized architectures update the * cpu core maps. It is supposed to return 1 if the topology changed * or 0 if it stayed the same. */ int __attribute__((weak)) arch_update_cpu_topology(void) { return 0; } cpumask_var_t *alloc_sched_domains(unsigned int ndoms) { int i; cpumask_var_t *doms; doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL); if (!doms) return NULL; for (i = 0; i < ndoms; i++) { if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) { free_sched_domains(doms, i); return NULL; } } return doms; } void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms) { unsigned int i; for (i = 0; i < ndoms; i++) free_cpumask_var(doms[i]); kfree(doms); } /* * Set up scheduler domains and groups. Callers must hold the hotplug lock. * For now this just excludes isolated cpus, but could be used to * exclude other special cases in the future. */ static int init_sched_domains(const struct cpumask *cpu_map) { int err; arch_update_cpu_topology(); ndoms_cur = 1; doms_cur = alloc_sched_domains(ndoms_cur); if (!doms_cur) doms_cur = &fallback_doms; cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map); dattr_cur = NULL; err = build_sched_domains(doms_cur[0], NULL); register_sched_domain_sysctl(); return err; } /* * Detach sched domains from a group of cpus specified in cpu_map * These cpus will now be attached to the NULL domain */ static void detach_destroy_domains(const struct cpumask *cpu_map) { int i; rcu_read_lock(); for_each_cpu(i, cpu_map) cpu_attach_domain(NULL, &def_root_domain, i); rcu_read_unlock(); } /* handle null as "default" */ static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur, struct sched_domain_attr *new, int idx_new) { struct sched_domain_attr tmp; /* fast path */ if (!new && !cur) return 1; tmp = SD_ATTR_INIT; return !memcmp(cur ? (cur + idx_cur) : &tmp, new ? (new + idx_new) : &tmp, sizeof(struct sched_domain_attr)); } /* * Partition sched domains as specified by the 'ndoms_new' * cpumasks in the array doms_new[] of cpumasks. This compares * doms_new[] to the current sched domain partitioning, doms_cur[]. * It destroys each deleted domain and builds each new domain. * * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'. * The masks don't intersect (don't overlap.) We should setup one * sched domain for each mask. CPUs not in any of the cpumasks will * not be load balanced. If the same cpumask appears both in the * current 'doms_cur' domains and in the new 'doms_new', we can leave * it as it is. * * The passed in 'doms_new' should be allocated using * alloc_sched_domains. This routine takes ownership of it and will * free_sched_domains it when done with it. If the caller failed the * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1, * and partition_sched_domains() will fallback to the single partition * 'fallback_doms', it also forces the domains to be rebuilt. * * If doms_new == NULL it will be replaced with cpu_online_mask. * ndoms_new == 0 is a special case for destroying existing domains, * and it will not create the default domain. * * Call with hotplug lock held */ void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[], struct sched_domain_attr *dattr_new) { int i, j, n; int new_topology; mutex_lock(&sched_domains_mutex); /* always unregister in case we don't destroy any domains */ unregister_sched_domain_sysctl(); /* Let architecture update cpu core mappings. */ new_topology = arch_update_cpu_topology(); n = doms_new ? ndoms_new : 0; /* Destroy deleted domains */ for (i = 0; i < ndoms_cur; i++) { for (j = 0; j < n && !new_topology; j++) { if (cpumask_equal(doms_cur[i], doms_new[j]) && dattrs_equal(dattr_cur, i, dattr_new, j)) goto match1; } /* no match - a current sched domain not in new doms_new[] */ detach_destroy_domains(doms_cur[i]); match1: ; } if (doms_new == NULL) { ndoms_cur = 0; doms_new = &fallback_doms; cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map); WARN_ON_ONCE(dattr_new); } /* Build new domains */ for (i = 0; i < ndoms_new; i++) { for (j = 0; j < ndoms_cur && !new_topology; j++) { if (cpumask_equal(doms_new[i], doms_cur[j]) && dattrs_equal(dattr_new, i, dattr_cur, j)) goto match2; } /* no match - add a new doms_new */ build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL); match2: ; } /* Remember the new sched domains */ if (doms_cur != &fallback_doms) free_sched_domains(doms_cur, ndoms_cur); kfree(dattr_cur); /* kfree(NULL) is safe */ doms_cur = doms_new; dattr_cur = dattr_new; ndoms_cur = ndoms_new; register_sched_domain_sysctl(); mutex_unlock(&sched_domains_mutex); } #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT) static void reinit_sched_domains(void) { get_online_cpus(); /* Destroy domains first to force the rebuild */ partition_sched_domains(0, NULL, NULL); rebuild_sched_domains(); put_online_cpus(); } static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt) { unsigned int level = 0; if (sscanf(buf, "%u", &level) != 1) return -EINVAL; /* * level is always be positive so don't check for * level < POWERSAVINGS_BALANCE_NONE which is 0 * What happens on 0 or 1 byte write, * need to check for count as well? */ if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS) return -EINVAL; if (smt) sched_smt_power_savings = level; else sched_mc_power_savings = level; reinit_sched_domains(); return count; } #ifdef CONFIG_SCHED_MC static ssize_t sched_mc_power_savings_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%u\n", sched_mc_power_savings); } static ssize_t sched_mc_power_savings_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return sched_power_savings_store(buf, count, 0); } static DEVICE_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show, sched_mc_power_savings_store); #endif #ifdef CONFIG_SCHED_SMT static ssize_t sched_smt_power_savings_show(struct device *dev, struct device_attribute *attr, char *buf) { return sprintf(buf, "%u\n", sched_smt_power_savings); } static ssize_t sched_smt_power_savings_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { return sched_power_savings_store(buf, count, 1); } static DEVICE_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show, sched_smt_power_savings_store); #endif int __init sched_create_sysfs_power_savings_entries(struct device *dev) { int err = 0; #ifdef CONFIG_SCHED_SMT if (smt_capable()) err = device_create_file(dev, &dev_attr_sched_smt_power_savings); #endif #ifdef CONFIG_SCHED_MC if (!err && mc_capable()) err = device_create_file(dev, &dev_attr_sched_mc_power_savings); #endif return err; } #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */ static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */ /* * Update cpusets according to cpu_active mask. If cpusets are * disabled, cpuset_update_active_cpus() becomes a simple wrapper * around partition_sched_domains(). * * If we come here as part of a suspend/resume, don't touch cpusets because we * want to restore it back to its original state upon resume anyway. */ static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action, void *hcpu) { switch (action) { case CPU_ONLINE_FROZEN: case CPU_DOWN_FAILED_FROZEN: /* * num_cpus_frozen tracks how many CPUs are involved in suspend * resume sequence. As long as this is not the last online * operation in the resume sequence, just build a single sched * domain, ignoring cpusets. */ num_cpus_frozen--; if (likely(num_cpus_frozen)) { partition_sched_domains(1, NULL, NULL); break; } /* * This is the last CPU online operation. So fall through and * restore the original sched domains by considering the * cpuset configurations. */ case CPU_ONLINE: case CPU_DOWN_FAILED: cpuset_update_active_cpus(); break; default: return NOTIFY_DONE; } return NOTIFY_OK; } static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action, void *hcpu) { switch (action) { case CPU_DOWN_PREPARE: cpuset_update_active_cpus(); break; case CPU_DOWN_PREPARE_FROZEN: num_cpus_frozen++; partition_sched_domains(1, NULL, NULL); break; default: return NOTIFY_DONE; } return NOTIFY_OK; } void __init sched_init_smp(void) { cpumask_var_t non_isolated_cpus; alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL); alloc_cpumask_var(&fallback_doms, GFP_KERNEL); get_online_cpus(); mutex_lock(&sched_domains_mutex); init_sched_domains(cpu_active_mask); cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map); if (cpumask_empty(non_isolated_cpus)) cpumask_set_cpu(smp_processor_id(), non_isolated_cpus); mutex_unlock(&sched_domains_mutex); put_online_cpus(); hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE); hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE); /* RT runtime code needs to handle some hotplug events */ hotcpu_notifier(update_runtime, 0); init_hrtick(); /* Move init over to a non-isolated CPU */ if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0) BUG(); sched_init_granularity(); free_cpumask_var(non_isolated_cpus); init_sched_rt_class(); } #else void __init sched_init_smp(void) { sched_init_granularity(); } #endif /* CONFIG_SMP */ const_debug unsigned int sysctl_timer_migration = 1; int in_sched_functions(unsigned long addr) { return in_lock_functions(addr) || (addr >= (unsigned long)__sched_text_start && addr < (unsigned long)__sched_text_end); } #ifdef CONFIG_CGROUP_SCHED struct task_group root_task_group; LIST_HEAD(task_groups); #endif DECLARE_PER_CPU(cpumask_var_t, load_balance_tmpmask); void __init sched_init(void) { int i, j; unsigned long alloc_size = 0, ptr; #ifdef CONFIG_FAIR_GROUP_SCHED alloc_size += 2 * nr_cpu_ids * sizeof(void **); #endif #ifdef CONFIG_RT_GROUP_SCHED alloc_size += 2 * nr_cpu_ids * sizeof(void **); #endif #ifdef CONFIG_CPUMASK_OFFSTACK alloc_size += num_possible_cpus() * cpumask_size(); #endif if (alloc_size) { ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT); #ifdef CONFIG_FAIR_GROUP_SCHED root_task_group.se = (struct sched_entity **)ptr; ptr += nr_cpu_ids * sizeof(void **); root_task_group.cfs_rq = (struct cfs_rq **)ptr; ptr += nr_cpu_ids * sizeof(void **); #endif /* CONFIG_FAIR_GROUP_SCHED */ #ifdef CONFIG_RT_GROUP_SCHED root_task_group.rt_se = (struct sched_rt_entity **)ptr; ptr += nr_cpu_ids * sizeof(void **); root_task_group.rt_rq = (struct rt_rq **)ptr; ptr += nr_cpu_ids * sizeof(void **); #endif /* CONFIG_RT_GROUP_SCHED */ #ifdef CONFIG_CPUMASK_OFFSTACK for_each_possible_cpu(i) { per_cpu(load_balance_tmpmask, i) = (void *)ptr; ptr += cpumask_size(); } #endif /* CONFIG_CPUMASK_OFFSTACK */ } #ifdef CONFIG_SMP init_defrootdomain(); #endif init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime()); #ifdef CONFIG_RT_GROUP_SCHED init_rt_bandwidth(&root_task_group.rt_bandwidth, global_rt_period(), global_rt_runtime()); #endif /* CONFIG_RT_GROUP_SCHED */ #ifdef CONFIG_CGROUP_SCHED list_add(&root_task_group.list, &task_groups); INIT_LIST_HEAD(&root_task_group.children); INIT_LIST_HEAD(&root_task_group.siblings); autogroup_init(&init_task); #endif /* CONFIG_CGROUP_SCHED */ #ifdef CONFIG_CGROUP_CPUACCT root_cpuacct.cpustat = &kernel_cpustat; root_cpuacct.cpuusage = alloc_percpu(u64); /* Too early, not expected to fail */ BUG_ON(!root_cpuacct.cpuusage); #endif for_each_possible_cpu(i) { struct rq *rq; rq = cpu_rq(i); raw_spin_lock_init(&rq->lock); rq->nr_running = 0; rq->calc_load_active = 0; rq->calc_load_update = jiffies + LOAD_FREQ; init_cfs_rq(&rq->cfs); init_rt_rq(&rq->rt, rq); #ifdef CONFIG_FAIR_GROUP_SCHED root_task_group.shares = ROOT_TASK_GROUP_LOAD; INIT_LIST_HEAD(&rq->leaf_cfs_rq_list); /* * How much cpu bandwidth does root_task_group get? * * In case of task-groups formed thr' the cgroup filesystem, it * gets 100% of the cpu resources in the system. This overall * system cpu resource is divided among the tasks of * root_task_group and its child task-groups in a fair manner, * based on each entity's (task or task-group's) weight * (se->load.weight). * * In other words, if root_task_group has 10 tasks of weight * 1024) and two child groups A0 and A1 (of weight 1024 each), * then A0's share of the cpu resource is: * * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33% * * We achieve this by letting root_task_group's tasks sit * directly in rq->cfs (i.e root_task_group->se[] = NULL). */ init_cfs_bandwidth(&root_task_group.cfs_bandwidth); init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL); #endif /* CONFIG_FAIR_GROUP_SCHED */ rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime; #ifdef CONFIG_RT_GROUP_SCHED INIT_LIST_HEAD(&rq->leaf_rt_rq_list); init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL); #endif for (j = 0; j < CPU_LOAD_IDX_MAX; j++) rq->cpu_load[j] = 0; rq->last_load_update_tick = jiffies; #ifdef CONFIG_SMP rq->sd = NULL; rq->rd = NULL; rq->cpu_power = SCHED_POWER_SCALE; rq->post_schedule = 0; rq->active_balance = 0; rq->next_balance = jiffies; rq->push_cpu = 0; rq->cpu = i; rq->online = 0; rq->idle_stamp = 0; rq->avg_idle = 2*sysctl_sched_migration_cost; INIT_LIST_HEAD(&rq->cfs_tasks); rq_attach_root(rq, &def_root_domain); #ifdef CONFIG_NO_HZ rq->nohz_flags = 0; #endif #endif init_rq_hrtick(rq); atomic_set(&rq->nr_iowait, 0); } set_load_weight(&init_task); #ifdef CONFIG_PREEMPT_NOTIFIERS INIT_HLIST_HEAD(&init_task.preempt_notifiers); #endif #ifdef CONFIG_RT_MUTEXES plist_head_init(&init_task.pi_waiters); #endif /* * The boot idle thread does lazy MMU switching as well: */ atomic_inc(&init_mm.mm_count); enter_lazy_tlb(&init_mm, current); /* * Make us the idle thread. Technically, schedule() should not be * called from this thread, however somewhere below it might be, * but because we are the idle thread, we just pick up running again * when this runqueue becomes "idle". */ init_idle(current, smp_processor_id()); calc_load_update = jiffies + LOAD_FREQ; /* * During early bootup we pretend to be a normal task: */ current->sched_class = &fair_sched_class; #ifdef CONFIG_SMP zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT); /* May be allocated at isolcpus cmdline parse time */ if (cpu_isolated_map == NULL) zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT); #endif init_sched_fair_class(); scheduler_running = 1; } #ifdef CONFIG_DEBUG_ATOMIC_SLEEP static inline int preempt_count_equals(int preempt_offset) { int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth(); return (nested == preempt_offset); } static int __might_sleep_init_called; int __init __might_sleep_init(void) { __might_sleep_init_called = 1; return 0; } early_initcall(__might_sleep_init); void __might_sleep(const char *file, int line, int preempt_offset) { static unsigned long prev_jiffy; /* ratelimiting */ rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */ if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) || oops_in_progress) return; if (system_state != SYSTEM_RUNNING && (!__might_sleep_init_called || system_state != SYSTEM_BOOTING)) return; if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) return; prev_jiffy = jiffies; printk(KERN_ERR "BUG: sleeping function called from invalid context at %s:%d\n", file, line); printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n", in_atomic(), irqs_disabled(), current->pid, current->comm); debug_show_held_locks(current); if (irqs_disabled()) print_irqtrace_events(current); dump_stack(); } EXPORT_SYMBOL(__might_sleep); #endif #ifdef CONFIG_MAGIC_SYSRQ static void normalize_task(struct rq *rq, struct task_struct *p) { const struct sched_class *prev_class = p->sched_class; int old_prio = p->prio; int on_rq; on_rq = p->on_rq; if (on_rq) dequeue_task(rq, p, 0); __setscheduler(rq, p, SCHED_NORMAL, 0); if (on_rq) { enqueue_task(rq, p, 0); resched_task(rq->curr); } check_class_changed(rq, p, prev_class, old_prio); } void normalize_rt_tasks(void) { struct task_struct *g, *p; unsigned long flags; struct rq *rq; read_lock_irqsave(&tasklist_lock, flags); do_each_thread(g, p) { /* * Only normalize user tasks: */ if (!p->mm) continue; p->se.exec_start = 0; #ifdef CONFIG_SCHEDSTATS p->se.statistics.wait_start = 0; p->se.statistics.sleep_start = 0; p->se.statistics.block_start = 0; #endif if (!rt_task(p)) { /* * Renice negative nice level userspace * tasks back to 0: */ if (TASK_NICE(p) < 0 && p->mm) set_user_nice(p, 0); continue; } raw_spin_lock(&p->pi_lock); rq = __task_rq_lock(p); normalize_task(rq, p); __task_rq_unlock(rq); raw_spin_unlock(&p->pi_lock); } while_each_thread(g, p); read_unlock_irqrestore(&tasklist_lock, flags); } #endif /* CONFIG_MAGIC_SYSRQ */ #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) /* * These functions are only useful for the IA64 MCA handling, or kdb. * * They can only be called when the whole system has been * stopped - every CPU needs to be quiescent, and no scheduling * activity can take place. Using them for anything else would * be a serious bug, and as a result, they aren't even visible * under any other configuration. */ /** * curr_task - return the current task for a given cpu. * @cpu: the processor in question. * * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED! */ struct task_struct *curr_task(int cpu) { return cpu_curr(cpu); } #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */ #ifdef CONFIG_IA64 /** * set_curr_task - set the current task for a given cpu. * @cpu: the processor in question. * @p: the task pointer to set. * * Description: This function must only be used when non-maskable interrupts * are serviced on a separate stack. It allows the architecture to switch the * notion of the current task on a cpu in a non-blocking manner. This function * must be called with all CPU's synchronized, and interrupts disabled, the * and caller must save the original value of the current task (see * curr_task() above) and restore that value before reenabling interrupts and * re-starting the system. * * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED! */ void set_curr_task(int cpu, struct task_struct *p) { cpu_curr(cpu) = p; } #endif #ifdef CONFIG_CGROUP_SCHED /* task_group_lock serializes the addition/removal of task groups */ static DEFINE_SPINLOCK(task_group_lock); static void free_sched_group(struct task_group *tg) { free_fair_sched_group(tg); free_rt_sched_group(tg); autogroup_free(tg); kfree(tg); } /* allocate runqueue etc for a new task group */ struct task_group *sched_create_group(struct task_group *parent) { struct task_group *tg; unsigned long flags; tg = kzalloc(sizeof(*tg), GFP_KERNEL); if (!tg) return ERR_PTR(-ENOMEM); if (!alloc_fair_sched_group(tg, parent)) goto err; if (!alloc_rt_sched_group(tg, parent)) goto err; spin_lock_irqsave(&task_group_lock, flags); list_add_rcu(&tg->list, &task_groups); WARN_ON(!parent); /* root should already exist */ tg->parent = parent; INIT_LIST_HEAD(&tg->children); list_add_rcu(&tg->siblings, &parent->children); spin_unlock_irqrestore(&task_group_lock, flags); return tg; err: free_sched_group(tg); return ERR_PTR(-ENOMEM); } /* rcu callback to free various structures associated with a task group */ static void free_sched_group_rcu(struct rcu_head *rhp) { /* now it should be safe to free those cfs_rqs */ free_sched_group(container_of(rhp, struct task_group, rcu)); } /* Destroy runqueue etc associated with a task group */ void sched_destroy_group(struct task_group *tg) { unsigned long flags; int i; /* end participation in shares distribution */ for_each_possible_cpu(i) unregister_fair_sched_group(tg, i); spin_lock_irqsave(&task_group_lock, flags); list_del_rcu(&tg->list); list_del_rcu(&tg->siblings); spin_unlock_irqrestore(&task_group_lock, flags); /* wait for possible concurrent references to cfs_rqs complete */ call_rcu(&tg->rcu, free_sched_group_rcu); } /* change task's runqueue when it moves between groups. * The caller of this function should have put the task in its new group * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to * reflect its new group. */ void sched_move_task(struct task_struct *tsk) { struct task_group *tg; int on_rq, running; unsigned long flags; struct rq *rq; rq = task_rq_lock(tsk, &flags); running = task_current(rq, tsk); on_rq = tsk->on_rq; if (on_rq) dequeue_task(rq, tsk, 0); if (unlikely(running)) tsk->sched_class->put_prev_task(rq, tsk); tg = container_of(task_subsys_state_check(tsk, cpu_cgroup_subsys_id, lockdep_is_held(&tsk->sighand->siglock)), struct task_group, css); tg = autogroup_task_group(tsk, tg); tsk->sched_task_group = tg; #ifdef CONFIG_FAIR_GROUP_SCHED if (tsk->sched_class->task_move_group) tsk->sched_class->task_move_group(tsk, on_rq); else #endif set_task_rq(tsk, task_cpu(tsk)); if (unlikely(running)) tsk->sched_class->set_curr_task(rq); if (on_rq) enqueue_task(rq, tsk, 0); task_rq_unlock(rq, tsk, &flags); } #endif /* CONFIG_CGROUP_SCHED */ #if defined(CONFIG_RT_GROUP_SCHED) || defined(CONFIG_CFS_BANDWIDTH) static unsigned long to_ratio(u64 period, u64 runtime) { if (runtime == RUNTIME_INF) return 1ULL << 20; return div64_u64(runtime << 20, period); } #endif #ifdef CONFIG_RT_GROUP_SCHED /* * Ensure that the real time constraints are schedulable. */ static DEFINE_MUTEX(rt_constraints_mutex); /* Must be called with tasklist_lock held */ static inline int tg_has_rt_tasks(struct task_group *tg) { struct task_struct *g, *p; do_each_thread(g, p) { if (rt_task(p) && task_rq(p)->rt.tg == tg) return 1; } while_each_thread(g, p); return 0; } struct rt_schedulable_data { struct task_group *tg; u64 rt_period; u64 rt_runtime; }; static int tg_rt_schedulable(struct task_group *tg, void *data) { struct rt_schedulable_data *d = data; struct task_group *child; unsigned long total, sum = 0; u64 period, runtime; period = ktime_to_ns(tg->rt_bandwidth.rt_period); runtime = tg->rt_bandwidth.rt_runtime; if (tg == d->tg) { period = d->rt_period; runtime = d->rt_runtime; } /* * Cannot have more runtime than the period. */ if (runtime > period && runtime != RUNTIME_INF) return -EINVAL; /* * Ensure we don't starve existing RT tasks. */ if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg)) return -EBUSY; total = to_ratio(period, runtime); /* * Nobody can have more than the global setting allows. */ if (total > to_ratio(global_rt_period(), global_rt_runtime())) return -EINVAL; /* * The sum of our children's runtime should not exceed our own. */ list_for_each_entry_rcu(child, &tg->children, siblings) { period = ktime_to_ns(child->rt_bandwidth.rt_period); runtime = child->rt_bandwidth.rt_runtime; if (child == d->tg) { period = d->rt_period; runtime = d->rt_runtime; } sum += to_ratio(period, runtime); } if (sum > total) return -EINVAL; return 0; } static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime) { int ret; struct rt_schedulable_data data = { .tg = tg, .rt_period = period, .rt_runtime = runtime, }; rcu_read_lock(); ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data); rcu_read_unlock(); return ret; } static int tg_set_rt_bandwidth(struct task_group *tg, u64 rt_period, u64 rt_runtime) { int i, err = 0; mutex_lock(&rt_constraints_mutex); read_lock(&tasklist_lock); err = __rt_schedulable(tg, rt_period, rt_runtime); if (err) goto unlock; raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock); tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period); tg->rt_bandwidth.rt_runtime = rt_runtime; for_each_possible_cpu(i) { struct rt_rq *rt_rq = tg->rt_rq[i]; raw_spin_lock(&rt_rq->rt_runtime_lock); rt_rq->rt_runtime = rt_runtime; raw_spin_unlock(&rt_rq->rt_runtime_lock); } raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock); unlock: read_unlock(&tasklist_lock); mutex_unlock(&rt_constraints_mutex); return err; } int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us) { u64 rt_runtime, rt_period; rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period); rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC; if (rt_runtime_us < 0) rt_runtime = RUNTIME_INF; return tg_set_rt_bandwidth(tg, rt_period, rt_runtime); } long sched_group_rt_runtime(struct task_group *tg) { u64 rt_runtime_us; if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF) return -1; rt_runtime_us = tg->rt_bandwidth.rt_runtime; do_div(rt_runtime_us, NSEC_PER_USEC); return rt_runtime_us; } int sched_group_set_rt_period(struct task_group *tg, long rt_period_us) { u64 rt_runtime, rt_period; rt_period = (u64)rt_period_us * NSEC_PER_USEC; rt_runtime = tg->rt_bandwidth.rt_runtime; if (rt_period == 0) return -EINVAL; return tg_set_rt_bandwidth(tg, rt_period, rt_runtime); } long sched_group_rt_period(struct task_group *tg) { u64 rt_period_us; rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period); do_div(rt_period_us, NSEC_PER_USEC); return rt_period_us; } static int sched_rt_global_constraints(void) { u64 runtime, period; int ret = 0; if (sysctl_sched_rt_period <= 0) return -EINVAL; runtime = global_rt_runtime(); period = global_rt_period(); /* * Sanity check on the sysctl variables. */ if (runtime > period && runtime != RUNTIME_INF) return -EINVAL; mutex_lock(&rt_constraints_mutex); read_lock(&tasklist_lock); ret = __rt_schedulable(NULL, 0, 0); read_unlock(&tasklist_lock); mutex_unlock(&rt_constraints_mutex); return ret; } int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk) { /* Don't accept realtime tasks when there is no way for them to run */ if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0) return 0; return 1; } #else /* !CONFIG_RT_GROUP_SCHED */ static int sched_rt_global_constraints(void) { unsigned long flags; int i; if (sysctl_sched_rt_period <= 0) return -EINVAL; /* * There's always some RT tasks in the root group * -- migration, kstopmachine etc.. */ if (sysctl_sched_rt_runtime == 0) return -EBUSY; raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags); for_each_possible_cpu(i) { struct rt_rq *rt_rq = &cpu_rq(i)->rt; raw_spin_lock(&rt_rq->rt_runtime_lock); rt_rq->rt_runtime = global_rt_runtime(); raw_spin_unlock(&rt_rq->rt_runtime_lock); } raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags); return 0; } #endif /* CONFIG_RT_GROUP_SCHED */ int sched_rt_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret; int old_period, old_runtime; static DEFINE_MUTEX(mutex); mutex_lock(&mutex); old_period = sysctl_sched_rt_period; old_runtime = sysctl_sched_rt_runtime; ret = proc_dointvec(table, write, buffer, lenp, ppos); if (!ret && write) { ret = sched_rt_global_constraints(); if (ret) { sysctl_sched_rt_period = old_period; sysctl_sched_rt_runtime = old_runtime; } else { def_rt_bandwidth.rt_runtime = global_rt_runtime(); def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period()); } } mutex_unlock(&mutex); return ret; } #ifdef CONFIG_CGROUP_SCHED /* return corresponding task_group object of a cgroup */ static inline struct task_group *cgroup_tg(struct cgroup *cgrp) { return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id), struct task_group, css); } static struct cgroup_subsys_state *cpu_cgroup_create(struct cgroup *cgrp) { struct task_group *tg, *parent; if (!cgrp->parent) { /* This is early initialization for the top cgroup */ return &root_task_group.css; } parent = cgroup_tg(cgrp->parent); tg = sched_create_group(parent); if (IS_ERR(tg)) return ERR_PTR(-ENOMEM); return &tg->css; } static void cpu_cgroup_destroy(struct cgroup *cgrp) { struct task_group *tg = cgroup_tg(cgrp); sched_destroy_group(tg); } static int cpu_cgroup_allow_attach(struct cgroup *cgrp, struct cgroup_taskset *tset) { const struct cred *cred = current_cred(), *tcred; struct task_struct *task; cgroup_taskset_for_each(task, cgrp, tset) { tcred = __task_cred(task); if ((current != task) && !capable(CAP_SYS_NICE) && cred->euid != tcred->uid && cred->euid != tcred->suid) return -EACCES; } return 0; } static int cpu_cgroup_can_attach(struct cgroup *cgrp, struct cgroup_taskset *tset) { struct task_struct *task; cgroup_taskset_for_each(task, cgrp, tset) { #ifdef CONFIG_RT_GROUP_SCHED if (!sched_rt_can_attach(cgroup_tg(cgrp), task)) return -EINVAL; #else /* We don't support RT-tasks being in separate groups */ if (task->sched_class != &fair_sched_class) return -EINVAL; #endif } return 0; } static void cpu_cgroup_attach(struct cgroup *cgrp, struct cgroup_taskset *tset) { struct task_struct *task; cgroup_taskset_for_each(task, cgrp, tset) sched_move_task(task); } static void cpu_cgroup_exit(struct cgroup *cgrp, struct cgroup *old_cgrp, struct task_struct *task) { /* * cgroup_exit() is called in the copy_process() failure path. * Ignore this case since the task hasn't ran yet, this avoids * trying to poke a half freed task state from generic code. */ if (!(task->flags & PF_EXITING)) return; sched_move_task(task); } static u64 cpu_notify_on_migrate_read_u64(struct cgroup *cgrp, struct cftype *cft) { struct task_group *tg = cgroup_tg(cgrp); return tg->notify_on_migrate; } static int cpu_notify_on_migrate_write_u64(struct cgroup *cgrp, struct cftype *cft, u64 notify) { struct task_group *tg = cgroup_tg(cgrp); tg->notify_on_migrate = (notify > 0); return 0; } #ifdef CONFIG_FAIR_GROUP_SCHED static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype, u64 shareval) { return sched_group_set_shares(cgroup_tg(cgrp), scale_load(shareval)); } static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft) { struct task_group *tg = cgroup_tg(cgrp); return (u64) scale_load_down(tg->shares); } #ifdef CONFIG_CFS_BANDWIDTH static DEFINE_MUTEX(cfs_constraints_mutex); const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */ const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */ static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime); static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota) { int i, ret = 0, runtime_enabled, runtime_was_enabled; struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; if (tg == &root_task_group) return -EINVAL; /* * Ensure we have at some amount of bandwidth every period. This is * to prevent reaching a state of large arrears when throttled via * entity_tick() resulting in prolonged exit starvation. */ if (quota < min_cfs_quota_period || period < min_cfs_quota_period) return -EINVAL; /* * Likewise, bound things on the otherside by preventing insane quota * periods. This also allows us to normalize in computing quota * feasibility. */ if (period > max_cfs_quota_period) return -EINVAL; mutex_lock(&cfs_constraints_mutex); ret = __cfs_schedulable(tg, period, quota); if (ret) goto out_unlock; runtime_enabled = quota != RUNTIME_INF; runtime_was_enabled = cfs_b->quota != RUNTIME_INF; /* * If we need to toggle cfs_bandwidth_used, off->on must occur * before making related changes, and on->off must occur afterwards */ if (runtime_enabled && !runtime_was_enabled) cfs_bandwidth_usage_inc(); raw_spin_lock_irq(&cfs_b->lock); cfs_b->period = ns_to_ktime(period); cfs_b->quota = quota; __refill_cfs_bandwidth_runtime(cfs_b); /* restart the period timer (if active) to handle new period expiry */ if (runtime_enabled && cfs_b->timer_active) { /* force a reprogram */ cfs_b->timer_active = 0; __start_cfs_bandwidth(cfs_b); } raw_spin_unlock_irq(&cfs_b->lock); for_each_possible_cpu(i) { struct cfs_rq *cfs_rq = tg->cfs_rq[i]; struct rq *rq = cfs_rq->rq; raw_spin_lock_irq(&rq->lock); cfs_rq->runtime_enabled = runtime_enabled; cfs_rq->runtime_remaining = 0; if (cfs_rq->throttled) unthrottle_cfs_rq(cfs_rq); raw_spin_unlock_irq(&rq->lock); } if (runtime_was_enabled && !runtime_enabled) cfs_bandwidth_usage_dec(); out_unlock: mutex_unlock(&cfs_constraints_mutex); return ret; } int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us) { u64 quota, period; period = ktime_to_ns(tg->cfs_bandwidth.period); if (cfs_quota_us < 0) quota = RUNTIME_INF; else quota = (u64)cfs_quota_us * NSEC_PER_USEC; return tg_set_cfs_bandwidth(tg, period, quota); } long tg_get_cfs_quota(struct task_group *tg) { u64 quota_us; if (tg->cfs_bandwidth.quota == RUNTIME_INF) return -1; quota_us = tg->cfs_bandwidth.quota; do_div(quota_us, NSEC_PER_USEC); return quota_us; } int tg_set_cfs_period(struct task_group *tg, long cfs_period_us) { u64 quota, period; period = (u64)cfs_period_us * NSEC_PER_USEC; quota = tg->cfs_bandwidth.quota; return tg_set_cfs_bandwidth(tg, period, quota); } long tg_get_cfs_period(struct task_group *tg) { u64 cfs_period_us; cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period); do_div(cfs_period_us, NSEC_PER_USEC); return cfs_period_us; } static s64 cpu_cfs_quota_read_s64(struct cgroup *cgrp, struct cftype *cft) { return tg_get_cfs_quota(cgroup_tg(cgrp)); } static int cpu_cfs_quota_write_s64(struct cgroup *cgrp, struct cftype *cftype, s64 cfs_quota_us) { return tg_set_cfs_quota(cgroup_tg(cgrp), cfs_quota_us); } static u64 cpu_cfs_period_read_u64(struct cgroup *cgrp, struct cftype *cft) { return tg_get_cfs_period(cgroup_tg(cgrp)); } static int cpu_cfs_period_write_u64(struct cgroup *cgrp, struct cftype *cftype, u64 cfs_period_us) { return tg_set_cfs_period(cgroup_tg(cgrp), cfs_period_us); } struct cfs_schedulable_data { struct task_group *tg; u64 period, quota; }; /* * normalize group quota/period to be quota/max_period * note: units are usecs */ static u64 normalize_cfs_quota(struct task_group *tg, struct cfs_schedulable_data *d) { u64 quota, period; if (tg == d->tg) { period = d->period; quota = d->quota; } else { period = tg_get_cfs_period(tg); quota = tg_get_cfs_quota(tg); } /* note: these should typically be equivalent */ if (quota == RUNTIME_INF || quota == -1) return RUNTIME_INF; return to_ratio(period, quota); } static int tg_cfs_schedulable_down(struct task_group *tg, void *data) { struct cfs_schedulable_data *d = data; struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; s64 quota = 0, parent_quota = -1; if (!tg->parent) { quota = RUNTIME_INF; } else { struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth; quota = normalize_cfs_quota(tg, d); parent_quota = parent_b->hierarchal_quota; /* * ensure max(child_quota) <= parent_quota, inherit when no * limit is set */ if (quota == RUNTIME_INF) quota = parent_quota; else if (parent_quota != RUNTIME_INF && quota > parent_quota) return -EINVAL; } cfs_b->hierarchal_quota = quota; return 0; } static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota) { int ret; struct cfs_schedulable_data data = { .tg = tg, .period = period, .quota = quota, }; if (quota != RUNTIME_INF) { do_div(data.period, NSEC_PER_USEC); do_div(data.quota, NSEC_PER_USEC); } rcu_read_lock(); ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data); rcu_read_unlock(); return ret; } static int cpu_stats_show(struct cgroup *cgrp, struct cftype *cft, struct cgroup_map_cb *cb) { struct task_group *tg = cgroup_tg(cgrp); struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; cb->fill(cb, "nr_periods", cfs_b->nr_periods); cb->fill(cb, "nr_throttled", cfs_b->nr_throttled); cb->fill(cb, "throttled_time", cfs_b->throttled_time); return 0; } #endif /* CONFIG_CFS_BANDWIDTH */ #endif /* CONFIG_FAIR_GROUP_SCHED */ #ifdef CONFIG_RT_GROUP_SCHED static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft, s64 val) { return sched_group_set_rt_runtime(cgroup_tg(cgrp), val); } static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft) { return sched_group_rt_runtime(cgroup_tg(cgrp)); } static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype, u64 rt_period_us) { return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us); } static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft) { return sched_group_rt_period(cgroup_tg(cgrp)); } #endif /* CONFIG_RT_GROUP_SCHED */ static struct cftype cpu_files[] = { { .name = "notify_on_migrate", .read_u64 = cpu_notify_on_migrate_read_u64, .write_u64 = cpu_notify_on_migrate_write_u64, }, #ifdef CONFIG_FAIR_GROUP_SCHED { .name = "shares", .read_u64 = cpu_shares_read_u64, .write_u64 = cpu_shares_write_u64, }, #endif #ifdef CONFIG_CFS_BANDWIDTH { .name = "cfs_quota_us", .read_s64 = cpu_cfs_quota_read_s64, .write_s64 = cpu_cfs_quota_write_s64, }, { .name = "cfs_period_us", .read_u64 = cpu_cfs_period_read_u64, .write_u64 = cpu_cfs_period_write_u64, }, { .name = "stat", .read_map = cpu_stats_show, }, #endif #ifdef CONFIG_RT_GROUP_SCHED { .name = "rt_runtime_us", .read_s64 = cpu_rt_runtime_read, .write_s64 = cpu_rt_runtime_write, }, { .name = "rt_period_us", .read_u64 = cpu_rt_period_read_uint, .write_u64 = cpu_rt_period_write_uint, }, #endif }; static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont) { return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files)); } struct cgroup_subsys cpu_cgroup_subsys = { .name = "cpu", .create = cpu_cgroup_create, .destroy = cpu_cgroup_destroy, .can_attach = cpu_cgroup_can_attach, .attach = cpu_cgroup_attach, .allow_attach = cpu_cgroup_allow_attach, .exit = cpu_cgroup_exit, .populate = cpu_cgroup_populate, .subsys_id = cpu_cgroup_subsys_id, .early_init = 1, }; #endif /* CONFIG_CGROUP_SCHED */ #ifdef CONFIG_CGROUP_CPUACCT /* * CPU accounting code for task groups. * * Based on the work by Paul Menage (menage@google.com) and Balbir Singh * (balbir@in.ibm.com). */ /* create a new cpu accounting group */ static struct cgroup_subsys_state *cpuacct_create(struct cgroup *cgrp) { struct cpuacct *ca; if (!cgrp->parent) return &root_cpuacct.css; ca = kzalloc(sizeof(*ca), GFP_KERNEL); if (!ca) goto out; ca->cpuusage = alloc_percpu(u64); if (!ca->cpuusage) goto out_free_ca; ca->cpustat = alloc_percpu(struct kernel_cpustat); if (!ca->cpustat) goto out_free_cpuusage; return &ca->css; out_free_cpuusage: free_percpu(ca->cpuusage); out_free_ca: kfree(ca); out: return ERR_PTR(-ENOMEM); } /* destroy an existing cpu accounting group */ static void cpuacct_destroy(struct cgroup *cgrp) { struct cpuacct *ca = cgroup_ca(cgrp); free_percpu(ca->cpustat); free_percpu(ca->cpuusage); kfree(ca); } static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu) { u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu); u64 data; #ifndef CONFIG_64BIT /* * Take rq->lock to make 64-bit read safe on 32-bit platforms. */ raw_spin_lock_irq(&cpu_rq(cpu)->lock); data = *cpuusage; raw_spin_unlock_irq(&cpu_rq(cpu)->lock); #else data = *cpuusage; #endif return data; } static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val) { u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu); #ifndef CONFIG_64BIT /* * Take rq->lock to make 64-bit write safe on 32-bit platforms. */ raw_spin_lock_irq(&cpu_rq(cpu)->lock); *cpuusage = val; raw_spin_unlock_irq(&cpu_rq(cpu)->lock); #else *cpuusage = val; #endif } /* return total cpu usage (in nanoseconds) of a group */ static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft) { struct cpuacct *ca = cgroup_ca(cgrp); u64 totalcpuusage = 0; int i; for_each_present_cpu(i) totalcpuusage += cpuacct_cpuusage_read(ca, i); return totalcpuusage; } static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype, u64 reset) { struct cpuacct *ca = cgroup_ca(cgrp); int err = 0; int i; if (reset) { err = -EINVAL; goto out; } for_each_present_cpu(i) cpuacct_cpuusage_write(ca, i, 0); out: return err; } static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft, struct seq_file *m) { struct cpuacct *ca = cgroup_ca(cgroup); u64 percpu; int i; for_each_present_cpu(i) { percpu = cpuacct_cpuusage_read(ca, i); seq_printf(m, "%llu ", (unsigned long long) percpu); } seq_printf(m, "\n"); return 0; } static const char *cpuacct_stat_desc[] = { [CPUACCT_STAT_USER] = "user", [CPUACCT_STAT_SYSTEM] = "system", }; static int cpuacct_stats_show(struct cgroup *cgrp, struct cftype *cft, struct cgroup_map_cb *cb) { struct cpuacct *ca = cgroup_ca(cgrp); int cpu; s64 val = 0; for_each_online_cpu(cpu) { struct kernel_cpustat *kcpustat = per_cpu_ptr(ca->cpustat, cpu); val += kcpustat->cpustat[CPUTIME_USER]; val += kcpustat->cpustat[CPUTIME_NICE]; } val = cputime64_to_clock_t(val); cb->fill(cb, cpuacct_stat_desc[CPUACCT_STAT_USER], val); val = 0; for_each_online_cpu(cpu) { struct kernel_cpustat *kcpustat = per_cpu_ptr(ca->cpustat, cpu); val += kcpustat->cpustat[CPUTIME_SYSTEM]; val += kcpustat->cpustat[CPUTIME_IRQ]; val += kcpustat->cpustat[CPUTIME_SOFTIRQ]; } val = cputime64_to_clock_t(val); cb->fill(cb, cpuacct_stat_desc[CPUACCT_STAT_SYSTEM], val); return 0; } static struct cftype files[] = { { .name = "usage", .read_u64 = cpuusage_read, .write_u64 = cpuusage_write, }, { .name = "usage_percpu", .read_seq_string = cpuacct_percpu_seq_read, }, { .name = "stat", .read_map = cpuacct_stats_show, }, }; static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp) { return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files)); } /* * charge this task's execution time to its accounting group. * * called with rq->lock held. */ void cpuacct_charge(struct task_struct *tsk, u64 cputime) { struct cpuacct *ca; int cpu; if (unlikely(!cpuacct_subsys.active)) return; cpu = task_cpu(tsk); rcu_read_lock(); ca = task_ca(tsk); for (; ca; ca = parent_ca(ca)) { u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu); *cpuusage += cputime; } rcu_read_unlock(); } struct cgroup_subsys cpuacct_subsys = { .name = "cpuacct", .create = cpuacct_create, .destroy = cpuacct_destroy, .populate = cpuacct_populate, .subsys_id = cpuacct_subsys_id, }; #endif /* CONFIG_CGROUP_CPUACCT */
major91/Zeta_Chromium-L
kernel/sched/core.c
C
gpl-2.0
213,228
<?php /* Copyright (C) 2007 Stephane Graber <stgraber@ubuntu.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ function qawebsite_block($op = "list", $delta = 0, $edit = array()) { drupal_add_css('modules/qawebsite/qawebsite.css'); $blocks=array(); $blocks[0]['info'] = "QA-Website module action block"; $blocks[0]['function'] = "qawebsite_block_action"; $blocks[1]['info'] = "QA-Website top navigation bar"; $blocks[1]['function'] = "qawebsite_block_navigation"; $blocks[2]['info'] = "QA-Website module action block 2"; $blocks[2]['function'] = "qawebsite_block_action2"; switch($op) { case "list": return $blocks; break; case "configure": return; break; case "save": return; break; case "view": default: $data=array(); $data['content']=call_user_func($blocks[$delta]['function']); return $data; } } function qawebsite_block_action() { $site=QAWebsiteSite::getInstance(); $module=arg(0); if ($site == null || ($site->title == "Ubuntu QA" && arg(0) == "qatracker") || function_exists($module."_actionblock") == false) //FIXME: We need a proper implementation of default module return ""; $content=""; foreach (call_user_func($module."_actionblock") as $title => $values) { $content .= "<b class=\"qawebsite_menu_round\"> <b class=\"qawebsite_menu_round1\"></b> <b class=\"qawebsite_menu_round2\"></b> <b class=\"qawebsite_menu_round3\"></b> <b class=\"qawebsite_menu_round4\"><b></b></b> <b class=\"qawebsite_menu_round5\"><b></b></b></b>"; $content.="<table class=\"qawebsite_menu\"> <tr class=\"qawebsite_menuheader\"><td><b>".$title."</b></td></tr>"; if (is_array($values)) { foreach ($values as $item => $url) if($item != "") $content.="<tr><td class=\"qawebsite_menu_entry\"><a href=\"".$url."\">".t($item)."</a></td></tr>"; } else $content.="<tr><td style=\"padding:2px 5px 2px 5px;\">".$values."</td></tr>"; $content.="</table>"; } return $content; } function qawebsite_block_action2() { $site=QAWebsiteSite::getInstance(); $module=arg(0); if ($site == null || function_exists($module."_actionblock2") == false) return ""; $content=""; $data = call_user_func($module."_actionblock2"); //Include the pre-menu HTML $content = $data["premenu_html"]; //Include the menu foreach ($data["menu"] as $title => $values) { $content .= "<b class=\"qawebsite_menu_round\"> <b class=\"qawebsite_menu_round1\"></b> <b class=\"qawebsite_menu_round2\"></b> <b class=\"qawebsite_menu_round3\"></b> <b class=\"qawebsite_menu_round4\"><b></b></b> <b class=\"qawebsite_menu_round5\"><b></b></b></b>"; $content.="<table class=\"qawebsite_menu\"> <tr class=\"qawebsite_menuheader\"><td><b>".$title."</b></td></tr>"; if (is_array($values)) { foreach ($values as $item => $url) if($item != "") $content.="<tr><td class=\"qawebsite_menu_entry\"><a href=\"".$url."\">".t($item)."</a></td></tr>"; } else $content.="<tr><td style=\"padding:2px 5px 2px 5px;\">".$values."</td></tr>"; $content.="</table>"; } //Include the post-menu HTML $content .= $data["postmenu_html"]; return $content; } function qawebsite_block_navigation() { global $user; $site=QAWebsiteSite::getInstance(); if ($site != null) $title=$site->title; else $title="Ubuntu QA"; //Print the site title $content=" <table width=\"100%\"> <tr> <td style=\"width:1px;\"><span style=\"white-space:nowrap\">"; $content.="<b>" . $title . ":</b>"; $content.=" </span></td> <td align=\"left\"> <table class=\"qawebsite_topbar\"> <tr>"; if ($site != null && $site->getModules() != null ) { foreach ($site->getModules("title ASC") as $module) { if ($module->status == 1) { $content.="<td>"; $absolutepath = (substr($module->path, 0, 4) == "http"); if((($absolutepath == true && strpos(getCurrentURL(), $module->path) === false) || ($absolutepath == false && strpos($_SERVER["REQUEST_URI"], $module->path) === false)) && (arg(0) != $module->path)) $content .= "<a href=\"" . (($absolutepath == true)?"":"/") . $module->path."\">"; else $content .= "<b>"; if ($module->title) $content.=$module->title; else $content.=ucfirst(str_replace("qa","",$module->path)); if((($absolutepath == true && strpos(getCurrentURL(), $module->path) === false) || ($absolutepath == false && strpos($_SERVER["REQUEST_URI"], $module->path) === false)) && (arg(0) != $module->path)) $content .= "</a>"; else $content .= "</b>"; $content.="</td>"; } } } $content.=" </tr> </table> </td> <td align=\"right\"> <table class=\"qawebsite_topbar\"> <tr>"; //Since we are hiding arg(O) in some case, we have to use a dirty hack instead of drupal_get_destination $destination = $_GET['q']; if($destination == arg(0)) $destination = ""; else $destination = substr($_GET['q'], strpos($_GET['q'], "/") + 1); if ($user->uid != 0) { $content.="<td><b>Welcome, " . $user->name . "!</b></td>"; if (user_access("Administrator")) $content.="<td><a href=\"/admin\">Admin</a></td>"; $content.="<td><a href=\"/qawebsite/profile\">My profile</a></td>"; if(arg(0) == "ideatorrent") $content.="<td><a href=\"/logout?destination=" . $destination ."\">Log out</a></td>"; else $content.="<td><a href=\"/logout\">Log out</a></td>"; } elseif (variable_get("user_register",1)) { if(arg(0) == "ideatorrent") $content.="<td><a href=\"/user?destination=" . $destination ."\">Log in</a></td>"; else $content.="<td><a href=\"/user\">Log in</a></td>"; } else $content.="<td>&nbsp;</td>"; $content.=" </tr> </table> </td> </tr> </table>"; return $content; } ?>
pirata-cat/ideatorrent
qawebsite/qawebsite.block.php
PHP
gpl-2.0
6,549
/* * Copyright (C) 2011, 2015 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "SecurityOriginData.h" #include "Document.h" #include "FileSystem.h" #include "Frame.h" #include "SecurityOrigin.h" #include <wtf/text/CString.h> #include <wtf/text/StringBuilder.h> using namespace WebCore; namespace WebCore { SecurityOriginData SecurityOriginData::fromSecurityOrigin(const SecurityOrigin& securityOrigin) { SecurityOriginData securityOriginData; securityOriginData.protocol = securityOrigin.protocol(); securityOriginData.host = securityOrigin.host(); securityOriginData.port = securityOrigin.port(); return securityOriginData; } String SecurityOriginData::toString() const { return makeString(protocol, "://", host, ":", String::number(port.value_or(0))); } SecurityOriginData SecurityOriginData::fromFrame(Frame* frame) { if (!frame) return SecurityOriginData(); Document* document = frame->document(); if (!document) return SecurityOriginData(); return SecurityOriginData::fromSecurityOrigin(document->securityOrigin()); } Ref<SecurityOrigin> SecurityOriginData::securityOrigin() const { return SecurityOrigin::create(protocol.isolatedCopy(), host.isolatedCopy(), port); } static const char separatorCharacter = '_'; String SecurityOriginData::databaseIdentifier() const { // Historically, we've used the following (somewhat non-sensical) string // for the databaseIdentifier of local files. We used to compute this // string because of a bug in how we handled the scheme for file URLs. // Now that we've fixed that bug, we still need to produce this string // to avoid breaking existing persistent state. if (equalIgnoringASCIICase(protocol, "file")) return ASCIILiteral("file__0"); StringBuilder stringBuilder; stringBuilder.append(protocol); stringBuilder.append(separatorCharacter); stringBuilder.append(FileSystem::encodeForFileName(host)); stringBuilder.append(separatorCharacter); stringBuilder.appendNumber(port.value_or(0)); return stringBuilder.toString(); } std::optional<SecurityOriginData> SecurityOriginData::fromDatabaseIdentifier(const String& databaseIdentifier) { // Make sure there's a first separator size_t separator1 = databaseIdentifier.find(separatorCharacter); if (separator1 == notFound) return std::nullopt; // Make sure there's a second separator size_t separator2 = databaseIdentifier.reverseFind(separatorCharacter); if (separator2 == notFound) return std::nullopt; // Ensure there were at least 2 separator characters. Some hostnames on intranets have // underscores in them, so we'll assume that any additional underscores are part of the host. if (separator1 == separator2) return std::nullopt; // Make sure the port section is a valid port number or doesn't exist bool portOkay; int port = databaseIdentifier.right(databaseIdentifier.length() - separator2 - 1).toInt(&portOkay); bool portAbsent = (separator2 == databaseIdentifier.length() - 1); if (!(portOkay || portAbsent)) return std::nullopt; if (port < 0 || port > std::numeric_limits<uint16_t>::max()) return std::nullopt; return SecurityOriginData {databaseIdentifier.substring(0, separator1), databaseIdentifier.substring(separator1 + 1, separator2 - separator1 - 1), static_cast<uint16_t>(port)}; } SecurityOriginData SecurityOriginData::isolatedCopy() const { SecurityOriginData result; result.protocol = protocol.isolatedCopy(); result.host = host.isolatedCopy(); result.port = port; return result; } bool operator==(const SecurityOriginData& a, const SecurityOriginData& b) { if (&a == &b) return true; return a.protocol == b.protocol && a.host == b.host && a.port == b.port; } } // namespace WebCore
teamfx/openjfx-8u-dev-rt
modules/web/src/main/native/Source/WebCore/page/SecurityOriginData.cpp
C++
gpl-2.0
5,213
/** * */ package org.cuatrovientos.struts; import java.util.ArrayList; import java.util.List; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; /** * Main simple sample Struts2 action * @author Pello Altadill * */ public class Main extends ActionSupport implements ModelDriven<Customer>{ private String message; private Customer customer = new Customer(); private CustomerDAO customerDAO = new CustomerDAO(); private List<Customer> customers = new ArrayList<Customer>(); @Override public Customer getModel() { return customer; } /* (non-Javadoc) * @see com.opensymphony.xwork2.ActionSupport#validate() */ @Override public void validate() { // TODO Auto-generated method stub super.validate(); System.out.println("Main > Validate"); } /* (non-Javadoc) * @see com.opensymphony.xwork2.ActionSupport#execute() */ @Override public String execute() throws Exception { System.out.println("Main action> execute"); message = "Main action"; return SUCCESS; } /** * To list all users. * @return String */ public String selectAll() { System.out.println("Main action> Select all"); customers = customerDAO.selectAll(); System.out.println("Main action> Select all DAO done"); message = "Select all"; return SUCCESS; } /** * @return the message */ public String getMessage() { return message; } /** * @param message the message to set */ public void setMessage(String message) { this.message = message; } /** * @return the customer */ public Customer getCustomer() { return customer; } /** * @param customer the customer to set */ public void setCustomer(Customer customer) { this.customer = customer; } /** * @return the customers */ public List<Customer> getCustomers() { return customers; } /** * @param customers the customers to set */ public void setCustomers(List<Customer> customers) { this.customers = customers; } }
pxai/struts2-spring-hibernate
Struts2HibernateTemplate/src/org/cuatrovientos/struts/Main.java
Java
gpl-2.0
2,099
// // LinkedResourceTest.cs - NUnit Test Cases for System.Net.MailAddress.LinkedResource // // Authors: // John Luke (john.luke@gmail.com) // // (C) 2005 John Luke // using NUnit.Framework; using System; using System.IO; using System.Net.Mail; using System.Net.Mime; namespace MonoTests.System.Net.Mail { [TestFixture] public class LinkedResourceTest { LinkedResource lr; [SetUp] public void GetReady () { lr = LinkedResource.CreateLinkedResourceFromString ("test", new ContentType ("text/plain")); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void ArgumentNullException () { string s = null; new LinkedResource (s); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void ArgumentNullException2 () { Stream s = null; new LinkedResource (s); } [Test] public void TransferEncodingTest () { Assert.AreEqual (TransferEncoding.QuotedPrintable, lr.TransferEncoding); } } }
hardvain/mono-compiler
class/System/Test/System.Net.Mail/LinkedResourceTest.cs
C#
gpl-2.0
979
/* * u-boot/include/linux/mtd/nand_ids.h * * Copyright (c) 2000 David Woodhouse <dwmw2@mvhi.com> * Steven J. Hill <sjhill@cotw.com> * * $Id: nand_ids.h,v 1.1 2000/10/13 16:16:26 mdeans Exp $ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Info: * Contains standard defines and IDs for NAND flash devices * * Changelog: * 01-31-2000 DMW Created * 09-18-2000 SJH Moved structure out of the Disk-On-Chip drivers * so it can be used by other NAND flash device * drivers. I also changed the copyright since none * of the original contents of this file are specific * to DoC devices. David can whack me with a baseball * bat later if I did something naughty. * 10-11-2000 SJH Added private NAND flash structure for driver * 2000-10-13 BE Moved out of 'nand.h' - avoids duplication. */ #ifndef __LINUX_MTD_NAND_IDS_H #define __LINUX_MTD_NAND_IDS_H #ifndef CFG_NAND_LEGACY #error This module is for the legacy NAND support #endif static struct nand_flash_dev nand_flash_ids[] = { {"Toshiba TC5816BDC", NAND_MFR_TOSHIBA, 0x64, 21, 1, 2, 0x1000, 0}, {"Toshiba TC5832DC", NAND_MFR_TOSHIBA, 0x6b, 22, 0, 2, 0x2000, 0}, {"Toshiba TH58V128DC", NAND_MFR_TOSHIBA, 0x73, 24, 0, 2, 0x4000, 0}, {"Toshiba TC58256FT/DC", NAND_MFR_TOSHIBA, 0x75, 25, 0, 2, 0x4000, 0}, {"Toshiba TH58512FT", NAND_MFR_TOSHIBA, 0x76, 26, 0, 3, 0x4000, 0}, {"Toshiba TC58V32DC", NAND_MFR_TOSHIBA, 0xe5, 22, 0, 2, 0x2000, 0}, {"Toshiba TC58V64AFT/DC", NAND_MFR_TOSHIBA, 0xe6, 23, 0, 2, 0x2000, 0}, {"Toshiba TC58V16BDC", NAND_MFR_TOSHIBA, 0xea, 21, 1, 2, 0x1000, 0}, {"Toshiba TH58100FT", NAND_MFR_TOSHIBA, 0x79, 27, 0, 3, 0x4000, 0}, {"Samsung KM29N16000", NAND_MFR_SAMSUNG, 0x64, 21, 1, 2, 0x1000, 0}, {"Samsung unknown 4Mb", NAND_MFR_SAMSUNG, 0x6b, 22, 0, 2, 0x2000, 0}, {"Samsung KM29U128T", NAND_MFR_SAMSUNG, 0x73, 24, 0, 2, 0x4000, 0}, {"Samsung KM29U256T", NAND_MFR_SAMSUNG, 0x75, 25, 0, 2, 0x4000, 0}, {"Samsung unknown 64Mb", NAND_MFR_SAMSUNG, 0x76, 26, 0, 3, 0x4000, 0}, {"Samsung KM29W32000", NAND_MFR_SAMSUNG, 0xe3, 22, 0, 2, 0x2000, 0}, {"Samsung unknown 4Mb", NAND_MFR_SAMSUNG, 0xe5, 22, 0, 2, 0x2000, 0}, {"Samsung KM29U64000", NAND_MFR_SAMSUNG, 0xe6, 23, 0, 2, 0x2000, 0}, {"Samsung KM29W16000", NAND_MFR_SAMSUNG, 0xea, 21, 1, 2, 0x1000, 0}, {"Samsung K9F5616Q0C", NAND_MFR_SAMSUNG, 0x45, 25, 0, 2, 0x4000, 1}, {"Samsung K9K1216Q0C", NAND_MFR_SAMSUNG, 0x46, 26, 0, 3, 0x4000, 1}, {"Samsung K9K1208Q0C", NAND_MFR_SAMSUNG, 0x36, 26, 0, 3, 0x4000, 0}, {"Samsung K9F1G08U0M", NAND_MFR_SAMSUNG, 0xf1, 27, 0, 2, 0, 0}, {NULL,} }; #endif /* __LINUX_MTD_NAND_IDS_H */
michalliu/u-boot-1.2.0
include/linux/mtd/nand_ids.h
C
gpl-2.0
2,853
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>dune-istl: Dune::Amg::PropertiesGraph&lt; G, VP, EP, VM, EM &gt; Class Template Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">dune-istl &#160;<span id="projectnumber">2.2.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.1 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="a00360.html">Dune</a></li><li class="navelem"><a class="el" href="a00366.html">Amg</a></li><li class="navelem"><a class="el" href="a00205.html">PropertiesGraph</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#nested-classes">Classes</a> &#124; <a href="#pub-types">Public Types</a> &#124; <a href="#pub-methods">Public Member Functions</a> </div> <div class="headertitle"> <div class="title">Dune::Amg::PropertiesGraph&lt; G, VP, EP, VM, EM &gt; Class Template Reference<div class="ingroups"><a class="el" href="a00372.html">Parallel Algebraic Multigrid</a></div></div> </div> </div><!--header--> <div class="contents"> <p>Attaches properties to the edges and vertices of a graph. <a href="a00205.html#details">More...</a></p> <p><code>#include &lt;<a class="el" href="a00311_source.html">dune/istl/paamg/graph.hh</a>&gt;</code></p> <p><a href="a00705.html">List of all members.</a></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2><a name="nested-classes"></a> Classes</h2></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00113.html">EdgeIteratorT</a></td></tr> <tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00291.html">VertexIteratorT</a></td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2><a name="pub-types"></a> Public Types</h2></td></tr> <tr class="memitem:a6e83e9aa4e797967fa318b86459d0149"><td class="memItemLeft" align="right" valign="top">typedef G&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a6e83e9aa4e797967fa318b86459d0149">Graph</a></td></tr> <tr class="memdesc:a6e83e9aa4e797967fa318b86459d0149"><td class="mdescLeft">&#160;</td><td class="mdescRight">The graph we attach properties to. <a href="#a6e83e9aa4e797967fa318b86459d0149"></a><br/></td></tr> <tr class="memitem:acc1d8f22266e986a90c7ff0a380517d8"><td class="memItemLeft" align="right" valign="top">typedef Graph::VertexDescriptor&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a></td></tr> <tr class="memdesc:acc1d8f22266e986a90c7ff0a380517d8"><td class="mdescLeft">&#160;</td><td class="mdescRight">The vertex descriptor. <a href="#acc1d8f22266e986a90c7ff0a380517d8"></a><br/></td></tr> <tr class="memitem:a1e87b1382ebbf1cab6a77fc3cb3849c6"><td class="memItemLeft" align="right" valign="top">typedef Graph::EdgeDescriptor&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a1e87b1382ebbf1cab6a77fc3cb3849c6">EdgeDescriptor</a></td></tr> <tr class="memdesc:a1e87b1382ebbf1cab6a77fc3cb3849c6"><td class="mdescLeft">&#160;</td><td class="mdescRight">The edge descritor. <a href="#a1e87b1382ebbf1cab6a77fc3cb3849c6"></a><br/></td></tr> <tr class="memitem:aa13e4d256759286236ec4ca19ff73e9e"><td class="memItemLeft" align="right" valign="top">typedef VP&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#aa13e4d256759286236ec4ca19ff73e9e">VertexProperties</a></td></tr> <tr class="memdesc:aa13e4d256759286236ec4ca19ff73e9e"><td class="mdescLeft">&#160;</td><td class="mdescRight">The type of the properties of the vertices. <a href="#aa13e4d256759286236ec4ca19ff73e9e"></a><br/></td></tr> <tr class="memitem:a965116a5ca037414e1c5ae6ab342b8ad"><td class="memItemLeft" align="right" valign="top">typedef VM&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a965116a5ca037414e1c5ae6ab342b8ad">VertexMap</a></td></tr> <tr class="memdesc:a965116a5ca037414e1c5ae6ab342b8ad"><td class="mdescLeft">&#160;</td><td class="mdescRight">The type of the map for converting the VertexDescriptor to std::size_t. <a href="#a965116a5ca037414e1c5ae6ab342b8ad"></a><br/></td></tr> <tr class="memitem:aa8149c0a1d29a2b3c2d7fe2520aecaa2"><td class="memItemLeft" align="right" valign="top">typedef EP&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a></td></tr> <tr class="memdesc:aa8149c0a1d29a2b3c2d7fe2520aecaa2"><td class="mdescLeft">&#160;</td><td class="mdescRight">The type of the properties of the edges;. <a href="#aa8149c0a1d29a2b3c2d7fe2520aecaa2"></a><br/></td></tr> <tr class="memitem:a8179cbefa851d6c0094255659e1930a9"><td class="memItemLeft" align="right" valign="top">typedef EM&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a8179cbefa851d6c0094255659e1930a9">EdgeMap</a></td></tr> <tr class="memdesc:a8179cbefa851d6c0094255659e1930a9"><td class="mdescLeft">&#160;</td><td class="mdescRight">The type of the map for converting the EdgeDescriptor to std::size_t. <a href="#a8179cbefa851d6c0094255659e1930a9"></a><br/></td></tr> <tr class="memitem:a1ce0f1eaa14e3c256b2591bac899f4db"><td class="memItemLeft" align="right" valign="top">typedef <a class="el" href="a00113.html">EdgeIteratorT</a><br class="typebreak"/> &lt; <a class="el" href="a00205.html">PropertiesGraph</a>&lt; <a class="el" href="a00205.html#a6e83e9aa4e797967fa318b86459d0149">Graph</a>, <br class="typebreak"/> <a class="el" href="a00205.html#aa13e4d256759286236ec4ca19ff73e9e">VertexProperties</a>, <br class="typebreak"/> <a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a>, VM, EM &gt; &gt;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a1ce0f1eaa14e3c256b2591bac899f4db">EdgeIterator</a></td></tr> <tr class="memdesc:a1ce0f1eaa14e3c256b2591bac899f4db"><td class="mdescLeft">&#160;</td><td class="mdescRight">The type of the mutable edge iterator. <a href="#a1ce0f1eaa14e3c256b2591bac899f4db"></a><br/></td></tr> <tr class="memitem:a39d89142505784b2c0b19a879307b7a3"><td class="memItemLeft" align="right" valign="top">typedef <a class="el" href="a00113.html">EdgeIteratorT</a>&lt; const <br class="typebreak"/> <a class="el" href="a00205.html">PropertiesGraph</a>&lt; <a class="el" href="a00205.html#a6e83e9aa4e797967fa318b86459d0149">Graph</a>, <br class="typebreak"/> <a class="el" href="a00205.html#aa13e4d256759286236ec4ca19ff73e9e">VertexProperties</a>, <br class="typebreak"/> <a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a>, VM, EM &gt; &gt;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a39d89142505784b2c0b19a879307b7a3">ConstEdgeIterator</a></td></tr> <tr class="memdesc:a39d89142505784b2c0b19a879307b7a3"><td class="mdescLeft">&#160;</td><td class="mdescRight">The type of the constant edge iterator. <a href="#a39d89142505784b2c0b19a879307b7a3"></a><br/></td></tr> <tr class="memitem:a440ff33400310293b351b4172356d411"><td class="memItemLeft" align="right" valign="top">typedef <a class="el" href="a00291.html">VertexIteratorT</a><br class="typebreak"/> &lt; <a class="el" href="a00205.html">PropertiesGraph</a>&lt; <a class="el" href="a00205.html#a6e83e9aa4e797967fa318b86459d0149">Graph</a>, <br class="typebreak"/> <a class="el" href="a00205.html#aa13e4d256759286236ec4ca19ff73e9e">VertexProperties</a>, <br class="typebreak"/> <a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a>, VM, EM &gt; &gt;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a440ff33400310293b351b4172356d411">VertexIterator</a></td></tr> <tr class="memdesc:a440ff33400310293b351b4172356d411"><td class="mdescLeft">&#160;</td><td class="mdescRight">The type of the mutable Vertex iterator. <a href="#a440ff33400310293b351b4172356d411"></a><br/></td></tr> <tr class="memitem:a9bacf6679d481b3550c61128b716087d"><td class="memItemLeft" align="right" valign="top">typedef <a class="el" href="a00291.html">VertexIteratorT</a>&lt; const <br class="typebreak"/> <a class="el" href="a00205.html">PropertiesGraph</a>&lt; <a class="el" href="a00205.html#a6e83e9aa4e797967fa318b86459d0149">Graph</a>, <br class="typebreak"/> <a class="el" href="a00205.html#aa13e4d256759286236ec4ca19ff73e9e">VertexProperties</a>, <br class="typebreak"/> <a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a>, VM, EM &gt; &gt;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a9bacf6679d481b3550c61128b716087d">ConstVertexIterator</a></td></tr> <tr class="memdesc:a9bacf6679d481b3550c61128b716087d"><td class="mdescLeft">&#160;</td><td class="mdescRight">The type of the constant Vertex iterator. <a href="#a9bacf6679d481b3550c61128b716087d"></a><br/></td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:a3aabed15e52736a3db43b61b37457df7"><td class="memItemLeft" align="right" valign="top"><a class="el" href="a00205.html#a1ce0f1eaa14e3c256b2591bac899f4db">EdgeIterator</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a3aabed15e52736a3db43b61b37457df7">beginEdges</a> (const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;source)</td></tr> <tr class="memdesc:a3aabed15e52736a3db43b61b37457df7"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the mutable edge iterator over edges starting at a vertex. <a href="#a3aabed15e52736a3db43b61b37457df7"></a><br/></td></tr> <tr class="memitem:a5d1975f07023660d6983d37e2b318121"><td class="memItemLeft" align="right" valign="top"><a class="el" href="a00205.html#a1ce0f1eaa14e3c256b2591bac899f4db">EdgeIterator</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a5d1975f07023660d6983d37e2b318121">endEdges</a> (const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;source)</td></tr> <tr class="memdesc:a5d1975f07023660d6983d37e2b318121"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the mutable edge iterator over edges starting at a vertex. <a href="#a5d1975f07023660d6983d37e2b318121"></a><br/></td></tr> <tr class="memitem:a69defec024b44484d96373cfbaf8a44f"><td class="memItemLeft" align="right" valign="top"><a class="el" href="a00205.html#a39d89142505784b2c0b19a879307b7a3">ConstEdgeIterator</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a69defec024b44484d96373cfbaf8a44f">beginEdges</a> (const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;source) const </td></tr> <tr class="memdesc:a69defec024b44484d96373cfbaf8a44f"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the mutable edge iterator over edges starting at a vertex. <a href="#a69defec024b44484d96373cfbaf8a44f"></a><br/></td></tr> <tr class="memitem:a9e9557fc3cda72c1bddb3e579eaa966a"><td class="memItemLeft" align="right" valign="top"><a class="el" href="a00205.html#a39d89142505784b2c0b19a879307b7a3">ConstEdgeIterator</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a9e9557fc3cda72c1bddb3e579eaa966a">endEdges</a> (const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;source) const </td></tr> <tr class="memdesc:a9e9557fc3cda72c1bddb3e579eaa966a"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the mutable edge iterator over edges starting at a vertex. <a href="#a9e9557fc3cda72c1bddb3e579eaa966a"></a><br/></td></tr> <tr class="memitem:a9b940011fec22f807ee73158a9f3be69"><td class="memItemLeft" align="right" valign="top"><a class="el" href="a00205.html#a440ff33400310293b351b4172356d411">VertexIterator</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a9b940011fec22f807ee73158a9f3be69">begin</a> ()</td></tr> <tr class="memdesc:a9b940011fec22f807ee73158a9f3be69"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get an iterator over the vertices. <a href="#a9b940011fec22f807ee73158a9f3be69"></a><br/></td></tr> <tr class="memitem:a15a79fe73b50a6c89aff4ad878380e2a"><td class="memItemLeft" align="right" valign="top"><a class="el" href="a00205.html#a440ff33400310293b351b4172356d411">VertexIterator</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a15a79fe73b50a6c89aff4ad878380e2a">end</a> ()</td></tr> <tr class="memdesc:a15a79fe73b50a6c89aff4ad878380e2a"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get an iterator over the vertices. <a href="#a15a79fe73b50a6c89aff4ad878380e2a"></a><br/></td></tr> <tr class="memitem:a8512cd6e027ab17cb01bf1b2069bfd44"><td class="memItemLeft" align="right" valign="top"><a class="el" href="a00205.html#a9bacf6679d481b3550c61128b716087d">ConstVertexIterator</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a8512cd6e027ab17cb01bf1b2069bfd44">begin</a> () const </td></tr> <tr class="memdesc:a8512cd6e027ab17cb01bf1b2069bfd44"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get an iterator over the vertices. <a href="#a8512cd6e027ab17cb01bf1b2069bfd44"></a><br/></td></tr> <tr class="memitem:a3ae871750d0ef4be146ab7b6bb8aef47"><td class="memItemLeft" align="right" valign="top"><a class="el" href="a00205.html#a9bacf6679d481b3550c61128b716087d">ConstVertexIterator</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a3ae871750d0ef4be146ab7b6bb8aef47">end</a> () const </td></tr> <tr class="memdesc:a3ae871750d0ef4be146ab7b6bb8aef47"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get an iterator over the vertices. <a href="#a3ae871750d0ef4be146ab7b6bb8aef47"></a><br/></td></tr> <tr class="memitem:ac7254be6511972118cfcb380377e2ed5"><td class="memItemLeft" align="right" valign="top"><a class="el" href="a00205.html#aa13e4d256759286236ec4ca19ff73e9e">VertexProperties</a> &amp;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#ac7254be6511972118cfcb380377e2ed5">getVertexProperties</a> (const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;vertex)</td></tr> <tr class="memdesc:ac7254be6511972118cfcb380377e2ed5"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the properties associated with a vertex. <a href="#ac7254be6511972118cfcb380377e2ed5"></a><br/></td></tr> <tr class="memitem:a6fa831c8ff39965efc4e05a762621b0d"><td class="memItemLeft" align="right" valign="top">const <a class="el" href="a00205.html#aa13e4d256759286236ec4ca19ff73e9e">VertexProperties</a> &amp;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a6fa831c8ff39965efc4e05a762621b0d">getVertexProperties</a> (const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;vertex) const </td></tr> <tr class="memdesc:a6fa831c8ff39965efc4e05a762621b0d"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the properties associated with a vertex. <a href="#a6fa831c8ff39965efc4e05a762621b0d"></a><br/></td></tr> <tr class="memitem:a48a8f8cb772902fed871a78feac25204"><td class="memItemLeft" align="right" valign="top"><a class="el" href="a00205.html#a1e87b1382ebbf1cab6a77fc3cb3849c6">EdgeDescriptor</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a48a8f8cb772902fed871a78feac25204">findEdge</a> (const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;source, const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;target)</td></tr> <tr class="memdesc:a48a8f8cb772902fed871a78feac25204"><td class="mdescLeft">&#160;</td><td class="mdescRight">Find the descriptor of an edge. <a href="#a48a8f8cb772902fed871a78feac25204"></a><br/></td></tr> <tr class="memitem:ab5f77ab35caef7e63a8c4444621ea929"><td class="memItemLeft" align="right" valign="top"><a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a> &amp;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#ab5f77ab35caef7e63a8c4444621ea929">getEdgeProperties</a> (const <a class="el" href="a00205.html#a1e87b1382ebbf1cab6a77fc3cb3849c6">EdgeDescriptor</a> &amp;edge)</td></tr> <tr class="memdesc:ab5f77ab35caef7e63a8c4444621ea929"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the properties associated with a edge. <a href="#ab5f77ab35caef7e63a8c4444621ea929"></a><br/></td></tr> <tr class="memitem:abf5bbf078d6f05c5ed17dc0d929d97e1"><td class="memItemLeft" align="right" valign="top">const <a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a> &amp;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#abf5bbf078d6f05c5ed17dc0d929d97e1">getEdgeProperties</a> (const <a class="el" href="a00205.html#a1e87b1382ebbf1cab6a77fc3cb3849c6">EdgeDescriptor</a> &amp;edge) const </td></tr> <tr class="memdesc:abf5bbf078d6f05c5ed17dc0d929d97e1"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the properties associated with a edge. <a href="#abf5bbf078d6f05c5ed17dc0d929d97e1"></a><br/></td></tr> <tr class="memitem:aa820797ec2e749b48f448809e818ea62"><td class="memItemLeft" align="right" valign="top"><a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a> &amp;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#aa820797ec2e749b48f448809e818ea62">getEdgeProperties</a> (const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;source, const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;target)</td></tr> <tr class="memdesc:aa820797ec2e749b48f448809e818ea62"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the properties associated with a edge. <a href="#aa820797ec2e749b48f448809e818ea62"></a><br/></td></tr> <tr class="memitem:a8eec13dd8da0a039112ee2ee7cd5cf38"><td class="memItemLeft" align="right" valign="top">const <a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a> &amp;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a8eec13dd8da0a039112ee2ee7cd5cf38">getEdgeProperties</a> (const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;source, const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;target) const </td></tr> <tr class="memdesc:a8eec13dd8da0a039112ee2ee7cd5cf38"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the properties associated with a edge. <a href="#a8eec13dd8da0a039112ee2ee7cd5cf38"></a><br/></td></tr> <tr class="memitem:a5fc4a922d58efed26ed62b998c4b4331"><td class="memItemLeft" align="right" valign="top">const <a class="el" href="a00205.html#a6e83e9aa4e797967fa318b86459d0149">Graph</a> &amp;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a5fc4a922d58efed26ed62b998c4b4331">graph</a> () const </td></tr> <tr class="memdesc:a5fc4a922d58efed26ed62b998c4b4331"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the graph the properties are attached to. <a href="#a5fc4a922d58efed26ed62b998c4b4331"></a><br/></td></tr> <tr class="memitem:ae33788af99559312f3f5d166382ba9d8"><td class="memItemLeft" align="right" valign="top">std::size_t&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#ae33788af99559312f3f5d166382ba9d8">noVertices</a> () const </td></tr> <tr class="memdesc:ae33788af99559312f3f5d166382ba9d8"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the number of vertices in the graph. <a href="#ae33788af99559312f3f5d166382ba9d8"></a><br/></td></tr> <tr class="memitem:a73afd0dcf2d685539e2989800c2f5fbd"><td class="memItemLeft" align="right" valign="top">std::size_t&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a73afd0dcf2d685539e2989800c2f5fbd">noEdges</a> () const </td></tr> <tr class="memdesc:a73afd0dcf2d685539e2989800c2f5fbd"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the number of edges in the graph. <a href="#a73afd0dcf2d685539e2989800c2f5fbd"></a><br/></td></tr> <tr class="memitem:a691070c63473ad3dda572c26a1660054"><td class="memItemLeft" align="right" valign="top"><a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a>&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#a691070c63473ad3dda572c26a1660054">maxVertex</a> () const </td></tr> <tr class="memdesc:a691070c63473ad3dda572c26a1660054"><td class="mdescLeft">&#160;</td><td class="mdescRight">Get the maximal vertex descriptor. <a href="#a691070c63473ad3dda572c26a1660054"></a><br/></td></tr> <tr class="memitem:aeefc7a872cf23aa05a94ef097c0b4343"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="a00205.html#aeefc7a872cf23aa05a94ef097c0b4343">PropertiesGraph</a> (<a class="el" href="a00205.html#a6e83e9aa4e797967fa318b86459d0149">Graph</a> &amp;<a class="el" href="a00205.html#a5fc4a922d58efed26ed62b998c4b4331">graph</a>, const <a class="el" href="a00205.html#a965116a5ca037414e1c5ae6ab342b8ad">VertexMap</a> &amp;vmap=<a class="el" href="a00205.html#a965116a5ca037414e1c5ae6ab342b8ad">VertexMap</a>(), const <a class="el" href="a00205.html#a8179cbefa851d6c0094255659e1930a9">EdgeMap</a> &amp;emap=<a class="el" href="a00205.html#a8179cbefa851d6c0094255659e1930a9">EdgeMap</a>())</td></tr> <tr class="memdesc:aeefc7a872cf23aa05a94ef097c0b4343"><td class="mdescLeft">&#160;</td><td class="mdescRight">Constructor. <a href="#aeefc7a872cf23aa05a94ef097c0b4343"></a><br/></td></tr> </table> <hr/><a name="details" id="details"></a><h2>Detailed Description</h2> <div class="textblock"><h3>template&lt;class G, class VP, class EP, class VM = IdentityMap, class EM = IdentityMap&gt;<br/> class Dune::Amg::PropertiesGraph&lt; G, VP, EP, VM, EM &gt;</h3> <p>Attaches properties to the edges and vertices of a graph. </p> </div><hr/><h2>Member Typedef Documentation</h2> <a class="anchor" id="a39d89142505784b2c0b19a879307b7a3"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">typedef <a class="el" href="a00113.html">EdgeIteratorT</a>&lt;const <a class="el" href="a00205.html">PropertiesGraph</a>&lt;<a class="el" href="a00205.html#a6e83e9aa4e797967fa318b86459d0149">Graph</a>, <a class="el" href="a00205.html#aa13e4d256759286236ec4ca19ff73e9e">VertexProperties</a>, <a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a>,VM,EM&gt; &gt; <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::<a class="el" href="a00205.html#a39d89142505784b2c0b19a879307b7a3">ConstEdgeIterator</a></td> </tr> </table> </div><div class="memdoc"> <p>The type of the constant edge iterator. </p> </div> </div> <a class="anchor" id="a9bacf6679d481b3550c61128b716087d"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">typedef <a class="el" href="a00291.html">VertexIteratorT</a>&lt;const <a class="el" href="a00205.html">PropertiesGraph</a>&lt;<a class="el" href="a00205.html#a6e83e9aa4e797967fa318b86459d0149">Graph</a>, <a class="el" href="a00205.html#aa13e4d256759286236ec4ca19ff73e9e">VertexProperties</a>, <a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a>,VM,EM&gt; &gt; <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::<a class="el" href="a00205.html#a9bacf6679d481b3550c61128b716087d">ConstVertexIterator</a></td> </tr> </table> </div><div class="memdoc"> <p>The type of the constant Vertex iterator. </p> </div> </div> <a class="anchor" id="a1e87b1382ebbf1cab6a77fc3cb3849c6"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">typedef Graph::EdgeDescriptor <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::<a class="el" href="a00205.html#a1e87b1382ebbf1cab6a77fc3cb3849c6">EdgeDescriptor</a></td> </tr> </table> </div><div class="memdoc"> <p>The edge descritor. </p> </div> </div> <a class="anchor" id="a1ce0f1eaa14e3c256b2591bac899f4db"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">typedef <a class="el" href="a00113.html">EdgeIteratorT</a>&lt;<a class="el" href="a00205.html">PropertiesGraph</a>&lt;<a class="el" href="a00205.html#a6e83e9aa4e797967fa318b86459d0149">Graph</a>, <a class="el" href="a00205.html#aa13e4d256759286236ec4ca19ff73e9e">VertexProperties</a>, <a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a>,VM,EM&gt; &gt; <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::<a class="el" href="a00205.html#a1ce0f1eaa14e3c256b2591bac899f4db">EdgeIterator</a></td> </tr> </table> </div><div class="memdoc"> <p>The type of the mutable edge iterator. </p> </div> </div> <a class="anchor" id="a8179cbefa851d6c0094255659e1930a9"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">typedef EM <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::<a class="el" href="a00205.html#a8179cbefa851d6c0094255659e1930a9">EdgeMap</a></td> </tr> </table> </div><div class="memdoc"> <p>The type of the map for converting the EdgeDescriptor to std::size_t. </p> <p>Has to provide the following method: std::size_t operator[](const EdgeDescriptor&amp; vertex)</p> <p>The following condition has to be met: Let e1 and e2 be two edge descriptors, e1 &lt; e2, and map be the index map. Then map[v1]&lt;map[v2] has to hold. </p> </div> </div> <a class="anchor" id="aa8149c0a1d29a2b3c2d7fe2520aecaa2"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">typedef EP <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::<a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a></td> </tr> </table> </div><div class="memdoc"> <p>The type of the properties of the edges;. </p> </div> </div> <a class="anchor" id="a6e83e9aa4e797967fa318b86459d0149"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">typedef G <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::<a class="el" href="a00205.html#a6e83e9aa4e797967fa318b86459d0149">Graph</a></td> </tr> </table> </div><div class="memdoc"> <p>The graph we attach properties to. </p> </div> </div> <a class="anchor" id="acc1d8f22266e986a90c7ff0a380517d8"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">typedef Graph::VertexDescriptor <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::<a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a></td> </tr> </table> </div><div class="memdoc"> <p>The vertex descriptor. </p> </div> </div> <a class="anchor" id="a440ff33400310293b351b4172356d411"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">typedef <a class="el" href="a00291.html">VertexIteratorT</a>&lt;<a class="el" href="a00205.html">PropertiesGraph</a>&lt;<a class="el" href="a00205.html#a6e83e9aa4e797967fa318b86459d0149">Graph</a>, <a class="el" href="a00205.html#aa13e4d256759286236ec4ca19ff73e9e">VertexProperties</a>, <a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a>,VM,EM&gt; &gt; <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::<a class="el" href="a00205.html#a440ff33400310293b351b4172356d411">VertexIterator</a></td> </tr> </table> </div><div class="memdoc"> <p>The type of the mutable Vertex iterator. </p> </div> </div> <a class="anchor" id="a965116a5ca037414e1c5ae6ab342b8ad"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">typedef VM <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::<a class="el" href="a00205.html#a965116a5ca037414e1c5ae6ab342b8ad">VertexMap</a></td> </tr> </table> </div><div class="memdoc"> <p>The type of the map for converting the VertexDescriptor to std::size_t. </p> <p>Has to provide the following method: std::size_t operator[](const VertexDescriptor&amp; vertex)</p> <p>The following condition has to be met: Let v1 and v2 be two vertex descriptors with v1 &lt; v2 and map be the index map. Then map[v1]&lt;map[v2] has to hold. </p> </div> </div> <a class="anchor" id="aa13e4d256759286236ec4ca19ff73e9e"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">typedef VP <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::<a class="el" href="a00205.html#aa13e4d256759286236ec4ca19ff73e9e">VertexProperties</a></td> </tr> </table> </div><div class="memdoc"> <p>The type of the properties of the vertices. </p> </div> </div> <hr/><h2>Constructor &amp; Destructor Documentation</h2> <a class="anchor" id="aeefc7a872cf23aa05a94ef097c0b4343"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::<a class="el" href="a00205.html">PropertiesGraph</a> </td> <td>(</td> <td class="paramtype"><a class="el" href="a00205.html#a6e83e9aa4e797967fa318b86459d0149">Graph</a> &amp;&#160;</td> <td class="paramname"><em>graph</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="a00205.html#a965116a5ca037414e1c5ae6ab342b8ad">VertexMap</a> &amp;&#160;</td> <td class="paramname"><em>vmap</em> = <code><a class="el" href="a00205.html#a965116a5ca037414e1c5ae6ab342b8ad">VertexMap</a>()</code>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="a00205.html#a8179cbefa851d6c0094255659e1930a9">EdgeMap</a> &amp;&#160;</td> <td class="paramname"><em>emap</em> = <code><a class="el" href="a00205.html#a8179cbefa851d6c0094255659e1930a9">EdgeMap</a>()</code>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>Constructor. </p> <dl class="params"><dt>Parameters:</dt><dd> <table class="params"> <tr><td class="paramname">graph</td><td>The graph we attach properties to. </td></tr> <tr><td class="paramname">vmap</td><td>The map of the vertices onto indices. </td></tr> <tr><td class="paramname">emap</td><td>The map of the edges onto indices. </td></tr> </table> </dd> </dl> </div> </div> <hr/><h2>Member Function Documentation</h2> <a class="anchor" id="a9b940011fec22f807ee73158a9f3be69"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00205.html#a440ff33400310293b351b4172356d411">VertexIterator</a> <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::begin </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Get an iterator over the vertices. </p> <dl class="section return"><dt>Returns:</dt><dd>A vertex Iterator positioned at the first vertex. </dd></dl> </div> </div> <a class="anchor" id="a8512cd6e027ab17cb01bf1b2069bfd44"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00205.html#a9bacf6679d481b3550c61128b716087d">ConstVertexIterator</a> <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::begin </td> <td>(</td> <td class="paramname"></td><td>)</td> <td> const</td> </tr> </table> </div><div class="memdoc"> <p>Get an iterator over the vertices. </p> <dl class="section return"><dt>Returns:</dt><dd>A vertex Iterator positioned at the first vertex. </dd></dl> </div> </div> <a class="anchor" id="a3aabed15e52736a3db43b61b37457df7"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00205.html#a1ce0f1eaa14e3c256b2591bac899f4db">EdgeIterator</a> <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::beginEdges </td> <td>(</td> <td class="paramtype">const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;&#160;</td> <td class="paramname"><em>source</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Get the mutable edge iterator over edges starting at a vertex. </p> <dl class="section return"><dt>Returns:</dt><dd>An edge iterator over edges starting at a vertex positioned at the first edge. </dd></dl> </div> </div> <a class="anchor" id="a69defec024b44484d96373cfbaf8a44f"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00205.html#a39d89142505784b2c0b19a879307b7a3">ConstEdgeIterator</a> <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::beginEdges </td> <td>(</td> <td class="paramtype">const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;&#160;</td> <td class="paramname"><em>source</em></td><td>)</td> <td> const</td> </tr> </table> </div><div class="memdoc"> <p>Get the mutable edge iterator over edges starting at a vertex. </p> <dl class="section return"><dt>Returns:</dt><dd>An edge iterator over edges starting at a vertex positioned at the first edge. </dd></dl> </div> </div> <a class="anchor" id="a15a79fe73b50a6c89aff4ad878380e2a"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00205.html#a440ff33400310293b351b4172356d411">VertexIterator</a> <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::end </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Get an iterator over the vertices. </p> <dl class="section return"><dt>Returns:</dt><dd>A vertex Iterator positioned behind the last vertex. </dd></dl> </div> </div> <a class="anchor" id="a3ae871750d0ef4be146ab7b6bb8aef47"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00205.html#a9bacf6679d481b3550c61128b716087d">ConstVertexIterator</a> <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::end </td> <td>(</td> <td class="paramname"></td><td>)</td> <td> const</td> </tr> </table> </div><div class="memdoc"> <p>Get an iterator over the vertices. </p> <dl class="section return"><dt>Returns:</dt><dd>A vertex Iterator positioned behind the last vertex. </dd></dl> </div> </div> <a class="anchor" id="a5d1975f07023660d6983d37e2b318121"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00205.html#a1ce0f1eaa14e3c256b2591bac899f4db">EdgeIterator</a> <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::endEdges </td> <td>(</td> <td class="paramtype">const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;&#160;</td> <td class="paramname"><em>source</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Get the mutable edge iterator over edges starting at a vertex. </p> <dl class="section return"><dt>Returns:</dt><dd>An edge iterator over edges starting at a vertex positioned after the last edge. </dd></dl> </div> </div> <a class="anchor" id="a9e9557fc3cda72c1bddb3e579eaa966a"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00205.html#a39d89142505784b2c0b19a879307b7a3">ConstEdgeIterator</a> <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::endEdges </td> <td>(</td> <td class="paramtype">const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;&#160;</td> <td class="paramname"><em>source</em></td><td>)</td> <td> const</td> </tr> </table> </div><div class="memdoc"> <p>Get the mutable edge iterator over edges starting at a vertex. </p> <dl class="section return"><dt>Returns:</dt><dd>An edge iterator over edges starting at a vertex positioned after the last edge. </dd></dl> </div> </div> <a class="anchor" id="a48a8f8cb772902fed871a78feac25204"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00205.html#a1e87b1382ebbf1cab6a77fc3cb3849c6">EdgeDescriptor</a> <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::findEdge </td> <td>(</td> <td class="paramtype">const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;&#160;</td> <td class="paramname"><em>source</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;&#160;</td> <td class="paramname"><em>target</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Find the descriptor of an edge. </p> <dl class="params"><dt>Parameters:</dt><dd> <table class="params"> <tr><td class="paramname">source</td><td>The source vertex of the edge we search for. </td></tr> <tr><td class="paramname">target</td><td>The target vertex of the edge we search for. </td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns:</dt><dd>The edge we found or numeric_limits&lt;EdgeIterator&gt;::max() if it does not exist. </dd></dl> </div> </div> <a class="anchor" id="ab5f77ab35caef7e63a8c4444621ea929"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a>&amp; <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::getEdgeProperties </td> <td>(</td> <td class="paramtype">const <a class="el" href="a00205.html#a1e87b1382ebbf1cab6a77fc3cb3849c6">EdgeDescriptor</a> &amp;&#160;</td> <td class="paramname"><em>edge</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Get the properties associated with a edge. </p> <dl class="params"><dt>Parameters:</dt><dd> <table class="params"> <tr><td class="paramname">edge</td><td>The descriptor identifying the edge. </td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns:</dt><dd>The properties of the edge. </dd></dl> </div> </div> <a class="anchor" id="abf5bbf078d6f05c5ed17dc0d929d97e1"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">const <a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a>&amp; <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::getEdgeProperties </td> <td>(</td> <td class="paramtype">const <a class="el" href="a00205.html#a1e87b1382ebbf1cab6a77fc3cb3849c6">EdgeDescriptor</a> &amp;&#160;</td> <td class="paramname"><em>edge</em></td><td>)</td> <td> const</td> </tr> </table> </div><div class="memdoc"> <p>Get the properties associated with a edge. </p> <dl class="params"><dt>Parameters:</dt><dd> <table class="params"> <tr><td class="paramname">edge</td><td>The descriptor identifying the edge. </td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns:</dt><dd>The properties of the edge. </dd></dl> </div> </div> <a class="anchor" id="aa820797ec2e749b48f448809e818ea62"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a>&amp; <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::getEdgeProperties </td> <td>(</td> <td class="paramtype">const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;&#160;</td> <td class="paramname"><em>source</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;&#160;</td> <td class="paramname"><em>target</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td> </tr> </table> </div><div class="memdoc"> <p>Get the properties associated with a edge. </p> <dl class="params"><dt>Parameters:</dt><dd> <table class="params"> <tr><td class="paramname">source</td><td>The descriptor identifying the source vertex of the edge. </td></tr> <tr><td class="paramname">target</td><td>The descriptor identifying the target vertex of the edge. </td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns:</dt><dd>The properties of the edge. </dd></dl> </div> </div> <a class="anchor" id="a8eec13dd8da0a039112ee2ee7cd5cf38"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">const <a class="el" href="a00205.html#aa8149c0a1d29a2b3c2d7fe2520aecaa2">EdgeProperties</a>&amp; <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::getEdgeProperties </td> <td>(</td> <td class="paramtype">const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;&#160;</td> <td class="paramname"><em>source</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;&#160;</td> <td class="paramname"><em>target</em>&#160;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td> const</td> </tr> </table> </div><div class="memdoc"> <p>Get the properties associated with a edge. </p> <dl class="params"><dt>Parameters:</dt><dd> <table class="params"> <tr><td class="paramname">source</td><td>The descriptor identifying the source vertex of the edge. </td></tr> <tr><td class="paramname">target</td><td>The descriptor identifying the target vertex of the edge. </td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns:</dt><dd>The properties of the edge. </dd></dl> </div> </div> <a class="anchor" id="ac7254be6511972118cfcb380377e2ed5"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00205.html#aa13e4d256759286236ec4ca19ff73e9e">VertexProperties</a>&amp; <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::getVertexProperties </td> <td>(</td> <td class="paramtype">const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;&#160;</td> <td class="paramname"><em>vertex</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Get the properties associated with a vertex. </p> <dl class="params"><dt>Parameters:</dt><dd> <table class="params"> <tr><td class="paramname">vertex</td><td>The descriptor identifying the vertex. </td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns:</dt><dd>The properties of the vertex. </dd></dl> </div> </div> <a class="anchor" id="a6fa831c8ff39965efc4e05a762621b0d"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">const <a class="el" href="a00205.html#aa13e4d256759286236ec4ca19ff73e9e">VertexProperties</a>&amp; <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::getVertexProperties </td> <td>(</td> <td class="paramtype">const <a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> &amp;&#160;</td> <td class="paramname"><em>vertex</em></td><td>)</td> <td> const</td> </tr> </table> </div><div class="memdoc"> <p>Get the properties associated with a vertex. </p> <dl class="params"><dt>Parameters:</dt><dd> <table class="params"> <tr><td class="paramname">vertex</td><td>The descriptor identifying the vertex. </td></tr> </table> </dd> </dl> <dl class="section return"><dt>Returns:</dt><dd>The properties of the vertex. </dd></dl> </div> </div> <a class="anchor" id="a5fc4a922d58efed26ed62b998c4b4331"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">const <a class="el" href="a00205.html#a6e83e9aa4e797967fa318b86459d0149">Graph</a>&amp; <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::graph </td> <td>(</td> <td class="paramname"></td><td>)</td> <td> const</td> </tr> </table> </div><div class="memdoc"> <p>Get the graph the properties are attached to. </p> <dl class="section return"><dt>Returns:</dt><dd>The underlying graph. </dd></dl> </div> </div> <a class="anchor" id="a691070c63473ad3dda572c26a1660054"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname"><a class="el" href="a00205.html#acc1d8f22266e986a90c7ff0a380517d8">VertexDescriptor</a> <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::maxVertex </td> <td>(</td> <td class="paramname"></td><td>)</td> <td> const</td> </tr> </table> </div><div class="memdoc"> <p>Get the maximal vertex descriptor. </p> <dl class="section return"><dt>Returns:</dt><dd>The minimum value v such that for all vertices w in the graph w&lt;v holds. </dd></dl> </div> </div> <a class="anchor" id="a73afd0dcf2d685539e2989800c2f5fbd"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">std::size_t <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::noEdges </td> <td>(</td> <td class="paramname"></td><td>)</td> <td> const</td> </tr> </table> </div><div class="memdoc"> <p>Get the number of edges in the graph. </p> </div> </div> <a class="anchor" id="ae33788af99559312f3f5d166382ba9d8"></a> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;class G , class VP , class EP , class VM = IdentityMap, class EM = IdentityMap&gt; </div> <table class="memname"> <tr> <td class="memname">std::size_t <a class="el" href="a00205.html">Dune::Amg::PropertiesGraph</a>&lt; G, VP, EP, VM, EM &gt;::noVertices </td> <td>(</td> <td class="paramname"></td><td>)</td> <td> const</td> </tr> </table> </div><div class="memdoc"> <p>Get the number of vertices in the graph. </p> </div> </div> <hr/>The documentation for this class was generated from the following file:<ul> <li><a class="el" href="a00311_source.html">graph.hh</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Jun 4 2012 12:02:19 for dune-istl by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.1 </small></address> </body> </html>
akva2/dune-istl
doc/doxygen/html/a00205.html
HTML
gpl-2.0
55,970
<?php namespace Drupal\content_entity_example\Entity; use Drupal\Core\Entity\EntityStorageInterface; use Drupal\Core\Field\BaseFieldDefinition; use Drupal\Core\Entity\ContentEntityBase; use Drupal\Core\Entity\EntityTypeInterface; use Drupal\content_entity_example\ContactInterface; use Drupal\user\UserInterface; use Drupal\Core\Entity\EntityChangedTrait; /** * Defines the ContentEntityExample entity. * * @ingroup content_entity_example * * This is the main definition of the entity type. From it, an entityType is * derived. The most important properties in this example are listed below. * * id: The unique identifier of this entityType. It follows the pattern * 'moduleName_xyz' to avoid naming conflicts. * * label: Human readable name of the entity type. * * handlers: Handler classes are used for different tasks. You can use * standard handlers provided by D8 or build your own, most probably derived * from the standard class. In detail: * * - view_builder: we use the standard controller to view an instance. It is * called when a route lists an '_entity_view' default for the entityType * (see routing.yml for details. The view can be manipulated by using the * standard drupal tools in the settings. * * - list_builder: We derive our own list builder class from the * entityListBuilder to control the presentation. * If there is a view available for this entity from the views module, it * overrides the list builder. @todo: any view? naming convention? * * - form: We derive our own forms to add functionality like additional fields, * redirects etc. These forms are called when the routing list an * '_entity_form' default for the entityType. Depending on the suffix * (.add/.edit/.delete) in the route, the correct form is called. * * - access: Our own accessController where we determine access rights based on * permissions. * * More properties: * * - base_table: Define the name of the table used to store the data. Make sure * it is unique. The schema is automatically determined from the * BaseFieldDefinitions below. The table is automatically created during * installation. * * - fieldable: Can additional fields be added to the entity via the GUI? * Analog to content types. * * - entity_keys: How to access the fields. Analog to 'nid' or 'uid'. * * - links: Provide links to do standard tasks. The 'edit-form' and * 'delete-form' links are added to the list built by the * entityListController. They will show up as action buttons in an additional * column. * * There are many more properties to be used in an entity type definition. For * a complete overview, please refer to the '\Drupal\Core\Entity\EntityType' * class definition. * * The following construct is the actual definition of the entity type which * is read and cached. Don't forget to clear cache after changes. * * @ContentEntityType( * id = "content_entity_example_contact", * label = @Translation("Contact entity"), * handlers = { * "view_builder" = "Drupal\Core\Entity\EntityViewBuilder", * "list_builder" = "Drupal\content_entity_example\Entity\Controller\ContactListBuilder", * "form" = { * "add" = "Drupal\content_entity_example\Form\ContactForm", * "edit" = "Drupal\content_entity_example\Form\ContactForm", * "delete" = "Drupal\content_entity_example\Form\ContactDeleteForm", * }, * "access" = "Drupal\content_entity_example\ContactAccessControlHandler", * }, * list_cache_contexts = { "user" }, * base_table = "contact", * admin_permission = "administer content_entity_example entity", * entity_keys = { * "id" = "id", * "label" = "name", * "uuid" = "uuid" * }, * links = { * "canonical" = "/content_entity_example_contact/{content_entity_example_contact}", * "edit-form" = "/content_entity_example_contact/{content_entity_example_contact}/edit", * "delete-form" = "/contact/{content_entity_example_contact}/delete", * "collection" = "/content_entity_example_contact/list" * }, * field_ui_base_route = "content_entity_example.contact_settings", * ) * * The 'links' above are defined by their path. For core to find the * corresponding route, the route name must follow the correct pattern: * * entity.<entity-name>.<link-name> (replace dashes with underscores) * Example: 'entity.content_entity_example_contact.canonical' * * See routing file above for the corresponding implementation * * The Contact class defines methods and fields for the contact entity. * * Being derived from the ContentEntityBase class, we can override the methods * we want. In our case we want to provide access to the standard fields about * creation and changed time stamps. * * Our interface (see ContactInterface) also exposes the EntityOwnerInterface. * This allows us to provide methods for setting and providing ownership * information. * * The most important part is the definitions of the field properties for this * entity type. These are of the same type as fields added through the GUI, but * they can by changed in code. In the definition we can define if the user with * the rights privileges can influence the presentation (view, edit) of each * field. * * The class also uses the EntityChangedTrait trait which allows it to record * timestamps of save operations. */ class Contact extends ContentEntityBase implements ContactInterface { use EntityChangedTrait; /** * {@inheritdoc} * * When a new entity instance is added, set the user_id entity reference to * the current user as the creator of the instance. */ public static function preCreate(EntityStorageInterface $storage_controller, array &$values) { parent::preCreate($storage_controller, $values); $values += array( 'user_id' => \Drupal::currentUser()->id(), ); } /** * {@inheritdoc} */ public function getCreatedTime() { return $this->get('created')->value; } /** * {@inheritdoc} */ public function getChangedTime() { return $this->get('changed')->value; } /** * {@inheritdoc} */ public function getOwner() { return $this->get('user_id')->entity; } /** * {@inheritdoc} */ public function getOwnerId() { return $this->get('user_id')->target_id; } /** * {@inheritdoc} */ public function setOwnerId($uid) { $this->set('user_id', $uid); return $this; } /** * {@inheritdoc} */ public function setOwner(UserInterface $account) { $this->set('user_id', $account->id()); return $this; } /** * {@inheritdoc} * * Define the field properties here. * * Field name, type and size determine the table structure. * * In addition, we can define how the field and its content can be manipulated * in the GUI. The behaviour of the widgets used can be determined here. */ public static function baseFieldDefinitions(EntityTypeInterface $entity_type) { // Standard field, used as unique if primary index. $fields['id'] = BaseFieldDefinition::create('integer') ->setLabel(t('ID')) ->setDescription(t('The ID of the Contact entity.')) ->setReadOnly(TRUE); // Standard field, unique outside of the scope of the current project. $fields['uuid'] = BaseFieldDefinition::create('uuid') ->setLabel(t('UUID')) ->setDescription(t('The UUID of the Contact entity.')) ->setReadOnly(TRUE); // Name field for the contact. // We set display options for the view as well as the form. // Users with correct privileges can change the view and edit configuration. $fields['name'] = BaseFieldDefinition::create('string') ->setLabel(t('Name')) ->setDescription(t('The name of the Contact entity.')) ->setSettings(array( 'default_value' => '', 'max_length' => 255, 'text_processing' => 0, )) ->setDisplayOptions('view', array( 'label' => 'above', 'type' => 'string', 'weight' => -6, )) ->setDisplayOptions('form', array( 'type' => 'string_textfield', 'weight' => -6, )) ->setDisplayConfigurable('form', TRUE) ->setDisplayConfigurable('view', TRUE); $fields['first_name'] = BaseFieldDefinition::create('string') ->setLabel(t('First Name')) ->setDescription(t('The first name of the Contact entity.')) ->setSettings(array( 'default_value' => '', 'max_length' => 255, 'text_processing' => 0, )) ->setDisplayOptions('view', array( 'label' => 'above', 'type' => 'string', 'weight' => -5, )) ->setDisplayOptions('form', array( 'type' => 'string_textfield', 'weight' => -5, )) ->setDisplayConfigurable('form', TRUE) ->setDisplayConfigurable('view', TRUE); // Gender field for the contact. // ListTextType with a drop down menu widget. // The values shown in the menu are 'male' and 'female'. // In the view the field content is shown as string. // In the form the choices are presented as options list. $fields['gender'] = BaseFieldDefinition::create('list_string') ->setLabel(t('Gender')) ->setDescription(t('The gender of the Contact entity.')) ->setSettings(array( 'allowed_values' => array( 'female' => 'female', 'male' => 'male', ), )) ->setDisplayOptions('view', array( 'label' => 'above', 'type' => 'string', 'weight' => -4, )) ->setDisplayOptions('form', array( 'type' => 'options_select', 'weight' => -4, )) ->setDisplayConfigurable('form', TRUE) ->setDisplayConfigurable('view', TRUE); // Owner field of the contact. // Entity reference field, holds the reference to the user object. // The view shows the user name field of the user. // The form presents a auto complete field for the user name. $fields['user_id'] = BaseFieldDefinition::create('entity_reference') ->setLabel(t('User Name')) ->setDescription(t('The Name of the associated user.')) ->setSetting('target_type', 'user') ->setSetting('handler', 'default') ->setDisplayOptions('view', array( 'label' => 'above', 'type' => 'author', 'weight' => -3, )) ->setDisplayOptions('form', array( 'type' => 'entity_reference_autocomplete', 'settings' => array( 'match_operator' => 'CONTAINS', 'size' => 60, 'placeholder' => '', ), 'weight' => -3, )) ->setDisplayConfigurable('form', TRUE) ->setDisplayConfigurable('view', TRUE); $fields['langcode'] = BaseFieldDefinition::create('language') ->setLabel(t('Language code')) ->setDescription(t('The language code of ContentEntityExample entity.')); $fields['created'] = BaseFieldDefinition::create('created') ->setLabel(t('Created')) ->setDescription(t('The time that the entity was created.')); $fields['changed'] = BaseFieldDefinition::create('changed') ->setLabel(t('Changed')) ->setDescription(t('The time that the entity was last edited.')); return $fields; } }
evasmidt/allsafe-drupal
modules/content_entity_example/src/Entity/Contact.php
PHP
gpl-2.0
11,324
<?php /* A simple RESTful webservices base class Use this as a template and build upon it */ class SimpleRest { private $httpVersion = "HTTP/1.1"; public function setHttpHeaders($statusCode){ $statusMessage = $this -> getHttpStatusMessage($statusCode); header($this->httpVersion. " ". $statusCode ." ". $statusMessage); header("Content-Type:". 'application/json'); // header("Access-Control-Allow-Origin: *"); } public function getHttpStatusMessage($statusCode){ $httpStatus = array( 100 => 'Continue', 101 => 'Switching Protocols', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => '(Unused)', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported'); return ($httpStatus[$statusCode]) ? $httpStatus[$statusCode] : $status[500]; } } ?>
HansellKopp/Deutsch-NotePad
php-backend/SimpleRest.php
PHP
gpl-2.0
1,834
#!/usr/bin/env python # -*- coding: utf-8 -*- """ [tests/stdlib/test_help.py] Test the help command. """ import unittest #import os #from ergonomica import ergo, ENV class TestHelp(unittest.TestCase): """Tests the 'help' command.""" def test_list_commands(self): """ Tests listing all commands using the 'help commands' command. """
ergonomica/ergonomica
tests/stdlib/test_help.py
Python
gpl-2.0
375
package control; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.Objects; import javax.annotation.Resource; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import java.util.Collection; import javax.enterprise.context.RequestScoped; import javax.faces.bean.ManagedProperty; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.UserTransaction; import model.*; @ManagedBean @ViewScoped public class ChatBean implements Serializable { @PersistenceContext private EntityManager em; @Resource private UserTransaction ut; @ManagedProperty(value="#{message}") private String message; @ManagedProperty(value="#{u1}") private Utilisateur u1 ; @ManagedProperty(value="#{u2}") private Utilisateur u2 ; private Date lastUpdate; /** * Permet de gérer la page de chat. Lors de l'arrivée sur cette page, si la liste d'attente n'éxiste aps elle est crée. */ public ChatBean() { ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); if(servletContext.getAttribute("listeUtilisateursAttente") == null){ servletContext.setAttribute("listeUtilisateursAttente", new ArrayList<Utilisateur>()); } lastUpdate = new Date(0); } public Utilisateur getU1() { return u1; } public void setU1(Utilisateur u1) { this.u1 = u1; } public Utilisateur getU2() { return u2; } public void setU2(Utilisateur u2) { this.u2 = u2; } public Date getLastUpdate(){ return lastUpdate; } public void setLastUpdate(Date lastUpdate){ this.lastUpdate = lastUpdate; } public String getCorrespondant(){ SessionChat c = getChat() ; if (c == null) return null ; if (c.getEstDemarree()) { if (c.getUtilisateur1().equals(getUtilisateurSession ())) return c.getUtilisateur2().getPseudo(); else return c.getUtilisateur1().getPseudo(); } return ""; } /** * Cette fonction permet de lancer le chat en mode aleatoire * @return * @throws Exception */ public String chatAleatoire() throws Exception { ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); ArrayList<Utilisateur> listeAttente = (ArrayList<Utilisateur>)servletContext.getAttribute("listeUtilisateursAttente") ; u1 = getUtilisateurSession() ; u2 = null ; //Normalement cela ne doit jamais ce produire if (u1 == null) return "index.xhtml" ; //Tout les chats de l'utilisateur doivent être fermé u1.closeAllChat () ; //on trouve un copain, si il y en a pas l'utilisateur attend u2 = obtenirChatteur (u1) ; if (u2 == null) { if (!listeAttente.contains(u1)) listeAttente.add(u1); return "profil.xhtml" ; } // on récupère ou on crée le chat obtenirChat (u1,u2) ; return "chat.xhtml" ; } public String chatCopain(Utilisateur ami) throws Exception { u1 = getUtilisateurSession() ; if ((u1 == null) || (ami == null)) return "profil.xthtml" ; //si il est dans la liste d'attente le sortir, pareil pour ami removeFromWaitList (u1) ; removeFromWaitList (ami) ; //Tout les chats de l'utilisateur doivent être fermé u1.closeAllChat () ; //si on est deja dans un chat ! if (u1.getSessionChatDemarree()!= null) return "chat.xhtml" ; obtenirChat(u1, ami) ; u2 = ami ; return "chat.xhtml" ; } public Utilisateur getUtilisateurSession () { FacesContext context = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) context.getExternalContext().getSession(false); Utilisateur u = (Utilisateur)em.find(Utilisateur.class,(String)session.getAttribute("pseudoUtilisateur")) ; return u ; } public SessionChat getChat() { //on recupere le chat de l'utilisateur en session Utilisateur u = getUtilisateurSession() ; return u.getSessionChatDemarree() ; } public ArrayList<Utilisateur> getListeUtilisateurAttente () { ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); return (ArrayList<Utilisateur>) servletContext.getAttribute("listeUtilisateursAttente") ; } public String getMessage () { return "" ; } public void setMessage (String message) { this.message = message ; } public void envoyerMessage () throws Exception { if (!message.isEmpty()) { this.ut.begin(); Utilisateur u = getUtilisateurSession() ; SessionChat chat = getChat(); MessageChat msg = new MessageChat(message,u); this.em.persist(msg); chat.getMessages().add(msg); this.em.merge(chat); this.ut.commit(); } //return "chat.xhtml" ; } /*public void envoyerMessage(ActionEvent evt) throws Exception { this.ut.begin(); Utilisateur u = getUtilisateurSession() ; SessionChat chat = getChat(); MessageChat msg = new MessageChat(message,u); this.em.persist(msg); chat.getMessages().add(msg); this.em.merge(chat); this.ut.commit(); }*/ private Utilisateur obtenirChatteur(Utilisateur u1) { ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); ArrayList<Utilisateur> listeAttente = (ArrayList<Utilisateur>) servletContext.getAttribute("listeUtilisateursAttente") ; if (listeAttente.isEmpty()) return null ; if (u1.equals(listeAttente.get(0))) { if (u1.equals(listeAttente.get(listeAttente.size()-1))) return null ; return listeAttente.remove(listeAttente.size()-1) ; } return listeAttente.remove(0) ; } private SessionChat obtenirChat(Utilisateur u1, Utilisateur u2) throws NotSupportedException, SystemException, RollbackException, HeuristicMixedException, HeuristicRollbackException { SessionChat c = u1.recupererChat (u2) ; this.ut.begin(); if (c == null) { c = new SessionChat (u1,u2) ; c.setEstDemarree(true); this.em.persist(c); u1.ajouterChat(c); this.em.merge(u1); u2.ajouterChat(c); this.em.merge(u2); } c.setEstDemarree(true); this.em.merge(c); this.ut.commit(); return u1.getSessionChatDemarree(); } private void removeFromWaitList(Utilisateur u1) { ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); ArrayList<Utilisateur> listeAttente = (ArrayList<Utilisateur>)servletContext.getAttribute("listeUtilisateursAttente") ; listeAttente.remove(u1); } /** * Cette methode est appellée lorque le client click sur quitter le chat afin de fermer la session chat en cours */ public void quitterChat() throws Exception{ this.ut.begin(); Utilisateur u= getUtilisateurSession() ; u.getSessionChatDemarree().setEstDemarree(false); this.em.merge(u); this.ut.commit(); } /* les 3 prochaines methode sont appelé quand on subit un quittage !! il faut gérerl'ajout à la liste d'amis grace a u1 et u2 stocké dans le bean qui permettent de retrouver le chat */ public String ajouterEtContinuer () throws Exception { return chatAleatoire() ; } public String passerEtContinuer () throws Exception { return chatAleatoire() ; } public String bloquerEtContinuer () throws Exception { return chatAleatoire() ; } /* on quitte et on part */ public String ajouterEtQuitter () throws Exception { quitterChat(); return "profil.xhtml" ; } public String rienEtQuitter () throws Exception { quitterChat(); return "profil.xhtml" ; } public String bloquerEtQuitter () throws Exception { quitterChat(); return "profil.xhtml" ; } /* on fait suivant ! */ public String ajouterEtSuivantDemande () throws Exception { quitterChat(); return chatAleatoire() ; } public String rienEtSuivantDemande () throws Exception { quitterChat(); return chatAleatoire() ; } public String bloquerEtSuivantDemande () throws Exception { quitterChat(); return chatAleatoire() ; } //quand on ets ami et qu'on subit un quittage public String sortirDuChat () { return "profil.xhtml" ; } public boolean getEstUnChatCopain () { // on remplit les utilisateur u1 = getUtilisateurSession() ; SessionChat c = u1.getSessionChatDemarree() ; if (c != null) { if (c.getUtilisateur1().equals(u1)) { u2 = c.getUtilisateur2(); } else { u2 = c.getUtilisateur1() ; } } if ((u1 == null) || (u2 == null)) { return false ; } return u1.estAmisAvec(u2) ; } public boolean getEstUnChatAlea () { System.out.println (getEstUnChatCopain()) ; return !getEstUnChatCopain() ; } }
matthew-morgan/PPIL
src/java/control/ChatBean.java
Java
gpl-2.0
10,922
<?php /* * You may not change or alter any portion of this comment or credits * of supporting developers from this source code or any supporting source code * which is considered copyrighted (c) material of the original comment or credit authors. * * 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. */ /** * @copyright XOOPS Project https://xoops.org/ * @license GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html) * @package * @since * @author XOOPS Development Team */ require dirname(__DIR__, 2) . '/mainfile.php'; $moduleDirName = basename(__DIR__); require XOOPS_ROOT_PATH . '/footer.php';
mambax7/uhq_radio
footer.php
PHP
gpl-2.0
773
#!/usr/bin/env php <? // Copyright(c)2005-(c)2015 Internet Archive. Software license GPL version 2. /* require_once '/petabox/setup.inc'; */ require_once '/home/ximm/petabox/setup.inc'; // must use schema in petabox/etc/solr/conf with our fields!!! require_once 'Console/CommandLine.php'; // um, part of PEAR require_once '/home/ximm/projects/search/listerine/ESIndexer.inc'; require_once '/home/ximm/projects/search/listerine/Listerine.inc'; // Elasticsearch linedump indexer // // Read a line dump from collections graph processing, post the item with provided calculated fields to an ES index // relies on ESIndexer.php::get_custom_collections() // cannabalized from se_indexer.php, with queue interactions stripped out and replaced by read of JSON linedump // NOTE // this indexzer is intended for bootstrapping an index only; queue must be used once index is up // TODO: // if --postlines exceeds available lines, process never quits // abstract line parsing, so can be used with any line-dump based single-shot indexing task Util::memory_limit('4000M'); // may get big! $GLOBALS['fatal-exceptions']=1; const QLIMIT = 40000; $pause_before_exit_seconds = 0; // Catch fatal errors (such as (null)->fncall() within a library.) // // In our case, we just want to pause before exiting (if --pause was // supplied) so that upstart doesn't give up on us. register_shutdown_function("fatal_handler"); function fatal_handler() { global $pause_before_exit_seconds; sleep( $pause_before_exit_seconds * (1 + (mt_rand() / mt_getrandmax()) * .5)); } class IndexerHelper { const ITEMS_LINE_DUMP = "/1/ximm_tmp/cut/linedump-cleaned_combined.json"; const POST_BATCH_SIZE = 1000; public function __construct( $dump_path=false, $ptr=false, $post=true ) { $this->IGNORES = ( // tasks that are not tasks for *actual* items (eg: rescue tasks): "'".join("','",Util::cmd("cd /petabox/sw/work && fgrep realItem *.php | fgrep -v fixer.php | perl -ne 'print if m/realItem\s*=\s*false/' | cut -f1 -d: | sort -u", "ARRAY","QUIET"))."'". // we dont update SE for bup.php tasks ",'bup.php'"); /* error_log("LIST OF TASKS TO IGNORE: $this->IGNORES"); */ $this->post_doc = $post; if ($dump_path) { $this->spl_file_object = new SplFileObject( $dump_path ); $this->spl_file_ptr_path = $dump_path . ".ptr"; } else { $this->spl_file_object = new SplFileObject( self::ITEMS_LINE_DUMP ); $this->spl_file_ptr_path = self::ITEMS_LINE_DUMP . ".ptr"; } $this->stop_file_name = dirname( $dump_path ) . '/' . 'ES_INDEXER_STOP' ; $this->pause_file_name = dirname( $dump_path ) . '/' . 'ES_INDEXER_PAUSE' ; $this->sleep_file_name = dirname( $dump_path ) . '/' . 'ES_INDEXER_SLEEP' ; $this->intrasleep_file_name = dirname( $dump_path ) . '/' . 'ES_INDEXER_INTRASLEEP' ; if ($ptr) { $this->spl_file_ptr = $ptr; } else { $this->spl_file_ptr = $this->read_ptr(); } } private function cache_ptr() { echo "Updating $this->spl_file_ptr_path\n"; $ptr_str = strval( $this->spl_file_ptr ) . "\n"; file_put_contents( $this->spl_file_ptr_path, $ptr_str ); } private function read_ptr() { if (file_exists( $this->spl_file_ptr_path )) { $ptr_str = trim( file_get_contents( $this->spl_file_ptr_path )); return intval( $ptr_str ); } else { return 0; } } // Pull $total_to_post items from file and index them in $batch_size batches // Optionally sleep between batches if magic control file appears in source file directory // Pause or stop indexing if magic control files appear in source file directory public function post_lines( $total_to_post, $batch_size = 1001 ) { $posted_so_far = 0; $stop_now = FALSE; $intra_request_sleep = 5000; if ( file_exists( $this->intrasleep_file_name ) ) { try { $sleep_contents = file_get_contents( $this->intrasleep_file_name ); if ( isset( $sleep_contents ) && ( strlen( $sleep_contents ) > 0 ) ) $intra_request_sleep = min( 1000000, intval( $sleep_contents )); } catch (Exception $e) { ; } } while (( $posted_so_far < $total_to_post ) && ( $stop_now == FALSE ) ) { $left_to_post = $total_to_post - $posted_so_far; $to_post_this_time = min( $batch_size, $left_to_post ); if (self::post_batch( $to_post_this_time, $intra_request_sleep )) $posted_so_far += $to_post_this_time; while ( file_exists( $this->pause_file_name ) && (! file_exists( $this->stop_file_name )) ) sleep ( 5 ); if ( file_exists( $this->sleep_file_name ) && (! file_exists( $this->stop_file_name )) ) { $sleep_secs = 1; try { $sleep_contents = file_get_contents( $this->sleep_file_name ); if ( isset( $sleep_contents ) && ( strlen( $sleep_contents ) > 0 ) ) $sleep_secs = min( 120, intval( $sleep_contents )); } catch (Exception $e) { ; } sleep( $sleep_secs ); } $stop_now = file_exists( $this->stop_file_name ); } $success = ( $posted_so_far >= $total_to_post ); return $success; } // Pull $batch_size items from file and index them. private function post_batch( $batch_size, $intra_request_sleep=5000 ) { $updated = false; $ids = Array(); $line_hints = Array(); $this->spl_file_object->seek( $this->spl_file_ptr ); if (!$this->spl_file_object->eof()) { $hint_ln = $this->spl_file_object->current(); $this->spl_file_ptr += 1; if ( (! isset($hint_ln)) || $hint_ln=='' ) continue; $left = max( 0, $batch_size - 1); $hla = json_decode( $hint_ln, TRUE ); if ( isset( $hla ) ) { if (isset($hla['id'])) { $ids[] = $hla['id']; $line_hints[ $hla['id'] ] = trim( $hint_ln ); } } else { $maybe = trim( $hint_ln ); if ( isset( $maybe ) && ( $maybe !='' ) ) $ids[] = $maybe; } while (!$this->spl_file_object->eof() && ($left > 0) ) { $hint_ln = $this->spl_file_object->fgets(); $this->spl_file_ptr += 1; if ( (! isset($hint_ln)) || $hint_ln=='' ) continue; $left -= 1; $hla = json_decode( $hint_ln, TRUE ); if ( isset( $hla ) ) { if (isset($hla['id'])) { $ids[] = $hla['id']; $line_hints[ $hla['id'] ] = trim( $hint_ln ); } } else { $maybe = trim( $hint_ln ); if ( isset( $maybe ) && ( $maybe !='' ) ) $ids[] = $maybe; } } } if ( count( $ids ) ){ $updated = true; error_log('updating for '.count($ids).' ids'); } $finished = array(); $notes = array(); foreach ( $ids as $id ) { $success = false; try { if ( isset( $line_hints[$id] ) ) $ln_hint = $line_hints[ $id ]; else $ln_hint = false; $msg = ESIndexer::id2se( $id, true, // post if accumulated lines =... $batch_size, $success, $this->post_doc, $ln_hint ); usleep( $intra_request_sleep ); } catch (Exception $e) { $msg = $e->getMessage(); $success = false; } error_log("$id\t$msg"); if ($success) $finished[] = $id; else $notes[$id] = $msg; } $this->cache_ptr(); $post_errors = array(); ESIndexer::post_flush($post_errors); // might fail (with exception) $finished = array_diff($finished, array_keys($post_errors)); $notes = $notes + $post_errors; ESIndexer::flush_deletes(); return $updated; } } function main() { $parser = new Console_CommandLine(); $parser->description = "Post from static list to ES.\n\n" . "To re-queue unfinished tasks from the end of the retry queue, do:\n" . "es_indexer.php --list-failures | cut -f-1 | tail -25 | es_indexer.php --ids=- --queue=0 --priority=5 --finish"; $parser->add_version_option = false; $parser->name = 'es_indexer.php'; $parser->addOption('dryrun', array( 'long_name' => '--dryrun', 'description' => 'create a solr doc for the given id, and dump to stdout', 'action' => 'StoreTrue' )); $parser->addOption('postlines', array( 'long_name' => '--postlines', 'help_name' => 'N', 'description' => 'read up to N lines from dumpfile and index them', 'action' => 'StoreInt' )); $parser->addOption('ldpath', array( 'long_name' => '--ldpath', 'help_name' => 'PATH', 'description' => 'path for dump file', 'action' => 'StoreString', )); $parser->addOption('ldptr', array( 'long_name' => '--ldptr', 'help_name' => 'N', 'description' => 'line pointer for dump file', 'action' => 'StoreInt', )); $parser->addOption('count', array( 'long_name' => '--count', 'help_name' => 'N', 'description' => 'lines N to post', 'action' => 'StoreInt', 'default' => 5 )); $parser->addOption('pause', array( 'long_name' => '--pause', 'help_name' => 'N', 'description' => 'pause N seconds before exiting (+ 50% jitter)', 'action' => 'StoreInt', 'default' => 0 )); $parser->addOption('loop', array( 'long_name' => '--loop', 'description' => 'loop if lines remain', 'action' => 'StoreTrue' )); try { $c = $parser->parse(); } catch (Exception $e) { $parser->displayError($e->getMessage()); } $sawopt = false; foreach(array_values($c->options) as $val){ if ($val !== null) $sawopt = true; } if (!$sawopt) $parser->displayUsage(); Util::must_run_on('bigsearch0'); if ($c->options['pause']) { global $pause_before_exit_seconds; $pause_before_exit_seconds = max(1,$c->options['pause']); } if ( $c->options['ldpath'] ) { if ( file_exists($c->options['ldpath']) == FALSE ) { error_log( "Source file does not exist " . $c->options['ldpath'] ); } else { $dryrun = isset($c->options['dryrun']); if ( isset( $c->options['ldptr'] )) $ptr = $c->options['ldptr']; else $ptr = false; $indexer = new IndexerHelper( $c->options['ldpath'], $ptr, $dryrun ); $lines_posted = false; while (true) { if ($c->options['postlines']) $to_post = intval( $c->options['postlines'] ); $lines_posted = $indexer->post_lines( $to_post, IndexerHelper::POST_BATCH_SIZE ); if (!($lines_posted) || !$c->options['loop']) break; } // we don't explicitly pause here, as fatal_handler does it for us. } } exit(0); } main(); // Working examples of using an external command.... // TODO: UPDATE FOR THIS VERSION // php /home/ximm/projects/search/es_indexer.php --postlines=150000 --ldpath=/1/ximm_tmp/cut/linedump-cleaned_combined.json &>/1/ximm_tmp/cut/logs/linedump-cleaned_combined.log // php /home/ximm/projects/search/es_indexer.php --postlines=1 --ldpath=/1/ximm_tmp/cut/donow &>/1/ximm_tmp/cut/logs/donow.log /* (~/petabox/sw/bin/es_indexer.php --unqueue=500 --external-command='python /home/mccabe/s/archive/search/update_beta.py -' --loop) &> unq4& */ /* while `true`; do ~/petabox/sw/bin/es_indexer.php --queue=1000 --unqueue=500 --loop --external-command='python /home/mccabe/s/archive/search/update_beta.py -' --pause=10; done */
ximm/listerine
es_indexer.php
PHP
gpl-2.0
12,421
<?php /** * @package phpBB to WP connector * @version $Id: 1.5.0 * @copyright (c) 2013-2014 danielx64.com * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @author Danielx64 * @based off: phpBB 3.0.9 :: BRIDGE phpBB & WordPress -> WordPress root/wp-content/themes/phpBB/includes * @orginal author: leviatan21 - http://www.phpbb.com/community/memberlist.php?mode=viewprofile&u=345763 * */ /** * @ignore */ if (!defined('IN_WP_PHPBB_BRIDGE')) { exit; } class bridge { /** * Bridge configuration member * * @var bridge_config */ public static $config; /** * Reads a configuration file with an assoc. config array * * @param boolean $force force to update WP settings */ public static function set_config($force = false) { global $wp_phpbb_bridge_config; // Some default options $propress_options = get_option( 'phpbbtowp' ); $phpbb_root_path = $propress_options['phpbb_path']; // bypass our own settings $path = $phpbb_root_path; // Measn the plugin is not enabbled yet! // or the plugin is not set yet! // Check against WP settings $wp_phpbb_bridge_settings = $propress_options; // If checks fails, display the proper message if (defined('WP_ADMIN') && WP_ADMIN == true) { define('PHPBB_ROOT_PATH', '../' . $path); } else { define('PHPBB_ROOT_PATH', $path); } self::$config = $wp_phpbb_bridge_config; // Make that phpBB itself understands out paths global $phpbb_root_path, $phpEx; $propress_options = get_option( 'phpbbtowp' ); $phpbb_root_path = $propress_options['phpbb_path']; $phpEx = PHP_EXT; } /** * Check the Bridge settings... * * @param (bolean) $active * @param (string) $path * @param (string) $theme * @return (array) */ public static function wp_phpbb_bridge_check($active = false, $path = '../phpBB/', $theme = '') { $error = false; $message = ''; $action = ''; return array('error' => $error, 'message' => $message, 'action' => $action); } } /** * phpBB class that will be used in place of globalising these variables. * * Based off : Titania 0.3.11 * * File : titania/includes/core/phpbb.php */ class phpbb { /** @var auth phpBB Auth class */ public static $auth; /** @var cache phpBB Cache class */ public static $cache; /** @var config phpBB Config class */ public static $config; /** @var db phpBB DBAL class */ public static $db; /** @var template phpBB Template class */ public static $template; /** @var user phpBB User class */ public static $user; /** * Absolute Wordpress and phpBB Path * * @var string */ public static $absolute_phpbb_script_path; public static $absolute_wordpress_script_path; public static $absolute_phpbb_url_path; /** * Static Constructor. */ public static function initialise() { global $wpdb; $wpdb = self::wp_phpbb_get_wp_db(); global $auth, $config, $db, $template, $user, $cache; self::$auth = &$auth; self::$config = &$config; self::$db = &$db; self::$template = &$template; self::$user = &$user; self::$cache = &$cache; // Set the absolute wordpress/phpbb path $propress_options = get_option( 'phpbbtowp' ); self::$absolute_phpbb_script_path = $propress_options['phpbb_path']; // self::$absolute_wordpress_script_path = phpbb::$config['wordpress_script_path']; self::$absolute_phpbb_url_path = phpbb::$config['wp_phpbb_bridge_board_path']; // enhance phpbb $config data with WP $config data self::wp_get_config(); // Start session management if (!defined('PHPBB_INCLUDED')) { self::$user->session_begin(); self::$auth->acl(self::$user->data); self::$user->setup(); } $action = request_var('action', ''); if (($action != 'logout' || $action != 'log-out') && !defined('PHPBB_INAJAX')) // if ($action != 'logout' || $action != 'log-out') { self::wp_phpbb_sanitize_user(); } } /** * Load the correct database class file. * * This function is used to load the database class file either at runtime or by * wp-admin/setup-config.php. We must globalize $wpdb to ensure that it is * defined globally by the inline code in wp-db.php. * * @since 2.5.0 * @global $wpdb WordPress Database Object * * Based off : wordpress 3.1.3 * File : wordpress/wp-includes/load.php */ public static function wp_phpbb_get_wp_db() { global $wpdb; require_once(ABSPATH . WPINC . '/wp-db.php'); if (@file_exists(WP_CONTENT_DIR . '/db.php')) { require_once(WP_CONTENT_DIR . '/db.php'); } $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST); $wpdb->set_prefix(WP_TABLE_PREFIX); return $wpdb; } /** * Update phpbb user data with wp user data * And update wp user data with phpbb user data * * based off the WP add-on by Jason Sanborn <jsanborn@simplicitypoint.com> http://www.e-xtnd.it/wp-phpbb-bridge/ */ public static function wp_phpbb_sanitize_user() { global $wp_user; $wp_user_id = self::wp_phpbb_get_userid(); // if ($wp_user_id != 0) // if ($wp_user_id <= 0 && is_user_logged_in()) if (!phpbb::$user->data['is_registered']) { wp_logout(); // wp_redirect('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); } else if ($wp_user_id > 0 && $wp_user_id != $wp_user->ID) { wp_set_current_user($wp_user_id); wp_set_auth_cookie($wp_user_id, true, false); } // Get the WP user data //$wp_user_data = get_userdata($wp_user_id); $wp_user_data = get_userdata($wp_user->ID); if (!isset($wp_user_data->phpbb_userid) || $wp_user_data->phpbb_userid == 0 || $wp_user_data->phpbb_userid != self::$user->data['user_id']) { $wp_user_data = self::$user->data['user_id']; update_metadata('user', $wp_user_id, 'phpbb_userid', $wp_user_data); } // If all went fine, we doesnt' needed this values anymore (added at functions.php -> function wp_phpbb_phpbb_loginbox_head()) if (isset($wp_user_data->phpbb_userid) && isset($wp_user_data->WPphpBBlogin)) { delete_user_meta($wp_user_id, 'WPphpBBlogin'); } $default_userdata = array( 'ID' => $wp_user_id, 'phpbb_userid' => self::$user->data['user_id'], 'user_url' => self::$user->data['user_website'], 'user_email' => self::$user->data['user_email'], 'nickname' => self::$user->data['username'], 'jabber' => self::$user->data['user_jabber'], 'aim' => self::$user->data['user_aim'], 'yim' => self::$user->data['user_yim'], ); self::$user->data['wp_user'] = array_merge($default_userdata, (array) $wp_user_data); // print_r(self::$user->data); } /** * Get the WP user ID, based off the phpBB user ID * * @param (integer) $wp_user_id a default value, in WP the anonymous user is ID 0 * @return (integer) $wp_user_id */ public static function wp_phpbb_get_userid($wp_user_id = 0) { global $wpdb; if (self::$user->data['user_type'] == USER_FOUNDER && self::$user->data['user_id'] == self::$config['wp_phpbb_bridge_forum_founder_user_id']) { return (int) self::$config['wp_phpbb_bridge_blog_founder_user_id']; } if (self::$user->data['user_type'] == USER_NORMAL || self::$user->data['user_type'] == USER_FOUNDER) { // $id_list = $wpdb->get_col($wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = 'phpbb_userid' AND meta_value = %d", self::$user->data['user_id'])); $usermeta_id = $wpdb->get_var($wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = 'phpbb_userid' AND meta_value = %s", self::$user->data['user_id'])); // if (empty($id_list)) if (!$usermeta_id) { // return (int) $wp_user_id; $users_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_login = %s", self::$user->data['username'])); if ($users_id) { return (int) $users_id; } } else { // return (int) $id_list[0]; return (int) $usermeta_id; } } return $wp_user_id; } /** * Set and Force some variables * We do this instead made an ACP module for phpBB to manage this bridge configurations */ public static function wp_get_config() { $wp_phpbb_bridge_forum_founder_user_id = phpbb::$config['wp_phpbb_bridge_blog_founder_user_id']; $wp_phpbb_bridge_blog_founder_user_id = phpbb::$config['wp_phpbb_bridge_forum_founder_user_id']; $wp_phpbb_bridge_post_forum_id = phpbb::$config['wp_phpbb_bridge_post_forum_id']; $wp_phpbb_bridge_widgets_column_width = phpbb::$config['wp_phpbb_bridge_widgets_column_width']; $wp_phpbb_bridge_comments_avatar_width = phpbb::$config['wp_phpbb_bridge_comments_avatar_width']; self::$config = array_merge(self::$config, array( // Disable to call the function leave_newly_registered() 'new_member_post_limit' => null, // The ID of user forum founder 'wp_phpbb_bridge_forum_founder_user_id' => (int) $wp_phpbb_bridge_forum_founder_user_id, // The ID of user blog founder 'wp_phpbb_bridge_blog_founder_user_id' => (int) $wp_phpbb_bridge_blog_founder_user_id, // For the moment the ID of you forum where to post a new entry whenever is published in the Wordpress 'wp_phpbb_bridge_post_forum_id' => (int) $wp_phpbb_bridge_post_forum_id, // The left column width, in pixels 'wp_phpbb_bridge_widgets_column_width' => (int) $wp_phpbb_bridge_widgets_column_width, // The width size of avatars in comments, in pixels 'wp_phpbb_bridge_comments_avatar_width' => (int) $wp_phpbb_bridge_comments_avatar_width, )); } /** * Include a phpBB includes file * * @param string $file The name of the file * @param string|bool $function_check Bool false to ignore; string function name to check if the function exists (and not load the file if it does) * @param string|bool $class_check Bool false to ignore; string class name to check if the class exists (and not load the file if it does) * * Based off : Titania 0.3.11 * File : titania/includes/core/phpbb.php */ public static function _include($file, $function_check = false, $class_check = false) { if ($function_check !== false) { if (function_exists($function_check)) { return; } } if ($class_check !== false) { if (class_exists($class_check)) { return; } } // Make that phpBB itself understands out paths global $phpbb_root_path, $phpEx; // $phpbb_root_path = PHPBB_ROOT_PATH; // $phpEx = PHP_EXT; $propress_options = get_option( 'phpbbtowp' ); include($propress_options['phpbb_path']. "includes/" . $file . "." . PHP_EXT); } /** * Shortcut for phpbb's append_sid function (do not send the root path/phpext in the url part) * * @param mixed $url * @param mixed $params * @param mixed $is_amp * @param mixed $session_id * @return string * * Based off : Titania 0.3.11 * File : titania/includes/core/phpbb.php */ public static function append_sid($script, $params = false, $is_amp = true, $session_id = false) { return append_sid(self::$absolute_phpbb_url_path . $script . '.' . PHP_EXT, $params, $is_amp, $session_id); } /** * Page header function for phpBB stuff */ public static function page_header() { // Determine board url - we may need it later $board_url = generate_board_url(false) . '/'; $web_path = phpbb::$config['wp_phpbb_bridge_board_path']; $blog_path = get_option('siteurl'); /** * Print the <title> tag based on what is being viewed. */ global $page, $paged; $wp_title = wp_title('|', false, 'right'); // Add the blog name. $wp_title .= get_bloginfo('name', 'display'); // Add the blog description for the home/front page. $site_description = get_bloginfo('description', 'display'); if ($site_description && (is_home() || is_front_page())) { $wp_title .= " | $site_description"; } // Add a page number if necessary: if ($paged >= 2 || $page >= 2) { $wp_title .= ' | ' . sprintf(self::$user->lang['WP_PAGE_NUMBER'], max($paged, $page)); } // Credits to Dion Designs for the hack :) $menu = array( 'theme_location' => 'primary', 'container' => false, 'menu_class' => 'linklist leftside wpmenu', 'menu_id' => '', 'echo' => 0, 'fallback_cb' => false, 'walker' => '' ); $header_menu = wp_nav_menu($menu); $menu['theme_location'] = 'secondary'; $footer_menu = wp_nav_menu($menu); // Do the phpBB page header stuff first page_header($wp_title, false); $redirect = request_var('redirect', home_url(add_query_arg(array()))); self::$template->assign_vars(array( 'PHPBB_IN_FORUM' => false, 'PHPBB_IN_WEB' => false, 'PHPBB_IN_BLOG' => true, 'PHPBB_IN_PASTEBIN' => false, 'SCRIPT_NAME' => 'blog ' . self::wp_location(), 'IN_HOME' => is_home(), // 'U_WEB' => append_sid($web_path), 'U_INDEX' => append_sid($web_path), 'U_BLOG' => append_sid($blog_path), 'PAGE_TITLE' => $wp_title, 'SITENAME' => get_bloginfo('name', 'display'), 'SITE_DESCRIPTION' => get_bloginfo('description', 'display'), 'BLOG_HEADER' => self::wp_page_header(), 'HEADER_IMAGE' => '<img src="' . get_header_image() . '" />', 'S_DISPLAY_SEARCH' => false, 'S_ENABLE_FEEDS' => false, 'HEADER_MENU' => $header_menu, 'FOOTER_MENU' => $footer_menu, 'S_REGISTER_ENABLED'=> (self::$config['require_activation'] != USER_ACTIVATION_DISABLE) ? true : false, 'U_REGISTER_POPUP' => "$web_path/ucp.php?mode=register", 'S_LOGIN_REDIRECT' => build_hidden_fields(array('redirect' => $redirect)), 'U_LOGIN_LOGOUT_POPUP' => (!self::wp_phpbb_user_logged()) ? "$web_path/ucp.php?mode=login&amp;redirect=" . $redirect : "$web_path/ucp.php?mode=logout&amp;sid=" . phpbb::$user->session_id . "&amp;redirect=" . $redirect , 'U_WP_ACP' => (self::$user->data['user_type'] == USER_FOUNDER || current_user_can('Contributor')) ? admin_url() : '', 'U_POST_NEW_TOPIC' => (self::$user->data['user_type'] == USER_FOUNDER || current_user_can('Contributor')) ? admin_url('post-new.php') : '', 'BLOG_POST_IMG' => self::wp_imageset('button_blogpost_new', 'WP_POST_TOPIC', 'BLOG_POST_IMG_CLASS'), 'POST_IMG' => self::$user->img('button_topic_new', 'POST_NEW_TOPIC'), 'DYNAMIC_SIDEBAR_W' => (int) self::$config['wp_phpbb_bridge_widgets_column_width'], 'WPT_TEMPLATE_PATH' => get_template_directory_uri(), 'WPT_STYLESHEETPATH'=> get_stylesheet_directory(), 'A_BASE_URL' => esc_url( get_home_url( null, '/wp-content/themes/phpBB')), 'T_THEME_PATH' => "{$web_path}styles/" . self::$user->theme['theme_path'] . '/theme', 'T_STYLESHEET_LINK' => (!self::$user->theme['theme_storedb']) ? "{$web_path}styles/" . self::$user->theme['theme_path'] . '/theme/stylesheet.css' : append_sid("{$web_path}style." . PHP_EXT, 'id=' . self::$user->theme['style_id'] . '&amp;lang=' . self::$user->data['user_lang']), )); if (is_404() || is_category() || is_day() || is_month() || is_year() || is_search() || is_paged()) { self::wp_notes(); } } public static function wp_phpbb_user_logged() { $is_wp_user_logged_in = $is_phpbb_user_logged_in = (self::$user->data['user_id'] != ANONYMOUS) ? true : false; if (function_exists('is_user_logged_in')) { $is_wp_user_logged_in = (is_user_logged_in()) ? true : false; } return ($is_phpbb_user_logged_in || $is_wp_user_logged_in) ? true : false; } public static function wp_location($location = 'index') { $m = get_query_var('m'); $year = get_query_var('year'); $monthnum = get_query_var('monthnum'); $day = get_query_var('day'); $search = get_query_var('s'); // If there is a post if (is_single() || (is_home() && !is_front_page()) || (is_page() && !is_front_page())) { $location = 'single'; } // If there's a category or tag if (is_category() || is_tag()) { $location = 'category'; } // If there's a taxonomy if (is_tax()) { $location = 'taxonomy'; } // If there's an author if (is_author()) { $location = 'author'; } // If there's a post type archive if ( is_post_type_archive() ) { $location = 'archive'; } // If there's a month if (is_archive() && !empty($m)) { $location = 'archive month'; } // If there's a year if (is_archive() && !empty($year)) { $location = 'archive year'; } // If it's a search if (is_search()) { $location = 'search'; } // If it's a 404 page if (is_404()) { $location = 'wp-error'; } return $location; } /** * Enter description here... * See also WordPress root/wp-content/theme/phpBB/functions.php * * @return unknown */ public static function wp_page_header() { $blog_header = "\n"; // $blog_header .= '<link rel="pingback" href="' . get_bloginfo('pingback_url') . '" />' . "\n"; // Main layout 1 column // $blog_header .= '<link rel="stylesheet" type="text/css" media="all" href="' . get_bloginfo('stylesheet_url') . '?ver=' . WP_PHPBB_BRIDGE_VERSION . '" />' . "\n"; // Some js files /* Always have wp_head() just before the closing </head> * tag of your theme, or you will break many plugins, which * generally use this hook to add elements to <head> such * as styles, scripts, and meta tags. */ $blog_header .= wp_do_action('wp_head'); return $blog_header; } public static function wp_notes() { $is_404 = $is_category = $is_day = $is_month = $is_year = $is_search = $is_paged = ''; // If this is a 404 page if (is_404()) { $error_404 = self::$user->lang['WP_ERROR_404']; } // If this is a category archive else if (is_category()) { $is_category = sprintf(self::$user->lang['WP_TITLE_CATEGORIES_EXPLAIN'], single_cat_title('', false)); } // If this is a yearly archive else if (is_day()) { $is_day = sprintf(self::$user->lang['WP_TITLE_ARCHIVE_DAY_EXPLAIN'], home_url(), get_bloginfo('name'), get_the_time(__('l, F jS, Y', 'default'))); } // If this is a monthly archive else if (is_month()) { $is_month = sprintf(self::$user->lang['WP_TITLE_ARCHIVE_MONTH_EXPLAIN'], home_url(), get_bloginfo('name'), get_the_time(__('F, Y', 'default'))); } // If this is a yearly archive else if (is_year()) { $is_year = sprintf(self::$user->lang['WP_TITLE_ARCHIVE_YEAR_EXPLAIN'], home_url(), get_bloginfo('name'), get_the_time('Y')); } // If this is a monthly archive else if (is_search()) { $is_search = sprintf(self::$user->lang['WP_TITLE_ARCHIVE_SEARCH_EXPLAIN'], home_url(), get_bloginfo('name'), get_search_query()); } // If this is a monthly archive else if (isset($_GET['paged']) && !empty($_GET['paged'])) { $is_paged = sprintf(self::$user->lang['WP_TITLE_ARCHIVE_EXPLAIN'], home_url(), get_bloginfo('name')); } self::$template->assign_vars(array( 'WP_NOTES_IS_404' => $is_404, 'WP_NOTES_IS_CATEGORY' => $is_category, 'WP_NOTES_IS_MONTH' => $is_month, 'WP_NOTES_IS_YEAR' => $is_year, 'WP_NOTES_IS_SEARCH' => $is_search, 'WP_NOTES_IS_PAGED' => $is_paged, )); } /** * Page right collumn function handling the WP tasks */ public static function page_sidebar($post_id = 0) { // Author information $post_id = request_var('p', $post_id); if (is_single() && $post_id) { $post = get_post($post_id); self::phpbb_the_autor_full($post->post_author, true, false); } get_sidebar(); } /** * Allows you to display a list of recent topics within a specific forum id's. * */ public static function phpbb_recet_topics($instance, $defaults) { $instance = wp_parse_args($instance, $defaults); $instance['forums'] = explode(',', $instance['forums']); // We need to find at least one postable forum where the user can read if ($instance['forums'][0] == 0) { // $forum_ids = array_keys(self::$auth->acl_getf('f_read', true)); $instance['forums'] = array_keys(self::$auth->acl_getf('f_read', true)); } // User cannot read any forums if (empty($instance['forums'])) { return false; } $sql_array = array( 'SELECT' => 'f.forum_id, f.forum_name, t.topic_id, t.forum_id, t.topic_title, t.topic_poster, t.topic_first_poster_name, t.topic_first_poster_colour, t.topic_last_post_id, t.topic_last_poster_id, t.topic_last_poster_name, t.topic_last_poster_colour, t.topic_views, t.topic_replies, t.topic_replies_real, t.topic_time, t.topic_last_post_time, t.topic_status, t.topic_type, t.poll_start, u.username, u.user_colour', 'FROM' => array( TOPICS_TABLE => 't', ), 'LEFT_JOIN' => array( array( 'FROM' => array(FORUMS_TABLE => 'f'), 'ON' => 't.forum_id = f.forum_id', ), array( 'FROM' => array(USERS_TABLE => 'u'), 'ON' => 't.topic_poster = u.user_id', ), ), 'WHERE' => self::$db->sql_in_set('t.forum_id', $instance['forums']) . ' AND t.topic_status <> ' . ITEM_MOVED . ' AND t.topic_approved = 1 OR t.forum_id = 0', //OR t.forum_id = 0, esta linea es para que muestre tambien los globales ya que el id del foro de estos es 0 'ORDER_BY' => 't.topic_type DESC, t.topic_last_post_time DESC', ); $sql = self::$db->sql_build_query('SELECT', $sql_array); $result = self::$db->sql_query_limit($sql, (int) $instance['total']); while ($row = self::$db->sql_fetchrow($result)) { $topic_list[] = $row; } self::$db->sql_freeresult($result); if (!isset($topic_list) || !sizeof($topic_list)) { return; } // Output the topics for ($i = 0, $end = sizeof($topic_list); $i < $end; ++$i) { $topic_data =& $topic_list[$i]; /** $topic_forum_id = (int) $topic_data['forum_id']; // Replies $replies = (self::$auth->acl_get('m_approve', $topic_forum_id)) ? $topic_data['topic_replies_real'] : $topic_data['topic_replies']; $unread_topic = false; // Get folder img, topic status/type related information $folder_img = $folder_alt = $topic_type = ''; topic_status($topic_data, $replies, $unread_topic, $folder_img, $folder_alt, $topic_type); **/ // Dump vars into template self::$template->assign_block_vars('recettopicsrow', array( 'TOPIC_TITLE' => $topic_data['topic_title'], 'U_VIEW_TOPIC' => self::append_sid("viewtopic", array('f' => $topic_data['forum_id'], 't' => $topic_data['topic_id'])), 'FORUM_NAME' => $topic_data['forum_name'], 'U_VIEW_FORUM' => self::append_sid("viewforum", array('f' => $topic_data['forum_id'])), 'TOPIC_AUTHOR_FULL' => get_username_string('full', $topic_data['topic_poster'], $topic_data['topic_first_poster_name'], $topic_data['topic_first_poster_colour']), 'FIRST_POST_TIME' => self::$user->format_date($topic_data['topic_time']), 'U_LAST_POST' => self::append_sid("viewtopic", array('f' => $topic_data['forum_id'], 't' => $topic_data['topic_id'], 'p'=> $topic_data['topic_last_post_id'] . '#p' . $topic_data['topic_last_post_id'])), 'LAST_POST_AUTHOR_FULL' => get_username_string('full', $topic_data['topic_last_poster_id'], $topic_data['topic_last_poster_name'], $topic_data['topic_last_poster_colour']), 'LAST_POST_TIME' => self::$user->format_date($topic_data['topic_last_post_time']), )); } self::$template->assign_vars(array( 'L_RECENT_TOPICS' => ($instance['title']) ? $instance['title'] : phpbb::$user->lang['WP_TITLE_RECENT_TOPICS'], 'S_RECENT_TOPICS' => sizeof($topic_list), 'LAST_POST_IMG' => self::$user->img('icon_topic_latest', 'VIEW_LATEST_POST'), )); // A major-league hack, but it's Wordpress. That's what you do. :) echo '<|DD_RECENT_TOPICS|>'; // Make sure we set up the sidebar style if (!did_action('wp_phpbb_stylesheet')) { // Extra layout 2 columns add_action('wp_head', 'wp_phpbb_stylesheet'); } } /** * function handling the users data */ public static function phpbb_the_autor_full($wp_poster_id = 0, $dump = false, $is_commen = false) { global $user_cache; if (empty($user_cache) || !is_array($user_cache)) { $user_cache = array(); } $wp_poster_id = (int) $wp_poster_id; /* * Cache various user specific data ... so we don't have to recompute * this each time the same user appears on this page * unless we need to display the author data in the sidebar */ if (!isset($user_cache[$wp_poster_id]) || !$is_commen) { $wp_poster_data = get_userdata($wp_poster_id); // In WP the anonymous user is ID 0, we change that to the phpbb anonymous user ID if ($wp_poster_id == 0 || !$wp_poster_data) { // $wp_poster_data->display_name = $wp_poster_data->user_nicename = (!$wp_poster_data) ? self::$user->lang['GUEST'] : get_comment_author($wp_poster_id); $wp_poster_data->display_name = get_comment_author(); $wp_poster_data->user_nicename = get_comment_author_link(); $wp_poster_data->phpbb_userid = ANONYMOUS; } $poster_id = (int) $wp_poster_data->phpbb_userid; $sql = 'SELECT * FROM ' . USERS_TABLE . ' WHERE user_id = ' . $poster_id; $result = self::$db->sql_query($sql); $row = self::$db->sql_fetchrow($result); self::$db->sql_freeresult($result); if (!$row) { return self::phpbb_the_autor_full(0, $dump, $is_commen); // return array(); } self::_include('functions_display', 'get_user_avatar'); self::_include('bbcode', false, 'bbcode'); $user_sig = ''; $bbcode_bitfield = ''; // We add the signature to every posters entry because enable_sig is post dependant if ($row['user_sig'] && self::$config['allow_sig'] && self::$user->optionget('viewsigs')) { $bbcode_bitfield = $bbcode_bitfield | base64_decode($row['user_sig_bbcode_bitfield']); // Instantiate BBCode if need be if ($bbcode_bitfield !== '') { $bbcode = new bbcode(base64_encode($bbcode_bitfield)); } $row['user_sig'] = censor_text($row['user_sig']); if ($row['user_sig_bbcode_bitfield']) { $bbcode->bbcode_second_pass($row['user_sig'], $row['user_sig_bbcode_uid'], $row['user_sig_bbcode_bitfield']); } $row['sig'] = bbcode_nl2br($row['user_sig']); $row['sig'] = smiley_text($row['user_sig']); $user_sig = $row['sig']; } if ($is_commen || !$row['user_avatar_width']) { $row['user_avatar_width'] = $row['user_avatar_height'] = self::$config['wp_phpbb_bridge_comments_avatar_width']; } // IT'S A HACK! for images like avatar and rank global $phpbb_root_path; $phpbb_root_path = self::$absolute_phpbb_url_path; $user_cache[$wp_poster_id] = array( 'author_full' => ($poster_id != ANONYMOUS) ? get_username_string('full', $poster_id, $row['username'], $row['user_colour']) : get_username_string('full', $poster_id, $wp_poster_data->user_nicename, $row['user_colour']), 'author_colour' => ($poster_id != ANONYMOUS) ? get_username_string('colour', $poster_id, $row['username'], $row['user_colour']) : get_username_string('colour', $poster_id, $wp_poster_data->user_nicename, $row['user_colour']), 'author_username' => ($poster_id != ANONYMOUS) ? get_username_string('username', $poster_id, $row['username'], $row['user_colour']) : get_username_string('username', $poster_id, $wp_poster_data->user_nicename, $row['user_colour']), 'author_profile' => ($poster_id != ANONYMOUS) ? get_username_string('profile', $poster_id, $row['username'], $row['user_colour']) : get_username_string('profile', $poster_id, $wp_poster_data->user_nicename, $row['user_colour']), 'username' => ($poster_id != ANONYMOUS) ? $row['username'] : $wp_poster_data->display_name , 'user_colour' => ($poster_id != ANONYMOUS) ? $row['user_colour'] :'', 'author_pm' => $poster_id, // 'online' => false, 'avatar' => (self::$user->optionget('viewavatars')) ? get_user_avatar($row['user_avatar'], $row['user_avatar_type'], $row['user_avatar_width'], $row['user_avatar_height']) : false, 'avatar_width' => $row['user_avatar_width'], 'avatar_height' => $row['user_avatar_height'], 'rank_title' => '', 'rank_image' => '', 'rank_image_src' => '', 'joined' => self::$user->format_date($row['user_regdate']), 'posts' => $row['user_posts'], 'from' => (!empty($row['user_from'])) ? $row['user_from'] : '', 'warnings' => (isset($row['user_warnings'])) ? $row['user_warnings'] : 0, 'age' => '', 'sig' => $user_sig, 'search' => (self::$auth->acl_get('u_search')) ? self::append_sid("search", "author_id=$poster_id&amp;sr=posts") : '', 'viewonline' => $row['user_allow_viewonline'], 'allow_pm' => $row['user_allow_pm'], 'profile' => self::append_sid("memberlist", "mode=viewprofile&amp;u=$poster_id"), 'email' => '', 'icq_status_img' => '', 'icq' => '', 'www' => $row['user_website'], 'aim' => ($row['user_aim'] && self::$auth->acl_get('u_sendim')) ? self::append_sid("memberlist", "mode=contact&amp;action=aim&amp;u=$poster_id") : '', 'msn' => ($row['user_msnm'] && self::$auth->acl_get('u_sendim')) ? self::append_sid("memberlist", "mode=contact&amp;action=msnm&amp;u=$poster_id") : '', 'yim' => ($row['user_yim']) ? 'http://edit.yahoo.com/config/send_webmesg?.target=' . urlencode($row['user_yim']) . '&amp;.src=pg' : '', 'jabber' => ($row['user_jabber'] && self::$auth->acl_get('u_sendim')) ? self::append_sid("memberlist", "mode=contact&amp;action=jabber&amp;u=$poster_id") : '', ); get_user_rank($row['user_rank'], $row['user_posts'], $user_cache[$wp_poster_id]['rank_title'], $user_cache[$wp_poster_id]['rank_image'], $user_cache[$wp_poster_id]['rank_image_src']); // Undo HACK! for images like avatar and rank $phpbb_root_path = PHPBB_ROOT_PATH; if ((!empty($row['user_allow_viewemail']) && self::$auth->acl_get('u_sendemail')) || self::$auth->acl_get('a_email')) { $user_cache[$wp_poster_id]['email'] = (self::$config['board_email_form'] && self::$config['email_enable']) ? self::append_sid("memberlist", "mode=email&amp;u=$poster_id") : ((self::$config['board_hide_emails'] && !self::$auth->acl_get('a_email')) ? '' : 'mailto:' . $row['user_email']); } if (!empty($row['user_icq'])) { $user_cache[$wp_poster_id]['icq'] = 'http://www.icq.com/people/webmsg.php?to=' . $row['user_icq']; $user_cache[$wp_poster_id]['icq_status_img'] = '<img src="http://web.icq.com/whitepages/online?icq=' . $row['user_icq'] . '&amp;img=5" width="18" height="18" alt="" />'; } if (self::$config['allow_birthdays'] && !empty($row['user_birthday'])) { list($bday_day, $bday_month, $bday_year) = array_map('intval', explode('-', $row['user_birthday'])); if ($bday_year) { $now = getdate(time() + self::$user->timezone + self::$user->dst - date('Z')); $diff = $now['mon'] - $bday_month; if ($diff == 0) { $diff = ($now['mday'] - $bday_day < 0) ? 1 : 0; } else { $diff = ($diff < 0) ? 1 : 0; } $user_cache[$wp_poster_id]['age'] = (int) ($now['year'] - $bday_year - $diff); } } if ($is_commen || $user_cache[$wp_poster_id]['avatar'] !== false) { // <img height="32" width="32" class="avatar avatar-32 photo avatar-default" src="http://0.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?s=32" alt=""> $user_cache[$wp_poster_id]['avatar'] = str_replace('<img', '<img class="avatar avatar-32 photo avatar-default"', $user_cache[$wp_poster_id]['avatar']); } $user_cache[$wp_poster_id]['avatar'] = ($user_cache[$wp_poster_id]['avatar'] !== false) ? (($user_cache[$wp_poster_id]['avatar']) ? $user_cache[$wp_poster_id]['avatar'] : get_avatar($wp_poster_id, $user_cache[$wp_poster_id]['avatar_width'])) : ''; } // Dump vars into template $autor = array( 'POSTER_ID' => $wp_poster_id, 'POST_AUTHOR_FULL' => $user_cache[$wp_poster_id]['author_full'], 'POST_AUTHOR_COLOUR' => $user_cache[$wp_poster_id]['author_colour'], 'POST_AUTHOR' => $user_cache[$wp_poster_id]['author_username'], 'U_POST_AUTHOR' => $user_cache[$wp_poster_id]['author_profile'], 'U_FORUM_POSTS_AUTHOR' => self::append_sid("search", array('author_id' => 2, 'sr' => 'posts')), 'U_BLOG_POSTS_AUTHOR' => get_author_posts_url($wp_poster_id), 'S_POSTS_AUTHOR' => get_the_author_posts(), // 'ONLINE_IMG' => ($poster_id == ANONYMOUS || !self::$config['load_onlinetrack']) ? '' : (($user_cache[$wp_poster_id]['online']) ? self::$user->img('icon_user_online', 'ONLINE') : self::$user->img('icon_user_offline', 'OFFLINE')), // 'S_ONLINE' => ($poster_id == ANONYMOUS || !self::$config['load_onlinetrack']) ? false : (($user_cache[$wp_poster_id]['online']) ? true : false), 'POSTER_AVATAR' => $user_cache[$wp_poster_id]['avatar'], 'RANK_TITLE' => $user_cache[$wp_poster_id]['rank_title'], 'RANK_IMG' => $user_cache[$wp_poster_id]['rank_image'], 'RANK_IMG_SRC' => $user_cache[$wp_poster_id]['rank_image_src'], 'POSTER_JOINED' => $user_cache[$wp_poster_id]['joined'], 'POSTER_POSTS' => $user_cache[$wp_poster_id]['posts'], 'POSTER_FROM' => $user_cache[$wp_poster_id]['from'], 'POSTER_WARNINGS' => $user_cache[$wp_poster_id]['warnings'], 'POSTER_AGE' => $user_cache[$wp_poster_id]['age'], 'SIGNATURE' => $user_cache[$wp_poster_id]['sig'], 'PROFILE_IMG' => self::$user->img('icon_user_profile', 'READ_PROFILE'), 'PM_IMG' => self::$user->img('icon_contact_pm', 'SEND_PRIVATE_MESSAGE'), 'EMAIL_IMG' => self::$user->img('icon_contact_email', 'SEND_EMAIL'), 'WWW_IMG' => self::$user->img('icon_contact_www', 'VISIT_WEBSITE'), 'ICQ_IMG' => self::$user->img('icon_contact_icq', 'ICQ'), 'AIM_IMG' => self::$user->img('icon_contact_aim', 'AIM'), 'MSN_IMG' => self::$user->img('icon_contact_msnm', 'MSNM'), 'YIM_IMG' => self::$user->img('icon_contact_yahoo', 'YIM'), 'JABBER_IMG' => self::$user->img('icon_contact_jabber', 'JABBER') , 'U_PROFILE' => $user_cache[$wp_poster_id]['profile'], // 'U_SEARCH' => $user_cache[$wp_poster_id]['search'], 'U_PM' => ( self::$config['allow_privmsg'] && self::$auth->acl_get('u_sendpm') && ($user_cache[$wp_poster_id]['allow_pm'] || self::$auth->acl_gets('a_', 'm_') || self::$auth->acl_getf_global('m_'))) ? self::append_sid("ucp", 'i=pm&amp;mode=compose&amp;&u=' . $user_cache[$wp_poster_id]['author_pm']) : '', 'U_EMAIL' => $user_cache[$wp_poster_id]['email'], 'U_WWW' => $user_cache[$wp_poster_id]['www'], 'U_ICQ' => $user_cache[$wp_poster_id]['icq'], 'U_AIM' => $user_cache[$wp_poster_id]['aim'], 'U_MSN' => $user_cache[$wp_poster_id]['msn'], 'U_YIM' => $user_cache[$wp_poster_id]['yim'], 'U_JABBER' => $user_cache[$wp_poster_id]['jabber'], ); // Dump vars into template ? if ($dump) { self::$template->assign_vars($autor); } return $autor; } /** * Page footer function handling the phpBB tasks */ public static function page_footer($run_cron = true, $template_body = false) { self::$template->assign_vars(array( 'BLOG_FOOTER' => self::wp_page_footer(), )); self::$template->set_filenames(array( 'body' => ($template_body !== false) ? $template_body : 'wordpress/index_body.html', )); /** * If the user is admin, we add a hook to fix the ACP & DEBUG url * To works property the function wp_phpbb_u_acp() is located in the WordPress root/wp-content/themes/phpBB/includes/wp_phpbb_bridge.php file */ if (self::$auth->acl_get('a_') && !empty(self::$user->data['is_registered'])) { global $phpbb_hook; $phpbb_hook->register(array('template', 'display'), 'wp_phpbb_u_acp'); } // Do the phpBB page footer at least but do not run cron jobs page_footer(false); } public static function wp_page_footer() { $blog_footer = '&nbsp;|&nbsp;Powered by <a href="http://wordpress.org/" title="Semantic Personal Publishing Platform" rel="generator" id="site-generator">WordPress</a><br />'; $blog_footer .= '<!-- If you\'d like to support WordPress, having the "powered by" link somewhere on your blog is the best way; it\'s our only promotion or advertising. -->' . "\n"; // $blog_footer .= wp_do_action('wp_footer'); // Output page creation time if (defined('WP_DEBUG') and WP_DEBUG == true) { $blog_footer .= '<br />' . sprintf(self::$user->lang['WP_DEBUG_NOTE'], get_num_queries(), timer_stop(0, 3)); } return $blog_footer; } /** * Some images for the * with fallback to a default the phpbb image */ function wp_imageset($img = 'all', $lang_var = '', $tpl_name = '') { static $imageset = array(); if (empty($imageset)) { $imageset = array( 'icon_wp_trash' => array( 'image_name' => 'icon_wp_trash', 'image_class' => 'wp-trash-icon', 'image_name_fallback' => 'icon_post_delete', 'image_class_fallback' => 'wp-delete-icon', ), 'icon_wp_untrash' => array( 'image_name' => 'icon_wp_trash', 'image_class' => 'wp-untrash-icon', 'image_name_fallback' => 'icon_post_delete', 'image_class_fallback' => 'wp-undelete-icon', ), 'icon_wp_approve' => array( 'image_name' => 'icon_wp_approve', 'image_class' => 'wp-approve-icon', 'image_name_fallback' => 'icon_post_report', 'image_class_fallback' => 'wp-report-icon', ), 'icon_wp_unapprove' => array( 'image_name' => 'icon_wp_unapprove', 'image_class' => 'wp-unapprove-icon', 'image_name_fallback' => 'icon_topic_unapproved', 'image_class_fallback' => 'wp-noreport-icon', ), 'icon_wp_spam' => array( 'image_name' => 'icon_wp_spam', 'image_class' => 'wp-spam-icon', 'image_name_fallback' => 'icon_post_report', 'image_class_fallback' => 'wp-info-icon', ), 'icon_wp_nospam' => array( 'image_name' => 'icon_wp_spam', 'image_class' => 'wp-nospam-icon', 'image_name_fallback' => 'icon_user_warn', 'image_class_fallback' => 'wp-noinfo-icon', ), 'button_blogpost_new' => array( 'image_name' => 'button_blogpost_new', 'image_class' => 'blogpostnew-icon', 'image_name_fallback' => 'button_topic_new', 'image_class_fallback' => 'wp-post-icon', ), ); } foreach ($imageset as $image => $img_data) { if ($img == $image) { $imagedata = self::$user->img($img_data['image_name'], $lang_var); if (!$imagedata != '') { $imagedata = self::$user->img($img_data['image_name_fallback'], $lang_var); $img_data['image_class'] = $img_data['image_class_fallback']; } self::$template->assign_var($tpl_name, $img_data['image_class']); // For Subsilver2 return urldecode($imagedata); } } } } ?>
Danielx64/WP-phpbb-bridge
phpBB-WordPress-bridge/wordpress plugin/phpbb-to-wp-connector/functions/wp_phpbb_bridge_core.php
PHP
gpl-2.0
38,385
/* Copyright (C) 2007 The SpringLobby Team. All rights reserved. */ // // Class: Battle // #include "battle.h" #include "ui.h" #include "springunitsync.h" #include "server.h" #include "user.h" #include "utils/misc.h" #include "utils/debug.h" #include "utils/conversion.h" #include "utils/math.h" #include "utils/uievents.h" #include "utils/battleevents.h" #include "uiutils.h" #include "settings.h" #include "useractions.h" #include "utils/customdialogs.h" #include "springunitsynclib.h" #include "iconimagelist.h" #include "spring.h" #include <wx/timer.h> #include <wx/image.h> #include <wx/string.h> #include <wx/log.h> #include <wx/filename.h> const unsigned int TIMER_INTERVAL = 1000; const unsigned int TIMER_ID = 101; BEGIN_EVENT_TABLE(Battle, wxEvtHandler) EVT_TIMER(TIMER_ID, Battle::OnTimer) END_EVENT_TABLE() Battle::Battle( Server& serv, int id ) : m_serv(serv), m_ah(*this), m_autolock_on_start(false), m_id( id ) { m_opts.battleid = m_id; } Battle::~Battle() { } void Battle::SendHostInfo( HostInfo update ) { m_serv.SendHostInfo( update ); } void Battle::SendHostInfo( const wxString& Tag ) { m_serv.SendHostInfo( Tag ); } void Battle::Update() { BattleEvents::GetBattleEventSender( BattleEvents::BattleInfoUpdate ).SendEvent( std::make_pair(this,wxString()) ); } void Battle::Update( const wxString& Tag ) { BattleEvents::GetBattleEventSender( BattleEvents::BattleInfoUpdate ).SendEvent( std::make_pair(this,Tag) ); } void Battle::Join( const wxString& password ) { m_serv.JoinBattle( m_opts.battleid, password ); m_is_self_in = true; } void Battle::Leave() { m_serv.LeaveBattle( m_opts.battleid ); } void Battle::OnRequestBattleStatus() { UserBattleStatus& bs = m_serv.GetMe().BattleStatus(); bs.team = GetFreeTeam( true ); bs.ally = GetFreeAlly( true ); bs.spectator = false; bs.colour = sett().GetBattleLastColour(); bs.side = sett().GetBattleLastSideSel( GetHostModName() ); // theres some highly annoying bug with color changes on player join/leave. if ( !bs.colour.IsOk() ) bs.colour = GetFreeColour( GetMe() ); SendMyBattleStatus(); } void Battle::SendMyBattleStatus() { UserBattleStatus& bs = m_serv.GetMe().BattleStatus(); if ( IsSynced() ) bs.sync = SYNC_SYNCED; else bs.sync = SYNC_UNSYNCED; m_serv.SendMyBattleStatus( bs ); } void Battle::SetImReady( bool ready ) { UserBattleStatus& bs = m_serv.GetMe().BattleStatus(); bs.ready = ready; //m_serv.GetMe().SetBattleStatus( bs ); SendMyBattleStatus(); } /*bool Battle::HasMod() { return usync().ModExists( m_opts.modname ); }*/ void Battle::Say( const wxString& msg ) { m_serv.SayBattle( m_opts.battleid, msg ); } void Battle::DoAction( const wxString& msg ) { m_serv.DoActionBattle( m_opts.battleid, msg ); } void Battle::SetLocalMap( const UnitSyncMap& map ) { IBattle::SetLocalMap( map ); if ( IsFounderMe() ) LoadMapDefaults( map.name ); } User& Battle::GetMe() { return m_serv.GetMe(); } const User& Battle::GetMe() const { return m_serv.GetMe(); } void Battle::SaveMapDefaults() { // save map preset wxString mapname = LoadMap().name; wxString startpostype = CustomBattleOptions().getSingleValue( _T("startpostype"), OptionsWrapper::EngineOption ); sett().SetMapLastStartPosType( mapname, startpostype); std::vector<Settings::SettStartBox> rects; for( unsigned int i = 0; i <= GetLastRectIdx(); ++i ) { BattleStartRect rect = GetStartRect( i ); if ( rect.IsOk() ) { Settings::SettStartBox box; box.ally = rect.ally; box.topx = rect.left; box.topy = rect.top; box.bottomx = rect.right; box.bottomy = rect.bottom; rects.push_back( box ); } } sett().SetMapLastRectPreset( mapname, rects ); } void Battle::LoadMapDefaults( const wxString& mapname ) { CustomBattleOptions().setSingleOption( _T("startpostype"), sett().GetMapLastStartPosType( mapname ), OptionsWrapper::EngineOption ); SendHostInfo( wxFormat( _T("%d_startpostype") ) % OptionsWrapper::EngineOption ); for( unsigned int i = 0; i <= GetLastRectIdx(); ++i ) if ( GetStartRect( i ).IsOk() ) RemoveStartRect(i); // remove all rects SendHostInfo( IBattle::HI_StartRects ); std::vector<Settings::SettStartBox> savedrects = sett().GetMapLastRectPreset( mapname ); for ( std::vector<Settings::SettStartBox>::const_iterator itor = savedrects.begin(); itor != savedrects.end(); ++itor ) { AddStartRect( itor->ally, itor->topx, itor->topy, itor->bottomx, itor->bottomy ); } SendHostInfo( IBattle::HI_StartRects ); } User& Battle::OnUserAdded( User& user ) { user = IBattle::OnUserAdded( user ); if ( &user == &GetMe() ) { m_timer = new wxTimer(this,TIMER_ID); m_timer->Start( TIMER_INTERVAL ); } user.SetBattle( this ); user.BattleStatus().isfromdemo = false; if ( IsFounderMe() ) { if ( CheckBan( user ) ) return user; if ( ( &user != &GetMe() ) && !user.BattleStatus().IsBot() && ( m_opts.rankneeded != UserStatus::RANK_1 ) && !user.BattleStatus().spectator ) { if ( m_opts.rankneeded > UserStatus::RANK_1 && user.GetStatus().rank < m_opts.rankneeded ) { DoAction( _T("Rank limit autospec: ") + user.GetNick() ); ForceSpectator( user, true ); } else if ( m_opts.rankneeded < UserStatus::RANK_1 && user.GetStatus().rank > ( -m_opts.rankneeded - 1 ) ) { DoAction( _T("Rank limit autospec: ") + user.GetNick() ); ForceSpectator( user, true ); } } m_ah.OnUserAdded( user ); if ( !user.BattleStatus().IsBot() && sett().GetBattleLastAutoAnnounceDescription() ) DoAction( m_opts.description ); } // any code here may be skipped if the user was autokicked return user; } void Battle::OnUserBattleStatusUpdated( User &user, UserBattleStatus status ) { if ( IsFounderMe() ) { if ( ( &user != &GetMe() ) && !status.IsBot() && ( m_opts.rankneeded != UserStatus::RANK_1 ) && !status.spectator ) { if ( m_opts.rankneeded > UserStatus::RANK_1 && user.GetStatus().rank < m_opts.rankneeded ) { DoAction( _T("Rank limit autospec: ") + user.GetNick() ); ForceSpectator( user, true ); } else if ( m_opts.rankneeded < UserStatus::RANK_1 && user.GetStatus().rank > ( -m_opts.rankneeded - 1 ) ) { DoAction( _T("Rank limit autospec: ") + user.GetNick() ); ForceSpectator( user, true ); } } UserBattleStatus previousstatus = user.BattleStatus(); if ( m_opts.lockexternalbalancechanges ) { if ( previousstatus.team != status.team ) { ForceTeam( user, previousstatus.team ); status.team = previousstatus.team; } if ( previousstatus.ally != status.ally ) { ForceAlly( user, previousstatus.ally ); status.ally = previousstatus.ally; } } } IBattle::OnUserBattleStatusUpdated( user, status ); if ( status.handicap != 0 ) { UiEvents::GetUiEventSender( UiEvents::OnBattleActionEvent ).SendEvent( UiEvents::OnBattleActionData( wxString(_T(" ")) , ( _T("Warning: user ") + user.GetNick() + _T(" got bonus ") ) << status.handicap ) ); } if ( IsFounderMe() ) { if ( ShouldAutoStart() ) { if ( sett().GetBattleLastAutoStartState() ) { if ( !spring().IsRunning() ) StartHostedBattle(); } } } if ( !GetMe().BattleStatus().spectator ) SetAutoUnspec(false); // we don't need auto unspec anymore ShouldAutoUnspec(); #ifndef SL_QT_MODE ui().OnUserBattleStatus( *this, user ); #endif } void Battle::OnUserRemoved( User& user ) { m_ah.OnUserRemoved(user); IBattle::OnUserRemoved( user ); ShouldAutoUnspec(); } void Battle::RingNotReadyPlayers() { for (user_map_t::size_type i = 0; i < GetNumUsers(); i++) { User& u = GetUser(i); UserBattleStatus& bs = u.BattleStatus(); if ( bs.IsBot() ) continue; if ( !bs.ready && !bs.spectator ) m_serv.Ring( u.GetNick() ); } } void Battle::RingNotSyncedPlayers() { for (user_map_t::size_type i = 0; i < GetNumUsers(); i++) { User& u = GetUser(i); UserBattleStatus& bs = u.BattleStatus(); if ( bs.IsBot() ) continue; if ( !bs.sync && !bs.spectator ) m_serv.Ring( u.GetNick() ); } } void Battle::RingNotSyncedAndNotReadyPlayers() { for (user_map_t::size_type i = 0; i < GetNumUsers(); i++) { User& u = GetUser(i); UserBattleStatus& bs = u.BattleStatus(); if ( bs.IsBot() ) continue; if ( ( !bs.sync || !bs.ready ) && !bs.spectator ) m_serv.Ring( u.GetNick() ); } } void Battle::RingPlayer( const User& u ) { if ( u.BattleStatus().IsBot() ) return; m_serv.Ring( u.GetNick() ); } bool Battle::ExecuteSayCommand( const wxString& cmd ) { wxString cmd_name=cmd.BeforeFirst(' ').Lower(); if ( cmd_name == _T("/me") ) { m_serv.DoActionBattle( m_opts.battleid, cmd.AfterFirst(' ') ); return true; } if ( cmd_name == _T("/replacehostip") ) { wxString ip = cmd.AfterFirst(' '); if ( ip.IsEmpty() ) return false; m_opts.ip = ip; return true; } //< quick hotfix for bans if (IsFounderMe()) { if ( cmd_name == _T("/ban") ) { wxString nick=cmd.AfterFirst(' '); m_banned_users.insert(nick); try { User& user = GetUser( nick ); m_serv.BattleKickPlayer( m_opts.battleid, user ); } catch( assert_exception ) {} UiEvents::GetUiEventSender( UiEvents::OnBattleActionEvent ).SendEvent( UiEvents::OnBattleActionData( wxString(_T(" ")) , nick+_T(" banned") ) ); //m_serv.DoActionBattle( m_opts.battleid, cmd.AfterFirst(' ') ); return true; } if ( cmd_name == _T("/unban") ) { wxString nick=cmd.AfterFirst(' '); m_banned_users.erase(nick); UiEvents::GetUiEventSender( UiEvents::OnBattleActionEvent ).SendEvent( UiEvents::OnBattleActionData( wxString(_T(" ")) , nick+_T(" unbanned") ) ); //m_serv.DoActionBattle( m_opts.battleid, cmd.AfterFirst(' ') ); return true; } if ( cmd_name == _T("/banlist") ) { UiEvents::GetUiEventSender( UiEvents::OnBattleActionEvent ).SendEvent( UiEvents::OnBattleActionData( wxString(_T(" ")) , _T("banlist:") ) ); for (std::set<wxString>::const_iterator i=m_banned_users.begin();i!=m_banned_users.end();++i) { UiEvents::GetUiEventSender( UiEvents::OnBattleActionEvent ).SendEvent( UiEvents::OnBattleActionData( wxString(_T(" ")) , *i ) ); } for (std::set<wxString>::iterator i=m_banned_ips.begin();i!=m_banned_ips.end();++i) { UiEvents::GetUiEventSender( UiEvents::OnBattleActionEvent ).SendEvent( UiEvents::OnBattleActionData( wxString(_T(" ")) , *i ) ); } return true; } if ( cmd_name == _T("/unban") ) { wxString nick=cmd.AfterFirst(' '); m_banned_users.erase(nick); m_banned_ips.erase(nick); UiEvents::GetUiEventSender( UiEvents::OnBattleActionEvent ).SendEvent( UiEvents::OnBattleActionData( wxString(_T(" ")) , nick+_T(" unbanned") ) ); //m_serv.DoActionBattle( m_opts.battleid, cmd.AfterFirst(' ') ); return true; } if ( cmd_name == _T("/ipban") ) { wxString nick=cmd.AfterFirst(' '); m_banned_users.insert(nick); UiEvents::GetUiEventSender( UiEvents::OnBattleActionEvent ).SendEvent( UiEvents::OnBattleActionData( wxString(_T(" ")) , nick+_T(" banned") ) ); if (UserExists(nick)) { User &user=GetUser(nick); if (!user.BattleStatus().ip.empty()) { m_banned_ips.insert(user.BattleStatus().ip); UiEvents::GetUiEventSender( UiEvents::OnBattleActionEvent ).SendEvent( UiEvents::OnBattleActionData( wxString(_T(" ")) , user.BattleStatus().ip+_T(" banned") ) ); } m_serv.BattleKickPlayer( m_opts.battleid, user ); } //m_banned_ips.erase(nick); //m_serv.DoActionBattle( m_opts.battleid, cmd.AfterFirst(' ') ); return true; } } //> return false; } ///< quick hotfix for bans /// returns true if user is banned (and hence has been kicked) bool Battle::CheckBan(User &user) { if (IsFounderMe()) { if (m_banned_users.count(user.GetNick())>0 || useractions().DoActionOnUser(UserActions::ActAutokick, user.GetNick() ) ) { KickPlayer(user); UiEvents::GetUiEventSender( UiEvents::OnBattleActionEvent ).SendEvent( UiEvents::OnBattleActionData( wxString(_T(" ")) , user.GetNick()+_T(" is banned, kicking") ) ); return true; } else if (m_banned_ips.count(user.BattleStatus().ip)>0) { UiEvents::GetUiEventSender( UiEvents::OnBattleActionEvent ).SendEvent( UiEvents::OnBattleActionData( wxString(_T(" ")) , user.BattleStatus().ip+_T(" is banned, kicking") ) ); KickPlayer(user); return true; } } return false; } ///> void Battle::SetAutoLockOnStart( bool value ) { m_autolock_on_start = value; } bool Battle::GetAutoLockOnStart() { return m_autolock_on_start; } void Battle::SetLockExternalBalanceChanges( bool value ) { if ( value ) DoAction( _T("has locked player balance changes") ); else DoAction( _T("has unlocked player balance changes") ); m_opts.lockexternalbalancechanges = value; } bool Battle::GetLockExternalBalanceChanges() { return m_opts.lockexternalbalancechanges; } void Battle::AddBot( const wxString& nick, UserBattleStatus status ) { m_serv.AddBot( m_opts.battleid, nick, status ); } void Battle::ForceSide( User& user, int side ) { m_serv.ForceSide( m_opts.battleid, user, side ); } void Battle::ForceTeam( User& user, int team ) { IBattle::ForceTeam( user, team ); m_serv.ForceTeam( m_opts.battleid, user, team ); } void Battle::ForceAlly( User& user, int ally ) { IBattle::ForceAlly( user, ally ); m_serv.ForceAlly( m_opts.battleid, user, ally ); } void Battle::ForceColour( User& user, const wxColour& col ) { IBattle::ForceColour( user, col ); m_serv.ForceColour( m_opts.battleid, user, col ); } void Battle::ForceSpectator( User& user, bool spectator ) { m_serv.ForceSpectator( m_opts.battleid, user, spectator ); } void Battle::KickPlayer( User& user ) { m_serv.BattleKickPlayer( m_opts.battleid, user ); } void Battle::SetHandicap( User& user, int handicap) { m_serv.SetHandicap ( m_opts.battleid, user, handicap ); } void Battle::ForceUnsyncedToSpectate() { size_t numusers = GetNumUsers(); for ( size_t i = 0; i < numusers; ++i ) { User &user = GetUser(i); UserBattleStatus& bs = user.BattleStatus(); if ( bs.IsBot() ) continue; if ( !bs.spectator && !bs.sync ) ForceSpectator( user, true ); } } void Battle::ForceUnReadyToSpectate() { size_t numusers = GetNumUsers(); for ( size_t i = 0; i < numusers; ++i ) { User &user = GetUser(i); UserBattleStatus& bs = user.BattleStatus(); if ( bs.IsBot() ) continue; if ( !bs.spectator && !bs.ready ) ForceSpectator( user, true ); } } void Battle::ForceUnsyncedAndUnreadyToSpectate() { size_t numusers = GetNumUsers(); for ( size_t i = 0; i < numusers; ++i ) { User &user = GetUser(i); UserBattleStatus& bs = user.BattleStatus(); if ( bs.IsBot() ) continue; if ( !bs.spectator && ( !bs.sync || !bs.ready ) ) ForceSpectator( user, true ); } } void Battle::UserPositionChanged( const User& user ) { m_serv.SendUserPosition( user ); } void Battle::SendScriptToClients() { m_serv.SendScriptToClients( GetScript() ); } void Battle::StartHostedBattle() { if ( UserExists( GetMe().GetNick() ) ) { if ( IsFounderMe() ) { if ( sett().GetBattleLastAutoControlState() ) { FixTeamIDs( (IBattle::BalanceType)sett().GetFixIDMethod(), sett().GetFixIDClans(), sett().GetFixIDStrongClans(), sett().GetFixIDGrouping() ); Autobalance( (IBattle::BalanceType)sett().GetBalanceMethod(), sett().GetBalanceClans(), sett().GetBalanceStrongClans(), sett().GetBalanceGrouping() ); FixColours(); } if ( IsProxy() ) { if ( UserExists( GetProxy() ) && !GetUser(GetProxy()).Status().in_game ) { // DON'T set m_generating_script here, it will trick the script generating code to think we're the host wxString hostscript = spring().WriteScriptTxt( *this ); try { wxString path = sett().GetCurrentUsedDataDir() + wxFileName::GetPathSeparator() + _T("relayhost_script.txt"); if ( !wxFile::Access( path, wxFile::write ) ) { wxLogError( _T("Access denied to script.txt.") ); } wxFile f( path, wxFile::write ); f.Write( hostscript ); f.Close(); } catch (...) {} m_serv.SendScriptToProxy( hostscript ); } } if( GetAutoLockOnStart() ) { SetIsLocked( true ); SendHostInfo( IBattle::HI_Locked ); } sett().SetLastHostMap( GetServer().GetCurrentBattle()->GetHostMapName() ); sett().SaveSettings(); if ( !IsProxy() ) GetServer().StartHostedBattle(); else if ( UserExists( GetProxy() ) && GetUser(GetProxy()).Status().in_game ) // relayhost is already ingame, let's try to join it { StartSpring(); } } } } void Battle::StartSpring() { if ( UserExists( GetMe().GetNick() ) && !GetMe().Status().in_game ) { GetMe().BattleStatus().ready = false; SendMyBattleStatus(); // set m_generating_script, this will make the script.txt writer realize we're just clients even if using a relayhost m_generating_script = true; GetMe().Status().in_game = spring().Run( *this ); m_generating_script = false; GetMe().SendMyUserStatus(); } ui().OnBattleStarted( *this ); } void Battle::OnTimer( wxTimerEvent& ) { if ( !IsFounderMe() ) return; if ( m_ingame ) return; int autospect_trigger_time = sett().GetBattleLastAutoSpectTime(); if ( autospect_trigger_time == 0 ) return; time_t now = time(0); for ( unsigned int i = 0; i < GetNumUsers(); i++) { User& usr = GetUser( i ); UserBattleStatus& status = usr.BattleStatus(); if ( status.IsBot() || status.spectator ) continue; if ( status.sync && status.ready ) continue; if ( &usr == &GetMe() ) continue; std::map<wxString, time_t>::const_iterator itor = m_ready_up_map.find( usr.GetNick() ); if ( itor != m_ready_up_map.end() ) { if ( ( now - itor->second ) > autospect_trigger_time ) { ForceSpectator( usr, true ); } } } } void Battle::SetInGame( bool value ) { time_t now = time(0); if ( m_ingame && !value ) { for ( int i = 0; i < long(GetNumUsers()); i++ ) { User& user = GetUser( i ); UserBattleStatus& status = user.BattleStatus(); if ( status.IsBot() || status.spectator ) continue; if ( status.ready && status.sync ) continue; m_ready_up_map[user.GetNick()] = now; } } IBattle::SetInGame( value ); } void Battle::FixColours() { if ( !IsFounderMe() )return; std::vector<wxColour> &palette = GetFixColoursPalette( m_teams_sizes.size() + 1 ); std::vector<int> palette_use( palette.size(), 0 ); wxColour my_col = GetMe().BattleStatus().colour; // Never changes color of founder (me) :-) int my_diff = 0; int my_col_i = GetClosestFixColour( my_col, palette_use,my_diff ); palette_use[my_col_i]++; std::set<int> parsed_teams; for ( user_map_t::size_type i = 0; i < GetNumUsers(); i++ ) { User &user=GetUser(i); if ( &user == &GetMe() ) continue; // skip founder ( yourself ) UserBattleStatus& status = user.BattleStatus(); if ( status.spectator ) continue; if ( parsed_teams.find( status.team ) != parsed_teams.end() ) continue; // skip duplicates parsed_teams.insert( status.team ); wxColour &user_col=status.colour; int user_col_i=GetClosestFixColour(user_col,palette_use, 60); palette_use[user_col_i]++; for ( user_map_t::size_type j = 0; j < GetNumUsers(); j++ ) { User &usr=GetUser(j); if ( usr.BattleStatus().team == status.team ) { ForceColour( usr, palette[user_col_i]); } } } } bool PlayerRankCompareFunction( User *a, User *b ) // should never operate on nulls. Hence, ASSERT_LOGIC is appropriate here. { ASSERT_LOGIC( a, _T("fail in Autobalance, NULL player") ); ASSERT_LOGIC( b, _T("fail in Autobalance, NULL player") ); return ( a->GetBalanceRank() > b->GetBalanceRank() ); } bool PlayerTeamCompareFunction( User *a, User *b ) // should never operate on nulls. Hence, ASSERT_LOGIC is appropriate here. { ASSERT_LOGIC( a, _T("fail in Autobalance, NULL player") ); ASSERT_LOGIC( b, _T("fail in Autobalance, NULL player") ); return ( a->BattleStatus().team > b->BattleStatus().team ); } struct Alliance { std::vector<User *>players; float ranksum; int allynum; Alliance(): ranksum(0), allynum(-1) {} Alliance(int i): ranksum(0), allynum(i) {} void AddPlayer( User *player ) { if ( player ) { players.push_back( player ); ranksum += player->GetBalanceRank(); } } void AddAlliance( Alliance &other ) { for ( std::vector<User *>::const_iterator i = other.players.begin(); i != other.players.end(); ++i ) AddPlayer( *i ); } bool operator < ( const Alliance &other ) const { return ranksum < other.ranksum; } }; struct ControlTeam { std::vector<User*> players; float ranksum; int teamnum; ControlTeam(): ranksum(0), teamnum(-1) {} ControlTeam( int i ): ranksum(0), teamnum(i) {} void AddPlayer( User *player ) { if ( player ) { players.push_back( player ); ranksum += player->GetBalanceRank(); } } void AddTeam( ControlTeam &other ) { for ( std::vector<User*>::const_iterator i = other.players.begin(); i != other.players.end(); ++i ) AddPlayer( *i ); } bool operator < (const ControlTeam &other) const { return ranksum < other.ranksum; } }; int my_random( int range ) { return rand() % range; } void shuffle(std::vector<User *> &players) // proper shuffle. { for ( size_t i=0; i < players.size(); ++i ) // the players below i are shuffled, the players above arent { int rn = i + my_random( players.size() - i ); // the top of shuffled part becomes random card from unshuffled part User *tmp = players[i]; players[i] = players[rn]; players[rn] = tmp; } } /* bool ClanRemovalFunction(const std::map<wxString, Alliance>::value_type &v){ return v.second.players.size()<2; } */ /* struct ClannersRemovalPredicate{ std::map<wxString, Alliance> &clans; PlayerRemovalPredicate(std::map<wxString, Alliance> &clans_):clans(clans_) { } bool operator()(User *u) const{ return clans.find(u->GetClan()); } }*/ void Battle::Autobalance( BalanceType balance_type, bool support_clans, bool strong_clans, int numallyteams ) { wxLogMessage(_T("Autobalancing alliances, type=%d, clans=%d, strong_clans=%d, numallyteams=%d"),balance_type, support_clans,strong_clans, numallyteams); //size_t i; //int num_alliances; std::vector<Alliance>alliances; if ( numallyteams == 0 || numallyteams == -1 ) // 0 or 1 -> use num start rects { int ally = 0; for ( unsigned int i = 0; i < GetNumRects(); ++i ) { BattleStartRect sr = GetStartRect(i); if ( sr.IsOk() ) { ally=i; alliances.push_back( Alliance( ally ) ); ally++; } } // make at least two alliances while ( alliances.size() < 2 ) { alliances.push_back( Alliance( ally ) ); ally++; } } else { for ( int i = 0; i < numallyteams; i++ ) alliances.push_back( Alliance( i ) ); } //for(i=0;i<alliances.size();++i)alliances[i].allynum=i; wxLogMessage( _T("number of alliances: %u"), alliances.size() ); std::vector<User*> players_sorted; players_sorted.reserve( GetNumUsers() ); for ( size_t i = 0; i < GetNumUsers(); ++i ) { User& usr = GetUser( i ); if ( !usr.BattleStatus().spectator ) { players_sorted.push_back( &usr ); } } // remove players in the same team so only one remains std::map< int, User*> dedupe_teams; for ( std::vector<User*>::const_iterator it = players_sorted.begin(); it != players_sorted.end(); ++it ) { dedupe_teams[(*it)->BattleStatus().team] = *it; } players_sorted.clear(); players_sorted.reserve( dedupe_teams.size() ); for ( std::map<int, User*>::const_iterator it = dedupe_teams.begin(); it != dedupe_teams.end(); ++it ) { players_sorted.push_back( it->second ); } shuffle( players_sorted ); std::map<wxString, Alliance> clan_alliances; if ( support_clans ) { for ( size_t i=0; i < players_sorted.size(); ++i ) { wxString clan = players_sorted[i]->GetClan(); if ( !clan.empty() ) { clan_alliances[clan].AddPlayer( players_sorted[i] ); } } }; if ( balance_type != balance_random ) std::sort( players_sorted.begin(), players_sorted.end(), PlayerRankCompareFunction ); if ( support_clans ) { std::map<wxString, Alliance>::iterator clan_it = clan_alliances.begin(); while ( clan_it != clan_alliances.end() ) { Alliance &clan = (*clan_it).second; // if clan is too small (only 1 clan member in battle) or too big, dont count it as clan if ( ( clan.players.size() < 2 ) || ( !strong_clans && ( clan.players.size() > ( ( players_sorted.size() + alliances.size() -1 ) / alliances.size() ) ) ) ) { wxLogMessage( _T("removing clan %s"), (*clan_it).first.c_str() ); std::map<wxString, Alliance>::iterator next = clan_it; ++next; clan_alliances.erase( clan_it ); clan_it = next; continue; } wxLogMessage( _T("Inserting clan %s"), (*clan_it).first.c_str() ); std::sort( alliances.begin(), alliances.end() ); float lowestrank = alliances[0].ranksum; int rnd_k = 1;// number of alliances with rank equal to lowestrank while ( size_t( rnd_k ) < alliances.size() ) { if ( fabs( alliances[rnd_k].ranksum - lowestrank ) > 0.01 ) break; rnd_k++; } wxLogMessage( _T("number of lowestrank alliances with same rank=%d"), rnd_k ); alliances[my_random( rnd_k )].AddAlliance( clan ); ++clan_it; } } for ( size_t i = 0; i < players_sorted.size(); ++i ) { // skip clanners, those have been added already. if ( clan_alliances.count( players_sorted[i]->GetClan() ) > 0 ) { wxLogMessage( _T("clanner already added, nick=%s"), players_sorted[i]->GetNick().c_str() ); continue; } // find alliances with lowest ranksum // insert current user into random one out of them // since performance doesnt matter here, i simply sort alliances, // then find how many alliances in beginning have lowest ranksum // note that balance player ranks range from 1 to 1.1 now // i.e. them are quasi equal // so we're essentially adding to alliance with smallest number of players, // the one with smallest ranksum. std::sort( alliances.begin(), alliances.end() ); float lowestrank = alliances[0].ranksum; int rnd_k = 1;// number of alliances with rank equal to lowestrank while ( size_t( rnd_k ) < alliances.size() ) { if ( fabs( alliances[rnd_k].ranksum - lowestrank ) > 0.01 ) break; rnd_k++; } wxLogMessage( _T("number of lowestrank alliances with same rank=%d"), rnd_k ); alliances[my_random( rnd_k )].AddPlayer( players_sorted[i] ); } UserList::user_map_t::size_type totalplayers = GetNumUsers(); for ( size_t i = 0; i < alliances.size(); ++i ) { for ( size_t j = 0; j < alliances[i].players.size(); ++j ) { ASSERT_LOGIC( alliances[i].players[j], _T("fail in Autobalance, NULL player") ); int balanceteam = alliances[i].players[j]->BattleStatus().team; wxLogMessage( _T("setting team %d to alliance %d"), balanceteam, i ); for ( size_t h = 0; h < totalplayers; h++ ) // change ally num of all players in the team { User& usr = GetUser( h ); if ( usr.BattleStatus().team == balanceteam ) ForceAlly( usr, alliances[i].allynum ); } } } } void Battle::FixTeamIDs( BalanceType balance_type, bool support_clans, bool strong_clans, int numcontrolteams ) { wxLogMessage(_T("Autobalancing teams, type=%d, clans=%d, strong_clans=%d, numcontrolteams=%d"),balance_type, support_clans, strong_clans, numcontrolteams); //size_t i; //int num_alliances; std::vector<ControlTeam> control_teams; if ( numcontrolteams == 0 || numcontrolteams == -1 ) numcontrolteams = GetNumUsers() - GetSpectators(); // 0 or -1 -> use num players, will use comshare only if no available team slots IBattle::StartType position_type = (IBattle::StartType)s2l( CustomBattleOptions().getSingleValue( _T("startpostype"), OptionsWrapper::EngineOption ) ); if ( ( position_type == ST_Fixed ) || ( position_type == ST_Random ) ) // if fixed start pos type or random, use max teams = start pos count { try { int mapposcount = LoadMap().info.positions.size(); numcontrolteams = std::min( numcontrolteams, mapposcount ); } catch( assert_exception ) {} } if ( numcontrolteams >= (int)( GetNumUsers() - GetSpectators() ) ) // autobalance behaves weird when trying to put one player per team and i CBA to fix it, so i'll reuse the old code :P { // apparently tasserver doesnt like when i fix/force ids of everyone. std::set<int> allteams; size_t numusers = GetNumUsers(); for( size_t i = 0; i < numusers; ++i ) { User &user = GetUser(i); if( !user.BattleStatus().spectator ) allteams.insert( user.BattleStatus().team ); } std::set<int> teams; int t = 0; for( size_t i = 0; i < GetNumUsers(); ++i ) { User &user = GetUser(i); if( !user.BattleStatus().spectator ) { if( teams.count( user.BattleStatus().team ) ) { while( allteams.count(t) || teams.count( t ) ) t++; ForceTeam( GetUser(i), t ); teams.insert( t ); } else { teams.insert( user.BattleStatus().team ); } } } return; } for ( int i = 0; i < numcontrolteams; i++ ) control_teams.push_back( ControlTeam( i ) ); wxLogMessage(_T("number of teams: %u"), control_teams.size() ); std::vector<User*> players_sorted; players_sorted.reserve( GetNumUsers() ); int player_team_counter = 0; for ( size_t i = 0; i < GetNumUsers(); ++i ) // don't count spectators { if ( !GetUser(i).BattleStatus().spectator ) { players_sorted.push_back( &GetUser(i) ); // -- server fail? it doesnt work right. //ForceTeam(GetUser(i),player_team_counter); player_team_counter++; } } shuffle( players_sorted ); std::map<wxString, ControlTeam> clan_teams; if ( support_clans ) { for ( size_t i = 0; i < players_sorted.size(); ++i ) { wxString clan = players_sorted[i]->GetClan(); if ( !clan.empty() ) { clan_teams[clan].AddPlayer( players_sorted[i] ); } } }; if ( balance_type != balance_random ) std::sort( players_sorted.begin(), players_sorted.end(), PlayerRankCompareFunction ); if ( support_clans ) { std::map<wxString, ControlTeam>::iterator clan_it = clan_teams.begin(); while ( clan_it != clan_teams.end() ) { ControlTeam &clan = (*clan_it).second; // if clan is too small (only 1 clan member in battle) or too big, dont count it as clan if ( ( clan.players.size() < 2 ) || ( !strong_clans && ( clan.players.size() > ( ( players_sorted.size() + control_teams.size() -1 ) / control_teams.size() ) ) ) ) { wxLogMessage(_T("removing clan %s"),(*clan_it).first.c_str()); std::map<wxString, ControlTeam>::iterator next = clan_it; ++next; clan_teams.erase( clan_it ); clan_it = next; continue; } wxLogMessage( _T("Inserting clan %s"), (*clan_it).first.c_str() ); std::sort( control_teams.begin(), control_teams.end() ); float lowestrank = control_teams[0].ranksum; int rnd_k = 1; // number of alliances with rank equal to lowestrank while ( size_t( rnd_k ) < control_teams.size() ) { if ( fabs( control_teams[rnd_k].ranksum - lowestrank ) > 0.01 ) break; rnd_k++; } wxLogMessage(_T("number of lowestrank teams with same rank=%d"), rnd_k ); control_teams[my_random( rnd_k )].AddTeam( clan ); ++clan_it; } } for (size_t i = 0; i < players_sorted.size(); ++i ) { // skip clanners, those have been added already. if ( clan_teams.count( players_sorted[i]->GetClan() ) > 0 ) { wxLogMessage( _T("clanner already added, nick=%s"),players_sorted[i]->GetNick().c_str() ); continue; } // find teams with lowest ranksum // insert current user into random one out of them // since performance doesnt matter here, i simply sort teams, // then find how many teams in beginning have lowest ranksum // note that balance player ranks range from 1 to 1.1 now // i.e. them are quasi equal // so we're essentially adding to teams with smallest number of players, // the one with smallest ranksum. std::sort( control_teams.begin(), control_teams.end() ); float lowestrank = control_teams[0].ranksum; int rnd_k = 1; // number of alliances with rank equal to lowestrank while ( size_t( rnd_k ) < control_teams.size() ) { if ( fabs ( control_teams[rnd_k].ranksum - lowestrank ) > 0.01 ) break; rnd_k++; } wxLogMessage( _T("number of lowestrank teams with same rank=%d"), rnd_k ); control_teams[my_random( rnd_k )].AddPlayer( players_sorted[i] ); } for ( size_t i=0; i < control_teams.size(); ++i ) { for ( size_t j = 0; j < control_teams[i].players.size(); ++j ) { ASSERT_LOGIC( control_teams[i].players[j], _T("fail in Autobalance teams, NULL player") ); wxString msg = wxFormat( _T("setting player %s to team and ally %d") ) % control_teams[i].players[j]->GetNick() % i; wxLogMessage( _T("%s"), msg.c_str() ); ForceTeam( *control_teams[i].players[j], control_teams[i].teamnum ); ForceAlly( *control_teams[i].players[j], control_teams[i].teamnum ); } } } void Battle::OnUnitsyncReloaded( GlobalEvents::GlobalEventData data ) { IBattle::OnUnitsyncReloaded( data ); if ( m_is_self_in ) SendMyBattleStatus(); } void Battle::ShouldAutoUnspec() { if ( m_auto_unspec && !IsLocked() && GetMe().BattleStatus().spectator ) { if ( GetNumActivePlayers() < m_opts.maxplayers ) { ForceSpectator(GetMe(),false); } } } void Battle::SetAutoUnspec(bool value) { m_auto_unspec = value; ShouldAutoUnspec(); }
N2maniac/springlobby-join-fork
src/battle.cpp
C++
gpl-2.0
36,385
<?hh namespace Pi\Interfaces; interface IServiceExecute { public function execute(IRequest $context, $instance, $request); }
guilhermegeek/communia
src/Pi-Interfaces/IServiceExecute.php
PHP
gpl-2.0
127
/* Theme Name: FlatOn Theme URI: http://www.webulousthemes.com/flaton/ Author: N. Venkat Raj Author URI: http://www.webulousthemes.com/ Description: FlatOn is inspired by flat design trend and comes with modern and responsive design. Also has two different color schemes. It uses skeleton framework for grids which keeps minimal css. Stylesheet is generated using SASS and so stays DRY. Best suited for Corporate/Business/Blog sites and also support Jigoshop eCommerce. Supports theme options panel and comes with lots of options. Has 4 Footer Widget Areas, allows Custom CSS via theme option panel. Demo: http://demo.webulous.in/flaton Version: 1.1.7 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Text Domain: flaton Tags: custom-background, custom-header, custom-menu, featured-images, post-formats, responsive-layout, right-sidebar, left-sidebar, sticky-post, threaded-comments, translation-ready, two-columns This theme, like WordPress, is licensed under the GPL. Use it to make something cool, have fun, and share what you've learned with others. Resetting and rebuilding styles have been helped along thanks to the fine work of Eric Meyer http://meyerweb.com/eric/tools/css/reset/index.html along with Nicolas Gallagher and Jonathan Neal http://necolas.github.com/normalize.css/ and Blueprint http://www.blueprintcss.org/ */ /*-------------------------------------------------------------- >>> TABLE OF CONTENTS: ---------------------------------------------------------------- 0.0 Reset 1.0 Grid 2.0 Typography 3.0 Elements 4.0 Forms 5.0 Navigation 5.1 Links 5.2 Menus 6.0 Accessibility 7.0 Alignments 8.0 Clearings 9.0 Widgets 10.0 Content 10.1 Posts and pages 10.2 Asides 10.3 Comments 11.0 Infinite scroll 12.0 Media 12.1 Captions 12.2 Galleries --------------------------------------------------------------*/ /*-------------------------------------------------------------- 0.0 Reset --------------------------------------------------------------*/ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { border: 0; font-family: inherit; font-size: 100%; font-style: inherit; font-weight: inherit; margin: 0; outline: 0; padding: 0; vertical-align: baseline; } html { font-size: 62.5%; /* Corrects text resizing oddly in IE6/7 when body font-size is set using em units http://clagnut.com/blog/348/#c790 */ overflow-y: scroll; /* Keeps page centered in all browsers regardless of content height */ -webkit-text-size-adjust: 100%; /* Prevents iOS text size adjust after orientation change, without disabling user zoom */ -ms-text-size-adjust: 100%; /* www.456bereastreet.com/archive/201012/controlling_text_size_in_safari_for_ios_without_disabling_user_zoom/ */ } *, *:before, *:after { /* apply a natural box layout model to all elements; see http://www.paulirish.com/2012/box-sizing-border-box-ftw/ */ -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } body { background: #FFFFFF; /* Fallback for when there is no custom background color defined. */ } article, aside, details, figcaption, figure, footer, header, main, nav, section { display: block; } /*ol, ul { list-style: none; }*/ table { /* tables still need 'cellspacing="0"' in the markup */ border-collapse: separate; border-spacing: 0; } caption, th, td { font-weight: normal; text-align: left; } blockquote:before, blockquote:after, q:before, q:after { content: ""; } blockquote, q { quotes: "" ""; } a:focus { outline: thin dotted; } a:hover, a:active { outline: 0; } a img { border: 0; } /*-------------------------------------------------------------- 1.0 Grid --------------------------------------------------------------*/ .container { position: relative; width: 93%; max-width: 1170px; margin: 0 auto; padding: 0; } .container .one.column { width: 4.1%; } .container .two.columns { width: 10.4%; } .container .three.columns { width: 16.6%; } .container .four.columns { width: 22.9%; } .container .five.columns { width: 29.16%; } .container .six.columns { width: 35%; } .container .seven.columns { width: 41.6%; } .container .eight.columns { width: 47.9%; } .container .nine.columns { width: 54.16%; } .container .ten.columns { width: 60%; } .container .eleven.columns { width: 66.66%; } .container .twelve.columns { width: 72.9%; } .container .thirteen.columns { width: 79.16%; } .container .fourteen.columns { width: 85%; } .container .fifteen.columns { width: 91.66%; } .container .sixteen.columns { width: 97.9%; } .container .one-third.column { width: 31.25%; } .container .tow-thirds.column { width: 64.5%; } .container .offset-by-one { padding-left: 6.25%; } .container .offset-by-two { padding-left: 12.5%; } .container .offset-by-three { padding-left: 18.75%; } .container .offset-by-four { padding-left: 25%; } .container .offset-by-five { padding-left: 31.25%; } .container .offset-by-six { padding-left: 37.5%; } .container .offset-by-seven { padding-left: 43.7%; } .container .offset-by-eight { padding-left: 50%; } .container .offset-by-nine { padding-left: 56.25%; } .container .offset-by-ten { padding-left: 62.5%; } .container .offset-by-eleven { padding-left: 68.75%; } .container .offset-by-twelve { padding-left: 75%; } .container .offset-by-thirteen { padding-left: 81.25%; } .container .offset-by-fourteen { padding-left: 87.5%; } .container .offset-by-fifteen { padding-left: 93.75%; } .column, .columns { float: left; display: inline; margin-left: 1%; margin-right: 1%; } .column .alpha, .columns .alpha { margin-left: 0; } .column .omega, .columns .omega { margin-right: 0; } .row { margin-bottom: 2%; } @media only screen and (min-width: 768px) and (max-width: 959px) { .container { width: 93%; } .container .column, .container .columns { margin-left: 1.3%; margin-right: 1.3%; } .container .column .alpha, .container .columns .alpha { margin-left: 0; margin-right: 1.3%; } .container .column .omega, .container .columns .omega { margin-left: 1.3%; margin-right: 0%; } .container .one.column { width: 3.64%; } .container .two.columns { width: 9.89%; } .container .three.columns { width: 16.1%; } .container .four.columns { width: 22.39%; } .container .five.columns { width: 28.64%; } .container .six.columns { width: 34.89%; } .container .seven.columns { width: 41.14%; } .container .eight.columns { width: 47.39%; } .container .nine.columns { width: 53.64%; } .container .ten.columns { width: 59.89%; } .container .eleven.columns { width: 66.14%; } .container .twelve.columns { width: 72.39%; } .container .thirteen.columns { width: 78.64%; } .container .fourteen.columns { width: 84.89%; } .container .fifteen.columns { width: 91.14%; } .container .sixteen.columns { width: 97.39%; } .container .one-third.column { width: 30.72%; } .container .two-thirds.column { width: 64%; } .container .offset-by-one { padding-left: 6.25%; } .container .offset-by-two { padding-left: 12.5%; } .container .offset-by-three { padding-left: 18.75%; } .container .offset-by-four { padding-left: 25%; } .container .offset-by-five { padding-left: 31.25%; } .container .offset-by-six { padding-left: 37.5%; } .container .offset-by-seven { padding-left: 43.75%; } .container .offset-by-eight { padding-left: 45%; } .container .offset-by-nine { padding-left: 56.25%; } .container .offset-by-ten { padding-left: 62.5%; } .container .offset-by-eleven { padding-left: 68.75%; } .container .offset-by-twelve { padding-left: 75%; } .container .offset-by-thirteen { padding-left: 81.25%; } .container .offset-by-fourteen { padding-left: 87.5%; } .container .offset-by-fifteen { padding-left: 93.75%; } } @media only screen and (max-width: 767px) { .container { width: 93%; } .container .one.column, .container .two.columns, .container .three.columns, .container .four.columns, .container .five.columns, .container .six.columns, .container .seven.columns, .container .eight.columns, .container .nine.columns, .container .ten.columns, .container .eleven.columns, .container .twelve.columns, .container .thirteen.columns, .container .fourteen.columns, .container .fifteen.columns, .container .sixteen.columns, .container .one-third.column, .container .two-thirds.column { width: 100%; } .container .offset-by-one, .container .offset-by-two, .container .offset-by-three, .container .offset-by-four, .container .offset-by-five, .container .offset-by-six, .container .offset-by-seven, .container .offset-by-eight, .container .offset-by-nine, .container .offset-by-ten, .container .offset-by-eleven, .container .offset-by-twelve, .container .offset-by-thirteen, .container .offset-by-fourteen, .container .offset-by-fifteen { padding-left: 0; } .columns, .column { margin: 0; } } @media only screen and (min-width: 480px) and (max-width: 767px) { .container { width: 93%; } .container .one.column, .container .two.columns, .container .three.columns, .container .four.columns, .container .five.columns, .container .six.columns, .container .seven.columns, .container .eight.columns, .container .nine.columns, .container .ten.columns, .container .eleven.columns, .container .twelve.columns, .container .thirteen.columns, .container .fourteen.columns, .container .fifteen.columns, .container .sixteen.columns, .container .one-third.column, .container .two-thirds.column { width: 100%; } .columns, .column { margin: 0; } } /* #Clearing ================================================== */ /* Self Clearing Goodness */ .container:after { content: "\0020"; display: block; height: 0; clear: both; visibility: hidden; } /* Use clearfix class on parent to clear nested columns, or wrap each row of columns in a <div class="row"> */ .clearfix:before, .clearfix:after, .row:before, .row:after, .panel-row-style-full-width-layout:before, .panel-row-style-full-width-layout:after, .panel-row-style-section-divider:before, .panel-row-style-section-divider:after { content: '\0020'; display: block; overflow: hidden; visibility: hidden; width: 0; height: 0; } .row:after, .clearfix:after, .panel-row-style-full-width-layout:before, .panel-row-style-full-width-layout:after, .panel-row-style-section-divider:before, .panel-row-style-section-divider:after { clear: both; } .row, .clearfix { zoom: 1; } /* You can also use a <br class="clear" /> to clear columns */ .clear { clear: both; display: block; overflow: hidden; visibility: hidden; width: 0; height: 0; } /* ==|== primary styles ===================================================== Author: Lucas - Skeleton Based Media Queries ========================================================================== */ /* Smaller than standard 960 (devices and browsers) */ /* Tablet Portrait size to standard 960 (devices and browsers) */ /* All Mobile Sizes (devices and browser) */ /* Mobile Landscape Size to Tablet Portrait (devices and browsers) */ /* Mobile Portrait Size to Mobile Landscape Size (devices and browsers) */ /*-------------------------------------------------------------- 2.0 Typography --------------------------------------------------------------*/ body, button, input, select, textarea { color: #34495E; font-family: "Source Sans Pro", sans-serif; font-size: 16px; font-size: 1.6rem; line-height: 1.5; } h1, h2, h3, h4, h5, h6 { clear: both; font-family: "Bitter", serif; font-weight: 700; } h1 { font-size: 40px; font-size: 4rem; } h2 { font-size: 30px; font-size: 3rem; } h3 { font-size: 22px; font-size: 2.2rem; } h4 { font-size: 20px; font-size: 2rem; } h5 { font-size: 18px; font-size: 1.8rem; } h6 { font-size: 16px; font-size: 1.6rem; } p { margin-bottom: 1.5em; } b, strong { font-weight: bold; } dfn, cite, em, i { font-style: italic; } blockquote { margin: 0 1.5em; } address { margin: 0 0 1.5em; } pre { background: #F5F5F5; font-family: "Courier 10 Pitch", Courier, monospace; font-size: 15px; font-size: 1.5rem; line-height: 1.6; margin-bottom: 1.6em; max-width: 100%; overflow: auto; padding: 1.6em; border: 1px solid #ECF0F1; } code, kbd, tt, var { font-size: 15px; font-size: 1.5rem; font-family: Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace; } abbr, acronym { border-bottom: 1px dotted #34495E; cursor: help; } mark, ins { background: #b9c8d8; text-decoration: none; } sup, sub { font-size: 75%; height: 0; line-height: 0; position: relative; vertical-align: baseline; } sup { bottom: 1ex; } sub { top: .5ex; } small { font-size: 75%; } big { font-size: 125%; } /*-------------------------------------------------------------- 3.0 Elements --------------------------------------------------------------*/ hr { background-color: #ECF0F1; border: 0; height: 1px; margin-bottom: 1.5em; } ul, ol { margin: 0 0 1.5em 3em; } /*ul { list-style: disc; } ol { list-style: decimal; }*/ li > ul, li > ol { margin-bottom: 0; margin-left: 1.5em; } dt { font-weight: bold; } dd { margin: 0 1.5em 1.5em; } img { height: auto; /* Make sure images are scaled correctly. */ max-width: 100%; /* Adhere to container width. */ } figure { margin: 0; } table { width: 100%; border-spacing: 0; margin: 0 0 1.5em; border-collapse: separate; border: 1px solid #ECF0F1; } table th { font-weight: bold; } table caption, table td, table th { text-align: center; padding: 5px; } table td, table th { border: 1px solid #ECF0F1; border-top: 0; border-right: 0; } table td#today { background-color: #3498db; color: #FFFFFF; } table { border-left: 0; border-bottom: 0; } /*-------------------------------------------------------------- 4.0 Forms --------------------------------------------------------------*/ button, input, select, textarea { font-size: 100%; /* Corrects font size not being inherited in all browsers */ margin: 0; /* Addresses margins set differently in IE6/7, F3/4, S5, Chrome */ vertical-align: baseline; /* Improves appearance and consistency in all browsers */ } button, input[type="button"], input[type="reset"], input[type="submit"] { background: #3498db; color: #FFFFFF; cursor: pointer; /* Improves usability and consistency of cursor style between image-type 'input' and others */ -webkit-appearance: button; /* Corrects inability to style clickable 'input' types in iOS */ line-height: 1; padding: 7px 10px; border: 0; -webkit-transition: background-color 1s ease; -moz-transition: background-color 1s ease; -ms-transition: background-color 1s ease; -o-transition: background-color 1s ease; transition: background-color 1s ease; } button:hover, input[type="button"]:hover, input[type="reset"]:hover, input[type="submit"]:hover { background-color: #34495E; } button:focus, input[type="button"]:focus, input[type="reset"]:focus, input[type="submit"]:focus, button:active, input[type="button"]:active, input[type="reset"]:active, input[type="submit"]:active { border-color: #34495E; } input[type="checkbox"], input[type="radio"] { padding: 0; /* Addresses excess padding in IE8/9 */ } input[type="search"] { -webkit-appearance: textfield; /* Addresses appearance set to searchfield in S5, Chrome */ -webkit-box-sizing: content-box; /* Addresses box sizing set to border-box in S5, Chrome (include -moz to future-proof) */ -moz-box-sizing: content-box; box-sizing: content-box; } input[type="search"]::-webkit-search-decoration { /* Corrects inner padding displayed oddly in S5, Chrome on OSX */ -webkit-appearance: none; } button::-moz-focus-inner, input::-moz-focus-inner { /* Corrects inner padding and border displayed oddly in FF3/4 www.sitepen.com/blog/2008/05/14/the-devils-in-the-details-fixing-dojos-toolbar-buttons/ */ border: 0; padding: 0; } input[type="text"], input[type="email"], input[type="url"], input[type="password"], input[type="search"], textarea { color: #6D6D6D; border: 1px solid #ECF0F1; background-clip: padding-box; /* stops bg color from leaking outside the border: */ -webkit-border-radius: 3px; border-radius: 3px; } input[type="text"]:focus, input[type="email"]:focus, input[type="url"]:focus, input[type="password"]:focus, input[type="search"]:focus, textarea:focus { color: #6D6D6D; } input[type="text"], input[type="email"], input[type="url"], input[type="password"], input[type="search"] { padding: 3px; } textarea { overflow: auto; /* Removes default vertical scrollbar in IE6/7/8/9 */ padding-left: 3px; vertical-align: top; /* Improves readability and alignment in all browsers */ width: 100%; } /*-------------------------------------------------------------- 5.0 Navigation --------------------------------------------------------------*/ /*-------------------------------------------------------------- 5.1 Links --------------------------------------------------------------*/ a { color: #3498db; text-decoration: none; } a:visited { color: #3498db; } a:hover, a:focus, a:active { color: #196090; -webkit-transition: color 0.5s ease; -moz-transition: color 0.5s ease; -ms-transition: color 0.5s ease; -o-transition: color 0.5s ease; transition: color 0.5s ease; } /*-------------------------------------------------------------- 5.2 Menus --------------------------------------------------------------*/ .main-navigation { clear: both; display: block; float: left; width: 100%; } .main-navigation ul { list-style: none; margin: 0; padding-left: 0; } .main-navigation ul ul { box-shadow: 0 3px 3px rgba(0, 0, 0, 0.2); background-color: #34495E; float: left; position: absolute; top: 57px; left: -999em; z-index: 99999; } .main-navigation ul ul ul { left: -999em; top: 0; } .main-navigation ul ul li { line-height: 40px; } .main-navigation ul ul li:hover > ul { left: 100%; } .main-navigation ul ul a { width: 300px; border-left: 5px solid transparent; padding-left: 15px; } .main-navigation ul ul :hover > a { padding-left: 25px; -webkit-transition: padding 0.5s ease; -moz-transition: padding 0.5s ease; -ms-transition: padding 0.5s ease; -o-transition: padding 0.5s ease; transition: padding 0.5s ease; } .main-navigation ul ul a:hover { border-color: #1aace7; } .main-navigation ul li:hover > ul { left: auto; } .main-navigation li { float: left; position: relative; line-height: 57px; } .main-navigation li:hover > a { background-color: #3498db; } .main-navigation a { display: block; text-decoration: none; padding: 0 25px; color: #FFFFFF; } .main-navigation .current_page_item a, .main-navigation .current-menu-item a { background-color: #3498db; } /* Small menu */ .menu-toggle { display: none; } @media screen and (max-width: 600px) { .menu-toggle, .main-navigation.toggled .nav-menu { display: block !important; padding: 15px 0; margin: 5px 0; width: 100%; } .main-navigation li { float: none; line-height: 40px; } .main-navigation li ul { display: block; top: 40px; } .main-navigation ul ul li:hover > ul { left: 25px; } .main-navigation ul { display: none; } } .comment-navigation .nav-previous a, .paging-navigation .nav-previous a, .post-navigation .nav-previous a, .comment-navigation .nav-next a, .paging-navigation .nav-next a, .post-navigation .nav-next a, .page-links a, .more-link { display: inline-block; background-color: #3498db; color: #FFFFFF; padding: 7px 10px; -webkit-transition: background-color 1s ease; -moz-transition: background-color 1s ease; -ms-transition: background-color 1s ease; -o-transition: background-color 1s ease; transition: background-color 1s ease; } .comment-navigation .nav-previous a:hover, .paging-navigation .nav-previous a:hover, .post-navigation .nav-previous a:hover, .comment-navigation .nav-next a:hover, .paging-navigation .nav-next a:hover, .post-navigation .nav-next a:hover, .page-links a:hover, .more-link:hover { background-color: #34495E; color: #FFFFFF; } .site-main .comment-navigation, .site-main .paging-navigation, .site-main .post-navigation { margin: 0 0 1.5em; overflow: hidden; } .comment-navigation .nav-previous, .paging-navigation .nav-previous, .post-navigation .nav-previous { float: left; width: 50%; } .comment-navigation .nav-previous .meta-nav, .paging-navigation .nav-previous .meta-nav, .post-navigation .nav-previous .meta-nav { padding: 6px 10px; } .comment-navigation .nav-next, .paging-navigation .nav-next, .post-navigation .nav-next { float: right; text-align: right; width: 50%; } .comment-navigation .nav-next .meta-nav, .paging-navigation .nav-next .meta-nav, .post-navigation .nav-next .meta-nav { padding: 6px 10px; } /*-------------------------------------------------------------- 6.0 Accessibility --------------------------------------------------------------*/ /* Text meant only for screen readers */ .screen-reader-text { clip: rect(1px, 1px, 1px, 1px); position: absolute !important; height: 1px; width: 1px; overflow: hidden; } .screen-reader-text:hover, .screen-reader-text:active, .screen-reader-text:focus { background-color: #FFFFFF; background-clip: padding-box; /* stops bg color from leaking outside the border: */ -webkit-border-radius: 3px; border-radius: 3px; box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.6); clip: auto !important; color: #6D6D6D; display: block; font-size: 14px; font-size: 1.4rem; font-weight: bold; height: auto; left: 5px; line-height: normal; padding: 15px 23px 14px; text-decoration: none; top: 5px; width: auto; z-index: 100000; /* Above WP toolbar */ } /*-------------------------------------------------------------- 7.0 Alignments --------------------------------------------------------------*/ .alignleft { display: inline; float: left; margin-right: 1.5em; } .alignright { display: inline; float: right; margin-left: 1.5em; } .aligncenter { display: block; margin: 0 auto; } /*-------------------------------------------------------------- 8.0 Clearings --------------------------------------------------------------*/ .clear:before, .clear:after, .entry-content:before, .entry-content:after, .comment-content:before, .comment-content:after, .site-header:before, .site-header:after, .site-content:before, .site-content:after, .site-footer:before, .site-footer:after { content: ""; display: table; } .clear:after, .entry-content:after, .comment-content:after, .site-header:after, .site-content:after, .site-footer:after { clear: both; } /*-------------------------------------------------------------- 9.0 Widgets --------------------------------------------------------------*/ .widget-title { color: #3498db; } .widget { margin: 0 0 1.5em; /* Make sure select elements fit in widgets */ } .widget h3 { margin-bottom: .5em; } .widget select { max-width: 100%; width: 100%; } .widget ul { margin: 0; list-style: none; } .widget ul li { border-bottom: 1px solid #ECF0F1; color: #797979; } .widget ul li a { padding-left: 15px; background: url("images/list.png") no-repeat left 8px; -webkit-transition: all 0.5s; -moz-transition: all 0.5s; -o-transition: all 0.5s; -ms-transition: all 0.5s; transition: all 0.5s; } .widget ul li a:hover { background-position: 5px 8px; } .widget ul li li { padding-left: 20px; } .widget a { color: #34495E; } .widget a:hover { color: #3498db; } .widget_recent_comments ul li a, .widget_rss ul li a { padding: 0; background: none; } .widget_rss ul li { padding: 8px 0; } .widget_rss ul li .rss-date { color: #3498db; display: block; } .widget_rss ul li cite { color: #797979; } /* Search widget */ .widget_search .search-submit { display: none; } .widget_search input { width: 100%; padding: 5px 10px; } .widget_archive li, .widget_categories li, .widget_pages li, .widget_meta li, .widget_recent_comments li, .widget_recent_entries li, .widget_nav_menu li { padding: 10px 0; } .widget li ul { border-top: 1px solid #ECF0F1; margin-top: 10px; } .widget_tag_cloud a { background-color: #ECF0F1; padding: 5px; margin: 2px; display: inline-block; } .widget_tag_cloud a:hover { color: #FFFFFF; background-color: #3498db; } /*-------------------------------------------------------------- 10.0 Content --------------------------------------------------------------*/ .site-branding { height: 106px; padding: 20px 0 0; } .site-title { line-height: 1; } .site-title a { color: #34495E; } .site-title a:hover { color: #3498db; } .site-description { font-size: 18px; font-size: 1.8rem; color: #6D6D6D; } #site-navigation { background-color: #34495E; height: 57px; } .site-footer { background-color: #34495E; } .site-footer a { color: #FFFFFF; } .site-footer a:hover { color: #3498db; } .site-footer .widget li a { color: #FFFFFF; background: url("images/list-white.png") no-repeat left 10px; display: block; } .site-footer .widget li a:hover { color: #3498db; background-position: 5px 10px; } .site-footer .widget_tag_cloud a { background-color: #7F8C8D; } .site-footer .widget_tag_cloud a:hover { color: #FFFFFF; background-color: #3498db; } #colophon { color: #FFFFFF; } .site-info { padding: 20px 0; } .footer-top { border-bottom: 1px solid #263340; padding: 20px 0 0; } .footer-bottom { border-top: 1px solid #4d647b; } .footer-bottom a { color: #3498db; } .footer-bottom a:hover { color: #FFFFFF; } #content { padding-top: 20px; } /*-------------------------------------------------------------- 10.1 Posts and pages --------------------------------------------------------------*/ .sticky { display: block; background-color: #F5F5F5; padding: 10px; border: 1px solid #d6e6ea; background-clip: padding-box; /* stops bg color from leaking outside the border: */ -webkit-border-radius: 8px; border-radius: 8px; } .hentry { margin: 0 0 1.5em; } .entry-meta, .entry-footer { border-top: 1px solid #d6e6ea; border-bottom: 1px solid #d6e6ea; padding: 8px 0; color: #7F8C8D; margin-top: 10px; } .entry-meta span, .entry-footer span { padding-right: 25px; } .entry-meta span span, .entry-footer span span { padding-right: 0; } .entry-meta span i, .entry-footer span i { padding-right: 5px; } .entry-meta a, .entry-footer a { color: #7F8C8D; } .entry-meta a:hover, .entry-footer a:hover { color: #34495E; } .updated:not(.published) { display: none; } .single .byline, .group-blog .byline { display: inline; } .page-content, .entry-content, .entry-summary { margin: 1.5em 0 0; } .page-links { clear: both; margin: 0 0 1.5em; } blockquote { position: relative; margin-bottom: 1.5em; } blockquote:before { position: absolute; content: "\f10d"; color: #3498db; font-size: 1.4em; font-family: 'FontAwesome'; } blockquote p { width: 95%; margin: 0 0 0 35px; } /*-------------------------------------------------------------- 10.2 Asides --------------------------------------------------------------*/ .blog .format-aside .entry-title, .archive .format-aside .entry-title { display: none; } /*-------------------------------------------------------------- 10.3 Comments --------------------------------------------------------------*/ .comment-content a { word-wrap: break-word; } .bypostauthor { display: block; } h2.comments-title { margin-bottom: 30px; padding-bottom: 10px; line-height: normal; } ol.comment-list { margin: 0 0 1.5em 0; list-style-type: none; } ol.comment-list li.pingback { border: 1px solid #F5F5F5; margin: 5px; padding: 10px; } ol.comment-list .bypostauthor { display: block; } ol.comment-list ol.children { list-style-type: none; } ol.comment-list .comment-body { border: 2px solid #F0F2F3; left: 60px; padding: 5px 20px 10px; position: relative; width: 92%; } ol.comment-list .comment-body p { margin-bottom: 10px; } ol.comment-list .comment-author img { top: 0; left: -60px; position: absolute; } ol.comment-list .parent article { border: 2px solid #F0F2F3; margin-bottom: 20px; padding: 5px 20px 10px; } ol.comment-list .comment-metadata { display: block; font-size: 13px; font-size: 1.3rem; margin-bottom: 20px; } ol.comment-list .comment-metadata a { color: #797979; } ol.comment-list .comment-metadata a:hover { color: #3498db; } ol.comment-list .comment-author cite { font-style: normal; } ol.comment-list .comment-author cite a { font-size: 17px; font-size: 1.7rem; color: #34495E; } ol.comment-list .comment-author cite a:hover { color: #3498db; } ol.comment-list .comment-content li { list-style-type: unset; overflow: visible; } ol.comment-list > li { margin-bottom: 20px; } ol.comment-list .even.depth-1 .comment-body { background-color: #F0F2F3; } ol.comment-list .odd.depth-1 .comment-body { background-color: #fff; } ol.comment-list .even.depth-2 .comment-body { background-color: #F0F2F3; } ol.comment-list .odd.depth-3 .comment-body { background-color: #fff; } ol.comment-list .even.depth-4 .comment-body { background-color: #F0F2F3; } ol.comment-list .odd.depth-5 .comment-body { background-color: #fff; } ol.comment-list .bypostauthor > .comment-body { background-color: #d6e6ea !important; } ol.comment-list li.pingback .comment-body { border: 0; padding: 0; position: static; width: 100%; background-color: transparent !important; } .comment-form label { min-width: 80px; display: inline-block; } .comment-form input[type="text"], .comment-form input[type="email"], .comment-form input[type="url"], .comment-form textarea { padding: 5px 10px; } .comment-form textarea { margin-top: 10px; } .services { padding-top: 50px; } h2.service-title, h3.service-subtitle { text-align: center; } h2.service-title { font-size: 2.8em; display: block; text-align: center; margin-bottom: 30px; } h2.service-title div { display: inline; padding-bottom: 10px; margin-bottom: 30px; background-image: url("images/bg-line-title.gif"), url("images/bg-line-title.gif"), url("images/bgrepeat-line-title.gif"); background-position: left bottom, right bottom, center bottom; background-repeat: no-repeat, no-repeat, repeat-x; } h3.service-subtitle { margin-bottom: 30px; } #service-tabs ul { text-align: center; margin: 0 0 50px; list-style-type: none; } .ui-tabs-nav li { display: inline; } #service-tabs ul li a { padding: 12px 30px; display: inline-block; color: #FFFFFF; } .ui-tabs-panel { clear: both; } .tab-icon { text-align: center; } .tab-icon i { font-size: 8em; /*padding: 25px;*/ border-radius: 25px 0 25px 0; } #service-tabs .ui-tabs-panel { min-height: 250px; position: relative; } #service-tabs .ui-tabs-panel .tab-icon { /* min-height: 140px; position: absolute; top: 50%; -webkit-transform: translateY(-50%); -moz-transform: translateY(-50%); transform: translateY(-50%); width: 22%; */ text-align: center; padding: 50px 0; background-color: #F0F2F3; } .team-col { min-height: 170px; } .team-col:nth-of-type(2), .team-col:nth-of-type(4) { border-right: 0; } .team-col:nth-of-type(3), .team-col:nth-of-type(4) { border-bottom: 0; } #service-tabs .service-desc li { float: none; list-style-type: disc; } #service-tabs .service-desc ol { list-style-type: disc; } #service-tabs .service-desc ul { text-align: left; margin-left: 30px; list-style-type: disc; } .team-col strong { display: block; font-size: 1.4em; } .team-col h5 { font-size: 1em; font-weight: normal; } .team-col img { float: left; margin-right: 15px; margin-bottom: 15px; } .team-col p { text-align: justify; } .team-col p, .team-col h5 { margin-left: 135px; } .team-content { background-image: url("images/circle.gif"), url("images/circle.gif"), url("images/circle.gif"), url("images/line-repeat.gif"); background-position: 51% top, 51% bottom, 51% center, 51% top; background-repeat: no-repeat, no-repeat, no-repeat, repeat-y; margin-bottom: 50px; } .team-col { padding: 25px; } .innercol { background-image: url("images/circle.gif"), url("images/circle.gif"), url("images/circle.gif"), url("images/line-repeat.gif"); background-position: left center, right center, 51% center, center center; background-repeat: no-repeat, no-repeat, no-repeat, repeat-x; } #add-info h1, #add-info h2, #add-info h3, #add-info h4, #add-info h5 { clear: none; } #add-info h2 { text-align: center; margin-bottom: 35px; } #add-info img { margin-right: 75px; } .recent-work { margin: 10px; height: 250px; overflow: hidden; position: relative; width: 250px; float: left; } .recent-work:hover .rk-thumb { opacity: .5; transition: all .5s; } .rk-content { position: absolute; top: 0; left: 0; padding: 15px; opacity: 0; -webkit-transition: all .5s; -moz-transition: all .5s; transition: all .5s; width: 100%; min-height: 250px; line-height: 1.2; } .recent-work:hover .rk-content { opacity: 1; } .rk-content p { text-align: justify; } .rk-content h3 { padding-bottom: 10px; } .rk-content h3 a { color: #3498db; } .rk-content h3 a:hover { color: #FFFFFF; } .rk-content p.readmore { text-align: center; } .rk-content p.readmore a { background-color: #34495E; } .rk-content p.readmore a:hover { color: #FFFFFF; background-color: #3498db; } .rk-content { background-color: rgba(51, 73, 94, 0.8); color: #FFFFFF; } /* Recent Work Animation */ .rk-thumb { overflow: hidden; } .rk-thumb img { -webkit-transition: all 0.2s linear; -moz-transition: all 0.2s linear; -o-transition: all 0.2s linear; -ms-transition: all 0.2s linear; transition: all 0.2s linear; } .rk-content { -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter: alpha(opacity=0); opacity: 0; -webkit-transition: all 0.4s ease-in-out; -moz-transition: all 0.4s ease-in-out; -o-transition: all 0.4s ease-in-out; -ms-transition: all 0.4s ease-in-out; transition: all 0.4s ease-in-out; } .rk-content h3 { -webkit-transform: translateY(-100px); -moz-transform: translateY(-100px); -o-transform: translateY(-100px); -ms-transform: translateY(-100px); transform: translateY(-100px); -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter: alpha(opacity=0); opacity: 0; -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; -ms-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .rk-content p { -webkit-transform: translateY(100px); -moz-transform: translateY(100px); -o-transform: translateY(100px); -ms-transform: translateY(100px); transform: translateY(100px); -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter: alpha(opacity=0); opacity: 0; -webkit-transition: all 0.2s linear; -moz-transition: all 0.2s linear; -o-transition: all 0.2s linear; -ms-transition: all 0.2s linear; transition: all 0.2s linear; } .recent-work:hover img { -webkit-transform: scale(1.1, 1.1); -moz-transform: scale(1.1, 1.1); -o-transform: scale(1.1, 1.1); -ms-transform: scale(1.1, 1.1); transform: scale(1.1, 1.1); } .view-first a.info { -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=0)"; filter: alpha(opacity=0); opacity: 0; -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; -ms-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .recent-work:hover .rk-content { -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=100)"; filter: alpha(opacity=100); opacity: 1; } .recent-work:hover h3, .recent-work:hover p, .recent-work:hover a.info { -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=100)"; filter: alpha(opacity=100); opacity: 1; -webkit-transform: translateY(0px); -moz-transform: translateY(0px); -o-transform: translateY(0px); -ms-transform: translateY(0px); transform: translateY(0px); } .recent-work:hover p { -webkit-transition-delay: 0.1s; -moz-transition-delay: 0.1s; -o-transition-delay: 0.1s; -ms-transition-delay: 0.1s; transition-delay: 0.1s; } .recent-work:hover a.info { -webkit-transition-delay: 0.2s; -moz-transition-delay: 0.2s; -o-transition-delay: 0.2s; -ms-transition-delay: 0.2s; transition-delay: 0.2s; } .team-col h5 { color: #3498db; } #service-tabs ul li a { background-color: #34495E; } #service-tabs ul li a:hover, #service-tabs ul li.ui-tabs-active a { background-color: #3498db; } .flex-direction-nav a:hover { background: #3498db; } .flex-caption { position: absolute; color: #FFFFFF; top: 10%; left: 0; width: 100%; text-align: center; } .flex-caption h1, .flex-caption h2, .flex-caption h3, .flex-caption h4, .flex-caption h5, .flex-caption h6, .flex-caption p, .flex-caption ul { margin: 0 0 .5em; padding: 0 30px; } .flex-caption h2, .flex-caption h3 { text-shadow: 1px 1px 1px #000; } .flexslider .slides > li { position: relative; } /* Skill Styls Starts -------------------------------------- */ .skill-container { margin-top: 20px; padding-bottom: 1px; } .skill { height: 12px; position: relative; margin: -8px 0 10px 50px; background-color: #F0F2F3; } .skill-percentage { height: 12px; position: absolute; background-color: #3498db; } .skill-container i { color: #FFFFFF; } .skill-container [class*="fa fa-"]:before { background: #34495E; color: #FFFFFF; } .circle { top: -3px; width: 17px; right: -3px; height: 17px; position: absolute; display: none; } .skill-content { top: -26px; position: relative; } .skill-content span { float: right; } .skill-container [class*="fa fa-"]:before { -webkit-border-radius: 30px; -moz-border-radius: 30px; border-radius: 30px; padding: 8px; } .percent5 { width: 5%; } .percent10 { width: 10%; } .percent15 { width: 15%; } .percent20 { width: 20%; } .percent25 { width: 25%; } .percent30 { width: 30%; } .percent35 { width: 35%; } .percent40 { width: 40%; } .percent45 { width: 45%; } .percent50 { width: 50%; } .percent55 { width: 55%; } .percent60 { width: 60%; } .percent65 { width: 65%; } .percent70 { width: 70%; } .percent75 { width: 75%; } .percent80 { width: 80%; } .percent85 { width: 85%; } .percent90 { width: 90%; } .percent95 { width: 95%; } .percent100 { width: 100%; } .percent5.start { width: 0%; -webkit-animation: percent5 2s ease-out forwards; -moz-animation: percent5 2s ease-out forwards; -ms-animation: percent5 2s ease-out forwards; -o-animation: percent5 2s ease-out forwards; animation: percent5 2s ease-out forwards; } .percent10.start { width: 0%; -webkit-animation: percent10 2s ease-out forwards; -moz-animation: percent10 2s ease-out forwards; -ms-animation: percent10 2s ease-out forwards; -o-animation: percent10 2s ease-out forwards; animation: percent10 2s ease-out forwards; } .percent15.start { width: 0%; -webkit-animation: percent15 2s ease-out forwards; -moz-animation: percent15 2s ease-out forwards; -ms-animation: percent15 2s ease-out forwards; -o-animation: percent15 2s ease-out forwards; animation: percent15 2s ease-out forwards; } .percent20.start { width: 0%; -webkit-animation: percent20 2s ease-out forwards; -moz-animation: percent20 2s ease-out forwards; -ms-animation: percent20 2s ease-out forwards; -o-animation: percent20 2s ease-out forwards; animation: percent20 2s ease-out forwards; } .percent25.start { width: 0%; -webkit-animation: percent25 2s ease-out forwards; -moz-animation: percent25 2s ease-out forwards; -ms-animation: percent25 2s ease-out forwards; -o-animation: percent25 2s ease-out forwards; animation: percent25 2s ease-out forwards; } .percent30.start { width: 0%; -webkit-animation: percent30 2s ease-out forwards; -moz-animation: percent30 2s ease-out forwards; -ms-animation: percent30 2s ease-out forwards; -o-animation: percent30 2s ease-out forwards; animation: percent30 2s ease-out forwards; } .percent35.start { width: 0%; -webkit-animation: percent35 2s ease-out forwards; -moz-animation: percent35 2s ease-out forwards; -ms-animation: percent35 2s ease-out forwards; -o-animation: percent35 2s ease-out forwards; animation: percent35 2s ease-out forwards; } .percent40.start { width: 0%; -webkit-animation: percent40 2s ease-out forwards; -moz-animation: percent40 2s ease-out forwards; -ms-animation: percent40 2s ease-out forwards; -o-animation: percent40 2s ease-out forwards; animation: percent40 2s ease-out forwards; } .percent45.start { width: 0%; -webkit-animation: percent45 2s ease-out forwards; -moz-animation: percent45 2s ease-out forwards; -ms-animation: percent45 2s ease-out forwards; -o-animation: percent45 2s ease-out forwards; animation: percent45 2s ease-out forwards; } .percent50.start { width: 0%; -webkit-animation: percent50 2s ease-out forwards; -moz-animation: percent50 2s ease-out forwards; -ms-animation: percent50 2s ease-out forwards; -o-animation: percent50 2s ease-out forwards; animation: percent50 2s ease-out forwards; } .percent55.start { width: 0%; -webkit-animation: percent55 2s ease-out forwards; -moz-animation: percent55 2s ease-out forwards; -ms-animation: percent55 2s ease-out forwards; -o-animation: percent55 2s ease-out forwards; animation: percent55 2s ease-out forwards; } .percent60.start { width: 0%; -webkit-animation: percent60 2s ease-out forwards; -moz-animation: percent60 2s ease-out forwards; -ms-animation: percent60 2s ease-out forwards; -o-animation: percent60 2s ease-out forwards; animation: percent60 2s ease-out forwards; } .percent65.start { width: 0%; -webkit-animation: percent65 2s ease-out forwards; -moz-animation: percent65 2s ease-out forwards; -ms-animation: percent65 2s ease-out forwards; -o-animation: percent65 2s ease-out forwards; animation: percent65 2s ease-out forwards; } .percent70.start { width: 0%; -webkit-animation: percent70 2s ease-out forwards; -moz-animation: percent70 2s ease-out forwards; -ms-animation: percent70 2s ease-out forwards; -o-animation: percent70 2s ease-out forwards; animation: percent70 2s ease-out forwards; } .percent75.start { width: 0%; -webkit-animation: percent75 2s ease-out forwards; -moz-animation: percent75 2s ease-out forwards; -ms-animation: percent75 2s ease-out forwards; -o-animation: percent75 2s ease-out forwards; animation: percent75 2s ease-out forwards; } .percent80.start { width: 0%; -webkit-animation: percent80 2s ease-out forwards; -moz-animation: percent80 2s ease-out forwards; -ms-animation: percent80 2s ease-out forwards; -o-animation: percent80 2s ease-out forwards; animation: percent80 2s ease-out forwards; } .percent85.start { width: 0%; -webkit-animation: percent85 2s ease-out forwards; -moz-animation: percent85 2s ease-out forwards; -ms-animation: percent85 2s ease-out forwards; -o-animation: percent85 2s ease-out forwards; animation: percent85 2s ease-out forwards; } .percent90.start { width: 0%; -webkit-animation: percent90 2s ease-out forwards; -moz-animation: percent90 2s ease-out forwards; -ms-animation: percent90 2s ease-out forwards; -o-animation: percent90 2s ease-out forwards; animation: percent90 2s ease-out forwards; } .percent95.start { width: 0%; -webkit-animation: percent95 2s ease-out forwards; -moz-animation: percent95 2s ease-out forwards; -ms-animation: percent95 2s ease-out forwards; -o-animation: percent95 2s ease-out forwards; animation: percent95 2s ease-out forwards; } .percent100 { width: 0%; -webkit-animation: percent100 2s ease-out forwards; -moz-animation: percent100 2s ease-out forwards; -ms-animation: percent100 2s ease-out forwards; -o-animation: percent100 2s ease-out forwards; animation: percent100 2s ease-out forwards; } @-moz-keyframes percent5 { 0% { width: 0px; } 100% { width: 5%; } } @-moz-keyframes percent10 { 0% { width: 0px; } 100% { width: 10%; } } @-moz-keyframes percent15 { 0% { width: 0px; } 100% { width: 15%; } } @-moz-keyframes percent20 { 0% { width: 0px; } 100% { width: 20%; } } @-moz-keyframes percent25 { 0% { width: 0px; } 100% { width: 25%; } } @-moz-keyframes percent30 { 0% { width: 0px; } 100% { width: 30%; } } @-moz-keyframes percent35 { 0% { width: 0px; } 100% { width: 35%; } } @-moz-keyframes percent40 { 0% { width: 0px; } 100% { width: 40%; } } @-moz-keyframes percent45 { 0% { width: 0px; } 100% { width: 45%; } } @-moz-keyframes percent50 { 0% { width: 0px; } 100% { width: 50%; } } @-moz-keyframes percent55 { 0% { width: 0px; } 100% { width: 55%; } } @-moz-keyframes percent60 { 0% { width: 0px; } 100% { width: 60%; } } @-moz-keyframes percent65 { 0% { width: 0px; } 100% { width: 65%; } } @-moz-keyframes percent70 { 0% { width: 0px; } 100% { width: 70%; } } @-moz-keyframes percent75 { 0% { width: 0px; } 100% { width: 75%; } } @-moz-keyframes percent80 { 0% { width: 0px; } 100% { width: 80%; } } @-moz-keyframes percent85 { 0% { width: 0px; } 100% { width: 85%; } } @-moz-keyframes percent90 { 0% { width: 0px; } 100% { width: 90%; } } @-moz-keyframes percent95 { 0% { width: 0px; } 100% { width: 95%; } } @-moz-keyframes percent100 { 0% { width: 0px; } 100% { width: 100%; } } @-webkit-keyframes percent5 { 0% { width: 0px; } 100% { width: 5%; } } @-webkit-keyframes percent10 { 0% { width: 0px; } 100% { width: 10%; } } @-webkit-keyframes percent15 { 0% { width: 0px; } 100% { width: 15%; } } @-webkit-keyframes percent20 { 0% { width: 0px; } 100% { width: 20%; } } @-webkit-keyframes percent25 { 0% { width: 0px; } 100% { width: 25%; } } @-webkit-keyframes percent30 { 0% { width: 0px; } 100% { width: 30%; } } @-webkit-keyframes percent35 { 0% { width: 0px; } 100% { width: 35%; } } @-webkit-keyframes percent40 { 0% { width: 0px; } 100% { width: 40%; } } @-webkit-keyframes percent45 { 0% { width: 0px; } 100% { width: 45%; } } @-webkit-keyframes percent50 { 0% { width: 0px; } 100% { width: 50%; } } @-webkit-keyframes percent55 { 0% { width: 0px; } 100% { width: 55%; } } @-webkit-keyframes percent60 { 0% { width: 0px; } 100% { width: 60%; } } @-webkit-keyframes percent65 { 0% { width: 0px; } 100% { width: 65%; } } @-webkit-keyframes percent70 { 0% { width: 0px; } 100% { width: 70%; } } @-webkit-keyframes percent75 { 0% { width: 0px; } 100% { width: 75%; } } @-webkit-keyframes percent80 { 0% { width: 0px; } 100% { width: 80%; } } @-webkit-keyframes percent85 { 0% { width: 0px; } 100% { width: 85%; } } @-webkit-keyframes percent90 { 0% { width: 0px; } 100% { width: 90%; } } @-webkit-keyframes percent95 { 0% { width: 0px; } 100% { width: 95%; } } @-webkit-keyframes percent100 { 0% { width: 0px; } 100% { width: 100%; } } /* Skill Styls Ends -------------------------------------- */ .flexslider .slides img { width: 100%; height: 100%; } p.readmore a, p.btn-slider a, p.btn-more a { display: inline-block; padding: 5px 15px; } p.btn-slider a { padding: 7px 20px; padding-left: 15px; } p.btn-slider a i { padding-right: 8px; } p.btn-slider a, p.btn-more a { background-color: #34495E; color: #FFFFFF; } p.btn-slider a:hover, p.btn-more a:hover { background-color: #3498db; } #service-tabs ul li a { background-color: #34495E; } #service-tabs ul li a:hover, #service-tabs ul li.ui-tabs-active a { background-color: #3498db; } .flex-direction-nav a:hover { background: #3498db; color: #FFFFFF; } .flex-control-paging li a { border-color: #3498db !important; background-color: #FFFFFF; } .flex-control-paging li a.flex-active, .flex-control-paging li a:hover { background-color: #3498db !important; } .jigoshop #breadcrumb a { color: #3498db !important; text-decoration: underline; } .jigoshop #breadcrumb a:hover { text-decoration: none; } .jigoshop .site-content { width: 1170px; } .jigoshop .products li { width: 32%; min-height: 150px; margin-bottom: 65px; padding: 20px 0 !important; } .jigoshop .products li a.button { position: absolute; right: 10px; bottom: 20px; margin: 0; } .jigoshop .products li a:hover img { border: 0; } .jigoshop .products li strong { padding: 0 10px; min-height: 50px; text-align: center; line-height: normal; } .jigoshop .products li strong:hover { color: #3498db; } a.button, button.button, input.button, #review_form #submit { background-color: #3498db; background-clip: padding-box; /* stops bg color from leaking outside the border: */ -webkit-border-radius: 0; border-radius: 0; } a.button:hover, button.button:hover, input.button:hover, #review_form #submit:hover { background-color: #34495E; color: #FFFFFF; } .products li .price, div.product p.price, p.stock { color: #ff4200; } .products li .price .from, .products li .price del { font-size: 12px; } span.onsale { margin: 0 !important; background-clip: padding-box; /* stops bg color from leaking outside the border: */ -webkit-border-radius: 0; border-radius: 0; background-color: #DA54C8; padding: 10px 20px; left: 0; right: auto; } .button-alt { margin-top: 0; padding: 7px; background: #34495e; /* Old browsers */ background: -moz-linear-gradient(top, #34495e 0%, #273347 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #34495e), color-stop(100%, #273347)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #34495e 0%, #273347 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #34495e 0%, #273347 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #34495e 0%, #273347 100%); /* IE10+ */ background: linear-gradient(to bottom, #34495e 0%, #273347 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#34495e', endColorstr='#273347',GradientType=0 ); /* IE6-9 */ border: 1px solid #34495E; -webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.075), inset 0 1px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.1); -moz-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.075), inset 0 1px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.1); box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.075), inset 0 1px 0 rgba(255, 255, 255, 0.3), 0 1px 2px rgba(0, 0, 0, 0.1); } a.button-alt { color: #FFFFFF; } .button-alt:hover { background: #3498db; /* Old browsers */ background: -moz-linear-gradient(top, #3498db 0%, #3498db 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #3498db), color-stop(100%, #3498db)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #3498db 0%, #3498db 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #3498db 0%, #3498db 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #3498db 0%, #3498db 100%); /* IE10+ */ background: linear-gradient(to bottom, #3498db 0%, #3498db 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#3498db', endColorstr='#3498db',GradientType=0 ); /* IE6-9 */ border-color: #136CAB; } .jigoshop .site-content .quantity input.plus, .jigoshop .site-content .quantity input.minus { background-color: #34495E; } .jigoshop .site-content .quantity input.plus:hover, .jigoshop .site-content .quantity input.minus:hover { background-color: #3498db; } .related ul.products { float: none; width: 100%; } div.product div.summary, div.product div.images { width: 48%; } .single-product div.product div.images img { width: 100%; border-color: #d6e6ea; background-color: #FFFFFF; } div.product #tabs ul.tabs { background-color: #D7D7D7; } div.product #tabs .panel { border-color: #D7D7D7; } div.product #tabs ul.tabs a { background-color: #F0F2F3; } .products li span.price { float: none; text-align: left; padding-left: 10px; } ins { background-color: #34495E; color: #FFFFFF; padding: 0 5px; } .product-remove a.remove { background-color: #fa0000; margin: 0 auto; } .product-remove a.remove:hover { background-color: #34495E; } .product-name a:hover { color: #34495E; } table.shop_table th { color: #34495E; font-size: 14px; } .quantity input.qty { text-align: center; } .shop_table.cart .actions a.checkout-button:hover { color: #FFFFFF; } .cart-collaterals .cart_totals, .cart-collaterals .shipping_calculator { width: 48%; } form .form-row input.input-text:focus, #content .form-row input.input-text:focus, form .form-row textarea:focus, #content .form-row textarea:focus { box-shadow: inset 0 0 0 1px #3498db; -webkit-box-shadow: inset 0 0 0 1px #3498db; -moz-box-shadow: inset 0 0 0 1px #3498db; } #payment div.payment_box { background: #88bfe8; /* Old browsers */ background: -moz-linear-gradient(top, #88bfe8 0%, #70b0e0 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #88bfe8), color-stop(100%, #70b0e0)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #88bfe8 0%, #70b0e0 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #88bfe8 0%, #70b0e0 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #88bfe8 0%, #70b0e0 100%); /* IE10+ */ background: linear-gradient(to bottom, #88bfe8 0%, #70b0e0 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#88bfe8', endColorstr='#70b0e0',GradientType=0 ); /* IE6-9 */ border-color: #3498db; } #payment div.payment_box p { color: #FFFFFF; } #payment div.payment_box:after { border-bottom-color: #3498db; } .form-row .required { color: #f94242; } form .form-row input.input-text, #content .form-row input.input-text, form .form-row textarea, #content .form-row textarea { line-height: normal; } #payment .payment_methods.methods li input#payment_method_cheque, #payment .payment_methods.methods li label { display: inline; } td.cart-row-subtotal, td.cart-row-total { color: #3498db; } .checkout .jigoshop-invalid input.input-text, .checkout .jigoshop-validated select { border-color: #3498db !important; } .jigoshop .site-content div.jigoshop_error, .jigoshop .site-content div.jigoshop_message { position: relative; text-shadow: 0 1px 0 #fff; list-style: none outside !important; *zoom: 1; width: auto; -webkit-box-shadow: inset 0 -2px 6px rgba(0, 0, 0, 0.05), inset 0 -2px 30px rgba(0, 0, 0, 0.015), inset 0 1px 0 #fff, 0 1px 2px rgba(0, 0, 0, 0.3); box-shadow: inset 0 -2px 6px rgba(0, 0, 0, 0.05), inset 0 -2px 30px rgba(0, 0, 0, 0.015), inset 0 1px 0 #fff, 0 1px 2px rgba(0, 0, 0, 0.3); border: 0; border-top: 3px solid #3498db; background-color: #F0F2F3; } .woocommerce-error li strong { color: #ff0000; } .jigoshop .site-content div.jigoshop_error span, .jigoshop .site-content div.jigoshop_message span { padding-bottom: 5px; color: #secondary_color; } a.button, button.button, input.button, #review_form #submit { padding: 6px 10px; } .jigoshop .products li { border: 1px solid #d6e6ea; position: relative; } .products li a img { border: 0; margin-bottom: 10px !important; display: block; margin-left: auto !important; margin-right: auto !important; } .related.products li a img { width: 150px !important; height: 150px !important; } .star-rating, p.stars span, .star-rating span, p.stars span a:hover, p.stars span a:focus, p.stars span a.active { background-image: url("images/star.png"); } a.lost_password { padding: 5px 10px; display: inline-block; } a.lost_password:hover { color: #34495E; } .info a { color: #3498db; } .info a:hover { color: #3498db; } .related.products li span.price { font-size: 15px; padding-top: 5px; } .form-cart-items td.actions a.checkout-button.button-alt:nth-of-type(2) { background: #87e0fd; /* Old browsers */ background: -moz-linear-gradient(top, #87e0fd 0%, #53cbf1 40%, #05abe0 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #87e0fd), color-stop(40%, #53cbf1), color-stop(100%, #05abe0)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #87e0fd 0%, #53cbf1 40%, #05abe0 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #87e0fd 0%, #53cbf1 40%, #05abe0 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #87e0fd 0%, #53cbf1 40%, #05abe0 100%); /* IE10+ */ background: linear-gradient(to bottom, #87e0fd 0%, #53cbf1 40%, #05abe0 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#87e0fd', endColorstr='#05abe0',GradientType=0 ); /* IE6-9 */ border-color: #6FB4E6; color: #FFFFFF; } .form-cart-items td.actions a.checkout-button.button-alt:nth-of-type(2):hover { background: #05abe0; /* Old browsers */ background: -moz-linear-gradient(top, #05abe0 0%, #53cbf1 60%, #87e0fd 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #05abe0), color-stop(60%, #53cbf1), color-stop(100%, #87e0fd)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #05abe0 0%, #53cbf1 60%, #87e0fd 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #05abe0 0%, #53cbf1 60%, #87e0fd 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #05abe0 0%, #53cbf1 60%, #87e0fd 100%); /* IE10+ */ background: linear-gradient(to bottom, #05abe0 0%, #53cbf1 60%, #87e0fd 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#05abe0', endColorstr='#87e0fd',GradientType=0 ); /* IE6-9 */ } a.button, button.button, input.button, #review_form #submit { color: #FFFFFF; } .products ul, ul.products { float: none; } #payment ul.payment_methods li input { margin-right: 5px !important; } button:hover, input[type="button"]:hover, input[type="reset"]:hover, input[type="submit"]:hover { background: #34495E; } #reviews h2 { margin-bottom: 20px; } /*-------------------------------------------------------------- 11.0 Infinite scroll --------------------------------------------------------------*/ /* Globally hidden elements when Infinite Scroll is supported and in use. */ .infinite-scroll .paging-navigation, .infinite-scroll.neverending .site-footer { /* Theme Footer (when set to scrolling) */ display: none; } /* When Infinite Scroll has reached its end we need to re-display elements that were hidden (via .neverending) before */ .infinity-end.neverending .site-footer { display: block; } /*-------------------------------------------------------------- 12.0 Media --------------------------------------------------------------*/ .page-content img.wp-smiley, .entry-content img.wp-smiley, .comment-content img.wp-smiley { border: none; margin-bottom: 0; margin-top: 0; padding: 0; } /* Make sure embeds and iframes fit their containers */ embed, iframe, object { max-width: 100%; } /*-------------------------------------------------------------- 12.1 Captions --------------------------------------------------------------*/ .wp-caption { margin-bottom: 1.5em; max-width: 100%; } .wp-caption img[class*="wp-image-"] { display: block; margin: 0 auto; } .wp-caption .wp-caption-text { margin: 0.8075em 0; } .wp-caption-text { text-align: center; } /*-------------------------------------------------------------- 12.2 Galleries --------------------------------------------------------------*/ .gallery { margin-bottom: 1.5em; } .gallery-item { display: inline-block; text-align: center; vertical-align: top; width: 100%; margin-bottom: 20px; } .gallery-item img { border: 1px solid #3498db; } .gallery-columns-2 .gallery-item { max-width: 50%; } .gallery-columns-3 .gallery-item { max-width: 33.33%; } .gallery-columns-4 .gallery-item { max-width: 25%; } .gallery-columns-5 .gallery-item { max-width: 20%; } .gallery-columns-6 .gallery-item { max-width: 16.66%; } .gallery-columns-7 .gallery-item { max-width: 14.28%; } .gallery-columns-8 .gallery-item { max-width: 12.5%; } .gallery-columns-9 .gallery-item { max-width: 11.11%; } .gallery-caption { display: block; } /*-------------------------------------------------------------- 12.3 Galleries --------------------------------------------------------------*/ @media only screen and (max-width: 1024px) { .jigoshop .site-content { width: 100%; } } @media only screen and (max-width: 960px) { .site-branding { height: auto; padding: 20px 0; } } @media only screen and (max-width: 768px) { .team-content, .innercol { background: none; } .team-col, .team-col:nth-of-type(3) { border-bottom: 1px solid #ccc; } .service-desc { margin-top: 20px; } } @media only screen and (max-width: 700px) { .flexslider .flex-image { height: auto; } #site-navigation { height: auto; } ol.comment-list .comment-body { width: 88%; } } @media only screen and (max-width: 500px) { .menu-toggle, .main-navigation.toggled .nav-menu { display: none; } .menu-all-pages-container { padding: 10px 0; } .menu-all-pages-container select { width: 100%; padding: 5px 0; } #service-tabs ul li a { border-bottom: 1px solid #425A73; display: block; } .comment-navigation .nav-previous, .paging-navigation .nav-previous, .post-navigation .nav-previous, .comment-navigation .nav-next, .paging-navigation .nav-next, .post-navigation .nav-next { float: none; width: 100%; margin-bottom: 10px; } .comment-navigation .nav-previous a, .paging-navigation .nav-previous a, .post-navigation .nav-previous a, .comment-navigation .nav-next a, .paging-navigation .nav-next a, .post-navigation .nav-next a { display: block; } .post-password-form input[type="submit"], .post-password-form input[type="password"] { width: 100%; margin-bottom: 10px; } ol.comment-list .comment-body { width: 85%; } ol.comment-list li > ul, ol.comment-list li > ol { margin-left: 0; } .widget_search input { width: 95%; } .gallery { width: 95%; } .gallery img { max-width: 90%; } .team-col p, .team-col h5 { margin: 0; float: none; } .team-col img { float: none; display: block; margin: 0 auto; } .flex-caption { top: 2%; } .flex-caption p { line-height: normal; } .flex-direction-nav a { top: 40%; } } /*# sourceMappingURL=style.css.map */
Tamiiy/spartan-english
wp-content/themes/flaton/style.css
CSS
gpl-2.0
65,339
<?php /* * Admin Page Framework v3.9.0 by Michael Uno * Compiled with Admin Page Framework Compiler <https://github.com/michaeluno/amazon-auto-links-compiler> * <https://en.michaeluno.jp/amazon-auto-links> * Copyright (c) 2013-2022, Michael Uno; Licensed under MIT <https://opensource.org/licenses/MIT> */ abstract class AmazonAutoLinks_AdminPageFramework_PostType_Model extends AmazonAutoLinks_AdminPageFramework_PostType_Router { public function __construct($oProp) { parent::__construct($oProp); add_action("set_up_{$this->oProp->sClassName}", array( $this, '_replyToRegisterPostType' ), 999); if ($this->oProp->bIsAdmin) { add_action('load_' . $this->oProp->sPostType, array( $this, '_replyToSetUpHooksForModel' )); if ($this->oProp->sCallerPath) { new AmazonAutoLinks_AdminPageFramework_PostType_Model__FlushRewriteRules($this); } } } public function _replyToSetUpHooksForModel() { add_filter("manage_{$this->oProp->sPostType}_posts_columns", array( $this, '_replyToSetColumnHeader' )); add_filter("manage_edit-{$this->oProp->sPostType}_sortable_columns", array( $this, '_replyToSetSortableColumns' )); add_action("manage_{$this->oProp->sPostType}_posts_custom_column", array( $this, '_replyToPrintColumnCell' ), 10, 2); add_action('admin_enqueue_scripts', array( $this, '_replyToDisableAutoSave' )); $this->oProp->aColumnHeaders = array( 'cb' => '<input type="checkbox" />', 'title' => $this->oMsg->get('title'), 'author' => $this->oMsg->get('author'), 'comments' => '<div class="comment-grey-bubble"></div>', 'date' => $this->oMsg->get('date'), ); } public function _replyToSetSortableColumns($aColumns) { return $this->oUtil->getAsArray($this->oUtil->addAndApplyFilter($this, "sortable_columns_{$this->oProp->sPostType}", $aColumns)); } public function _replyToSetColumnHeader($aHeaderColumns) { return $this->oUtil->getAsArray($this->oUtil->addAndApplyFilter($this, "columns_{$this->oProp->sPostType}", $aHeaderColumns)); } public function _replyToPrintColumnCell($sColumnKey, $iPostID) { echo $this->oUtil->addAndApplyFilter($this, "cell_{$this->oProp->sPostType}_{$sColumnKey}", '', $iPostID); } public function _replyToDisableAutoSave() { if ($this->oProp->bEnableAutoSave) { return; } if ($this->oProp->sPostType != get_post_type()) { return; } wp_dequeue_script('autosave'); } public function _replyToRegisterPostType() { register_post_type($this->oProp->sPostType, $this->oProp->aPostTypeArgs); new AmazonAutoLinks_AdminPageFramework_PostType_Model__SubMenuOrder($this); } public function _replyToRegisterTaxonomies() { foreach ($this->oProp->aTaxonomies as $_sTaxonomySlug => $_aArguments) { $this->_registerTaxonomy($_sTaxonomySlug, $this->oUtil->getAsArray($this->oProp->aTaxonomyObjectTypes[ $_sTaxonomySlug ]), $_aArguments); } } public function _registerTaxonomy($sTaxonomySlug, array $aObjectTypes, array $aArguments) { if (! in_array($this->oProp->sPostType, $aObjectTypes)) { $aObjectTypes[] = $this->oProp->sPostType; } register_taxonomy($sTaxonomySlug, array_unique($aObjectTypes), $aArguments); $this->_setCustomMenuOrderForTaxonomy($this->oUtil->getElement($aArguments, 'submenu_order', 15), $sTaxonomySlug); } private function _setCustomMenuOrderForTaxonomy($nSubMenuOrder, $sTaxonomySlug) { if (15 == $nSubMenuOrder) { return; } $this->oProp->aTaxonomySubMenuOrder[ "edit-tags.php?taxonomy={$sTaxonomySlug}&amp;post_type={$this->oProp->sPostType}" ] = $nSubMenuOrder; } public function _replyToRemoveTexonomySubmenuPages() { foreach ($this->oProp->aTaxonomyRemoveSubmenuPages as $sSubmenuPageSlug => $sTopLevelPageSlug) { remove_submenu_page($sTopLevelPageSlug, $sSubmenuPageSlug); unset($this->oProp->aTaxonomyRemoveSubmenuPages[ $sSubmenuPageSlug ]); } } }
michaeluno/amazon-auto-links
include/library/apf/factory/post_type/AdminPageFramework_PostType_Model.php
PHP
gpl-2.0
4,203
/* $Id: thread-r0drv-freebsd.c 56290 2015-06-09 14:01:31Z vboxsync $ */ /** @file * IPRT - Threads (Part 1), Ring-0 Driver, FreeBSD. */ /* * Copyright (C) 2007-2015 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ /******************************************************************************* * Header Files * *******************************************************************************/ #include "the-freebsd-kernel.h" #include "internal/iprt.h" #include <iprt/thread.h> #include <iprt/asm.h> #include <iprt/asm-amd64-x86.h> #include <iprt/assert.h> #include <iprt/err.h> #include <iprt/mp.h> #include "internal/thread.h" RTDECL(RTNATIVETHREAD) RTThreadNativeSelf(void) { return (RTNATIVETHREAD)curthread; } static int rtR0ThreadFbsdSleepCommon(RTMSINTERVAL cMillies) { int rc; int cTicks; /* * 0 ms sleep -> yield. */ if (!cMillies) { RTThreadYield(); return VINF_SUCCESS; } /* * Translate milliseconds into ticks and go to sleep. */ if (cMillies != RT_INDEFINITE_WAIT) { if (hz == 1000) cTicks = cMillies; else if (hz == 100) cTicks = cMillies / 10; else { int64_t cTicks64 = ((uint64_t)cMillies * hz) / 1000; cTicks = (int)cTicks64; if (cTicks != cTicks64) cTicks = INT_MAX; } } else cTicks = 0; /* requires giant lock! */ rc = tsleep((void *)RTThreadSleep, PZERO | PCATCH, "iprtsl", /* max 6 chars */ cTicks); switch (rc) { case 0: return VINF_SUCCESS; case EWOULDBLOCK: return VERR_TIMEOUT; case EINTR: case ERESTART: return VERR_INTERRUPTED; default: AssertMsgFailed(("%d\n", rc)); return VERR_NO_TRANSLATION; } } RTDECL(int) RTThreadSleep(RTMSINTERVAL cMillies) { return rtR0ThreadFbsdSleepCommon(cMillies); } RTDECL(int) RTThreadSleepNoLog(RTMSINTERVAL cMillies) { return rtR0ThreadFbsdSleepCommon(cMillies); } RTDECL(bool) RTThreadYield(void) { #if __FreeBSD_version >= 900032 kern_yield(curthread->td_user_pri); #else uio_yield(); #endif return false; /** @todo figure this one ... */ } RTDECL(bool) RTThreadPreemptIsEnabled(RTTHREAD hThread) { Assert(hThread == NIL_RTTHREAD); return curthread->td_critnest == 0 && ASMIntAreEnabled(); /** @todo is there a native freebsd function/macro for this? */ } RTDECL(bool) RTThreadPreemptIsPending(RTTHREAD hThread) { Assert(hThread == NIL_RTTHREAD); return curthread->td_owepreempt == 1; } RTDECL(bool) RTThreadPreemptIsPendingTrusty(void) { /* yes, RTThreadPreemptIsPending is reliable. */ return true; } RTDECL(bool) RTThreadPreemptIsPossible(void) { /* yes, kernel preemption is possible. */ return true; } RTDECL(void) RTThreadPreemptDisable(PRTTHREADPREEMPTSTATE pState) { AssertPtr(pState); Assert(pState->u32Reserved == 0); pState->u32Reserved = 42; critical_enter(); RT_ASSERT_PREEMPT_CPUID_DISABLE(pState); } RTDECL(void) RTThreadPreemptRestore(PRTTHREADPREEMPTSTATE pState) { AssertPtr(pState); Assert(pState->u32Reserved == 42); pState->u32Reserved = 0; RT_ASSERT_PREEMPT_CPUID_RESTORE(pState); critical_exit(); } RTDECL(bool) RTThreadIsInInterrupt(RTTHREAD hThread) { Assert(hThread == NIL_RTTHREAD); NOREF(hThread); /** @todo FreeBSD: Implement RTThreadIsInInterrupt. Required for guest * additions! */ return !ASMIntAreEnabled(); }
carmark/vbox
src/VBox/Runtime/r0drv/freebsd/thread-r0drv-freebsd.c
C
gpl-2.0
4,634
/* * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.xml.internal.rngom.parse.host; import com.sun.xml.internal.rngom.ast.builder.Annotations; import com.sun.xml.internal.rngom.ast.builder.BuildException; import com.sun.xml.internal.rngom.ast.builder.Scope; import com.sun.xml.internal.rngom.ast.om.Location; import com.sun.xml.internal.rngom.ast.om.ParsedPattern; /** * * @author * Kohsuke Kawaguchi (kk@kohsuke.org) */ public class ScopeHost extends GrammarSectionHost implements Scope { protected final Scope lhs; protected final Scope rhs; protected ScopeHost( Scope lhs, Scope rhs ) { super(lhs,rhs); this.lhs = lhs; this.rhs = rhs; } public ParsedPattern makeParentRef(String name, Location _loc, Annotations _anno) throws BuildException { LocationHost loc = cast(_loc); AnnotationsHost anno = cast(_anno); return new ParsedPatternHost( lhs.makeParentRef(name, loc.lhs, anno.lhs), rhs.makeParentRef(name, loc.rhs, anno.rhs)); } public ParsedPattern makeRef(String name, Location _loc, Annotations _anno) throws BuildException { LocationHost loc = cast(_loc); AnnotationsHost anno = cast(_anno); return new ParsedPatternHost( lhs.makeRef(name, loc.lhs, anno.lhs), rhs.makeRef(name, loc.rhs, anno.rhs)); } }
TheTypoMaster/Scaper
openjdk/jaxws/drop_included/jaxws_src/src/com/sun/xml/internal/rngom/parse/host/ScopeHost.java
Java
gpl-2.0
2,549
#!/usr/bin/perl use strict; use warnings; use RPi::I2C; package Rrdpi::Gas; sub new { my ($class, $conf) = @_; my $self = {conf => $conf}; bless( $self, $class ); $self->{rrdParams} = $self->getRrdParams(); return $self; } sub getRrdParams { my ($self) = @_; return { name => 'gas', datafiles => [$self->{conf}->{DBPATH}."/gas.rrd"], picBase => [$self->{conf}->{OUTPATH}."/gas-"], DS => ['gas'], DSDescr => ['Gas level'], DSChecks => [{warn=>'$_>100', fail=>'$_>200'}], rrdCreate => [ "DS:gas:GAUGE:300:-10:500", ], graphTitles => [''], rrdGraph => [ '--lazy', '--imgformat=PNG', '--title=Gas level', "--width=".$self->{conf}->{GRAPH_WIDTH}, "--height=".$self->{conf}->{GRAPH_HEIGHT}, '--lower-limit=0', # '--upper-limit=100', '--rigid', "DEF:gas=DATAFILE:gas:AVERAGE", 'AREA:gas#3535FF:Gas level', 'COMMENT:\n', 'COMMENT: ' ] }; } sub gather { my ($self) = @_; my $device = RPi::I2C->new(0x28, '/dev/i2c-3'); my $reading = $device->read_word(0x81); $reading = 'U' if $reading == -1; return [sprintf("N:%s", $reading)]; } 1;
asmirn01/rrdpi
Rrdpi/Gas.pm
Perl
gpl-2.0
1,124
/* * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import com.sun.net.httpserver.*; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.math.BigInteger; import java.net.InetSocketAddress; import java.security.KeyStore; import java.security.PrivateKey; import java.security.Signature; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.Calendar; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.Locale; import sun.security.pkcs.ContentInfo; import sun.security.pkcs.PKCS7; import sun.security.pkcs.PKCS9Attribute; import sun.security.pkcs.SignerInfo; import sun.security.timestamp.TimestampToken; import sun.security.util.DerOutputStream; import sun.security.util.DerValue; import sun.security.util.ObjectIdentifier; import sun.security.x509.AlgorithmId; import sun.security.x509.X500Name; public class TimestampCheck { static final String TSKS = "tsks"; static final String JAR = "old.jar"; static final String defaultPolicyId = "2.3.4.5"; static class Handler implements HttpHandler, AutoCloseable { private final HttpServer httpServer; private final String keystore; @Override public void handle(HttpExchange t) throws IOException { int len = 0; for (String h: t.getRequestHeaders().keySet()) { if (h.equalsIgnoreCase("Content-length")) { len = Integer.valueOf(t.getRequestHeaders().get(h).get(0)); } } byte[] input = new byte[len]; t.getRequestBody().read(input); try { int path = 0; if (t.getRequestURI().getPath().length() > 1) { path = Integer.parseInt( t.getRequestURI().getPath().substring(1)); } byte[] output = sign(input, path); Headers out = t.getResponseHeaders(); out.set("Content-Type", "application/timestamp-reply"); t.sendResponseHeaders(200, output.length); OutputStream os = t.getResponseBody(); os.write(output); } catch (Exception e) { e.printStackTrace(); t.sendResponseHeaders(500, 0); } t.close(); } /** * @param input The data to sign * @param path different cases to simulate, impl on URL path * 0: normal * 1: Missing nonce * 2: Different nonce * 3: Bad digets octets in messageImprint * 4: Different algorithmId in messageImprint * 5: whole chain in cert set * 6: extension is missing * 7: extension is non-critical * 8: extension does not have timestamping * 9: no cert in response * 10: normal * 11: always return default policy id * 12: normal * otherwise: normal * @returns the signed */ byte[] sign(byte[] input, int path) throws Exception { // Read TSRequest DerValue value = new DerValue(input); System.err.println("\nIncoming Request\n==================="); System.err.println("Version: " + value.data.getInteger()); DerValue messageImprint = value.data.getDerValue(); AlgorithmId aid = AlgorithmId.parse( messageImprint.data.getDerValue()); System.err.println("AlgorithmId: " + aid); ObjectIdentifier policyId = new ObjectIdentifier(defaultPolicyId); BigInteger nonce = null; while (value.data.available() > 0) { DerValue v = value.data.getDerValue(); if (v.tag == DerValue.tag_Integer) { nonce = v.getBigInteger(); System.err.println("nonce: " + nonce); } else if (v.tag == DerValue.tag_Boolean) { System.err.println("certReq: " + v.getBoolean()); } else if (v.tag == DerValue.tag_ObjectId) { policyId = v.getOID(); System.err.println("PolicyID: " + policyId); } } // Write TSResponse System.err.println("\nResponse\n==================="); KeyStore ks = KeyStore.getInstance("JKS"); try (FileInputStream fis = new FileInputStream(keystore)) { ks.load(fis, "changeit".toCharArray()); } String alias = "ts"; if (path == 6) alias = "tsbad1"; if (path == 7) alias = "tsbad2"; if (path == 8) alias = "tsbad3"; if (path == 11) { policyId = new ObjectIdentifier(defaultPolicyId); } DerOutputStream statusInfo = new DerOutputStream(); statusInfo.putInteger(0); DerOutputStream token = new DerOutputStream(); AlgorithmId[] algorithms = {aid}; Certificate[] chain = ks.getCertificateChain(alias); X509Certificate[] signerCertificateChain = null; X509Certificate signer = (X509Certificate)chain[0]; if (path == 5) { // Only case 5 uses full chain signerCertificateChain = new X509Certificate[chain.length]; for (int i=0; i<chain.length; i++) { signerCertificateChain[i] = (X509Certificate)chain[i]; } } else if (path == 9) { signerCertificateChain = new X509Certificate[0]; } else { signerCertificateChain = new X509Certificate[1]; signerCertificateChain[0] = (X509Certificate)chain[0]; } DerOutputStream tst = new DerOutputStream(); tst.putInteger(1); tst.putOID(policyId); if (path != 3 && path != 4) { tst.putDerValue(messageImprint); } else { byte[] data = messageImprint.toByteArray(); if (path == 4) { data[6] = (byte)0x01; } else { data[data.length-1] = (byte)0x01; data[data.length-2] = (byte)0x02; data[data.length-3] = (byte)0x03; } tst.write(data); } tst.putInteger(1); Calendar cal = Calendar.getInstance(); tst.putGeneralizedTime(cal.getTime()); if (path == 2) { tst.putInteger(1234); } else if (path == 1) { // do nothing } else { tst.putInteger(nonce); } DerOutputStream tstInfo = new DerOutputStream(); tstInfo.write(DerValue.tag_Sequence, tst); DerOutputStream tstInfo2 = new DerOutputStream(); tstInfo2.putOctetString(tstInfo.toByteArray()); Signature sig = Signature.getInstance("SHA1withRSA"); sig.initSign((PrivateKey)(ks.getKey( alias, "changeit".toCharArray()))); sig.update(tstInfo.toByteArray()); ContentInfo contentInfo = new ContentInfo(new ObjectIdentifier( "1.2.840.113549.1.9.16.1.4"), new DerValue(tstInfo2.toByteArray())); System.err.println("Signing..."); System.err.println(new X500Name(signer .getIssuerX500Principal().getName())); System.err.println(signer.getSerialNumber()); SignerInfo signerInfo = new SignerInfo( new X500Name(signer.getIssuerX500Principal().getName()), signer.getSerialNumber(), aid, AlgorithmId.get("RSA"), sig.sign()); SignerInfo[] signerInfos = {signerInfo}; PKCS7 p7 = new PKCS7(algorithms, contentInfo, signerCertificateChain, signerInfos); ByteArrayOutputStream p7out = new ByteArrayOutputStream(); p7.encodeSignedData(p7out); DerOutputStream response = new DerOutputStream(); response.write(DerValue.tag_Sequence, statusInfo); response.putDerValue(new DerValue(p7out.toByteArray())); DerOutputStream out = new DerOutputStream(); out.write(DerValue.tag_Sequence, response); return out.toByteArray(); } private Handler(HttpServer httpServer, String keystore) { this.httpServer = httpServer; this.keystore = keystore; } /** * Initialize TSA instance. * * Extended Key Info extension of certificate that is used for * signing TSA responses should contain timeStamping value. */ static Handler init(int port, String keystore) throws IOException { HttpServer httpServer = HttpServer.create( new InetSocketAddress(port), 0); Handler tsa = new Handler(httpServer, keystore); httpServer.createContext("/", tsa); return tsa; } /** * Start TSA service. */ void start() { httpServer.start(); } /** * Stop TSA service. */ void stop() { httpServer.stop(0); } /** * Return server port number. */ int getPort() { return httpServer.getAddress().getPort(); } @Override public void close() throws Exception { stop(); } } public static void main(String[] args) throws Exception { try (Handler tsa = Handler.init(0, TSKS);) { tsa.start(); int port = tsa.getPort(); String cmd; // Use -J-Djava.security.egd=file:/dev/./urandom to speed up // nonce generation in timestamping request. Not avaibale on // Windows and defaults to thread seed generator, not too bad. if (System.getProperty("java.home").endsWith("jre")) { cmd = System.getProperty("java.home") + "/../bin/jarsigner"; } else { cmd = System.getProperty("java.home") + "/bin/jarsigner"; } cmd += " " + System.getProperty("test.tool.vm.opts") + " -J-Djava.security.egd=file:/dev/./urandom" + " -J-Duser.language=en -J-Duser.country=US" + " -debug -keystore " + TSKS + " -storepass changeit" + " -tsa http://localhost:" + port + "/%d" + " -signedjar new_%d.jar " + JAR + " old"; if (args.length == 0) { // Run this test jarsigner(cmd, 0, true); // Success, normal call jarsigner(cmd, 1, false); // These 4 should fail jarsigner(cmd, 2, false); jarsigner(cmd, 3, false); jarsigner(cmd, 4, false); jarsigner(cmd, 5, true); // Success, 6543440 solved. jarsigner(cmd, 6, false); // tsbad1 jarsigner(cmd, 7, false); // tsbad2 jarsigner(cmd, 8, false); // tsbad3 jarsigner(cmd, 9, false); // no cert in timestamp jarsigner(cmd + " -tsapolicyid 1.2.3.4", 10, true); checkTimestamp("new_10.jar", "1.2.3.4", "SHA-256"); jarsigner(cmd + " -tsapolicyid 1.2.3.5", 11, false); jarsigner(cmd + " -tsadigestalg SHA", 12, true); checkTimestamp("new_12.jar", defaultPolicyId, "SHA-1"); } else { // Run as a standalone server System.err.println("Press Enter to quit server"); System.in.read(); } } } static void checkTimestamp(String file, String policyId, String digestAlg) throws Exception { try (JarFile jf = new JarFile(file)) { JarEntry je = jf.getJarEntry("META-INF/OLD.RSA"); try (InputStream is = jf.getInputStream(je)) { byte[] content = is.readAllBytes(); PKCS7 p7 = new PKCS7(content); SignerInfo[] si = p7.getSignerInfos(); if (si == null || si.length == 0) { throw new Exception("Not signed"); } PKCS9Attribute p9 = si[0].getUnauthenticatedAttributes() .getAttribute(PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID); PKCS7 tsToken = new PKCS7((byte[]) p9.getValue()); TimestampToken tt = new TimestampToken(tsToken.getContentInfo().getData()); if (!tt.getHashAlgorithm().toString().equals(digestAlg)) { throw new Exception("Digest alg different"); } if (!tt.getPolicyID().equals(policyId)) { throw new Exception("policyId different"); } } } } /** * @param cmd the command line (with a hole to plug in) * @param path the path in the URL, i.e, http://localhost/path * @param expected if this command should succeed */ static void jarsigner(String cmd, int path, boolean expected) throws Exception { System.err.println("Test " + path); Process p = Runtime.getRuntime().exec(String.format(Locale.ROOT,cmd, path, path)); BufferedReader reader = new BufferedReader( new InputStreamReader(p.getErrorStream())); while (true) { String s = reader.readLine(); if (s == null) break; System.err.println(s); } // Will not see noTimestamp warning boolean seeWarning = false; reader = new BufferedReader( new InputStreamReader(p.getInputStream())); while (true) { String s = reader.readLine(); if (s == null) break; System.err.println(s); if (s.indexOf("Warning:") >= 0) { seeWarning = true; } } int result = p.waitFor(); if (expected && result != 0 || !expected && result == 0) { throw new Exception("Failed"); } if (seeWarning) { throw new Exception("See warning"); } } }
FauxFaux/jdk9-jdk
test/sun/security/tools/jarsigner/TimestampCheck.java
Java
gpl-2.0
15,695
class AddDeprecatableToStep < ActiveRecord::Migration def change add_column :steps, :superceded_by_id, :integer end end
emrojo/samples_extraction
db/migrate/20170226142235_add_deprecatable_to_step.rb
Ruby
gpl-2.0
128
package de.l3s.ppt.peertrustparser; public class Constants { public static final String ISSUER_CHAR = "@"; public static final String REQUESTER_CHAR = "$"; public static final String OPENING_BRACKET = "("; public static final String CLOSING_BRACKET = ")"; public static final String OPENING_SQUARE_BRACKET = "["; public static final String CLOSING_SQUARE_BRACKET = "]"; public static final String RULE_SEPARATOR = "<-"; public static final String DOT = "."; public static final String COMMA = ","; public static final String VERTICAL_SLASH = "|"; public static final String SIGNED_BY = "signedBy"; }
elitak/peertrust
src/de/l3s/ppt/peertrustparser/Constants.java
Java
gpl-2.0
627
/************************************************************************************* begin : Sun Feb 29 2004 copyright : (C) 2004 by Jeroen Wijnhout (Jeroen.Wijnhout@kdemail.net) *************************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "convert.h" #include <QFile> #include <QRegExp> #include <QTextCodec> #include <QTextStream> #include <KGlobal> #include <KMessageBox> #include <KStandardDirs> #include <KTextEditor/Document> #include "kiledebug.h" QMap<QString, ConvertMap*> ConvertMap::g_maps; bool ConvertMap::create(const QString & encoding) { KILE_DEBUG() << "\tlooking for map for " << encoding; ConvertMap * map = g_maps[encoding]; if(!map) { KILE_DEBUG() << "\tcreating a map for " << encoding; map = new ConvertMap(encoding); // FIXME This will never be deleted if load() succeeds... if(map->load()) { g_maps[encoding] = map; } else { delete map; map = NULL; } map = g_maps[encoding]; } return (map != NULL); } QString ConvertMap::encodingNameFor(const QString & name) { QString std; for(int i = 0; i < name.length(); ++i) { if(!name[i].isSpace()) { std += name[i]; } } std = std.toLower(); if(std.startsWith("iso8859-")) { return "latin" + std.right(1); } if(std.startsWith("cp")) { return "cp" + std.right(4); } return name; } QString ConvertMap::isoNameFor(const QString & name) { QString std; for(int i = 0; i < name.length(); ++i) { if(!name[i].isSpace()) { std += name[i]; } } std = std.toLower(); if(std.startsWith("latin")) { return "ISO 8859-" + std.right(1); } if(std.startsWith("cp")) { return "cp " + std.right(4); } return name; } ConvertMap::ConvertMap(const QString& enc) { m_aliases.append(encodingNameFor(enc)); m_aliases.append(isoNameFor(enc)); } void ConvertMap::addPair(QChar c, const QString& enc) { m_toASCII[c] = commandIsTerminated(enc) ? enc : enc + "{}" ; m_toEncoding[enc] = c; } bool ConvertMap::commandIsTerminated(const QString & command) { static QRegExp reCommandSequences("\\\\([a-zA-Z]+|\\\"|\\')$"); return (reCommandSequences.indexIn(command) == -1); } bool ConvertMap::load() { static QRegExp reMap("^(.*):(.*)"); //makeMap(encoding()); //if map already exists, replace it QFile qf(KGlobal::dirs()->findResource("appdata", "encodings/" + encoding() + ".enc")); if(qf.open(QIODevice::ReadOnly)) { QTextStream stream(&qf); QTextCodec *codec = QTextCodec::codecForName(isoName().toAscii()); if(codec) { stream.setCodec(codec); } while(!stream.atEnd()) { //parse the line if(stream.readLine().indexOf(reMap) != -1) { addPair(reMap.cap(1)[0], reMap.cap(2)); } } qf.close(); return true; } return false; } //BEGIN ConvertIO classes ConvertIO::ConvertIO(KTextEditor::Document *doc) : m_doc(doc), m_text(QString()), m_line(QString()), m_nLine(0) { } QString & ConvertIO::currentLine() { return m_line; } void ConvertIO::nextLine() { m_line = m_doc->line(m_nLine++); } void ConvertIO::writeText() { m_doc->setText(m_text); } int ConvertIO::current() { return m_nLine; } bool ConvertIO::done() { return current() == m_doc->lines(); } ConvertIOFile::ConvertIOFile(KTextEditor::Document *doc, const KUrl & url) : ConvertIO(doc), m_url(url) { } void ConvertIOFile::writeText() { QFile qf(m_url.toLocalFile()); if(qf.open(QIODevice::WriteOnly)) { //read the file QTextStream stream(&qf); stream << m_text; qf.close(); } else { kWarning() << "Could not open " << m_url.toLocalFile(); } } ConvertBase::ConvertBase(const QString & encoding, ConvertIO * io) : m_io(io), m_encoding(encoding), m_map(NULL) { } //END ConvertIO classes //BEGIN ConvertBase QString ConvertBase::mapNext(int &i) { return (QString)m_io->currentLine()[i++]; } bool ConvertBase::convert() { if(!setMap()) { return false; } m_io->text().clear(); do { m_io->nextLine(); int i = 0; while(i < m_io->currentLine().length()) { m_io->text() += mapNext(i); } if(!m_io->done()) { m_io->text() += '\n'; } } while(!m_io->done()); m_io->writeText(); return true; } bool ConvertBase::setMap() { //create map (or use existing) if(ConvertMap::create(m_encoding)) { m_map = ConvertMap::mapFor(m_encoding); } else { m_map = NULL; } return (m_map != NULL); } //END ConvertBase //BEGIN ConvertEncToASCII QString ConvertEncToASCII::mapNext(int &i) { return m_map->canDecode(m_io->currentLine()[i]) ? m_map->toASCII(m_io->currentLine()[i++]) : (QString)m_io->currentLine()[i++]; } //END ConvertEncToASCII //BEGIN ConvertASCIIToEnc //i is the position of the '\' QString ConvertASCIIToEnc::nextSequence(int &i) { //get first two characters QString seq = (QString)m_io->currentLine()[i++]; if(m_io->currentLine()[i].isLetter()) { while(m_io->currentLine()[i].isLetter()) { seq += (QString)m_io->currentLine()[i++]; } } else { return seq + (QString)m_io->currentLine()[i++]; } return seq; } bool ConvertASCIIToEnc::isModifier(const QString& seq) { static QRegExp reModifier("\\\\([cHkruv]|\"|\'|\\^|`|~|=|\\.)"); return reModifier.exactMatch(seq); } QString ConvertASCIIToEnc::getSequence(int &i) { QString seq = nextSequence(i); static QRegExp reBraces("\\{([a-zA-Z]?)\\}"); if(isModifier(seq)) { KILE_DEBUG() << "\tisModifier true : " << seq; if(seq[seq.length() - 1].isLetter()) { seq += ' '; } while(m_io->currentLine()[i].isSpace()) { ++i; } if(m_io->currentLine().mid(i, 2) == "{}") { i = i + 2; } if(m_io->currentLine()[i] == '\\') { seq += nextSequence(i); } else { if(reBraces.exactMatch(m_io->currentLine().mid(i, 3))) { KILE_DEBUG() << "\tbraces detected"; i = i + 3; seq += reBraces.cap(1); } else { QChar nextChar = m_io->currentLine()[i++]; if(!nextChar.isSpace()) { seq += (QString)nextChar; } } } } else if(m_map->canEncode(seq)) { if(m_io->currentLine().mid(i, 2) == "{}") { i = i + 2; } else if(m_io->currentLine()[i].isSpace()) { ++i; } } return seq; } QString ConvertASCIIToEnc::mapNext(int &i) { if(m_io->currentLine()[i] == '\\') { QString seq = getSequence(i); KILE_DEBUG() << "'\tsequence: " << seq; if(m_map->canEncode(seq)) { KILE_DEBUG() << "\tcan encode this"; //if ( m_io->currentLine().mid(i, 2) == "{}" ) i = i + 2; return m_map->toEncoding(seq); } else { return seq; } } return ConvertBase::mapNext(i); } //END ConvertASCIIToEnc
puneetsl/Mikhail
src/convert.cpp
C++
gpl-2.0
7,123
/* * * Iter Vehemens ad Necem (IVAN) * Copyright (C) Timo Kiviluoto * Released under the GNU General * Public License * * See LICENSING which should be included * along with this file for more details * */ #include <cmath> #include <ctime> #include "bitmap.h" #include "graphics.h" #include "save.h" #include "allocate.h" #include "femath.h" #include "rawbit.h" /* * Blitting must be as fast as possible, even if no optimizations are used; * therefore we can't use inline functions inside loops, since they may be * left unexpanded. These macros will do the job efficiently, even if they * are rather ugly */ #define LOAD_SRC() int SrcCol = *SrcPtr; #define LOAD_DEST() int DestCol = *DestPtr; #define LOAD_ALPHA() int Alpha = *AlphaPtr; #define STORE_COLOR() *DestPtr = Red | Green | Blue; #define NEW_LUMINATE_RED()\ int Red = (SrcCol & 0xF800) + NewRedLuminance;\ \ if(Red >= 0)\ {\ if(Red > 0xF800)\ Red = 0xF800;\ }\ else\ Red = 0; #define NEW_LUMINATE_GREEN()\ int Green = (SrcCol & 0x7E0) + NewGreenLuminance;\ \ if(Green >= 0)\ {\ if(Green > 0x7E0)\ Green = 0x7E0;\ }\ else\ Green = 0; #define NEW_LUMINATE_BLUE()\ int Blue = (SrcCol & 0x1F) + NewBlueLuminance;\ \ if(Blue >= 0)\ {\ if(Blue > 0x1F)\ Blue = 0x1F;\ }\ else\ Blue = 0; #define NEW_APPLY_ALPHA_RED()\ {\ int DestRed = (DestCol & 0xF800);\ Red = (((Red - DestRed) * Alpha >> 8) + DestRed) & 0xF800;\ } #define NEW_APPLY_ALPHA_GREEN()\ {\ int DestGreen = (DestCol & 0x7E0);\ Green = (((Green - DestGreen) * Alpha >> 8) + DestGreen) & 0x7E0;\ } #define NEW_APPLY_ALPHA_BLUE()\ {\ int DestBlue = (DestCol & 0x1F);\ Blue = ((Blue - DestBlue) * Alpha >> 8) + DestBlue;\ } #define NEW_LOAD_AND_APPLY_ALPHA_RED()\ int Red;\ {\ int DestRed = DestCol & 0xF800;\ Red = ((((SrcCol & 0xF800) - DestRed) * Alpha >> 8) + DestRed) & 0xF800;\ } #define NEW_LOAD_AND_APPLY_ALPHA_GREEN()\ int Green;\ {\ int DestGreen = DestCol & 0x7E0;\ Green = ((((SrcCol & 0x7E0) - DestGreen) * Alpha >> 8) + DestGreen)\ & 0x7E0;\ } #define NEW_LOAD_AND_APPLY_ALPHA_BLUE()\ int Blue;\ {\ int DestBlue = DestCol & 0x1F;\ Blue = (((SrcCol & 0x1F) - DestBlue) * Alpha >> 8) + DestBlue;\ } bitmap::bitmap(cfestring& FileName) : FastFlag(0), AlphaMap(0), PriorityMap(0), RandMap(0) { rawbitmap Temp(FileName); Size = Temp.Size; XSizeTimesYSize = Size.X * Size.Y; Alloc2D(Image, Size.Y, Size.X); packcol16* Buffer = Image[0]; paletteindex* TempBuffer = Temp.PaletteBuffer[0]; for(int y = 0; y < Size.Y; ++y) for(int x = 0; x < Size.X; ++x) { int Char1 = *TempBuffer++; int Char3 = Char1 + (Char1 << 1); *Buffer++ = int(Temp.Palette[Char3] >> 3) << 11 | int(Temp.Palette[Char3 + 1] >> 2) << 5 | int(Temp.Palette[Char3 + 2] >> 3); } } bitmap::bitmap(cbitmap* Bitmap, int Flags, truth CopyAlpha) : bitmap(Bitmap->Size) { if(CopyAlpha && Bitmap->AlphaMap) { Alloc2D(AlphaMap, Size.Y, Size.X); Bitmap->BlitAndCopyAlpha(this, Flags); } else { if(!Flags) Bitmap->FastBlit(this); else Bitmap->NormalBlit(this, Flags); } } bitmap::bitmap(v2 Size) : Size(Size), XSizeTimesYSize(Size.X * Size.Y), FastFlag(0), AlphaMap(0), PriorityMap(0), RandMap(0) { Alloc2D(Image, Size.Y, Size.X); } bitmap::bitmap(v2 Size, col16 Color) : bitmap(Size) { ClearToColor(Color); } bitmap::~bitmap() { delete [] Image; delete [] AlphaMap; delete [] PriorityMap; delete [] RandMap; } void bitmap::Save(outputfile& SaveFile) const { SaveFile.Write(reinterpret_cast<char*>(Image[0]), XSizeTimesYSize * sizeof(packcol16)); if(AlphaMap) { SaveFile.Put(true); SaveFile.Write(reinterpret_cast<char*>(AlphaMap[0]), XSizeTimesYSize * sizeof(packalpha)); } else SaveFile.Put(false); if(PriorityMap) { SaveFile.Put(true); SaveFile.Write(reinterpret_cast<char*>(PriorityMap[0]), XSizeTimesYSize * sizeof(packpriority)); } else SaveFile.Put(false); SaveFile << uchar(FastFlag); } void bitmap::Load(inputfile& SaveFile) { SaveFile.Read(reinterpret_cast<char*>(Image[0]), XSizeTimesYSize * sizeof(packcol16)); if(SaveFile.Get()) { Alloc2D(AlphaMap, Size.Y, Size.X); SaveFile.Read(reinterpret_cast<char*>(AlphaMap[0]), XSizeTimesYSize * sizeof(packalpha)); } if(SaveFile.Get()) { Alloc2D(PriorityMap, Size.Y, Size.X); SaveFile.Read(reinterpret_cast<char*>(PriorityMap[0]), XSizeTimesYSize * sizeof(packpriority)); } FastFlag = ReadType<uchar>(SaveFile); } void bitmap::Save(cfestring& FileName) const { static char BMPHeader[] = { char(0x42), char(0x4D), char(0xB6), char(0x4F), char(0x12), char(0x00), char(0x00), char(0x00), char(0x00), char(0x00), char(0x36), char(0x00), char(0x00), char(0x00), char(0x28), char(0x00), char(0x00), char(0x00), char(0x20), char(0x03), char(0x00), char(0x00), char(0xF4), char(0x01), char(0x00), char(0x00), char(0x01), char(0x00), char(0x18), char(0x00), char(0x00), char(0x00), char(0x00), char(0x00), char(0x80), char(0x4F), char(0x12), char(0x00), char(0x33), char(0x0B), char(0x00), char(0x00), char(0x33), char(0x0B), char(0x00), char(0x00), char(0x00), char(0x00), char(0x00), char(0x00), char(0x00), char(0x00), char(0x00), char(0x00) }; outputfile SaveFile(FileName); BMPHeader[0x12] = Size.X & 0xFF; BMPHeader[0x13] = (Size.X >> 8) & 0xFF; BMPHeader[0x16] = Size.Y & 0xFF; BMPHeader[0x17] = (Size.Y >> 8) & 0xFF; SaveFile.Write(BMPHeader, 0x36); for(int y = Size.Y - 1; y >= 0; --y) for(int x = 0; x < Size.X; ++x) { col16 Pixel = GetPixel(x, y); SaveFile << char(Pixel << 3) << char((Pixel >> 5) << 2) << char((Pixel >> 11) << 3); } } void bitmap::Fill(v2 TopLeft, int Width, int Height, col16 Color) { Fill(TopLeft.X, TopLeft.Y, Width, Height, Color); } void bitmap::Fill(int X, int Y, v2 FillSize, col16 Color) { Fill(X, Y, FillSize.X, FillSize.Y, Color); } void bitmap::Fill(v2 TopLeft, v2 FillSize, col16 Color) { Fill(TopLeft.X, TopLeft.Y, FillSize.X, FillSize.Y, Color); } void bitmap::Fill(int X, int Y, int Width, int Height, col16 Color) { if(X >= Size.X || Y >= Size.Y) return; if(X + Width > Size.X) Width = Size.X - X; if(Y + Height > Size.Y) Height = Size.Y - Y; if(Color >> 8 == (Color & 0xFF)) { Width <<= 1; for(int y = 0; y < Height; ++y) memset(&Image[Y + y][X], Color, Width); } else for(int y = 0; y < Height; ++y) { packcol16* Ptr = &Image[Y + y][X]; cpackcol16*const EndPtr = Ptr + Width; while(Ptr != EndPtr) *Ptr++ = Color; } } void bitmap::ClearToColor(col16 Color) { packcol16* Ptr = Image[0]; if(Color >> 8 == (Color & 0xFF)) memset(Ptr, Color, XSizeTimesYSize * sizeof(packcol16)); else { cpackcol16*const EndPtr = Ptr + XSizeTimesYSize; while(Ptr != EndPtr) *Ptr++ = Color; } } void bitmap::NormalBlit(cblitdata& BlitData) const { blitdata B = BlitData; if(!FastFlag) { if(!B.Border.X || !B.Border.Y) ABORT("Zero-sized bitmap blit attempt detected!"); if(B.Flags & ROTATE && B.Border.X != B.Border.Y) ABORT("Blit error: FeLib supports only square rotating!"); if(!femath::Clip(B.Src.X, B.Src.Y, B.Dest.X, B.Dest.Y, B.Border.X, B.Border.Y, Size.X, Size.Y, B.Bitmap->Size.X, B.Bitmap->Size.Y)) return; } packcol16** SrcImage = Image; packcol16** DestImage = B.Bitmap->Image; switch(B.Flags & 7) { case NONE: { if(!B.Src.X && !B.Src.Y && !B.Dest.X && !B.Dest.Y && B.Border.X == Size.X && B.Border.Y == Size.Y && B.Border.X == B.Bitmap->Size.X && B.Border.Y == B.Bitmap->Size.Y) memcpy(DestImage[0], SrcImage[0], XSizeTimesYSize * sizeof(packcol16)); else { cint Bytes = B.Border.X * sizeof(packcol16); for(int y = 0; y < B.Border.Y; ++y) memcpy(&DestImage[B.Dest.Y + y][B.Dest.X], &SrcImage[B.Src.Y + y][B.Src.X], Bytes); } break; } case MIRROR: { B.Dest.X += B.Border.X - 1; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = &DestImage[B.Dest.Y + y][B.Dest.X]; for(; SrcPtr != EndPtr; ++SrcPtr, --DestPtr) *DestPtr = *SrcPtr; } break; } case FLIP: { B.Dest.Y += B.Border.Y - 1; cint Bytes = B.Border.X * sizeof(packcol16); for(int y = 0; y < B.Border.Y; ++y) memcpy(&DestImage[B.Dest.Y - y][B.Dest.X], &SrcImage[B.Src.Y + y][B.Src.X], Bytes); break; } case (MIRROR | FLIP): { B.Dest.X += B.Border.X - 1; B.Dest.Y += B.Border.Y - 1; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = &DestImage[B.Dest.Y - y][B.Dest.X]; for(; SrcPtr != EndPtr; ++SrcPtr, --DestPtr) *DestPtr = *SrcPtr; } break; } case ROTATE: { B.Dest.X += B.Border.X - 1; int TrueDestXMove = B.Bitmap->Size.X; packcol16* DestBase = &DestImage[B.Dest.Y][B.Dest.X]; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = DestBase - y; for(; SrcPtr != EndPtr; ++SrcPtr, DestPtr += TrueDestXMove) *DestPtr = *SrcPtr; } break; } case (MIRROR | ROTATE): { int TrueDestXMove = B.Bitmap->Size.X; packcol16* DestBase = &DestImage[B.Dest.Y][B.Dest.X]; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = DestBase + y; for(; SrcPtr != EndPtr; ++SrcPtr, DestPtr += TrueDestXMove) *DestPtr = *SrcPtr; } break; } case (FLIP | ROTATE): { B.Dest.X += B.Border.X - 1; B.Dest.Y += B.Border.Y - 1; int TrueDestXMove = B.Bitmap->Size.X; packcol16* DestBase = &DestImage[B.Dest.Y][B.Dest.X]; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = DestBase - y; for(; SrcPtr != EndPtr; ++SrcPtr, DestPtr -= TrueDestXMove) *DestPtr = *SrcPtr; } break; } case (MIRROR | FLIP | ROTATE): { B.Dest.Y += B.Border.Y - 1; int TrueDestXMove = B.Bitmap->Size.X; packcol16* DestBase = &DestImage[B.Dest.Y][B.Dest.X]; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = DestBase + y; for(; SrcPtr != EndPtr; ++SrcPtr, DestPtr -= TrueDestXMove) *DestPtr = *SrcPtr; } break; } } } void bitmap::LuminanceBlit(cblitdata& BlitData) const { blitdata B = BlitData; if(B.Luminance == NORMAL_LUMINANCE) { B.Flags = 0; NormalBlit(B); return; } if(!FastFlag) { if(!B.Border.X || !B.Border.Y) ABORT("Zero-sized bitmap blit attempt detected!"); if(!femath::Clip(B.Src.X, B.Src.Y, B.Dest.X, B.Dest.Y, B.Border.X, B.Border.Y, Size.X, Size.Y, B.Bitmap->Size.X, B.Bitmap->Size.Y)) return; } packcol16** SrcImage = Image; packcol16** DestImage = B.Bitmap->Image; int NewRedLuminance = (B.Luminance >> 7 & 0x1F800) - 0x10000; int NewGreenLuminance = (B.Luminance >> 4 & 0xFE0) - 0x800; int NewBlueLuminance = (B.Luminance >> 2 & 0x3F) - 0x20; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = &DestImage[B.Dest.Y + y][B.Dest.X]; for(; SrcPtr != EndPtr; ++SrcPtr, ++DestPtr) { LOAD_SRC(); NEW_LUMINATE_RED(); NEW_LUMINATE_GREEN(); NEW_LUMINATE_BLUE(); STORE_COLOR(); } } } void bitmap::NormalMaskedBlit(cblitdata& BlitData) const { blitdata B = BlitData; if(!FastFlag) { if(!B.Border.X || !B.Border.Y) ABORT("Zero-sized bitmap masked blit attempt detected!"); if(B.Flags & ROTATE && B.Border.X != B.Border.Y) ABORT("MaskedBlit error: FeLib supports only square rotating!"); if(!femath::Clip(B.Src.X, B.Src.Y, B.Dest.X, B.Dest.Y, B.Border.X, B.Border.Y, Size.X, Size.Y, B.Bitmap->Size.X, B.Bitmap->Size.Y)) return; } packcol16** SrcImage = Image; packcol16** DestImage = B.Bitmap->Image; packcol16 PackedMaskColor = B.MaskColor; switch(B.Flags & 7) { case NONE: { for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = &DestImage[B.Dest.Y + y][B.Dest.X]; for(; SrcPtr != EndPtr; ++SrcPtr, ++DestPtr) if(*SrcPtr != PackedMaskColor) *DestPtr = *SrcPtr; } break; } case MIRROR: { B.Dest.X += B.Border.X - 1; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = &DestImage[B.Dest.Y + y][B.Dest.X]; for(; SrcPtr != EndPtr; ++SrcPtr, --DestPtr) if(*SrcPtr != PackedMaskColor) *DestPtr = *SrcPtr; } break; } case FLIP: { B.Dest.Y += B.Border.Y - 1; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = &DestImage[B.Dest.Y - y][B.Dest.X]; for(; SrcPtr != EndPtr; ++SrcPtr, ++DestPtr) if(*SrcPtr != PackedMaskColor) *DestPtr = *SrcPtr; } break; } case (MIRROR | FLIP): { B.Dest.X += B.Border.X - 1; B.Dest.Y += B.Border.Y - 1; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = &DestImage[B.Dest.Y - y][B.Dest.X]; for(; SrcPtr != EndPtr; ++SrcPtr, --DestPtr) if(*SrcPtr != PackedMaskColor) *DestPtr = *SrcPtr; } break; } case ROTATE: { B.Dest.X += B.Border.X - 1; int TrueDestXMove = B.Bitmap->Size.X; packcol16* DestBase = &DestImage[B.Dest.Y][B.Dest.X]; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = DestBase - y; for(; SrcPtr != EndPtr; ++SrcPtr, DestPtr += TrueDestXMove) if(*SrcPtr != PackedMaskColor) *DestPtr = *SrcPtr; } break; } case (MIRROR | ROTATE): { int TrueDestXMove = B.Bitmap->Size.X; packcol16* DestBase = &DestImage[B.Dest.Y][B.Dest.X]; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = DestBase + y; for(; SrcPtr != EndPtr; ++SrcPtr, DestPtr += TrueDestXMove) if(*SrcPtr != PackedMaskColor) *DestPtr = *SrcPtr; } break; } case (FLIP | ROTATE): { B.Dest.X += B.Border.X - 1; B.Dest.Y += B.Border.Y - 1; int TrueDestXMove = B.Bitmap->Size.X; packcol16* DestBase = &DestImage[B.Dest.Y][B.Dest.X]; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = DestBase - y; for(; SrcPtr != EndPtr; ++SrcPtr, DestPtr -= TrueDestXMove) if(*SrcPtr != PackedMaskColor) *DestPtr = *SrcPtr; } break; } case (MIRROR | FLIP | ROTATE): { B.Dest.Y += B.Border.Y - 1; int TrueDestXMove = B.Bitmap->Size.X; packcol16* DestBase = &DestImage[B.Dest.Y][B.Dest.X]; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = DestBase + y; for(; SrcPtr != EndPtr; ++SrcPtr, DestPtr -= TrueDestXMove) if(*SrcPtr != PackedMaskColor) *DestPtr = *SrcPtr; } break; } } } void bitmap::LuminanceMaskedBlit(cblitdata& BlitData) const { blitdata B = BlitData; if(B.Luminance == NORMAL_LUMINANCE) { B.Flags = 0; NormalMaskedBlit(B); return; } if(!FastFlag) { if(!B.Border.X || !B.Border.Y) ABORT("Zero-sized bitmap masked blit attempt detected!"); if(!femath::Clip(B.Src.X, B.Src.Y, B.Dest.X, B.Dest.Y, B.Border.X, B.Border.Y, Size.X, Size.Y, B.Bitmap->Size.X, B.Bitmap->Size.Y)) return; } packcol16** SrcImage = Image; packcol16** DestImage = B.Bitmap->Image; int NewRedLuminance = (B.Luminance >> 7 & 0x1F800) - 0x10000; int NewGreenLuminance = (B.Luminance >> 4 & 0xFE0) - 0x800; int NewBlueLuminance = (B.Luminance >> 2 & 0x3F) - 0x20; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = &DestImage[B.Dest.Y + y][B.Dest.X]; for(; SrcPtr != EndPtr; ++SrcPtr, ++DestPtr) { LOAD_SRC(); if(SrcCol != B.MaskColor) { NEW_LUMINATE_RED(); NEW_LUMINATE_GREEN(); NEW_LUMINATE_BLUE(); STORE_COLOR(); } } } } void bitmap::SimpleAlphaBlit(bitmap* Bitmap, alpha Alpha, col16 MaskColor) const { if(Alpha == 255) { blitdata B = { Bitmap, { 0, 0 }, { 0, 0 }, { Size.X, Size.Y }, { 0 }, MaskColor, 0 }; NormalMaskedBlit(B); return; } if(!FastFlag && (Size.X != Bitmap->Size.X || Size.Y != Bitmap->Size.Y)) ABORT("Fast simple alpha blit attempt of noncongruent bitmaps detected!"); cpackcol16* SrcPtr = Image[0]; cpackcol16* EndPtr = SrcPtr + XSizeTimesYSize; packcol16* DestPtr = Bitmap->Image[0]; for(; SrcPtr != EndPtr; ++SrcPtr, ++DestPtr) { LOAD_SRC(); if(SrcCol != MaskColor) { LOAD_DEST(); NEW_LOAD_AND_APPLY_ALPHA_RED(); NEW_LOAD_AND_APPLY_ALPHA_GREEN(); NEW_LOAD_AND_APPLY_ALPHA_BLUE(); STORE_COLOR(); } } } void bitmap::AlphaMaskedBlit(cblitdata& BlitData) const { blitdata B = BlitData; if(!AlphaMap) { B.Flags = 0; NormalMaskedBlit(B); return; } if(!FastFlag) { if(!B.Border.X || !B.Border.Y) ABORT("Zero-sized bitmap alpha blit attempt detected!"); if(!femath::Clip(B.Src.X, B.Src.Y, B.Dest.X, B.Dest.Y, B.Border.X, B.Border.Y, Size.X, Size.Y, B.Bitmap->Size.X, B.Bitmap->Size.Y)) return; } packcol16** SrcImage = Image; packalpha** SrcAlphaMap = AlphaMap; packcol16** DestImage = B.Bitmap->Image; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackalpha* AlphaPtr = &SrcAlphaMap[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = &DestImage[B.Dest.Y + y][B.Dest.X]; for(; SrcPtr != EndPtr; ++SrcPtr, ++DestPtr, ++AlphaPtr) { LOAD_SRC(); if(SrcCol != B.MaskColor) { LOAD_DEST(); LOAD_ALPHA(); NEW_LOAD_AND_APPLY_ALPHA_RED(); NEW_LOAD_AND_APPLY_ALPHA_GREEN(); NEW_LOAD_AND_APPLY_ALPHA_BLUE(); STORE_COLOR(); } } } } void bitmap::DrawLine(v2 From, int ToX, int ToY, col16 Color, truth Wide) { DrawLine(From.X, From.Y, ToX, ToY, Color, Wide); } void bitmap::DrawLine(int FromX, int FromY, v2 To, col16 Color, truth Wide) { DrawLine(FromX, FromY, To.X, To.Y, Color, Wide); } void bitmap::DrawLine(v2 From, v2 To, col16 Color, truth Wide) { DrawLine(From.X, From.Y, To.X, To.Y, Color, Wide); } void bitmap::DrawLine(int OrigFromX, int OrigFromY, int OrigToX, int OrigToY, col16 Color, truth Wide) { if(OrigFromY == OrigToY) { DrawHorizontalLine(OrigFromX, OrigToX, OrigFromY, Color, Wide); return; } if(OrigFromX == OrigToX) { DrawVerticalLine(OrigFromX, OrigFromY, OrigToY, Color, Wide); return; } static cint PointX[] = { 0, 0, -1, 1, 0 }; static cint PointY[] = { 0, -1, 0, 0, 1 }; cint Times = Wide ? 5 : 1; for(int c1 = 0; c1 < Times; ++c1) { cint X1 = OrigFromX + PointX[c1]; cint Y1 = OrigFromY + PointY[c1]; cint X2 = OrigToX + PointX[c1]; cint Y2 = OrigToY + PointY[c1]; cint DeltaX = abs(X2 - X1); cint DeltaY = abs(Y2 - Y1); int x, c2; int XChange, PtrXChange, PtrYChange; int DoubleDeltaX, DoubleDeltaY, End; if(DeltaX >= DeltaY) { x = X1; c2 = DeltaX; PtrXChange = XChange = X1 < X2 ? 1 : -1; PtrYChange = Y1 < Y2 ? Size.X : -Size.X; DoubleDeltaX = DeltaX << 1; DoubleDeltaY = DeltaY << 1; End = X2; } else { x = Y1; c2 = DeltaY; XChange = Y1 < Y2 ? 1 : -1; PtrXChange = Y1 < Y2 ? Size.X : -Size.X; PtrYChange = X1 < X2 ? 1 : -1; DoubleDeltaX = DeltaY << 1; DoubleDeltaY = DeltaX << 1; End = Y2; } packcol16* Ptr = &Image[Y1][X1]; *Ptr = Color; while(x != End) { x += XChange; Ptr += PtrXChange; c2 += DoubleDeltaY; if(c2 >= DoubleDeltaX) { c2 -= DoubleDeltaX; Ptr += PtrYChange; } *Ptr = Color; } } } void bitmap::DrawVerticalLine(int OrigX, int OrigFromY, int OrigToY, col16 Color, truth Wide) { static cint PointX[] = { 0, -1, 1 }; cint Times = Wide ? 3 : 1; for(int c = 0; c < Times; ++c) { int X = OrigX + PointX[c]; int FromY = OrigFromY; int ToY = OrigToY; if(FromY > ToY) Swap(FromY, ToY); if(Wide && !c) { --FromY; ++ToY; } if(X < 0 || X >= Size.X || ToY < 0 || FromY >= Size.Y) continue; FromY = Max(FromY, 0); ToY = Min(ToY, Size.Y-1); packcol16* Ptr = &Image[FromY][X]; for(int y = FromY; y <= ToY; ++y, Ptr += Size.X) *Ptr = Color; } } void bitmap::DrawHorizontalLine(int OrigFromX, int OrigToX, int OrigY, col16 Color, truth Wide) { static cint PointY[] = { 0, -1, 1 }; cint Times = Wide ? 3 : 1; for(int c = 0; c < Times; ++c) { int Y = OrigY + PointY[c]; int FromX = OrigFromX; int ToX = OrigToX; if(FromX > ToX) Swap(FromX, ToX); if(Wide && !c) { --FromX; ++ToX; } if(Y < 0 || Y >= Size.Y || ToX < 0 || FromX >= Size.X) continue; FromX = Max(FromX, 0); ToX = Min(ToX, Size.X-1); packcol16* Ptr = &Image[Y][FromX]; for(int x = FromX; x <= ToX; ++x, ++Ptr) *Ptr = Color; } } void bitmap::DrawPolygon(int CenterX, int CenterY, int Radius, int NumberOfSides, col16 Color, truth DrawSides, truth DrawDiameters, double Rotation) { if(!DrawSides && !DrawDiameters) return; v2* Point = new v2[NumberOfSides]; double AngleDelta = 2 * FPI / NumberOfSides; int c; for(c = 0; c < NumberOfSides; ++c) { Point[c].X = CenterX + int(sin(AngleDelta * c + Rotation) * Radius); Point[c].Y = CenterY + int(cos(AngleDelta * c + Rotation) * Radius); } if(DrawDiameters) { if(DrawSides) { for(c = 0; c < NumberOfSides; ++c) for(int a = 0; a < NumberOfSides; ++a) if(c != a) DrawLine(Point[c].X, Point[c].Y, Point[a].X, Point[a].Y, Color, true); } else { for(c = 0; c < NumberOfSides; ++c) for(int a = 0; a < NumberOfSides; ++a) if((c - a > 1 || a - c > 1) && (a || c != NumberOfSides - 1) && (c || a != NumberOfSides - 1)) DrawLine(Point[c].X, Point[c].Y, Point[a].X, Point[a].Y, Color, true); } } else { for(c = 0; c < NumberOfSides - 1; ++c) DrawLine(Point[c].X, Point[c].Y, Point[c + 1].X, Point[c + 1].Y, Color, true); DrawLine(Point[NumberOfSides - 1].X, Point[NumberOfSides - 1].Y, Point[0].X, Point[0].Y, Color, true); } delete [] Point; } void bitmap::CreateAlphaMap(alpha InitialValue) { if(AlphaMap) ABORT("Alpha leak detected!"); Alloc2D(AlphaMap, Size.Y, Size.X); memset(AlphaMap[0], InitialValue, XSizeTimesYSize); } truth bitmap::Fade(long& AlphaSum, packalpha& AlphaAverage, int Amount) { if(!AlphaMap) ABORT("No alpha map to fade."); truth Changes = false; long Alphas = 0; long NewAlphaSum = 0; long Size = XSizeTimesYSize; for(long c = 0; c < Size; ++c) { packalpha* AlphaPtr = &AlphaMap[0][c]; if(*AlphaPtr) { if(*AlphaPtr > Amount) { *AlphaPtr -= Amount; NewAlphaSum += *AlphaPtr; ++Alphas; Changes = true; } else { *AlphaPtr = 0; Changes = true; if(RandMap) UpdateRandMap(c, false); } } } AlphaSum = NewAlphaSum; AlphaAverage = Alphas ? NewAlphaSum / Alphas : 0; return Changes; } void bitmap::Outline(col16 Color, alpha Alpha, priority Priority) { if(!AlphaMap) CreateAlphaMap(255); col16 LastColor, NextColor; int XMax = Size.X; int YMax = Size.Y - 1; for(int x = 0; x < XMax; ++x) { packcol16* Buffer = &Image[0][x]; LastColor = *Buffer; for(int y = 0; y < YMax; ++y) { NextColor = *(Buffer + XMax); if((LastColor == TRANSPARENT_COLOR || !y) && NextColor != TRANSPARENT_COLOR) { *Buffer = Color; SetAlpha(x, y, Alpha); SafeSetPriority(x, y, Priority); } Buffer += XMax; if(LastColor != TRANSPARENT_COLOR && (NextColor == TRANSPARENT_COLOR || y == YMax - 1)) { *Buffer = Color; SetAlpha(x, y + 1, Alpha); SafeSetPriority(x, y + 1, Priority); } LastColor = NextColor; } } --XMax; ++YMax; for(int y = 0; y < YMax; ++y) { packcol16* Buffer = Image[y]; LastColor = *Buffer; for(int x = 0; x < XMax; ++x) { NextColor = *(Buffer + 1); if((LastColor == TRANSPARENT_COLOR || !x) && NextColor != TRANSPARENT_COLOR) { *Buffer = Color; SetAlpha(x, y, Alpha); SafeSetPriority(x, y, Priority); } ++Buffer; if(LastColor != TRANSPARENT_COLOR && (NextColor == TRANSPARENT_COLOR || x == XMax - 1)) { *Buffer = Color; SetAlpha(x + 1, y, Alpha); SafeSetPriority(x + 1, y, Priority); } LastColor = NextColor; } } } void bitmap::FadeToScreen(bitmapeditor BitmapEditor) { bitmap Backup(DOUBLE_BUFFER); Backup.ActivateFastFlag(); blitdata B = { DOUBLE_BUFFER, { 0, 0 }, { 0, 0 }, { RES.X, RES.Y }, { 0 }, 0, 0 }; for(int c = 0; c <= 5; ++c) { clock_t StartTime = clock(); int Element = 127 - c * 25; B.Luminance = MakeRGB24(Element, Element, Element); Backup.LuminanceMaskedBlit(B); if(BitmapEditor) BitmapEditor(this, true); SimpleAlphaBlit(DOUBLE_BUFFER, c * 50, 0); graphics::BlitDBToScreen(); while(clock() - StartTime < 0.05 * CLOCKS_PER_SEC); } DOUBLE_BUFFER->ClearToColor(0); if(BitmapEditor) BitmapEditor(this, true); B.Flags = 0; NormalMaskedBlit(B); graphics::BlitDBToScreen(); } void bitmap::StretchBlit(cblitdata& BlitData) const { blitdata B = BlitData; if(!FastFlag) { if(!B.Border.X || !B.Border.Y) ABORT("Zero-sized bitmap stretch blit attempt detected!"); if(!femath::Clip(B.Src.X, B.Src.Y, B.Dest.X, B.Dest.Y, B.Border.X, B.Border.Y, Size.X, Size.Y, B.Bitmap->Size.X, B.Bitmap->Size.Y)) return; } if(B.Stretch > 1) { int tx = B.Dest.X; for(int x1 = B.Src.X; x1 < B.Src.X + B.Border.X; ++x1, tx += B.Stretch) { int ty = B.Dest.Y; for(int y1 = B.Src.Y; y1 < B.Src.Y + B.Border.Y; ++y1, ty += B.Stretch) { packcol16 Pixel = Image[y1][x1]; if(Pixel != TRANSPARENT_COLOR) for(int x2 = tx; x2 < tx + B.Stretch; ++x2) for(int y2 = ty; y2 < ty + B.Stretch; ++y2) B.Bitmap->Image[y2][x2] = Pixel; } } return; } else if(B.Stretch < -1) { int tx = B.Dest.X; for(int x1 = B.Src.X; x1 < B.Src.X + B.Border.X; x1 -= B.Stretch, ++tx) { int ty = B.Dest.Y; for(int y1 = B.Src.Y; y1 < B.Src.Y + B.Border.Y; y1 -= B.Stretch, ++ty) { packcol16 Pixel = Image[y1][x1]; if(Pixel != TRANSPARENT_COLOR) B.Bitmap->Image[ty][tx] = Pixel; } } return; } else { B.Flags = 0; NormalMaskedBlit(B); return; } } outputfile& operator<<(outputfile& SaveFile, cbitmap* Bitmap) { if(Bitmap) { SaveFile.Put(1); SaveFile << Bitmap->GetSize(); Bitmap->Save(SaveFile); } else SaveFile.Put(0); return SaveFile; } inputfile& operator>>(inputfile& SaveFile, bitmap*& Bitmap) { if(SaveFile.Get()) { Bitmap = new bitmap(ReadType<v2>(SaveFile)); Bitmap->Load(SaveFile); } else Bitmap = 0; return SaveFile; } void bitmap::DrawRectangle(v2 TopLeft, int Right, int Bottom, col16 Color, truth Wide) { DrawRectangle(TopLeft.X, TopLeft.Y, Right, Bottom, Color, Wide); } void bitmap::DrawRectangle(int Left, int Top, v2 BottomRight, col16 Color, truth Wide) { DrawRectangle(Left, Top, BottomRight.X, BottomRight.Y, Color, Wide); } void bitmap::DrawRectangle(v2 TopLeft, v2 BottomRight, col16 Color, truth Wide) { DrawRectangle(TopLeft.X, TopLeft.Y, BottomRight.X, BottomRight.Y, Color, Wide); } void bitmap::DrawRectangle(int Left, int Top, int Right, int Bottom, col16 Color, truth Wide) { DrawHorizontalLine(Left, Right, Top, Color, Wide); DrawHorizontalLine(Left, Right, Bottom, Color, Wide); DrawVerticalLine(Right, Top, Bottom, Color, Wide); DrawVerticalLine(Left, Top, Bottom, Color, Wide); } void bitmap::AlphaLuminanceBlit(cblitdata& BlitData) const { if(BlitData.Luminance == NORMAL_LUMINANCE) { AlphaMaskedBlit(BlitData); return; } if(!AlphaMap) { LuminanceMaskedBlit(BlitData); return; } blitdata B = BlitData; if(!FastFlag) { if(!B.Border.X || !B.Border.Y) ABORT("Zero-sized bitmap alpha blit attempt detected!"); if(!femath::Clip(B.Src.X, B.Src.Y, B.Dest.X, B.Dest.Y, B.Border.X, B.Border.Y, Size.X, Size.Y, B.Bitmap->Size.X, B.Bitmap->Size.Y)) return; } packcol16** SrcImage = Image; packalpha** SrcAlphaMap = AlphaMap; packcol16** DestImage = B.Bitmap->Image; int NewRedLuminance = (B.Luminance >> 7 & 0x1F800) - 0x10000; int NewGreenLuminance = (B.Luminance >> 4 & 0xFE0) - 0x800; int NewBlueLuminance = (B.Luminance >> 2 & 0x3F) - 0x20; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackalpha* AlphaPtr = &SrcAlphaMap[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = &DestImage[B.Dest.Y + y][B.Dest.X]; for(; SrcPtr != EndPtr; ++SrcPtr, ++DestPtr, ++AlphaPtr) { LOAD_SRC(); if(SrcCol != B.MaskColor) { LOAD_DEST(); LOAD_ALPHA(); NEW_LUMINATE_RED(); NEW_APPLY_ALPHA_RED(); NEW_LUMINATE_GREEN(); NEW_APPLY_ALPHA_GREEN(); NEW_LUMINATE_BLUE(); NEW_APPLY_ALPHA_BLUE(); STORE_COLOR(); } } } } /* Only works for 16x16 pictures :( */ void bitmap::CreateFlames(rawbitmap* RawBitmap, v2 RawPos, ulong SeedNFlags, int Frame) { femath::SaveSeed(); femath::SetSeed(SeedNFlags); int FlameTop[16], FlameBottom[16], FlamePhase[16]; int x, y; for(x = 0; x < 16; ++x) { FlameBottom[x] = NO_FLAME; for(y = 0; y < 16; ++y) if(GetPixel(x, y) != TRANSPARENT_COLOR) { if(1 << RawBitmap->GetMaterialColorIndex(RawPos.X + x, RawPos.Y + y) & SeedNFlags) { FlamePhase[x] = RAND_16; if(y > 1) { FlameBottom[x] = y - 1; if(y >= 5) FlameTop[x] = (y - (RAND_32 * y >> 5)) >> 1; else FlameTop[x] = 0; } else { FlameBottom[x] = 1; FlameTop[x] = 0; } } break; } } for(x = 0; x < 16; ++x) { if(FlameBottom[x] != NO_FLAME) { int Phase = (Frame + FlamePhase[x]) & 15; int Length = FlameBottom[x] - FlameTop[x]; int Top = FlameBottom[x] - Length + Phase * (15 - Phase) * Length / 56; for(y = Top; y <= FlameBottom[x]; ++y) { int Pos = y - Top; PowerPutPixel(x, y, MakeRGB16(255, 255 - (Pos << 7) / Length, 0), 127 + (Pos << 6) / Length, AVERAGE_PRIORITY); } } } femath::LoadSeed(); } void bitmap::CreateSparkle(v2 SparklePos, int Frame) { if(Frame) { int Size = (Frame - 1) * (16 - Frame) / 10; PowerPutPixel(SparklePos.X, SparklePos.Y, WHITE, 255, SPARKLE_PRIORITY); for(int c = 1; c < Size; ++c) { int Lightness = 191 + ((Size - c) << 6) / Size; col16 RGB = MakeRGB16(Lightness, Lightness, Lightness); PowerPutPixel(SparklePos.X + c, SparklePos.Y, RGB, 255, SPARKLE_PRIORITY); PowerPutPixel(SparklePos.X - c, SparklePos.Y, RGB, 255, SPARKLE_PRIORITY); PowerPutPixel(SparklePos.X, SparklePos.Y + c, RGB, 255, SPARKLE_PRIORITY); PowerPutPixel(SparklePos.X, SparklePos.Y - c, RGB, 255, SPARKLE_PRIORITY); } } } void bitmap::CreateFlies(ulong Seed, int Frame, int FlyAmount) { femath::SaveSeed(); femath::SetSeed(Seed); for(int c = 0; c < FlyAmount; ++c) { double Constant = double(RAND() % 10000) / 10000 * FPI; v2 StartPos = v2(5 + RAND() % 6, 5 + RAND() % 6); double Temp = (double(16 - Frame) * FPI) / 16; if(RAND() & 1) Temp = -Temp; v2 Where; Where.X = int(StartPos.X + sin(Constant + Temp) * 3); Where.Y = int(StartPos.Y + sin(2 * (Constant + Temp)) * 3); PowerPutPixel(Where.X, Where.Y, MakeRGB16(40, 40, 60), 255, FLY_PRIORITY); } femath::LoadSeed(); } void bitmap::CreateLightning(ulong Seed, col16 Color) { femath::SaveSeed(); femath::SetSeed(Seed); v2 StartPos; v2 Direction(0, 0); do { do { if(RAND() & 1) { if(RAND() & 1) { StartPos.X = 0; Direction.X = 1; } else { StartPos.X = Size.X - 1; Direction.X = -1; } StartPos.Y = RAND() % Size.Y; } else { if(RAND() & 1) { StartPos.Y = 0; Direction.Y = 1; } else { StartPos.Y = Size.Y - 1; Direction.Y = -1; } StartPos.X = RAND() % Size.X; } } while(GetPixel(StartPos) != TRANSPARENT_COLOR); } while(!CreateLightning(StartPos, Direction, NO_LIMIT, Color)); femath::LoadSeed(); } struct pixelvectorcontroller { static truth Handler(int x, int y) { if(CurrentSprite->GetPixel(x, y) == TRANSPARENT_COLOR) { PixelVector.push_back(v2(x, y)); return true; } else return false; } static std::vector<v2> PixelVector; static bitmap* CurrentSprite; }; std::vector<v2> pixelvectorcontroller::PixelVector; bitmap* pixelvectorcontroller::CurrentSprite; truth bitmap::CreateLightning(v2 StartPos, v2 Direction, int MaxLength, col16 Color) { pixelvectorcontroller::CurrentSprite = this; std::vector<v2>& PixelVector = pixelvectorcontroller::PixelVector; PixelVector.clear(); v2 LastMove(0, 0); int Counter = 0; for(;;) { v2 Move(1 + (RAND() & 3), 1 + (RAND() & 3)); if(Direction.X < 0 || (!Direction.X && RAND() & 1)) Move.X = -Move.X; if(Direction.Y < 0 || (!Direction.Y && RAND() & 1)) Move.Y = -Move.Y; LimitRef(Move.X, -StartPos.X, Size.X - StartPos.X - 1); LimitRef(Move.Y, -StartPos.Y, Size.X - StartPos.Y - 1); if(Counter < 10 && ((!Move.Y && !LastMove.Y) || (Move.Y && LastMove.Y && (Move.X << 10) / Move.Y == (LastMove.X << 10) / LastMove.Y))) { ++Counter; continue; } Counter = 0; if(!mapmath<pixelvectorcontroller>::DoLine(StartPos.X, StartPos.Y, StartPos.X + Move.X, StartPos.Y + Move.Y) || ulong(MaxLength) <= PixelVector.size()) { int Limit = Min<int>(PixelVector.size(), MaxLength); for(int c = 0; c < Limit; ++c) { PutPixel(PixelVector[c], Color); SafeSetPriority(PixelVector[c], LIGHTNING_PRIORITY); } PixelVector.clear(); return true; } StartPos += Move; LastMove = Move; if((Direction.X && (!StartPos.X || StartPos.X == Size.X - 1)) || (Direction.Y && (!StartPos.Y || StartPos.Y == Size.X - 1))) { PixelVector.clear(); return false; } } } void bitmap::BlitAndCopyAlpha(bitmap* Bitmap, int Flags) const { if(!FastFlag) { if(!AlphaMap || !Bitmap->AlphaMap) ABORT("Attempt to blit and copy alpha without an alpha map detected!"); if(Flags & ROTATE && Size.X != Size.Y) ABORT("Blit and copy alpha error: FeLib supports only square rotating!"); if(Size.X != Bitmap->Size.X || Size.Y != Bitmap->Size.Y) ABORT("Blit and copy alpha attempt of noncongruent bitmaps detected!"); } packcol16** SrcImage = Image; packalpha** SrcAlphaMap = AlphaMap; packcol16** DestImage = Bitmap->Image; packalpha** DestAlphaMap = Bitmap->AlphaMap; switch(Flags & 7) { case NONE: { memcpy(DestImage[0], SrcImage[0], XSizeTimesYSize * sizeof(packcol16)); memcpy(DestAlphaMap[0], SrcAlphaMap[0], XSizeTimesYSize * sizeof(packalpha)); break; } case MIRROR: { int Width = Size.X; int Height = Size.Y; int DestX = Width - 1; cpackcol16* SrcPtr = SrcImage[0]; cpackalpha* SrcAlphaPtr = SrcAlphaMap[0]; for(int y = 0; y < Height; ++y) { cpackcol16* EndPtr = SrcPtr + Width; packcol16* DestPtr = &DestImage[y][DestX]; packalpha* DestAlphaPtr = &DestAlphaMap[y][DestX]; for(; SrcPtr != EndPtr; ++SrcPtr, --DestPtr, ++SrcAlphaPtr, --DestAlphaPtr) { *DestPtr = *SrcPtr; *DestAlphaPtr = *SrcAlphaPtr; } } break; } case FLIP: { int Height = Size.Y; int Width = Size.X; int DestY = Height - 1; for(int y = 0; y < Height; ++y) { memcpy(DestImage[DestY - y], SrcImage[y], Width * sizeof(packcol16)); memcpy(DestAlphaMap[DestY - y], SrcAlphaMap[y], Width * sizeof(packalpha)); } break; } case (MIRROR | FLIP): { cpackcol16* SrcPtr = SrcImage[0]; cpackcol16* EndPtr = SrcPtr + XSizeTimesYSize; cpackalpha* SrcAlphaPtr = SrcAlphaMap[0]; packcol16* DestPtr = &DestImage[Size.Y - 1][Size.X - 1]; packalpha* DestAlphaPtr = &DestAlphaMap[Size.Y - 1][Size.X - 1]; for(; SrcPtr != EndPtr; ++SrcPtr, --DestPtr, ++SrcAlphaPtr, --DestAlphaPtr) { *DestPtr = *SrcPtr; *DestAlphaPtr = *SrcAlphaPtr; } break; } case ROTATE: { cint Width = Size.X; cpackcol16* SrcPtr = SrcImage[0]; cpackalpha* SrcAlphaPtr = SrcAlphaMap[0]; packcol16* DestBase = &DestImage[0][Width - 1]; packalpha* DestAlphaBase = &DestAlphaMap[0][Width - 1]; for(int y = 0; y < Width; ++y) { cpackcol16* EndPtr = SrcPtr + Width; packcol16* DestPtr = DestBase - y; packalpha* DestAlphaPtr = DestAlphaBase - y; for(; SrcPtr != EndPtr; ++SrcPtr, DestPtr += Width, ++SrcAlphaPtr, DestAlphaPtr += Width) { *DestPtr = *SrcPtr; *DestAlphaPtr = *SrcAlphaPtr; } } break; } case (MIRROR | ROTATE): { cint Width = Size.X; cpackcol16* SrcPtr = SrcImage[0]; cpackalpha* SrcAlphaPtr = SrcAlphaMap[0]; packcol16* DestBase = DestImage[0]; packalpha* DestAlphaBase = DestAlphaMap[0]; for(int y = 0; y < Width; ++y) { cpackcol16* EndPtr = SrcPtr + Width; packcol16* DestPtr = DestBase + y; packalpha* DestAlphaPtr = DestAlphaBase + y; for(; SrcPtr != EndPtr; ++SrcPtr, DestPtr += Width, ++SrcAlphaPtr, DestAlphaPtr += Width) { *DestPtr = *SrcPtr; *DestAlphaPtr = *SrcAlphaPtr; } } break; } case (FLIP | ROTATE): { cint Width = Size.X; cpackcol16* SrcPtr = SrcImage[0]; cpackalpha* SrcAlphaPtr = SrcAlphaMap[0]; packcol16* DestBase = &DestImage[Width - 1][Width - 1]; packalpha* DestAlphaBase = &DestAlphaMap[Width - 1][Width - 1]; for(int y = 0; y < Width; ++y) { cpackcol16* EndPtr = SrcPtr + Width; packcol16* DestPtr = DestBase - y; packalpha* DestAlphaPtr = DestAlphaBase - y; for(; SrcPtr != EndPtr; ++SrcPtr, DestPtr -= Width, ++SrcAlphaPtr, DestAlphaPtr -= Width) { *DestPtr = *SrcPtr; *DestAlphaPtr = *SrcAlphaPtr; } } break; } case (MIRROR | FLIP | ROTATE): { cint Width = Size.X; cpackcol16* SrcPtr = SrcImage[0]; cpackalpha* SrcAlphaPtr = SrcAlphaMap[0]; packcol16* DestBase = DestImage[Width - 1]; packalpha* DestAlphaBase = DestAlphaMap[Width - 1]; for(int y = 0; y < Width; ++y) { cpackcol16* EndPtr = SrcPtr + Width; packcol16* DestPtr = DestBase + y; packalpha* DestAlphaPtr = DestAlphaBase + y; for(; SrcPtr != EndPtr; ++SrcPtr, DestPtr -= Width, ++SrcAlphaPtr, DestAlphaPtr -= Width) { *DestPtr = *SrcPtr; *DestAlphaPtr = *SrcAlphaPtr; } } break; } } } void bitmap::FillAlpha(alpha Alpha) { memset(AlphaMap[0], Alpha, XSizeTimesYSize); } void bitmap::PowerPutPixel(int X, int Y, col16 Color, alpha Alpha, priority Priority) { if(X >= 0 && Y >= 0 && X < Size.X && Y < Size.Y) { Image[Y][X] = Color; if(AlphaMap) AlphaMap[Y][X] = Alpha; else if(Alpha != 255) { CreateAlphaMap(255); AlphaMap[Y][X] = Alpha; } if(PriorityMap) PriorityMap[Y][X] = Priority; } } void bitmap::MaskedPriorityBlit(cblitdata& BlitData) const { if(!PriorityMap || !BlitData.Bitmap->PriorityMap) { LuminanceMaskedBlit(BlitData); return; } blitdata B = BlitData; if(!FastFlag) { if(!B.Border.X || !B.Border.Y) ABORT("Zero-sized bitmap masked priority blit attempt detected!"); if(!femath::Clip(B.Src.X, B.Src.Y, B.Dest.X, B.Dest.Y, B.Border.X, B.Border.Y, Size.X, Size.Y, B.Bitmap->Size.X, B.Bitmap->Size.Y)) return; } packcol16** SrcImage = Image; packpriority** SrcPriorityMap = PriorityMap; packcol16** DestImage = B.Bitmap->Image; packpriority** DestPriorityMap = B.Bitmap->PriorityMap; int NewRedLuminance = (B.Luminance >> 7 & 0x1F800) - 0x10000; int NewGreenLuminance = (B.Luminance >> 4 & 0xFE0) - 0x800; int NewBlueLuminance = (B.Luminance >> 2 & 0x3F) - 0x20; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackpriority* SrcPriorityPtr = &SrcPriorityMap[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = &DestImage[B.Dest.Y + y][B.Dest.X]; packpriority* DestPriorityPtr = &DestPriorityMap[B.Dest.Y + y][B.Dest.X]; for(; SrcPtr != EndPtr; ++SrcPtr, ++DestPtr, ++SrcPriorityPtr, ++DestPriorityPtr) { LOAD_SRC(); if(SrcCol != B.MaskColor) { priority SrcPriority = *SrcPriorityPtr; priority DestPriority = *DestPriorityPtr; if((SrcPriority & 0xF) >= (DestPriority & 0xF) || (SrcPriority & 0xF0) >= (DestPriority & 0xF0)) { NEW_LUMINATE_RED(); NEW_LUMINATE_GREEN(); NEW_LUMINATE_BLUE(); STORE_COLOR(); *DestPriorityPtr = SrcPriority; } } } } } void bitmap::AlphaPriorityBlit(cblitdata& BlitData) const { if(!AlphaMap) { MaskedPriorityBlit(BlitData); return; } if(!PriorityMap || !BlitData.Bitmap->PriorityMap) { AlphaLuminanceBlit(BlitData); return; } blitdata B = BlitData; if(!FastFlag) { if(!B.Border.X || !B.Border.Y) ABORT("Zero-sized bitmap alpha priority blit attempt detected!"); if(!femath::Clip(B.Src.X, B.Src.Y, B.Dest.X, B.Dest.Y, B.Border.X, B.Border.Y, Size.X, Size.Y, B.Bitmap->Size.X, B.Bitmap->Size.Y)) return; } packcol16** SrcImage = Image; packalpha** SrcAlphaMap = AlphaMap; packpriority** SrcPriorityMap = PriorityMap; packcol16** DestImage = B.Bitmap->Image; packpriority** DestPriorityMap = B.Bitmap->PriorityMap; int NewRedLuminance = (B.Luminance >> 7 & 0x1F800) - 0x10000; int NewGreenLuminance = (B.Luminance >> 4 & 0xFE0) - 0x800; int NewBlueLuminance = (B.Luminance >> 2 & 0x3F) - 0x20; for(int y = 0; y < B.Border.Y; ++y) { cpackcol16* SrcPtr = &SrcImage[B.Src.Y + y][B.Src.X]; cpackalpha* AlphaPtr = &SrcAlphaMap[B.Src.Y + y][B.Src.X]; cpackpriority* SrcPriorityPtr = &SrcPriorityMap[B.Src.Y + y][B.Src.X]; cpackcol16* EndPtr = SrcPtr + B.Border.X; packcol16* DestPtr = &DestImage[B.Dest.Y + y][B.Dest.X]; packpriority* DestPriorityPtr = &DestPriorityMap[B.Dest.Y + y][B.Dest.X]; for(; SrcPtr != EndPtr; ++SrcPtr, ++DestPtr, ++AlphaPtr, ++SrcPriorityPtr, ++DestPriorityPtr) { LOAD_SRC(); if(SrcCol != B.MaskColor) { priority SrcPriority = *SrcPriorityPtr; priority DestPriority = *DestPriorityPtr; if((SrcPriority & 0xF) >= (DestPriority & 0xF) || (SrcPriority & 0xF0) >= (DestPriority & 0xF0)) { LOAD_DEST(); LOAD_ALPHA(); NEW_LUMINATE_RED(); NEW_APPLY_ALPHA_RED(); NEW_LUMINATE_GREEN(); NEW_APPLY_ALPHA_GREEN(); NEW_LUMINATE_BLUE(); NEW_APPLY_ALPHA_BLUE(); STORE_COLOR(); *DestPriorityPtr = SrcPriority; } } } } } void bitmap::InitPriorityMap(priority InitialValue) { if(!PriorityMap) Alloc2D(PriorityMap, Size.Y, Size.X); memset(PriorityMap[0], InitialValue, XSizeTimesYSize); } void bitmap::FillPriority(priority Priority) { memset(PriorityMap[0], Priority, XSizeTimesYSize); } void bitmap::FastBlitAndCopyAlpha(bitmap* Bitmap) const { if(!FastFlag) { if(!AlphaMap || !Bitmap->AlphaMap) ABORT("Attempt to fast blit and copy alpha without an alpha map detected!"); if(Size.X != Bitmap->Size.X || Size.Y != Bitmap->Size.Y) ABORT("Fast blit and copy alpha attempt of noncongruent bitmaps detected!"); } memcpy(Bitmap->Image[0], Image[0], XSizeTimesYSize * sizeof(packcol16)); memcpy(Bitmap->AlphaMap[0], AlphaMap[0], XSizeTimesYSize * sizeof(packalpha)); } void bitmap::UpdateRandMap(long Index, truth Value) { long c1 = XSizeTimesYSize + Index; RandMap[c1] = Value; for(long c2 = c1 >> 1; c2; c1 = c2, c2 >>= 1) { Value |= RandMap[c1 ^ 1]; if(!RandMap[c2] != !Value) RandMap[c2] = Value; else return; } } void bitmap::InitRandMap() { if(!RandMap) RandMap = new truth[XSizeTimesYSize << 1]; memset(RandMap, 0, (XSizeTimesYSize << 1) * sizeof(truth)); } v2 bitmap::RandomizePixel() const { if(!RandMap[1]) return ERROR_V2; long Rand = RAND(); ulong c, RandMask = 1; ulong MapSize = XSizeTimesYSize << 1; for(c = 2; c < MapSize; c <<= 1) if(RandMap[c + 1] && (!RandMap[c] || Rand & (RandMask <<= 1))) ++c; c = (c - MapSize) >> 1; return v2(c % Size.X, c / Size.X); } void bitmap::CalculateRandMap() { if(!AlphaMap) ABORT("Alpha map needed to calculate random map."); ulong Size = XSizeTimesYSize; for(ulong c = 0; c < Size; ++c) UpdateRandMap(c, AlphaMap[0][c]); } void bitmap::AlphaPutPixel(int x, int y, col16 SrcCol, col24 Luminance, alpha Alpha) { int DestCol = Image[y][x]; int NewRedLuminance = (Luminance >> 7 & 0x1F800) - 0x10000; int NewGreenLuminance = (Luminance >> 4 & 0xFE0) - 0x800; int NewBlueLuminance = (Luminance >> 2 & 0x3F) - 0x20; NEW_LUMINATE_RED(); NEW_APPLY_ALPHA_RED(); NEW_LUMINATE_GREEN(); NEW_APPLY_ALPHA_GREEN(); NEW_LUMINATE_BLUE(); NEW_APPLY_ALPHA_BLUE(); Image[y][x] = Red|Green|Blue; } alpha bitmap::CalculateAlphaAverage() const { if(!AlphaMap) ABORT("Alpha map needed to calculate alpha average!"); long Alphas = 0; long AlphaSum = 0; ulong Size = XSizeTimesYSize; for(ulong c = 0; c < Size; ++c) { packalpha* AlphaPtr = &AlphaMap[0][c]; if(*AlphaPtr) { AlphaSum += *AlphaPtr; ++Alphas; } } return Alphas ? AlphaSum / Alphas : 0; } cachedfont::cachedfont(v2 Size) : bitmap(Size) { Alloc2D(MaskMap, Size.Y, Size.X); } cachedfont::cachedfont(v2 Size, col16 Color) : bitmap(Size, Color) { Alloc2D(MaskMap, Size.Y, Size.X); } void cachedfont::PrintCharacter(cblitdata B) const { if(B.Dest.X < 0 || B.Dest.Y < 0 || B.Dest.X + 10 >= B.Bitmap->Size.X || B.Dest.Y + 9 >= B.Bitmap->Size.Y) { NormalMaskedBlit(B); return; } packcol16** SrcLine = &Image[B.Src.Y]; packcol16** EndLine = SrcLine + 9; packcol16** SrcMaskLine = &MaskMap[B.Src.Y]; packcol16** DestLine = &B.Bitmap->Image[B.Dest.Y]; for(; SrcLine != EndLine; ++SrcLine, ++SrcMaskLine, ++DestLine) { culong* FontPtr = reinterpret_cast<culong*>(*SrcLine + B.Src.X); // I don't know how correct this is, but longs are 64 bit on 64 bit. culong* EndPtr = FontPtr + (20 / sizeof(ulong)); culong* MaskPtr = reinterpret_cast<culong*>(*SrcMaskLine + B.Src.X); ulong* DestPtr = reinterpret_cast<ulong*>(*DestLine + B.Dest.X); for(; FontPtr != EndPtr; ++DestPtr, ++MaskPtr, ++FontPtr) *DestPtr = (*DestPtr & *MaskPtr) | *FontPtr; } } void cachedfont::CreateMaskMap() { packcol16* SrcPtr = Image[0]; packcol16* EndPtr = SrcPtr + XSizeTimesYSize; packcol16* MaskPtr = MaskMap[0]; for(; SrcPtr != EndPtr; ++SrcPtr, ++MaskPtr) if(*SrcPtr == TRANSPARENT_COLOR) { *SrcPtr = 0; *MaskPtr = 0xFFFF; } else *MaskPtr = 0; } cint WaveDelta[] = { 1, 2, 2, 2, 1, 0, -1, -2, -2, -2, -1 }; void bitmap::Wobble(int Frame, int SpeedShift, truth Horizontally) { int WavePos = (Frame << SpeedShift >> 1) - 14; if(Horizontally) { for(int c = 0; c < 11; ++c) if(WavePos + c >= 0 && WavePos + c < Size.Y) MoveLineHorizontally(WavePos + c, WaveDelta[c]); } else { for(int c = 0; c < 11; ++c) if(WavePos + c >= 0 && WavePos + c < Size.X) MoveLineVertically(WavePos + c, WaveDelta[c]); } } void bitmap::MoveLineVertically(int X, int Delta) { int y; if(Delta < 0) { for(y = 0; y < Size.Y + Delta; ++y) PowerPutPixel(X, y, GetPixel(X, y - Delta), AlphaMap ? GetAlpha(X, y - Delta) : 255, AVERAGE_PRIORITY); for(int y = -1; y >= Delta; --y) PowerPutPixel(X, Size.Y + y, TRANSPARENT_COLOR, 255, AVERAGE_PRIORITY); } else if(Delta > 0) { for(y = Size.Y - 1; y >= Delta; --y) PowerPutPixel(X, y, GetPixel(X, y - Delta), AlphaMap ? GetAlpha(X, y - Delta) : 255, AVERAGE_PRIORITY); for(y = 0; y < Delta; ++y) PowerPutPixel(X, y, TRANSPARENT_COLOR, 255, AVERAGE_PRIORITY); } } void bitmap::MoveLineHorizontally(int Y, int Delta) { int x; if(Delta < 0) { for(x = 0; x < Size.X + Delta; ++x) PowerPutPixel(x, Y, GetPixel(x - Delta, Y), AlphaMap ? GetAlpha(x - Delta, Y) : 255, AVERAGE_PRIORITY); for(x = -1; x >= Delta; --x) PowerPutPixel(Size.X + x, Y, TRANSPARENT_COLOR, 255, AVERAGE_PRIORITY); } else if(Delta > 0) { for(x = Size.X - 1; x >= Delta; --x) PowerPutPixel(x, Y, GetPixel(x - Delta, Y), AlphaMap ? GetAlpha(x - Delta, Y) : 255, AVERAGE_PRIORITY); for(x = 0; x < Delta; ++x) PowerPutPixel(x, Y, TRANSPARENT_COLOR, 255, AVERAGE_PRIORITY); } } void bitmap::InterLace() { for(int y = 0; y < Size.Y; ++y) if(!(y % 3)) for(int x = 0; x < Size.X; ++x) if(Image[y][x] != 0) Image[y][x] = 1; }
emlai/ivan
FeLib/Source/bitmap.cpp
C++
gpl-2.0
53,098
/* * 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 es.us.isa.sedl.module.sedl4people; import es.us.isa.sedl.module.SEDLModule; import es.us.isa.sedl.module.SEDLModuleRegistry; import es.us.isa.sedl.module.SEDLModuleUnmarshaller; import es.us.isa.sedl.core.EmpiricalStudy; import es.us.isa.sedl.core.ExtensionPointElement; import es.us.isa.sedl.core.util.Error; import es.us.isa.sedl.marshaller.SEDL4PeopleExtensionPointsUnmarshaller; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * * @author japarejo */ public class SEDL4PeopleExtensionPointsUnmarshallerImplementation implements SEDL4PeopleExtensionPointsUnmarshaller { private final SEDLModuleRegistry registry=new SEDLModuleRegistry(); public List<Error> unmarshall(List<String> importedModules, Map<String, List<ExtensionPointElement>> extensionPointsInstantiations, EmpiricalStudy experiment) { List<Error> errors=new ArrayList<Error>(); SEDLModule module; SEDLModuleUnmarshaller unmarshaller; List<ExtensionPointElement> elements; for(String moduleName:importedModules) { module=registry.getModule(moduleName); if(module!=null){ for(String extensionPointID:extensionPointsInstantiations.keySet()) { elements=extensionPointsInstantiations.get(extensionPointID); for(ExtensionPointElement element:elements){ if(module.getModuleNames().contains(element.getElementIdentifier())){ unmarshaller=module.getModuleUnmarshaller("SEDL4People", extensionPointID, experiment); errors.addAll(unmarshaller.unmarshall(element,experiment)); } } } }else{ Error error=new Error(0, Error.ERROR_SEVERITY.ERROR, "'"+moduleName+"' is not a valid module name."); errors.add(error); } } return errors; } }
isa-group/SEDL
modules/SEDLModuleManager/src/main/java/es/us/isa/sedl/module/sedl4people/SEDL4PeopleExtensionPointsUnmarshallerImplementation.java
Java
gpl-2.0
2,316
<div class="announce instapaper_body md" data-path="README.md" id="readme"><article class="markdown-body entry-content" itemprop="mainContentOfPage"><h1> <a name="user-content-legacy-cc" class="anchor" href="#legacy-cc" aria-hidden="true"><span class="octicon octicon-link"></span></a>legacy-cc</h1> <p>The earliest versions of the very first c compiler known to exist in the wild written by the late legend himself dmr. </p> <p>These are not capable of being compiled today with modern c compilers like gcc. I am only posting these here for the enjoyment and reminiscing of the spark that ignited a soon to be trillion dollar industry. Enjoy. :) </p> <p>You guys might be able to play around building this compilier with Aiju's pdp-11/unix emulator. I havent tried building this myself so I cant confirm it works, but I posted the link to his emulator for anybody wanting to hack around with it.</p> <p>Source: [<a href="http://cm.bell-labs.com/cm/cs/who/dmr/primevalC.html">http://cm.bell-labs.com/cm/cs/who/dmr/primevalC.html</a>] PDP-11 Emulator[<a href="http://pdp11.aiju.de/">http://pdp11.aiju.de/</a>]</p></article></div>
lalo/readme-fads
readme_files/c/52-readme.html
HTML
gpl-2.0
1,134
/************************************************************************** desktop.cpp - KPager's desktop Copyright (C) 2000 Antonio Larrosa Jimenez Matthias Ettrich Matthias Elter This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Send comments and bug fixes to larrosa@kde.org ***************************************************************************/ #include "kpager.h" #include <dcopobject.h> #include <dcopclient.h> #include <kdatastream.h> #include <tdeapplication.h> #include <tdeglobalsettings.h> #include <twinmodule.h> #include <twin.h> #include <tdeconfig.h> #include <tdeglobal.h> #include <kdebug.h> #include <ksharedpixmap.h> #include <kpixmapio.h> #include <tdepopupmenu.h> #include <netwm.h> #include <tqcstring.h> #include <tqpixmap.h> #include <tqpainter.h> #include <tqdrawutil.h> #include <tqpoint.h> #include "desktop.h" #include "config.h" #include "windowdrag.h" Desktop::Desktop( int desk, TQString desktopName, TQWidget *parent, const char *name): TQWidget(parent,name) { m_desk = desk; m_name = desktopName; m_bgSmallPixmap=0L; m_bgCommonSmallPixmap=0L; m_bgPixmap = 0L; m_bgDirty=true; m_grabWindows=false; setAcceptDrops(TRUE); setBackgroundMode(NoBackground); if (m_desk==1) Desktop::m_windowPixmaps.setAutoDelete(true); TDEConfig *cfg= TDEGlobal::config(); m_transparentMode=static_cast<WindowTransparentMode> (cfg->readNumEntry("windowTransparentMode", c_defWindowTransparentMode)); resize(67, 50); } Desktop::~Desktop() { delete m_bgPixmap; delete m_bgSmallPixmap; } void Desktop::mouseMoveEvent( TQMouseEvent *ev ) { if ( !KPagerConfigDialog::m_windowDragging ) return; if ( (ev->state() & Qt::LeftButton) == 0 ) return; TQPoint p( ev->pos() - pressPos ); if ( p.manhattanLength() >= tqApp->startDragDistance() ) startDrag( pressPos ); } void Desktop::mousePressEvent( TQMouseEvent * ev) { bool showWindows= KPagerConfigDialog::m_showWindows; if (ev->button()==Qt::LeftButton){ pressPos = ev->pos(); } else if ((ev->button()==Qt::MidButton)&&(showWindows)) startDrag(ev->pos()); else if (ev->button()==Qt::RightButton) { TQPoint pos; KWin::WindowInfo *info = windowAtPosition(ev->pos(), &pos); if ( info && showWindows ) pager()->showPopupMenu(info->win(), mapToGlobal(ev->pos())); else pager()->showPopupMenu(0, mapToGlobal(ev->pos())); } } void Desktop::mouseReleaseEvent( TQMouseEvent *ev ) { /** Note that mouseReleaseEvent is not called when releasing the mouse to drop a window in this desktop */ if (ev->button()==Qt::LeftButton) { bool showWindows= KPagerConfigDialog::m_showWindows; TQPoint pos; KWin::setCurrentDesktop(m_desk); if (showWindows) { KWin::WindowInfo *info = windowAtPosition(ev->pos(), &pos); if (info) { KWin::forceActiveWindow(info->win()); // if ( static_cast<WindowDrawMode>( KPagerConfigDialog::m_windowDrawMode ) == Pixmap ) // m_windowPixmapsDirty.replace(info->win,true); } } } } KWin::WindowInfo *Desktop::windowAtPosition(const TQPoint &p, TQPoint *internalpos) { TQRect r; const TQValueList<WId> &list(pager()->twin()->stackingOrder()); if (list.count() <= 0) return 0L; for (TQValueList<WId>::ConstIterator it = list.fromLast(); ; --it) { KWin::WindowInfo* info = pager()->info( *it ); if (shouldPaintWindow(info)) { r=info->geometry(); convertRectS2P(r); if (r.contains(p)) { if (internalpos) { internalpos->setX(p.x()-r.x()); internalpos->setY(p.y()-r.y()); } return info; } } if (it == list.begin()) break; } return 0L; } void Desktop::convertRectS2P(TQRect &r) { TQRect tmp(r); r.setRect(deskX()+tmp.x()*deskWidth()/kapp->desktop()->width(), deskY()+tmp.y()*deskHeight()/kapp->desktop()->height(), tmp.width()*deskWidth()/kapp->desktop()->width(), tmp.height()*deskHeight()/kapp->desktop()->height()); } void Desktop::convertCoordP2S(int &x, int &y) { x=(x-deskX())*(kapp->desktop()->width())/deskWidth(); y=(y-deskY())*(kapp->desktop()->height())/deskHeight(); } TQPixmap scalePixmap(const TQPixmap &pixmap, int width, int height) { if (pixmap.width()>100) { KPixmapIO io; TQImage img(io.convertToImage(pixmap)); return io.convertToPixmap(img.smoothScale(width,height)); } TQImage img(TQImage(pixmap.convertToImage()).smoothScale(width,height)); TQPixmap pix; pix.convertFromImage(img); return pix; } TQPixmap fastScalePixmap(const TQPixmap &pixmap, int width, int height) { TQWMatrix m; m.scale(width/(double)pixmap.width(), height/(double)pixmap.height()); return pixmap.xForm(m); } void Desktop::loadBgPixmap(void) { bool retval; // if (!m_bgDirty) return; DCOPClient *client = kapp->dcopClient(); if (!client->isAttached()) client->attach(); TQByteArray data, data2, replyData; TQCString replyType; if (client->call("kdesktop", "KBackgroundIface", "isCommon()", data, replyType, replyData)) { TQDataStream reply(replyData, IO_ReadOnly); if (replyType == "bool") { reply >> m_isCommon; } } if ( m_isCommon && m_desk!=1 ) return; /* TQDataStream args2( data2, IO_WriteOnly ); args2 << m_desk-1 << 0 << 0 << -1 << -1 << 200 << 150 ; if (client->call("kdesktop", "KBackgroundIface", "wallpaper(int,int,int,int,int,int,int)", data2, replyType, replyData)) { TQDataStream reply(replyData, IO_ReadOnly); if (replyType == "TQPixmap") { TQPixmap pixmap; reply >> pixmap; if (!pixmap.isNull()) { kdDebug() << "getting small bg through dcop\n"; if (m_isCommon) { if (m_bgSmallPixmap) { delete m_bgSmallPixmap; m_bgSmallPixmap=0L; } if (!m_bgCommonSmallPixmap) m_bgCommonSmallPixmap=new TQPixmap(pixmap); else *m_bgCommonSmallPixmap=pixmap; } else { if (m_bgCommonSmallPixmap) { delete m_bgCommonSmallPixmap; m_bgCommonSmallPixmap=0L; } if (!m_bgSmallPixmap) m_bgSmallPixmap=new TQPixmap(pixmap); else *m_bgSmallPixmap=pixmap; } return; } } } kdDebug() << "getting whole bg through shpixmap\n"; */ if (!m_bgPixmap) { m_bgPixmap = new TDESharedPixmap; connect(m_bgPixmap, TQT_SIGNAL(done(bool)), TQT_SLOT(backgroundLoaded(bool))); } retval = m_bgPixmap->loadFromShared(TQString("DESKTOP%1").arg(m_isCommon?1:m_desk)); if (retval == false) { TQDataStream args( data, IO_WriteOnly ); args << 1; // Argument is 1 (true) client->send("kdesktop", "KBackgroundIface", "setExport(int)", data); retval = m_bgPixmap->loadFromShared(TQString("DESKTOP%1").arg(m_isCommon?1:m_desk)); } } void Desktop::paintWindow(TQPainter &p, const KWin::WindowInfo *info, bool onDesktop) { switch (static_cast<WindowDrawMode>(KPagerConfigDialog::m_windowDrawMode ) ) { case (Plain) : paintWindowPlain (p, info, onDesktop);break; case (Icon) : paintWindowIcon (p, info, onDesktop);break; case (Pixmap) : paintWindowPixmap(p, info, onDesktop);break; } } TQPixmap *Desktop::paintNewWindow(const KWin::WindowInfo *info) { TQRect r = info->frameGeometry(); int dw = TQApplication::desktop()->width(); int dh = TQApplication::desktop()->height(); r = TQRect( r.x() * width() / dw, 2 + r.y() * height() / dh, r.width() * width() / dw, r.height() * height() / dh ); r.moveTopLeft(TQPoint(0,0)); TQPixmap *pixmap=new TQPixmap(r.width(),r.height()); TQPainter p; p.begin(pixmap); p.setFont(font()); p.fillRect( r, colorGroup().brush(TQColorGroup::Dark)); paintWindow(p, info, false); p.end(); return pixmap; } void Desktop::startDrag(const TQPoint &p) { TQPoint dragpos; KWin::WindowInfo *info=windowAtPosition(p,&dragpos); if ( (!info)/* || (info->state & NET::Max)*/ ) return; TQPixmap *pixmap=paintNewWindow(info); int deltax=dragpos.x(); int deltay=dragpos.y(); PagerWindowDrag *wdrag= new PagerWindowDrag( info->win(), deltax, deltay, m_desk, this); wdrag->setPixmap( *pixmap, TQPoint( deltax, deltay) ); delete pixmap; wdrag->dragCopy(); } void Desktop::dragEnterEvent(TQDragEnterEvent *ev) { if (PagerWindowDrag::canDecode( ev )) ev->accept(); } void Desktop::dragMoveEvent(TQDragMoveEvent *) { // TODO Moving the window while dragging would be cool, wouldn't it ? // Matthias: No, is way to slow on low end machines. // Antonio:Ok, I'll make it configurable after 2.0 (it would add a string) } void Desktop::dropEvent(TQDropEvent *ev) { WId win=0; int deltax,deltay; int origdesk; if (!PagerWindowDrag::decode(ev,win,deltax,deltay,origdesk)) return; int x=ev->pos().x()-deltax; int y=ev->pos().y()-deltay; /* * x and y now contain the position (in local coordinates) which * has the origin of the window */ convertCoordP2S(x,y); // kdDebug() << "moving window " << win << "d from " << origdesk << " to " << m_desk << endl; // NETWinInfo NETinfo( tqt_xdisplay(), win, tqt_xrootwin(), NET::Client | NET::WMDesktop); if (m_desk==0) { /* * The next line moves the window to the active desktop. This is done * because in other case, kwm raises the window when it's in a semi * changed state and doesn't work well with kpager. Let's see how well * KWin behaves. * if (activedesktop!=KWM::desktop(w)) * KWM::moveToDesktop(w,activedesktop); */ // KWin::setState(win, NET::Sticky); KWin::setOnAllDesktops(win, true); } else { if (origdesk==0) KWin::setOnAllDesktops(win, false); KWin::WindowInfo *info = pager()->info(win); if (!info->onAllDesktops()) KWin::setOnDesktop(win, m_desk); } XMoveWindow(x11Display(), win, x, y ); } bool Desktop::shouldPaintWindow( KWin::WindowInfo *info ) { if (!info) return false; // if (info->mappingState != NET::Visible) // return false; NET::WindowType type = info->windowType( NET::NormalMask | NET::DesktopMask | NET::DockMask | NET::ToolbarMask | NET::MenuMask | NET::DialogMask | NET::OverrideMask | NET::TopMenuMask | NET::UtilityMask | NET::SplashMask ); if (type == NET::Desktop || type == NET::Dock || type == NET::TopMenu) return false; if (!info->isOnDesktop(m_desk)) return false; if (info->state() & NET::SkipPager || info->state() & NET::Shaded ) return false; if (info->win() == pager()->winId()) return false; if ( info->isMinimized() ) return false; return true; } void Desktop::paintFrame(bool active) { TQPainter p(this); if ( active ) p.setPen(yellow); else p.setPen(TQColorGroup::Base); p.drawRect(rect()); p.end(); } void Desktop::paintEvent( TQPaintEvent * ) { TQPixmap pixmap(width(),height()); TQPainter p; p.begin(&pixmap); // p.setFont(font()); // p.fillRect(rect(), colorGroup().brush(TQColorGroup::Dark)); // p.setPen(Qt::black); // p.drawRect(rect()); if (KPagerConfigDialog::m_showBackground ) { if ( ( !m_isCommon && !m_bgSmallPixmap ) || (m_isCommon && !m_bgCommonSmallPixmap) ) loadBgPixmap(); if ( ( !m_isCommon && m_bgSmallPixmap && !m_bgSmallPixmap->isNull() ) || ( m_isCommon && m_bgCommonSmallPixmap && !m_bgCommonSmallPixmap->isNull() ) ) { TQPixmap tmp; if ( m_isCommon ) tmp=fastScalePixmap(*m_bgCommonSmallPixmap, width(),height()); else tmp=fastScalePixmap(*m_bgSmallPixmap, width(),height()); p.drawPixmap(0,0,tmp); } else pixmap.fill(Qt::gray); } else p.fillRect(rect(), colorGroup().brush(TQColorGroup::Mid)); // set in/active pen if (isCurrent()) p.setPen(yellow); else p.setPen(TQColorGroup::Base); // paint number & name bool sname=KPagerConfigDialog::m_showName; bool snumber=KPagerConfigDialog::m_showNumber; if ( sname || snumber ) { TQString txt; // set font if (sname) { TQFont f(TDEGlobalSettings::generalFont().family(), 10, TQFont::Bold); p.setFont(f); } else { TQFont f(TDEGlobalSettings::generalFont().family(), 12, TQFont::Bold); p.setFont(f); } // draw text if ( sname && snumber ) txt=TQString("%1. %2").arg(m_desk).arg(pager()->twin()->desktopName( m_desk )); else if ( sname ) txt=pager()->twin()->desktopName( m_desk ); else if ( snumber ) txt=TQString::number( m_desk ); p.drawText(2, 0, width()-4, height(), AlignCenter, txt ); } // paint windows if ( KPagerConfigDialog::m_showWindows ) { TQValueList<WId>::ConstIterator it; for ( it = pager()->twin()->stackingOrder().begin(); it != pager()->twin()->stackingOrder().end(); ++it ) { KWin::WindowInfo* info = pager()->info( *it ); if (shouldPaintWindow(info)) paintWindow(p,info); } } // paint border rectangle p.drawRect(rect()); p.end(); // blit pixmap to widget p.begin(this); p.drawPixmap(0,0,pixmap); p.end(); m_grabWindows=false; } void Desktop::paintWindowPlain(TQPainter &p, const KWin::WindowInfo *info, bool onDesktop) { TQRect r = info->frameGeometry(); int dw = TQApplication::desktop()->width(); int dh = TQApplication::desktop()->height(); r = TQRect( r.x() * width() / dw, 2 + r.y() * height() / dh, r.width() * width() / dw, r.height() * height() / dh ); if ( !onDesktop ) r.moveTopLeft(TQPoint(0,0)); bool isActive=(pager()->twin()->activeWindow() == info->win()); TQBrush brush; if ( isActive ) brush=colorGroup().brush( TQColorGroup::Highlight ); else brush=colorGroup().brush( TQColorGroup::Button ); if ( m_transparentMode==AllWindows || (m_transparentMode==MaximizedWindows && ( info->state() & NET::Max )) ) brush.setStyle(Qt::Dense4Pattern); if ( isActive ) { qDrawShadeRect( &p, r, colorGroup(), false, 1, 0, &brush ); } else { p.fillRect( r, brush ); qDrawShadeRect( &p, r, colorGroup(), true, 1, 0 ); } } void Desktop::paintWindowIcon(TQPainter &p, const KWin::WindowInfo *info, bool onDesktop) { TQRect r = info->frameGeometry(); int dw = TQApplication::desktop()->width(); int dh = TQApplication::desktop()->height(); r = TQRect( r.x() * width() / dw, 2 + r.y() * height() / dh, r.width() * width() / dw, r.height() * height() / dh ); TQPixmap icon=KWin::icon( info->win(), int(r.width()*0.8), int(r.height()*0.8), true); NET::WindowType type = info->windowType( NET::NormalMask | NET::DesktopMask | NET::DockMask | NET::ToolbarMask | NET::MenuMask | NET::DialogMask | NET::OverrideMask | NET::TopMenuMask | NET::UtilityMask | NET::SplashMask ); if ( icon.isNull() || type!=NET::Override ) paintWindowPlain(p,info,onDesktop); if ( !onDesktop ) r.moveTopLeft(TQPoint(0,0)); p.drawPixmap( r.topLeft()+ TQPoint(int(r.width()*0.1),int(r.height()*0.1)), icon ); } void Desktop::paintWindowPixmap(TQPainter &p, const KWin::WindowInfo *info, bool onDesktop) { const int knDefaultPixmapWd = 100; const int knDefaultPixmapHg = 75; TQRect rSmall, r = info->frameGeometry(); int dw = TQApplication::desktop()->width(); int dh = TQApplication::desktop()->height(); rSmall = TQRect( r.x() * width() / dw, 2 + r.y() * height() / dh, r.width() * width() / dw, r.height() * height() / dh ); TQPixmap *pixmap=m_windowPixmaps[info->win()]; bool isDirty=m_windowPixmapsDirty[info->win()]; if ( !pixmap || isDirty || m_grabWindows ) { if ( isCurrent() ) { TQPixmap tmp=TQPixmap::grabWindow(info->win(), 0,0,r.width(),r.height()); if (!tmp.isNull() && tmp.width() > 0 && tmp.height() > 0) { tmp.setOptimization(TQPixmap::BestOptim); int nWd, nHg; if (rSmall.width() > knDefaultPixmapWd || rSmall.height() > knDefaultPixmapHg) { nWd = knDefaultPixmapWd; nHg = knDefaultPixmapHg; } else { nWd = rSmall.width(); nHg = rSmall.height(); } pixmap=new TQPixmap(fastScalePixmap(tmp, nWd, nHg)); m_windowPixmaps.replace(info->win(),pixmap); m_windowPixmapsDirty.replace(info->win(),false); } } // It was impossible to get the pixmap, let's fallback to the icon mode. if ( !pixmap || pixmap->isNull() ) { paintWindowIcon(p, info, onDesktop); return; } } if ( !onDesktop ) rSmall.moveTopLeft(TQPoint(0,0)); if (rSmall.width() != pixmap->width() || rSmall.height() != pixmap->height()) { TQPixmap pixmapSmall(fastScalePixmap(*pixmap,rSmall.width(),rSmall.height())); p.drawPixmap( rSmall.topLeft(), pixmapSmall ); } else { p.drawPixmap( rSmall.topLeft(), *pixmap); } } KPager *Desktop::pager() const { return reinterpret_cast<KPager *>(parent()); } bool Desktop::isCurrent() const { return pager()->twin()->currentDesktop()==m_desk; } void Desktop::backgroundLoaded(bool b) { if (b) { if (m_isCommon) { if (m_bgSmallPixmap) { delete m_bgSmallPixmap; m_bgSmallPixmap=0L ; }; if (!m_bgCommonSmallPixmap) m_bgCommonSmallPixmap=new TQPixmap; *m_bgCommonSmallPixmap=scalePixmap(*m_bgPixmap,200,150); } else { if (m_bgCommonSmallPixmap) { delete m_bgCommonSmallPixmap; m_bgCommonSmallPixmap=0L ; }; if (!m_bgSmallPixmap) m_bgSmallPixmap=new TQPixmap; *m_bgSmallPixmap=fastScalePixmap(*m_bgPixmap,200,150); } delete m_bgPixmap; m_bgPixmap=0L; if (m_isCommon) pager()->redrawDesktops(); else update(); } else kdDebug() << "Error getting the background\n"; } TQSize Desktop::sizeHint() const { return TQSize(67,50); } TQPixmap *Desktop::m_bgCommonSmallPixmap=0L; bool Desktop::m_isCommon=false; TQIntDict<TQPixmap> Desktop::m_windowPixmaps; TQMap<int,bool> Desktop::m_windowPixmapsDirty; // Default Configuration ------------------------------------------------- const bool Desktop::c_defShowName=false; const bool Desktop::c_defShowNumber=false; const bool Desktop::c_defShowWindows=true; const bool Desktop::c_defShowBackground=true; const bool Desktop::c_defWindowDragging=true; const Desktop::WindowDrawMode Desktop::c_defWindowDrawMode=Desktop::Icon; const Desktop::WindowTransparentMode Desktop::c_defWindowTransparentMode=Desktop::AllWindows; #include "desktop.moc"
Fat-Zer/tdebase
kpager/desktop.cpp
C++
gpl-2.0
18,847
//------------------------------------------------------------------------------ // <auto-generated> // Este código fue generado por una herramienta. // Versión de runtime:4.0.30319.18449 // // Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si // se vuelve a generar el código. // </auto-generated> //------------------------------------------------------------------------------ namespace contabilidad.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
EDBP/contasoft
Conta/contabilidad/contabilidad/Properties/Settings.Designer.cs
C#
gpl-2.0
1,113
#pragma once #include "Mat.h" #include <vector> #include "general.h" using namespace std; //#define MAX_MATSTACK (20) class MatStack { private: struct MatEntry { MatEntry() : msg(nullptr) {} MatEntry(const Mat4 _m, const char* _msg) : m(_m), msg(_msg) {} Mat4 m; const char* msg; }; public: MatStack() {} Mat4& cur() { return m_cur.m; } void push(const char* msg = nullptr) { #ifdef MAX_MATSTACK if (m_s.size() > MAX_MATSTACK) throw HCException("matrix stack overflow"); #endif m_s.push_back(MatEntry(m_cur.m, msg)); } void pop() { if (m_s.size() <= 0) throw HCException("matrix stack underflow"); m_cur = m_s.back(); m_s.pop_back(); } Mat4& peek(int back) { if (back == 0) return m_cur.m; if (m_s.size() < back) throw HCException("matrix stack underflow(peek)"); return m_s[m_s.size() - back].m; } void translate(float x, float y, float z) { m_cur.m.translate(x, y, z); } void rotate(float angle, float x, float y, float z) { m_cur.m.rotate(angle, x, y, z); } void scale(float x, float y, float z) { m_cur.m.scale(x, y, z); } void scale(float v) { m_cur.m.scale(v, v, v); } void mult(const Mat4& o) { m_cur.m.mult(o); } void identity() { m_cur.m.identity(); } void set(const Mat4& o) { m_cur.m = o; } private: MatEntry m_cur; vector<MatEntry> m_s; };
shooshx/happysolver
src/MatStack.h
C
gpl-2.0
1,647
// // RIPEMD160ManagedTest.cs - NUnit Test Cases for RIPEMD160 // http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html // // Author: // Sebastien Pouliot (sebastien@ximian.com) // // (C) 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using NUnit.Framework; using System.Security.Cryptography; namespace MonoTests.System.Security.Cryptography { [TestFixture] public class RIPEMD160ManagedTest : RIPEMD160Test { [SetUp] public void SetUp () { hash = new RIPEMD160Managed (); } // this will run ALL tests defined in RIPEMD160Test.cs with the RIPEMD160Managed implementation } }
hardvain/mono-compiler
class/corlib/Test/System.Security.Cryptography/RIPEMD160ManagedTest.cs
C#
gpl-2.0
1,762
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PhotoBookmart.Areas.Administration.Models { public class ListModel { public string Id { get; set; } public string Name { get; set; } } public class GoogleAnalyticResultModel { public int View { get; set; } public int Click { get; set; } public DateTime OnDate { get; set; } /// <summary> /// OnDate but in string format mm/dd/yyyy h:m:s /// </summary> public string OnDateRaw { get; set; } } public class UserUpdatePassword { public string CurrentPassword { get; set; } public string NewPassword { get; set; } public string NewPassword2 { get; set; } } /// <summary> /// this model is for cloning data from current language to other language /// </summary> public class CloneToOtherLangModel { public int Id { get; set; } public string LangCode { get; set; } public string NewName { get; set; } public bool CloneFile { get; set; } } }
dvchinh/HTQLNHCS
PhotoBookmart/Areas/Administration/Models/CommonModel.cs
C#
gpl-2.0
1,125
/* * Copyright (c) 2015. Marvin Hofmann <marvin@marv-productions.de> * * 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.marvprod.yabon.token; import de.marvprod.yabon.Encoder; import java.math.BigInteger; public class BigIntToken extends BinaryToken { public BigIntToken(byte[] data) { super(data); } public BigIntToken(long data) { super(BigInteger.valueOf(data).toByteArray()); } public BigIntToken(BigInteger data) { super(data.toByteArray()); } public TokenCategories getTokenCategory() { return TokenCategories.NUMBER_BIGINT; } @Override public String explain(String level) { byte[] enc = toBinary(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("\n") .append(Encoder.byteToString(enc[0])) .append(" ") .append(level) .append("BIGNIT") .append("(") .append(new BigInteger(data).toString()) .append(") length ") .append(data.length) .append(" byte size ") .append(size(data.length)) .append(" byte"); for (int i = 1; i < size(data.length) + 1; i++) { stringBuilder.append("\n") .append(Encoder.byteToString(enc[i])) .append(" ") .append(level).append(LEVEL) .append("BIGNIT") .append(" length byte ") .append(i); } for (int i = 1 + size(data.length); i < enc.length; i++) { stringBuilder.append("\n") .append(Encoder.byteToString(enc[i])) .append(" ") .append(level).append(LEVEL) .append("BIGNIT") .append(" byte ") .append(i); } return stringBuilder.toString(); } }
yabon-dev/yabon-java
src/java/de/marvprod/yabon/token/BigIntToken.java
Java
gpl-2.0
2,603
// // System.Drawing.PreviewPrintController.cs // // Author: // Dennis Hayes (dennish@Raytek.com) // // (C) 2002 Ximian, Inc // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Drawing.Imaging; namespace System.Drawing.Printing { public class PreviewPrintController : PrintController { bool useantialias; ArrayList pageInfoList; public PreviewPrintController() { pageInfoList = new ArrayList (); } public override bool IsPreview { get { return true; } } [MonoTODO] public override void OnEndPage(PrintDocument document, PrintPageEventArgs e) { } [MonoTODO] public override void OnStartPrint(PrintDocument document, PrintEventArgs e) { if (!document.PrinterSettings.IsValid) throw new InvalidPrinterException(document.PrinterSettings); /* maybe we should reuse the images, and clear them? */ foreach (PreviewPageInfo pi in pageInfoList) pi.Image.Dispose (); pageInfoList.Clear (); } [MonoTODO] public override void OnEndPrint(PrintDocument document, PrintEventArgs e) { } [MonoTODO] public override Graphics OnStartPage(PrintDocument document, PrintPageEventArgs e) { Image image = new Bitmap (e.PageSettings.PaperSize.Width, e.PageSettings.PaperSize.Height); PreviewPageInfo info = new PreviewPageInfo (image, new Size (e.PageSettings.PaperSize.Width, e.PageSettings.PaperSize.Height)); pageInfoList.Add (info); Graphics g = Graphics.FromImage (info.Image); g.FillRectangle (new SolidBrush (Color.White), new Rectangle (new Point (0,0), new Size (image.Width, image.Height))); return g; } public virtual bool UseAntiAlias { get{ return useantialias; } set{ useantialias = value; } } public PreviewPageInfo [] GetPreviewPageInfo() { PreviewPageInfo [] pi = new PreviewPageInfo[pageInfoList.Count]; pageInfoList.CopyTo (pi); return pi; } } }
hardvain/mono-compiler
class/System.Drawing/System.Drawing.Printing/PreviewPrintController.cs
C#
gpl-2.0
3,048
/** * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package com.iucn.whp.dbservice.service.base; import com.iucn.whp.dbservice.service.threat_summary_potentialLocalServiceUtil; import java.util.Arrays; /** * @author Brian Wing Shun Chan */ public class threat_summary_potentialLocalServiceClpInvoker { public threat_summary_potentialLocalServiceClpInvoker() { _methodName0 = "addthreat_summary_potential"; _methodParameterTypes0 = new String[] { "com.iucn.whp.dbservice.model.threat_summary_potential" }; _methodName1 = "createthreat_summary_potential"; _methodParameterTypes1 = new String[] { "long" }; _methodName2 = "deletethreat_summary_potential"; _methodParameterTypes2 = new String[] { "long" }; _methodName3 = "deletethreat_summary_potential"; _methodParameterTypes3 = new String[] { "com.iucn.whp.dbservice.model.threat_summary_potential" }; _methodName4 = "dynamicQuery"; _methodParameterTypes4 = new String[] { }; _methodName5 = "dynamicQuery"; _methodParameterTypes5 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery" }; _methodName6 = "dynamicQuery"; _methodParameterTypes6 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int" }; _methodName7 = "dynamicQuery"; _methodParameterTypes7 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int", "com.liferay.portal.kernel.util.OrderByComparator" }; _methodName8 = "dynamicQueryCount"; _methodParameterTypes8 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery" }; _methodName9 = "fetchthreat_summary_potential"; _methodParameterTypes9 = new String[] { "long" }; _methodName10 = "getthreat_summary_potential"; _methodParameterTypes10 = new String[] { "long" }; _methodName11 = "getPersistedModel"; _methodParameterTypes11 = new String[] { "java.io.Serializable" }; _methodName12 = "getthreat_summary_potentials"; _methodParameterTypes12 = new String[] { "int", "int" }; _methodName13 = "getthreat_summary_potentialsCount"; _methodParameterTypes13 = new String[] { }; _methodName14 = "updatethreat_summary_potential"; _methodParameterTypes14 = new String[] { "com.iucn.whp.dbservice.model.threat_summary_potential" }; _methodName15 = "updatethreat_summary_potential"; _methodParameterTypes15 = new String[] { "com.iucn.whp.dbservice.model.threat_summary_potential", "boolean" }; _methodName426 = "getBeanIdentifier"; _methodParameterTypes426 = new String[] { }; _methodName427 = "setBeanIdentifier"; _methodParameterTypes427 = new String[] { "java.lang.String" }; _methodName432 = "getthreat_summary_potentialByAssessmentId"; _methodParameterTypes432 = new String[] { "long" }; } public Object invokeMethod(String name, String[] parameterTypes, Object[] arguments) throws Throwable { if (_methodName0.equals(name) && Arrays.deepEquals(_methodParameterTypes0, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.addthreat_summary_potential((com.iucn.whp.dbservice.model.threat_summary_potential)arguments[0]); } if (_methodName1.equals(name) && Arrays.deepEquals(_methodParameterTypes1, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.createthreat_summary_potential(((Long)arguments[0]).longValue()); } if (_methodName2.equals(name) && Arrays.deepEquals(_methodParameterTypes2, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.deletethreat_summary_potential(((Long)arguments[0]).longValue()); } if (_methodName3.equals(name) && Arrays.deepEquals(_methodParameterTypes3, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.deletethreat_summary_potential((com.iucn.whp.dbservice.model.threat_summary_potential)arguments[0]); } if (_methodName4.equals(name) && Arrays.deepEquals(_methodParameterTypes4, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.dynamicQuery(); } if (_methodName5.equals(name) && Arrays.deepEquals(_methodParameterTypes5, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0]); } if (_methodName6.equals(name) && Arrays.deepEquals(_methodParameterTypes6, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0], ((Integer)arguments[1]).intValue(), ((Integer)arguments[2]).intValue()); } if (_methodName7.equals(name) && Arrays.deepEquals(_methodParameterTypes7, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0], ((Integer)arguments[1]).intValue(), ((Integer)arguments[2]).intValue(), (com.liferay.portal.kernel.util.OrderByComparator)arguments[3]); } if (_methodName8.equals(name) && Arrays.deepEquals(_methodParameterTypes8, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.dynamicQueryCount((com.liferay.portal.kernel.dao.orm.DynamicQuery)arguments[0]); } if (_methodName9.equals(name) && Arrays.deepEquals(_methodParameterTypes9, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.fetchthreat_summary_potential(((Long)arguments[0]).longValue()); } if (_methodName10.equals(name) && Arrays.deepEquals(_methodParameterTypes10, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.getthreat_summary_potential(((Long)arguments[0]).longValue()); } if (_methodName11.equals(name) && Arrays.deepEquals(_methodParameterTypes11, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.getPersistedModel((java.io.Serializable)arguments[0]); } if (_methodName12.equals(name) && Arrays.deepEquals(_methodParameterTypes12, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.getthreat_summary_potentials(((Integer)arguments[0]).intValue(), ((Integer)arguments[1]).intValue()); } if (_methodName13.equals(name) && Arrays.deepEquals(_methodParameterTypes13, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.getthreat_summary_potentialsCount(); } if (_methodName14.equals(name) && Arrays.deepEquals(_methodParameterTypes14, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.updatethreat_summary_potential((com.iucn.whp.dbservice.model.threat_summary_potential)arguments[0]); } if (_methodName15.equals(name) && Arrays.deepEquals(_methodParameterTypes15, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.updatethreat_summary_potential((com.iucn.whp.dbservice.model.threat_summary_potential)arguments[0], ((Boolean)arguments[1]).booleanValue()); } if (_methodName426.equals(name) && Arrays.deepEquals(_methodParameterTypes426, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.getBeanIdentifier(); } if (_methodName427.equals(name) && Arrays.deepEquals(_methodParameterTypes427, parameterTypes)) { threat_summary_potentialLocalServiceUtil.setBeanIdentifier((java.lang.String)arguments[0]); } if (_methodName432.equals(name) && Arrays.deepEquals(_methodParameterTypes432, parameterTypes)) { return threat_summary_potentialLocalServiceUtil.getthreat_summary_potentialByAssessmentId(((Long)arguments[0]).longValue()); } throw new UnsupportedOperationException(); } private String _methodName0; private String[] _methodParameterTypes0; private String _methodName1; private String[] _methodParameterTypes1; private String _methodName2; private String[] _methodParameterTypes2; private String _methodName3; private String[] _methodParameterTypes3; private String _methodName4; private String[] _methodParameterTypes4; private String _methodName5; private String[] _methodParameterTypes5; private String _methodName6; private String[] _methodParameterTypes6; private String _methodName7; private String[] _methodParameterTypes7; private String _methodName8; private String[] _methodParameterTypes8; private String _methodName9; private String[] _methodParameterTypes9; private String _methodName10; private String[] _methodParameterTypes10; private String _methodName11; private String[] _methodParameterTypes11; private String _methodName12; private String[] _methodParameterTypes12; private String _methodName13; private String[] _methodParameterTypes13; private String _methodName14; private String[] _methodParameterTypes14; private String _methodName15; private String[] _methodParameterTypes15; private String _methodName426; private String[] _methodParameterTypes426; private String _methodName427; private String[] _methodParameterTypes427; private String _methodName432; private String[] _methodParameterTypes432; }
iucn-whp/world-heritage-outlook
portlets/iucn-dbservice-portlet/docroot/WEB-INF/src/com/iucn/whp/dbservice/service/base/threat_summary_potentialLocalServiceClpInvoker.java
Java
gpl-2.0
9,477
--- title: Using the Rcpp sugar function clamp author: Dirk Eddelbuettel license: GPL (>= 2) tags: sugar benchmark featured summary: This post illustrates the sugar function clamp layout: post src: 2013-01-07-sugar-function-clamp.cpp --- Since the 0.10.* release series, Rcpp contains a new sugar function `clamp` which can be used to limit vectors to both a minimum and maximim value. [This recent StackOverflow question]() permitted `clamp` to shine. We retake some of the answers, including the `clamp` entry by Romain. We first define the three R versions. {% highlight r %} pminpmaxClamp <- function(x, a, b) { pmax(a, pmin(x, b) ) } ifelseClamp <- function(x, a, b) { ifelse(x <= a, a, ifelse(x >= b, b, x)) } operationsClamp <- function(x, a, b) { a + (x-a > 0)*(x-a) - (x-b > 0)*(x-b) } {% endhighlight %} We then define some data, and ensure that these versions all producing identical results. {% highlight r %} set.seed(42) x <- rnorm(100000) a <- -1.0 b <- 1.0 stopifnot(all.equal(pminpmaxClamp(x,a,b), ifelseClamp(x,a,b), operationsClamp(x,a,b))) {% endhighlight %} Next is the C++ solution: a one-liner thanks to the existing sugar function. {% highlight cpp %} #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericVector rcppClamp(NumericVector x, double mi, double ma) { return clamp(mi, x, ma); } {% endhighlight %} We can then check and benchmark the new C++ version. {% highlight r %} stopifnot(all.equal(pminpmaxClamp(x,a,b), rcppClamp(x,a,b))) library(rbenchmark) benchmark(pminpmaxClamp(x, a, b), ifelseClamp(x, a, b), operationsClamp(x, a, b), rcppClamp(x, a, b), order="relative")[,1:4] {% endhighlight %} <pre class="output"> test replications elapsed relative 4 rcppClamp(x, a, b) 100 0.134 1.000 3 operationsClamp(x, a, b) 100 0.509 3.799 1 pminpmaxClamp(x, a, b) 100 0.532 3.970 2 ifelseClamp(x, a, b) 100 5.266 39.299 </pre> We see a decent gain of the Rcpp version even relative to these vectorised R solutions. Among these, the simplest (based on `ifelse`) is by far the slowest. The parallel min/max version is about as faster as the clever-but-less-readable expression-based solution. Real "production" solutions will of course need some more testing of inputs etc. However, as an illustration of `clamp` this example has hopefully been compelling.
davharris/rcpp-gallery
_posts/2013-01-07-sugar-function-clamp.md
Markdown
gpl-2.0
2,471
// _________ __ __ // / _____// |_____________ _/ |______ ____ __ __ ______ // \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/ // / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ | // /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ > // \/ \/ \//_____/ \/ // ______________________ ______________________ // T H E W A R B E G I N S // Stratagus - A free fantasy real time strategy game engine // /**@name uibuttons_proc.cpp - The UI buttons processing code. */ // // (c) Copyright 1999-2006 by Andreas Arens, Jimmy Salmon, Nehal Mistry // // 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; only version 2 of the License. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. // //@{ /*---------------------------------------------------------------------------- -- Includes ----------------------------------------------------------------------------*/ #include "stratagus.h" #include "ui.h" #include "font.h" #include "menus.h" #include "player.h" #include "video.h" /*---------------------------------------------------------------------------- -- Variables ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- -- UI buttons operation functions ----------------------------------------------------------------------------*/ /** ** Draw UI button 'button' on x,y ** ** @param style Button style ** @param flags State of Button (clicked, mouse over...) ** @param x X display position ** @param y Y display position ** @param text text to print on button */ void DrawUIButton(ButtonStyle *style, unsigned flags, int x, int y, const std::string &text) { ButtonStyleProperties *p; if (flags & MI_FLAGS_CLICKED) { p = &style->Clicked; } else if (flags & MI_FLAGS_ACTIVE) { p = &style->Hover; } else { p = &style->Default; } // // Image // ButtonStyleProperties *pimage = p; if (!p->Sprite) { // No image. Try hover, selected, then default if ((flags & MI_FLAGS_ACTIVE) && style->Hover.Sprite) { pimage = &style->Hover; } else if (style->Default.Sprite) { pimage = &style->Default; } } if (pimage->Sprite) { pimage->Sprite->Load(); } if (pimage->Sprite) { CPlayerColorGraphic *colorGraphic = dynamic_cast<CPlayerColorGraphic *>(pimage->Sprite); if (colorGraphic && ThisPlayer) { colorGraphic->DrawPlayerColorFrameClip(ThisPlayer->Index, pimage->Frame, x, y); } else { pimage->Sprite->DrawFrame(pimage->Frame, x, y); } } // // Text // if (!text.empty()) { std::string oldnc; std::string oldrc; GetDefaultTextColors(oldnc, oldrc); CLabel label(*style->Font, (!p->TextNormalColor.empty() ? p->TextNormalColor : !style->TextNormalColor.empty() ? style->TextNormalColor : oldnc), (!p->TextReverseColor.empty() ? p->TextReverseColor : !style->TextReverseColor.empty() ? style->TextReverseColor : oldrc)); if (p->TextAlign == TextAlignCenter || p->TextAlign == TextAlignUndefined) { label.DrawCentered(x + p->TextPos.x, y + p->TextPos.y, text); } else if (p->TextAlign == TextAlignLeft) { label.Draw(x + p->TextPos.x, y + p->TextPos.y, text); } else { label.Draw(x + p->TextPos.x - style->Font->Width(text), y + p->TextPos.y, text); } } // // Border // if (!p->BorderColor) { p->BorderColor = Video.MapRGB(TheScreen->format, p->BorderColorRGB); } if (p->BorderSize) { for (int i = 0; i < p->BorderSize; ++i) { Video.DrawRectangleClip(p->BorderColor, x - i, y - i, style->Width + 2 * i, style->Height + 2 * i); } } } //@}
realhidden/stratagus
src/ui/uibuttons_proc.cpp
C++
gpl-2.0
4,392
/* * Copyright (C) 2014 AChep@xda <artemchep@gmail.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * 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. */ package com.achep.acdisplay.utils; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.achep.base.tests.Check; import java.lang.reflect.Method; /** * Created by Artem on 02.01.14. */ public class PendingIntentUtils { /** * Perform the operation associated with this PendingIntent. */ public static boolean sendPendingIntent(@Nullable PendingIntent pi) { return sendPendingIntent(pi, null, null); } /** * Perform the operation associated with this PendingIntent. */ public static boolean sendPendingIntent(@Nullable PendingIntent pi, Context context, Intent intent) { if (pi != null) try { // The Context of the caller may be null if // <var>intent</var> is also null. Check.getInstance().isTrue(context != null || intent == null); //noinspection ConstantConditions pi.send(context, 0, intent); return true; } catch (PendingIntent.CanceledException e) { /* unused */ } return false; } /** * Check whether this PendingIntent will launch an Activity. */ public static boolean isActivity(@NonNull PendingIntent pi) { Method method; try { method = PendingIntent.class.getDeclaredMethod("isActivity"); method.setAccessible(true); return (boolean) method.invoke(pi); } catch (Exception e) { e.printStackTrace(); } return true; // We must use `true` ss the fallback value } }
AChep/AcDisplay
project/app/src/main/java/com/achep/acdisplay/utils/PendingIntentUtils.java
Java
gpl-2.0
2,491
#!/usr/bin/python # -*- coding: utf-8 -*- """ Source : Les recettes Python de Tyrtamos http://python.jpvweb.com/mesrecettespython/doku.php?id=date_de_paques """ class jourferie: def datepaques(self,an): """Calcule la date de Pâques d'une année donnée an (=nombre entier)""" a=an//100 b=an%100 c=(3*(a+25))//4 d=(3*(a+25))%4 e=(8*(a+11))//25 f=(5*a+b)%19 g=(19*f+c-e)%30 h=(f+11*g)//319 j=(60*(5-d)+b)//4 k=(60*(5-d)+b)%4 m=(2*j-k-g+h)%7 n=(g-h+m+114)//31 p=(g-h+m+114)%31 jour=p+1 mois=n return [jour, mois, an] def dateliste(self,c, sep='/'): """Transforme une date chaîne 'j/m/a' en une date liste [j,m,a]""" j, m, a = c.split(sep) return [int(j), int(m), int(a)] def datechaine(self,d, sep='/'): """Transforme une date liste=[j,m,a] en une date chaîne 'jj/mm/aaaa'""" return ("%02d" + sep + "%02d" + sep + "%0004d") % (d[0], d[1], d[2]) def jourplus(self,d, n=1): """Donne la date du nième jour suivant d=[j, m, a] (n>=0)""" j, m, a = d fm = [0,31,28,31,30,31,30,31,31,30,31,30,31] if (a%4==0 and a%100!=0) or a%400==0: # bissextile? fm[2] = 29 for i in xrange(0,n): j += 1 if j > fm[m]: j = 1 m += 1 if m>12: m = 1 a += 1 return [j,m,a] def jourmoins(self,d, n=-1): """Donne la date du nième jour précédent d=[j, m, a] (n<=0)""" j, m, a = d fm = [0,31,28,31,30,31,30,31,31,30,31,30,31] if (a%4==0 and a%100!=0) or a%400==0: # bissextile? fm[2] = 29 for i in xrange(0,abs(n)): j -= 1 if j < 1: m -= 1 if m<1: m = 12 a -= 1 j = fm[m] return [j,m,a] def numjoursem(self,d): """Donne le numéro du jour de la semaine d'une date d=[j,m,a] lundi=1, mardi=2, ..., dimanche=7 Algorithme de Maurice Kraitchik (1882?1957)""" j, m, a = d if m<3: m += 12 a -= 1 n = (j +2*m + (3*(m+1))//5 +a + a//4 - a//100 + a//400 +2) % 7 return [6, 7, 1, 2, 3, 4, 5][n] def joursem(self,d): """Donne le jour de semaine en texte à partir de son numéro lundi=1, mardi=2, ..., dimanche=7""" return ["", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"][self.numjoursem(d)] def joursferiesliste(self,an, sd=0): """Liste des jours fériés France en date-liste de l'année an (nb entier). sd=0 (=defaut): tous les jours fériés. sd=1: idem sans les sammedis-dimanches. sd=2: tous + les 2 jours fériés supplémentaires d'Alsace-Moselle. sd=3: idem sd=2 sans les samedis-dimanches""" F = [] # =liste des dates des jours feries en date-liste d=[j,m,a] L = [] # =liste des libelles du jour ferie dp = self.datepaques(an) # Jour de l'an d = [1,1,an] nj = self.numjoursem(d) if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6): F.append(d) L.append(u"Jour de l'an") # Vendredi saint (pour l'Alsace-Moselle) d = self.jourmoins(dp, -2) if (sd==0) or (sd==2): #if sd>=2: F.append(d) L.append(u"Vendredi saint (Alsace-Moselle)") # Dimanche de Paques d = dp if (sd==0) or (sd==2): F.append(d) L.append(u"Dimanche de Paques") # Lundi de Paques d = self.jourplus(dp, +1) F.append(d) L.append(u"Lundi de Paques") # Fête du travail d = [1,5,an] nj = self.numjoursem(d) if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6): F.append(d) L.append(u"Fete du travail") # Victoire des allies 1945 d = [8,5,an] nj = self.numjoursem(d) if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6): F.append(d) L.append(u"Victoire des allies 1945") # Jeudi de l'Ascension d = self.jourplus(dp, +39) F.append(d) L.append(u"Jeudi de l'Ascension") # Dimanche de Pentecote d = self.jourplus(dp, +49) if (sd==0) or (sd==2): F.append(d) L.append(u"Dimanche de Pentecote") # Lundi de Pentecote d = self.jourplus(d, +1) F.append(d) L.append(u"Lundi de Pentecote") # Fete Nationale d = [14,7,an] nj = self.numjoursem(d) if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6): F.append(d) L.append(u"Fete Nationale") # Assomption d = [15,8,an] nj = self.numjoursem(d) if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6): F.append(d) L.append(u"Assomption") # Toussaint d = [1,11,an] nj = self.numjoursem(d) if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6): F.append(d) L.append(u"Toussaint") # Armistice 1918 d = [11,11,an] nj = self.numjoursem(d) if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6): F.append(d) L.append(u"Armistice 1918") # Jour de Noel d = [25,12,an] nj = self.numjoursem(d) if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6): F.append(d) L.append(u"Jour de Noel") # Saint Etienne Alsace d = [26,12,an] nj = self.numjoursem(d) if (sd==0) or (sd==1 and nj<6) or (sd==2) or (sd==3 and nj<6): F.append(d) L.append(u"Saint-Etienne (Alsace)") return F, L def joursferies(self,an, sd=0, sep='/'): """Liste des jours fériés France en date-chaine de l'année an (nb entier). sd=0 (=defaut): tous les jours fériés. sd=1: idem sans les sammedis-dimanches. sd=2: tous + les 2 jours fériés supplémentaires d'Alsace-Moselle. sd=3: idem sd=2 sans les samedis-dimanches""" C = [] J = [] F, L = self.joursferiesliste(an, sd) for i in xrange(0,len(F)): C.append(self.datechaine(F[i])) # conversion des dates-liste en dates-chaine J.append(self.joursem(F[i])) # ajout du jour de semaine return C, J, L def estferie(self,d,sd=0): """estferie(d,sd=0): => dit si une date d=[j,m,a] donnée est fériée France si la date est fériée, renvoie son libellé sinon, renvoie une chaine vide""" j,m,a = d F, L = self.joursferiesliste(a, sd) for i in xrange(0, len(F)): if j==F[i][0] and m==F[i][1] and a==F[i][2]: return L[i] return "False"
guiguiabloc/api-domogeek
Holiday.py
Python
gpl-2.0
6,861
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.picketlink.identity.federation.web.interfaces; import javax.security.auth.login.LoginException; /** * Handle authentication * @author Anil.Saldhana@redhat.com * @since Aug 18, 2009 */ public interface ILoginHandler { /** * Authenticate the user * @param username username * @param credential credential * @return true - authenticated * @throws LoginException */ public boolean authenticate(String username, Object credential) throws LoginException; }
taylor-project/taylor-picketlink-2.0.3
federation/picketlink-web/src/main/java/org/picketlink/identity/federation/web/interfaces/ILoginHandler.java
Java
gpl-2.0
1,536
#pragma once #include "Scene.h" #include "Woman.h" #include "ReaZyu.h" #include "Botch.h" #include "Sweats.h" #include "CharaButton.h" #include "Button.h" #include <list> class GameScene : public Scene { public: GameScene(GameModes* gameMode, BasicInput* input); ~GameScene(); void init(); void update(); float time; float timeFromBegin; float beginTime; private: long lastWomanSpawn = 0; std::list<DrawableBase*> Drawables; std::list<Botch> Botchs; std::list<Sweats> Sweats; std::list<CharaButton> CharaButtons; ReaZyu *reaZyu; void drawTimerString(); int backgroundHandle; };
LimeStreem/UNITUS_Hackerson_1
UNITUS_Hackerson_1/GameScene.h
C
gpl-2.0
595
# 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. """Make osversion.osmajor_id non-NULLable Revision ID: 5ab66e956c6b Revises: 286ed23a5c1b Create Date: 2017-12-20 15:54:38.825703 """ # revision identifiers, used by Alembic. revision = '5ab66e956c6b' down_revision = '286ed23a5c1b' from alembic import op from sqlalchemy import Integer def upgrade(): op.alter_column('osversion', 'osmajor_id', existing_type=Integer, nullable=False) def downgrade(): op.alter_column('osversion', 'osmajor_id', existing_type=Integer, nullable=True)
beaker-project/beaker
Server/bkr/server/alembic/versions/5ab66e956c6b_osversion_osmajor_id_non_nullable.py
Python
gpl-2.0
743
/* * linux/net/sunrpc/sysctl.c * * Sysctl interface to sunrpc module. * * I would prefer to register the sunrpc table below sys/net, but that's * impossible at the moment. */ #include <linux/types.h> #include <linux/linkage.h> #include <linux/ctype.h> #include <linux/fs.h> #include <linux/sysctl.h> #include <linux/module.h> #include <asm/uaccess.h> #include <linux/sunrpc/types.h> #include <linux/sunrpc/sched.h> #include <linux/sunrpc/stats.h> #include <linux/sunrpc/svc_xprt.h> #include "netns.h" /* * Declare the debug flags here */ unsigned int rpc_debug; EXPORT_SYMBOL_GPL(rpc_debug); unsigned int nfs_debug; EXPORT_SYMBOL_GPL(nfs_debug); unsigned int nfsd_debug; EXPORT_SYMBOL_GPL(nfsd_debug); unsigned int nlm_debug; EXPORT_SYMBOL_GPL(nlm_debug); #ifdef RPC_DEBUG static struct ctl_table_header *sunrpc_table_header; static ctl_table sunrpc_table[]; void rpc_register_sysctl(void) { if (!sunrpc_table_header) sunrpc_table_header = register_sysctl_table(sunrpc_table); } void rpc_unregister_sysctl(void) { if (sunrpc_table_header) { unregister_sysctl_table(sunrpc_table_header); sunrpc_table_header = NULL; } } static int proc_do_xprt(ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { char tmpbuf[256]; size_t len; if ((*ppos && !write) || !*lenp) { *lenp = 0; return 0; } len = svc_print_xprts(tmpbuf, sizeof(tmpbuf)); return simple_read_from_buffer(buffer, *lenp, ppos, tmpbuf, len); } static int proc_dodebug(ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { char tmpbuf[20], c, *s; char __user *p; unsigned int value; size_t left, len; if ((*ppos && !write) || !*lenp) { *lenp = 0; return 0; } left = *lenp; if (write) { if (!access_ok(VERIFY_READ, buffer, left)) return -EFAULT; p = buffer; while (left && __get_user(c, p) >= 0 && isspace(c)) left--, p++; if (!left) goto done; if (left > sizeof(tmpbuf) - 1) return -EINVAL; if (copy_from_user(tmpbuf, p, left)) return -EFAULT; tmpbuf[left] = '\0'; for (s = tmpbuf, value = 0; '0' <= *s && *s <= '9'; s++, left--) value = 10 * value + (*s - '0'); if (*s && !isspace(*s)) return -EINVAL; while (left && isspace(*s)) left--, s++; *(unsigned int *) table->data = value; /* Display the RPC tasks on writing to rpc_debug */ if (strcmp(table->procname, "rpc_debug") == 0) rpc_show_tasks(&init_net); } else { if (!access_ok(VERIFY_WRITE, buffer, left)) return -EFAULT; len = sprintf(tmpbuf, "%d", *(unsigned int *) table->data); if (len > left) len = left; if (__copy_to_user(buffer, tmpbuf, len)) return -EFAULT; if ((left -= len) > 0) { if (put_user('\n', (char __user *)buffer + len)) return -EFAULT; left--; } } done: *lenp -= left; *ppos += *lenp; return 0; } static ctl_table debug_table[] = { { .procname = "rpc_debug", .data = &rpc_debug, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dodebug }, { .procname = "nfs_debug", .data = &nfs_debug, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dodebug }, { .procname = "nfsd_debug", .data = &nfsd_debug, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dodebug }, { .procname = "nlm_debug", .data = &nlm_debug, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dodebug }, { .procname = "transports", .maxlen = 256, .mode = 0444, .proc_handler = proc_do_xprt, }, { } }; static ctl_table sunrpc_table[] = { { .procname = "sunrpc", .mode = 0555, .child = debug_table }, { } }; #endif
evolver56k/xpenology
net/sunrpc/sysctl.c
C
gpl-2.0
3,637
<?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/>. /** * Searches modules, filters and blocks for any Javascript files * that should be called on every page * * @package moodlecore * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ define('NO_MOODLE_COOKIES', true); define('NO_UPGRADE_CHECK', true); include('../config.php'); $output = "// Javascript from Moodle modules\n"; $plugintypes = array('mod', 'filter', 'block'); foreach ($plugintypes as $plugintype) { if ($mods = get_plugin_list($plugintype)) { foreach ($mods as $mod => $moddir) { if (is_readable($moddir.'/javascript.php')) { $output .= file_get_contents($moddir.'/javascript.php'); } } } } $lifetime = '86400'; @header('Content-type: text/javascript'); @header('Content-length: '.strlen($output)); @header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT'); @header('Cache-control: max-age='.$lifetime); @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .'GMT'); @header('Pragma: '); echo $output;
ajv/Offline-Caching
lib/javascript-mod.php
PHP
gpl-2.0
1,892
/*============================================================================= // // This software has been released under the terms of the GNU General Public // license. See http://www.gnu.org/copyleft/gpl.html for details. // // Copyright 2001 Anders Johansson ajh@atri.curtin.edu.au // //============================================================================= */ /* Equalizer filter, implementation of a 10 band time domain graphic equalizer using IIR filters. The IIR filters are implemented using a Direct Form II approach, but has been modified (b1 == 0 always) to save computation. */ #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <math.h> #include "af.h" #define L 2 // Storage for filter taps #define KM 10 // Max number of bands #define Q 1.2247449 /* Q value for band-pass filters 1.2247=(3/2)^(1/2) gives 4dB suppression @ Fc*2 and Fc/2 */ /* Center frequencies for band-pass filters The different frequency bands are: nr. center frequency 0 31.25 Hz 1 62.50 Hz 2 125.0 Hz 3 250.0 Hz 4 500.0 Hz 5 1.000 kHz 6 2.000 kHz 7 4.000 kHz 8 8.000 kHz 9 16.00 kHz */ #define CF {31.25,62.5,125,250,500,1000,2000,4000,8000,16000} // Maximum and minimum gain for the bands #define G_MAX +12.0 #define G_MIN -12.0 // Data for specific instances of this filter typedef struct af_equalizer_s { float a[KM][L]; // A weights float b[KM][L]; // B weights float wq[AF_NCH][KM][L]; // Circular buffer for W data float g[AF_NCH][KM]; // Gain factor for each channel and band int K; // Number of used eq bands int channels; // Number of channels float gain_factor; // applied at output to avoid clipping } af_equalizer_t; // 2nd order Band-pass Filter design static void bp2(float* a, float* b, float fc, float q){ double th= 2.0 * M_PI * fc; double C = (1.0 - tan(th*q/2.0))/(1.0 + tan(th*q/2.0)); a[0] = (1.0 + C) * cos(th); a[1] = -1 * C; b[0] = (1.0 - C)/2.0; b[1] = -1.0050; } // Initialization and runtime control static int control(struct af_instance_s* af, int cmd, void* arg) { af_equalizer_t* s = (af_equalizer_t*)af->setup; switch(cmd){ case AF_CONTROL_REINIT:{ int k =0, i =0; float F[KM] = CF; s->gain_factor=0.0; // Sanity check if(!arg) return AF_ERROR; af->data->rate = ((af_data_t*)arg)->rate; af->data->nch = ((af_data_t*)arg)->nch; af->data->format = AF_FORMAT_FLOAT_NE; af->data->bps = 4; // Calculate number of active filters s->K=KM; while(F[s->K-1] > (float)af->data->rate/2.2) s->K--; if(s->K != KM) af_msg(AF_MSG_INFO,"[equalizer] Limiting the number of filters to" " %i due to low sample rate.\n",s->K); // Generate filter taps for(k=0;k<s->K;k++) bp2(s->a[k],s->b[k],F[k]/((float)af->data->rate),Q); // Calculate how much this plugin adds to the overall time delay af->delay = 2 * af->data->nch * af->data->bps; // Calculate gain factor to prevent clipping at output for(k=0;k<AF_NCH;k++) { for(i=0;i<KM;i++) { if(s->gain_factor < s->g[k][i]) s->gain_factor=s->g[k][i]; } } s->gain_factor=log10(s->gain_factor + 1.0) * 20.0; if(s->gain_factor > 0.0) { s->gain_factor=0.1+(s->gain_factor/12.0); }else{ s->gain_factor=1; } return af_test_output(af,arg); } case AF_CONTROL_COMMAND_LINE:{ float g[10]={0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}; int i,j; sscanf((char*)arg,"%f:%f:%f:%f:%f:%f:%f:%f:%f:%f", &g[0], &g[1], &g[2], &g[3], &g[4], &g[5], &g[6], &g[7], &g[8] ,&g[9]); for(i=0;i<AF_NCH;i++){ for(j=0;j<KM;j++){ ((af_equalizer_t*)af->setup)->g[i][j] = pow(10.0,clamp(g[j],G_MIN,G_MAX)/20.0)-1.0; } } return AF_OK; } case AF_CONTROL_EQUALIZER_GAIN | AF_CONTROL_SET:{ float* gain = ((af_control_ext_t*)arg)->arg; int ch = ((af_control_ext_t*)arg)->ch; int k; if(ch >= AF_NCH || ch < 0) return AF_ERROR; for(k = 0 ; k<KM ; k++) s->g[ch][k] = pow(10.0,clamp(gain[k],G_MIN,G_MAX)/20.0)-1.0; return AF_OK; } case AF_CONTROL_EQUALIZER_GAIN | AF_CONTROL_GET:{ float* gain = ((af_control_ext_t*)arg)->arg; int ch = ((af_control_ext_t*)arg)->ch; int k; if(ch >= AF_NCH || ch < 0) return AF_ERROR; for(k = 0 ; k<KM ; k++) gain[k] = log10(s->g[ch][k]+1.0) * 20.0; return AF_OK; } } return AF_UNKNOWN; } // Deallocate memory static void uninit(struct af_instance_s* af) { if(af->data) free(af->data); if(af->setup) free(af->setup); } // Filter data through filter static af_data_t* play(struct af_instance_s* af, af_data_t* data) { af_data_t* c = data; // Current working data af_equalizer_t* s = (af_equalizer_t*)af->setup; // Setup uint32_t ci = af->data->nch; // Index for channels uint32_t nch = af->data->nch; // Number of channels while(ci--){ float* g = s->g[ci]; // Gain factor float* in = ((float*)c->audio)+ci; float* out = ((float*)c->audio)+ci; float* end = in + c->len/4; // Block loop end while(in < end){ register int k = 0; // Frequency band index register float yt = *in; // Current input sample in+=nch; // Run the filters for(;k<s->K;k++){ // Pointer to circular buffer wq register float* wq = s->wq[ci][k]; // Calculate output from AR part of current filter register float w=yt*s->b[k][0] + wq[0]*s->a[k][0] + wq[1]*s->a[k][1]; // Calculate output form MA part of current filter yt+=(w + wq[1]*s->b[k][1])*g[k]; // Update circular buffer wq[1] = wq[0]; wq[0] = w; } // Calculate output *out=yt*s->gain_factor; out+=nch; } } return c; } // Allocate memory and set function pointers static int af_open(af_instance_t* af){ af->control=control; af->uninit=uninit; af->play=play; af->mul=1; af->data=calloc(1,sizeof(af_data_t)); af->setup=calloc(1,sizeof(af_equalizer_t)); if(af->data == NULL || af->setup == NULL) return AF_ERROR; return AF_OK; } // Description of this filter af_info_t af_info_equalizer = { "Equalizer audio filter", "equalizer", "Anders", "", AF_FLAGS_NOT_REENTRANT, af_open };
scs/uclinux
user/blkfin-apps/mplayer/mplayer-svn-25211/libaf/af_equalizer.c
C
gpl-2.0
6,456
""" Functions performing URL trimming and cleaning """ ## This file is available from https://github.com/adbar/courlan ## under GNU GPL v3 license import logging import re from collections import OrderedDict from urllib.parse import parse_qs, urlencode, urlparse, ParseResult from .filters import validate_url from .settings import ALLOWED_PARAMS, CONTROL_PARAMS,\ TARGET_LANG_DE, TARGET_LANG_EN PROTOCOLS = re.compile(r'https?://') SELECTION = re.compile(r'(https?://[^">&? ]+?)(?:https?://)|(?:https?://[^/]+?/[^/]+?[&?]u(rl)?=)(https?://[^"> ]+)') MIDDLE_URL = re.compile(r'https?://.+?(https?://.+?)(?:https?://|$)') NETLOC_RE = re.compile(r'(?<=\w):(?:80|443)') PATH1 = re.compile(r'/+') PATH2 = re.compile(r'^(?:/\.\.(?![^/]))+') def clean_url(url, language=None): '''Helper function: chained scrubbing and normalization''' try: return normalize_url(scrub_url(url), language) except (AttributeError, ValueError): return None def scrub_url(url): '''Strip unnecessary parts and make sure only one URL is considered''' # trim # https://github.com/cocrawler/cocrawler/blob/main/cocrawler/urls.py # remove leading and trailing white space and unescaped control chars url = url.strip('\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f' '\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f \r\n') # clean the input string url = url.replace('[ \t]+', '') # <![CDATA[http://www.urbanlife.de/item/260-bmw-i8-hybrid-revolution-unter-den-sportwagen.html]]> if url.startswith('<![CDATA['): # re.match(r'<!\[CDATA\[', url): url = url.replace('<![CDATA[', '') # url = re.sub(r'^<!\[CDATA\[', '', url) url = url.replace(']]>', '') # url = re.sub(r'\]\]>$', '', url) # markup rests url = re.sub(r'</?a>', '', url) # &amp; if '&amp;' in url: url = url.replace('&amp;', '&') #if '"' in link: # link = link.split('"')[0] # double/faulty URLs protocols = PROTOCOLS.findall(url) if len(protocols) > 1 and not 'web.archive.org' in url: logging.debug('double url: %s %s', len(protocols), url) match = SELECTION.match(url) if match and validate_url(match.group(1))[0] is True: url = match.group(1) logging.debug('taking url: %s', url) else: match = MIDDLE_URL.match(url) if match and validate_url(match.group(1))[0] is True: url = match.group(1) logging.debug('taking url: %s', url) # too long and garbled URLs e.g. due to quotes URLs # https://github.com/cocrawler/cocrawler/blob/main/cocrawler/urls.py if len(url) > 500: # arbitrary choice match = re.match(r'(.*?)[<>"\'\r\n ]', url) if match: url = match.group(1) if len(url) > 500: logging.debug('invalid-looking link %s of length %d', url[:50] + '...', len(url)) # trailing ampersand url = url.strip('&') # trailing slashes in URLs without path or in embedded URLs if url.count('/') == 3 or url.count('://') > 1: url = url.rstrip('/') # lower # url = url.lower() return url def clean_query(parsed_url, strict=False, language=None): '''Strip unwanted query elements''' if len(parsed_url.query) > 0: qdict = parse_qs(parsed_url.query) newqdict = OrderedDict() for qelem in sorted(qdict.keys()): teststr = qelem.lower() # control param if strict is True and \ teststr not in ALLOWED_PARAMS and teststr not in CONTROL_PARAMS: continue # control language if language is not None and teststr in CONTROL_PARAMS: found_lang = str(qdict[qelem][0]) if (language == 'de' and found_lang not in TARGET_LANG_DE) or \ (language == 'en' and found_lang not in TARGET_LANG_EN) or \ found_lang != language: logging.debug('bad lang: %s %s %s', language, qelem, found_lang) raise ValueError # insert newqdict[qelem] = qdict[qelem] newstring = urlencode(newqdict, doseq=True) parsed_url = parsed_url._replace(query=newstring) return parsed_url def normalize_url(parsed_url, strict=False, language=None): '''Takes a URL string or a parsed URL and returns a (basically) normalized URL string''' if not isinstance(parsed_url, ParseResult): parsed_url = urlparse(parsed_url) # port if parsed_url.port is not None and parsed_url.port in (80, 443): parsed_url = parsed_url._replace(netloc=NETLOC_RE.sub('', parsed_url.netloc)) # path: https://github.com/saintamh/alcazar/blob/master/alcazar/utils/urls.py newpath = PATH1.sub('/', parsed_url.path) # Leading /../'s in the path are removed newpath = PATH2.sub('', newpath) # fragment if strict is True: newfragment = '' else: newfragment = parsed_url.fragment # lowercase + remove fragments parsed_url = parsed_url._replace( scheme=parsed_url.scheme.lower(), netloc=parsed_url.netloc.lower(), path=newpath, fragment=newfragment ) # strip unwanted query elements parsed_url = clean_query(parsed_url, strict, language) # rebuild return parsed_url.geturl()
adbar/url-tools
courlan/clean.py
Python
gpl-2.0
5,520
'use strict'; angular.module('tpjpaApp') .config(function ($stateProvider) { $stateProvider .state('metrics', { parent: 'admin', url: '/metrics', data: { roles: ['ROLE_ADMIN'], pageTitle: 'metrics.title' }, views: { 'content@': { templateUrl: 'scripts/app/admin/metrics/metrics.html', controller: 'MetricsController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('metrics'); return $translate.refresh(); }] } }); });
CherifAbdoul/TpSirM1MIAGE_Ierlomenko-Kinfack-Haidara
tpJpa/src/main/webapp/scripts/app/admin/metrics/metrics.js
JavaScript
gpl-2.0
919
<?php /** * @file * Returns the HTML for a single Drupal page. * * Complete documentation for this file is available online. * @see https://drupal.org/node/1728148 */ ?> <div class="container"> <header id="header"> <div class="logo"> <a href="/" title="Home" rel="home" id="logo"> </a> </div> <nav id="main-menu" class="navigation" role="navigation"> <h2 class="visually-hidden">Main menu</h2> <ul class="links"> <li class="menu-66" data-drupal-link-system-path="node/8"><a href="/services" title="Services" data-drupal-link-system-path="node/8">Services</a></li> <li class="menu-65" data-drupal-link-system-path="works"><a href="/works" title="Work" data-drupal-link-system-path="works">Clients</a></li> <li class="menu-63" data-drupal-link-system-path="blogs"><a href="/blogs" title="Our blogs" data-drupal-link-system-path="blogs">Blog</a></li> <li class="menu-64" data-drupal-link-system-path="contact"><a href="/contact" title="Contact" data-drupal-link-system-path="contact">Contact</a></li> <li class="menu-67-active-trail active" data-drupal-link-system-path="http://www.mariquecalcus.com/demo"><a href="/" title="The lab" class="active-trail active" data-drupal-link-system-path="http://www.mariquecalcus.com/demo">The lab</a></li> </ul> </nav> </header> <div id="main-wrapper"> <div id="mobile-container"> <a id="mobile-nav" href="#mobile-nav"> <i class="fa fa-2"></i> </a> <a id="mobile-logo" href="/" title="Home" rel="home" ></a> </div> <main id="main" role="main"> <div id="content-wrapper"> <div id="secondnav"> <?php $tree = menu_tree_all_data('main-menu'); print drupal_render(menu_tree_output($tree)); ?> </div> <div id="page-content"> <?php print render($tabs); ?> <?php print render($page['help']); ?> <?php print $messages; ?> <?php print render($title_suffix); ?> <?php if ($action_links): ?> <ul class="action-links"><?php print render($action_links); ?></ul> <?php endif; ?> <?php if ($title): ?> <h1 class="page__title title" id="page-title"><?php print $title; ?></h1> <?php endif; ?> <?php print render($page['content']); ?> </div> <aside id="aside_right"> <?php if ($page['sidebar_second']): ?> <?php print render($page['sidebar_second']); ?> <?php endif; ?> </aside> </div> </main> <footer id="footer" class="footer"> <div id="footer-top"> <div class="slogan"> We'd love to hear from you. </div> <div class="calltoaction"> <a href="/contact">Contact</a> </div> </div> <div id="footer-center"> <div class="contact"> <h3>Contact</h3> <ul> <li class="first">info@mariquecalcus.com</li> </ul> </div> <div class="navigation"> <h3>Navigate</h3> <ul> <li class="first"><a href="/about">About us</a></li> <li class=""><a href="/services">Services</a></li> <li class=""><a href="/blogs">Blogs</a></li> <li class="last"><a href="/contact">Contact</a></li> </ul> </div> <div class="legal"> <h3>Legal stuff</h3> <ul> <li class="first"><a href="/legal/privacy-policy">Privacy Policy</a></li> </ul> </div> <div class="logo"> <img src="/sites/all/themes/custom/prius/images/logos/logo_medium.svg" alt="" /> </div> </div> <div id="footer-bottom"> <div class="copyright"> Copyright <?php print date('Y') ?> by Mariquecalcus. All rights reserved. </div> <div class="social"> <ul> <li><a href="https://www.facebook.com" alt="Friend us on Facebook" target="_blank"><i class="fa fa-facebook"></i></a></li> <li><a href="https://plus.google.com" alt="Follow us on Google Plus" target="_blank"><i class="fa fa-google-plus"></i></a></li> <li><a href="https://twitter.com" alt="Follow us on Twitter" target="_blank"><i class="fa fa-twitter"></i></a></li> <li><a href="https://www.linkedin.com" alt="Network with us on LinkedIn" target="_blank"><i class="fa fa-linkedin"></i></a></li> </ul> </div> </div> </footer> </div> </div>
targoo/mariquecalcus_drupal_demo
sites/all/themes/custom/prius/templates/page.tpl.php
PHP
gpl-2.0
4,587
#include <iostream> #include <pthread.h> #include <vector> #include "time_wrap.h" using namespace time_wrap; //----------------------------------------------------------------------------- // Data structure to be modified by nthreads //----------------------------------------------------------------------------- template< typename T> struct Add_Data { Add_Data() : loop_count_(0) { pthread_mutex_init( &lock, (pthread_mutexattr_t *)NULL ); } void loop_count( unsigned int x ) { loop_count_=x;} unsigned int loop_count() const { return loop_count_; } void init() { begin_=0 , end_ = 0 ; } void incr() { end_++; } T begin() const { return begin_ ; } T end() const { return end_ ; } public: pthread_mutex_t lock; public: T begin_; T end_; unsigned int loop_count_; }; //----------------------------------------------------------------------------- // increment via method with locking //----------------------------------------------------------------------------- template< typename T> void *incr_with_mutex( void *p ) { Add_Data<T> *data = (Add_Data<T> *)(p); unsigned int l_count = 0; while( l_count++ < data->loop_count() ) { pthread_mutex_lock(&data->lock); data->incr(); pthread_mutex_unlock(&data->lock); } return p; } //----------------------------------------------------------------------------- // increment via method no locking //----------------------------------------------------------------------------- template< typename T> void *incr_no_lock( void *p ) { Add_Data<T> *data = (Add_Data<T> *)(p); unsigned int l_count = 0; while( l_count++ < data->loop_count() ) { data->incr(); } return p; } //----------------------------------------------------------------------------- // increment direct no locking //----------------------------------------------------------------------------- template< typename T> void *incr_direct_no_lock( void *p ) { Add_Data<T> *data = (Add_Data<T> *)(p); unsigned int l_count = 0; while( l_count++ < data->loop_count() ) { data->end_++; } return p; } //----------------------------------------------------------------------------- // check condition then increment via method //----------------------------------------------------------------------------- template< typename T> void *if_x_incr( void *p ) { Add_Data<T> *data = (Add_Data<T> *)(p); unsigned int l_count = 0; while( l_count++ <data->loop_count() ) { if ( data->loop_count() ) data->incr(); } return p; } //----------------------------------------------------------------------------- // check condition then increment direct //----------------------------------------------------------------------------- template< typename T> void *if_x_incr_direct( void *p ) { Add_Data<T> *data = (Add_Data<T> *)(p); unsigned int l_count = 0; while( l_count++ <data->loop_count() ) { if ( data->loop_count() ) data->end_++; } return p; } //----------------------------------------------------------------------------- // print results //----------------------------------------------------------------------------- void print_header( std::ostream &stream ) { stream << std::setw(15) << "type" << std::setw(15) << "operation" << " | " << std::setw(15) << "check_sum" << " | " << std::setw(15) << "run_sum" << " | " << std::setw(15) << "is_atomic?" << " | " << std::setw(15) << "time(us)" << std::endl; } void print_result( std::ostream &stream , const char * typ_str, const char * op_str, unsigned long check_sum, unsigned long sum, bool is_atomic, long usec ) { std::cout << std::setw(15) << typ_str << std::setw(15) << op_str << " | " << std::setw(15) << check_sum << " | " << std::setw(15) << sum << " | " << std::setw(15) << ( is_atomic ? "atomic" : "not atomic" ) << " | " << std::setw(15) << usec << std::endl; } //----------------------------------------------------------------------------- // run experiment //----------------------------------------------------------------------------- template< typename T > bool thread_run( void *(*thr_func)(void *) , Add_Data<T> *data , int threads , unsigned int &check_sum , unsigned int &run_sum , long &usec ) { std::vector<pthread_t> tidV; data->init(); Time tbegin = Time::now(); for( int i = 0 ; i < threads ; i++ ) { pthread_t tid; pthread_create( &tid , (pthread_attr_t *) NULL , thr_func , (void *)(data) ); tidV.push_back(tid); } for( size_t i = 0 ; i < tidV.size() ; i++ ) { pthread_join(tidV[i], (void **) NULL ); } if ( threads == 0 ) (*thr_func)( (void *) data); int niter = threads == 0 ? 1 : threads; Time tend = Time::now(); check_sum = niter * data->loop_count(); run_sum = data->end() - data->begin(); usec = ( tend.ticks() - tbegin.ticks() ) / Time::ticks_per_usec(); bool is_atomic = check_sum == run_sum; return is_atomic; } //----------------------------------------------------------------------------- // test if atomic //----------------------------------------------------------------------------- template< typename T> bool atomic_test( void *(*thr_func)(void *) , Add_Data<T> *data , int threads , const char *typ_str , const char *op_str ) { bool is_atomic; int i = 0 , num_trials = 15; unsigned int check_sum = 0 , run_sum = 0; long usec_avg = 0; while( i < num_trials ) { unsigned int csum = 0 , rsum = 0; long usec = 0; is_atomic = thread_run<T>( thr_func , data , threads , csum , rsum , usec ); i++; check_sum+= csum; run_sum += rsum; usec_avg += usec; if ( !is_atomic ) break; } check_sum /= i; run_sum /= i; usec_avg /= i; print_result( std::cout , typ_str , op_str , check_sum , run_sum , is_atomic, usec_avg ); } //----------------------------------------------------------------------------- // main //----------------------------------------------------------------------------- typedef unsigned long run_type; const char *typ_str = "unsigned long"; int main( int , char ** ) { Add_Data<run_type> data; data.loop_count(1000000); const int nthreads = 2; print_header( std::cout ); atomic_test<run_type>( if_x_incr<run_type> , &data , nthreads , typ_str , "if(x) incr()" ); atomic_test<run_type>( incr_no_lock<run_type> , &data , nthreads , typ_str, "incr()" ); atomic_test<run_type>( if_x_incr_direct<run_type> , &data , nthreads , typ_str , "if(x) ++ " ); atomic_test<run_type>( incr_direct_no_lock<run_type> , &data , nthreads , typ_str , "++ " ); atomic_test<run_type>( incr_with_mutex<run_type> , &data , nthreads , typ_str , "incr() w/mutex" ); atomic_test<run_type>( incr_no_lock<run_type> , &data , 1 , typ_str ,"incr()new thr" ); atomic_test<run_type>( incr_no_lock<run_type> , &data , 0 , typ_str ,"incr()main thr" ); }
jrrpanix/CPPCode
panix/atomic_tst.cpp
C++
gpl-2.0
7,057
/* * Author: Tatu Ylonen <ylo@cs.hut.fi> * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland * All rights reserved * Versions of malloc and friends that check their results, and never return * failure (they call fatal if they encounter an error). * * As far as I am concerned, the code I have written for this software * can be used freely for any purpose. Any derived versions of this * software must be clearly marked as such, and if the derived work is * incompatible with the protocol description in the RFC file, it must be * called by a name other than "ssh" or "Secure Shell". */ /* xmalloc.c taken from OpenSSH and adapted */ #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #ifndef SIZE_T_MAX #define SIZE_T_MAX UINT_MAX #endif #include <netcore-ng/macros.h> #include <netcore-ng/xmalloc.h> #include <netcore-ng/strlcpy.h> void *xmalloc(size_t size) { void *ptr; if (size == 0) { err("xmalloc: zero size"); exit(EXIT_FAILURE); } ptr = malloc(size); if (ptr == NULL) { err("xmalloc: out of memory (allocating %lu bytes)", (u_long) size); exit(EXIT_FAILURE); } return ptr; } void *xzmalloc(size_t size) { void *ptr; if (size == 0) { err("xmalloc: zero size"); exit(EXIT_FAILURE); } ptr = malloc(size); if (ptr == NULL) { err("xmalloc: out of memory (allocating %lu bytes)", (u_long) size); exit(EXIT_FAILURE); } memset(ptr, 0, size); return ptr; } void *xcalloc(size_t nmemb, size_t size) { void *ptr; if (size == 0 || nmemb == 0) { err("xcalloc: zero size"); exit(EXIT_FAILURE); } if (SIZE_T_MAX / nmemb < size) { err("xcalloc: nmemb * size > SIZE_T_MAX"); exit(EXIT_FAILURE); } ptr = calloc(nmemb, size); if (ptr == NULL) { err("xcalloc: out of memory (allocating %lu bytes)", (u_long)(size * nmemb)); exit(EXIT_FAILURE); } return ptr; } void *xrealloc(void *ptr, size_t nmemb, size_t size) { void *new_ptr; size_t new_size = nmemb * size; if (new_size == 0) { err("xrealloc: zero size"); exit(EXIT_FAILURE); } if (SIZE_T_MAX / nmemb < size) { err("xrealloc: nmemb * size > SIZE_T_MAX"); exit(EXIT_FAILURE); } if (ptr == NULL) { new_ptr = malloc(new_size); } else { new_ptr = realloc(ptr, new_size); } if (new_ptr == NULL) { err("xrealloc: out of memory (new_size %lu bytes)", (u_long) new_size); exit(EXIT_FAILURE); } return new_ptr; } void xfree(void *ptr) { if (ptr == NULL) { err("xfree: NULL pointer given as argument"); exit(EXIT_FAILURE); } free(ptr); } char *xstrdup(const char *str) { size_t len; char *cp; len = strlen(str) + 1; cp = xmalloc(len); strlcpy(cp, str, len); return cp; }
eroullit/net-toolbox
netcore-ng/xmalloc.c
C
gpl-2.0
2,750
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"/> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/> <meta name="HandheldFriendly" content="true"/> <meta name="MobileOptimized" content="320"/> <title>Hello H5+</title> <script type="text/javascript" src="../js/common.js"></script> <script type="text/javascript"> function getVersion(){ outSet("程序版本号:"+plus.runtime.version+"\n内核版本号:"+plus.runtime.innerVersion); } function getArguments(){ outSet("启动方式: "+plus.runtime.launcher+"\n启动参数: "+plus.runtime.arguments); } function restartApp() { plus.runtime.restart(); } function getWidgetInfo() { plus.runtime.getProperty( plus.runtime.appid, function ( wgtinfo ) { //appid属性 var wgtStr = "appid:"+wgtinfo.appid; //version属性 wgtStr += "\nversion:"+wgtinfo.version; //name属性 wgtStr += "\nname:"+wgtinfo.name; //description属性 wgtStr += "\ndescription:"+wgtinfo.description; //author属性 wgtStr += "\nauthor:"+wgtinfo.author; //email属性 wgtStr += "\nemail:"+wgtinfo.email; //licence属性 wgtStr += "\nlicense:"+wgtinfo.license; //licensehref属性 wgtStr += "\nlicensehref:"+wgtinfo.licensehref; //features 属性 wgtStr += "\nfeatures:"+wgtinfo.features; outSet( wgtStr ); } ); } function setBadge() { plus.runtime.setBadgeNumber( 50 ); outSet( "设置程序图标右上角显示的提示数字为50\n请返回桌面查看" ); if(plus.os.name=="iOS"){ outLine( '*如果无法设置提示数字,请到"设置"->"通知"中配置应用在通知中心显示!' ); }else{ outLine( "注:仅支持小米(MIUI v5),其它设备暂不支持此功能!" ); } } function clearBadge() { plus.runtime.setBadgeNumber( 0 ); outSet( "清除程序图标右上角显示的提示数字\n请返回桌面查看" ); if(plus.os.name=="iOS"){ outLine( '如果无法清除提示数字,请到"设置"->"通知"中配置应用在通知中心显示!' ); }else{ outLine( "注:仅支持小米(MIUI v5),其它设备暂不支持此功能!" ); } } function exitApp(){ if(plus.os.name=="Android"){ plus.runtime.quit(); }else{ outSet( "此平台不支持直接退出程序,请按Home键切换应用" ); } } function updateApp(){ var url='http://demo.dcloud.net.cn/helloh5/update/HelloH5.wgtu'; plus.nativeUI.showWaiting("升级中..."); var dtask = plus.downloader.createDownload( url, {method:"GET"}, function(d,status){ if ( status == 200 ) { console.log( "Download wgtu success: " + d.filename ); plus.runtime.install(d.filename,{},function(){ plus.nativeUI.closeWaiting(); plus.nativeUI.alert("Update wgtu success, restart now!",function(){ plus.runtime.restart(); }); },function(e){ plus.nativeUI.closeWaiting(); alert("Update wgtu failed: "+e.message); }); } else { plus.nativeUI.closeWaiting(); alert( "Download wgtu failed: " + status ); } } ); dtask.addEventListener('statechanged',function(d,status){ console.log("statechanged: "+d.state); }); dtask.start(); } </script> <link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8"/> </head> <body> <header id="header"> <div class="nvbt iback" onclick="back(true);"></div> <div class="nvtt">Runtime</div> <div class="nvbt idoc" onclick="openDoc('Runtime Document','/doc/runtime.html')"></div> </header> <div id="dcontent" class="dcontent"> <br/> <div class="button" onclick="clicked('runtime_launch.html',true);"> 调用第三方程序 </div> <br/> <ul class="dlist"> <li class="ditem" onclick="getVersion()">获取版本信息</li> <li class="ditem" onclick="getArguments()">获取启动信息</li> <li class="ditem" onclick="restartApp()">重启当前应用</li> <li class="ditem" onclick="getWidgetInfo()">获取当前应用的基本属性</li> <li class="ditem" onclick="setBadge()">设置程序图标右上角数字</li> <li class="ditem" onclick="clearBadge()">清除程序图标右上角数字</li> <li class="ditem" onclick="exitApp()">退出当前应用</li> <!--li class="ditem" onclick="updateApp()">WGTU Update</li--> </ul> </div> <div id="output"> Runtime管理程序运行时环境,可用于获取程序的各种信息、与第三方程序通讯等。 </div> </body> <script type="text/javascript" src="../js/immersed.js" ></script> </html>
NSStringDong/XlvrenCharge
XlvrenProject_Html/XlvrenCharge/plus/runtime.html
HTML
gpl-2.0
4,446
<?php /** * @version SVN $Id: default.php 1630 2013-08-15 09:50:14Z dhorsfall $ * @package hwdMediaShare * @copyright Copyright (C) 2011 Highwood Design Limited. All rights reserved. * @license GNU General Public License http://www.gnu.org/copyleft/gpl.html * @author Dave Horsfall * @since 14-Nov-2011 21:01:30 */ // No direct access to this file defined('_JEXEC') or die('Restricted access'); $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); $user = JFactory::getUser(); $canAdd = $user->authorise('core.create', 'com_hwdmediashare'); ?> <form action="<?php echo htmlspecialchars(JFactory::getURI()->toString()); ?>" method="post" name="adminForm" id="adminForm"> <div id="hwd-container"> <a name="top" id="top"></a> <!-- Media Navigation --> <?php echo hwdMediaShareHelperNavigation::getInternalNavigation(); ?> <!-- Media Header --> <div class="media-header"> <h2 class="media-user-title"><?php echo JText::_('COM_HWDMS_USER_CHANNELS'); ?></h2> <!-- View Type --> <ul class="media-category-ls"> <?php if ($this->params->get('list_details_button') != 'hide') :?><li><a href="<?php echo JRoute::_(hwdMediaShareHelperRoute::getSelfRoute('details')); ?>" class="ls-detail" title="<?php echo JText::_('COM_HWDMS_DETAILS'); ?>"><?php echo JText::_('COM_HWDMS_DETAILS'); ?></a></li><?php endif; ?> <?php if ($this->params->get('list_list_button') != 'hide') :?><li><a href="<?php echo JRoute::_(hwdMediaShareHelperRoute::getSelfRoute('list')); ?>" class="ls-list" title="<?php echo JText::_('COM_HWDMS_LIST'); ?>"><?php echo JText::_('COM_HWDMS_LIST'); ?></a></li><?php endif; ?> <?php if ($user->id) :?> <li><a href="<?php echo JRoute::_('index.php?option=com_hwdmediashare&view=user&id='.$user->id); ?>" title="<?php echo JText::_('COM_HWDMS_MY_CHANNEL'); ?>"><?php echo JText::_('COM_HWDMS_MY_CHANNEL'); ?></a> </li> <?php endif; ?> </ul> <div class="clear"></div> <!-- Search Filters --> <fieldset class="filters"> <?php if ($this->params->get('list_filter_search') != 'hide') :?> <legend class="hidelabeltxt"> <?php echo JText::_('JGLOBAL_FILTER_LABEL'); ?> </legend> <div class="filter-search"> <label class="filter-search-lbl" for="filter_search"><?php echo JText::_('JSEARCH_FILTER_LABEL'); ?></label> <input type="text" name="filter_search" id="filter_search" class="inputbox" value="<?php echo $this->escape($this->state->get('filter.search')); ?>" title="<?php echo JText::_('COM_HWDMS_SEARCH_IN_TITLE'); ?>" /> <button type="submit" class="button"><?php echo JText::_('JSEARCH_FILTER_SUBMIT'); ?></button> <button type="button" class="button" onclick="document.id('filter_search').value='';this.form.submit();"><?php echo JText::_('JSEARCH_FILTER_CLEAR'); ?></button> </div> <?php endif; ?> <?php if ($this->params->get('list_filter_pagination') != 'hide') : ?> <div class="display-limit"> <label class="filter-pagination-lbl" for="filter_pagination"><?php echo JText::_('JGLOBAL_DISPLAY_NUM'); ?></label> <?php echo $this->pagination->getLimitBox(); ?> </div> <?php endif; ?> <?php if ($this->display != 'list' && $this->params->get('list_filter_ordering') != 'hide') :?> <div class="display-limit"> <label class="filter-order-lbl" for="filter_order"><?php echo JText::_('COM_HWDMS_ORDER'); ?></label> <select onchange="this.form.submit()" size="1" class="inputbox" name="filter_order" id="filter_order"> <option value="a.created"<?php echo ($listOrder == 'a.created' ? ' selected="selected"' : false); ?>><?php echo JText::_( 'COM_HWDMS_OPTION_MOST_RECENT' ); ?></option> <?php if ($this->params->get('list_meta_hits') != 'hide') :?><option value="a.hits"<?php echo ($listOrder == 'a.hits' ? ' selected="selected"' : false); ?>><?php echo JText::_( 'COM_HWDMS_OPTION_MOST_HITS' ); ?></option><?php endif; ?> <?php if ($this->params->get('list_meta_likes') != 'hide') :?><option value="a.likes"<?php echo ($listOrder == 'a.likes' ? ' selected="selected"' : false); ?>><?php echo JText::_( 'COM_HWDMS_OPTION_MOST_LIKES' ); ?></option><?php endif; ?> <?php if ($this->params->get('list_meta_likes') != 'hide') :?><option value="a.dislikes"<?php echo ($listOrder == 'a.dislikes' ? ' selected="selected"' : false); ?>><?php echo JText::_( 'COM_HWDMS_OPTION_MOST_DISLIKES' ); ?></option><?php endif; ?> <option value="a.modified"<?php echo ($listOrder == 'a.modified' ? ' selected="selected"' : false); ?>><?php echo JText::_( 'COM_HWDMS_OPTION_RECENTLY_MODIFIED' ); ?></option> <?php if ($this->params->get('list_meta_title') != 'hide') :?><option value="title"<?php echo ($listOrder == 'title' ? ' selected="selected"' : false); ?>><?php echo JText::_( 'COM_HWDMS_OPTION_TITLE_ALPHABETICAL' ); ?></option><?php endif; ?> <option value="random"<?php echo ($listOrder == 'random' ? ' selected="selected"' : false); ?>><?php echo JText::_( 'COM_HWDMS_OPTION_RANDOM' ); ?></option> </select> </div> <?php else: ?> <input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>" /> <?php endif; ?> <!-- @TODO add hidden inputs --> <input type="hidden" name="task" value="" /> <input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>" /> <input type="hidden" name="limitstart" value="" /> </fieldset> <div class="clear"></div> </div> <?php echo $this->loadTemplate($this->display); ?> <!-- Pagination --> <div class="pagination"> <?php echo $this->pagination->getPagesLinks(); ?> </div> </div> </form>
Jbouska419/craftsman
templates/hybrid/html/com_hwdmediashare/src/users/default.php
PHP
gpl-2.0
5,891
<?php /** * @file * Unit testing. */ require_once "../../../unit-testing/boleto.test.php"; class TestOf341 extends BoletoTestCase{ protected $mockingArguments; function mockingArguments() { $this->mockingArguments = array( array( 'bank_code' => '341', 'agencia' => 1234, 'carteira' => '157', ), ); } }
glauberportella/Boleto
bancos/341/unit-testing/simpletest.php
PHP
gpl-2.0
355
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ts=4:sw=4:expandtab: # Copyright 2008 Mark Mitchell # License: see __license__ below. __doc__ = """ Reads a GraphicsMagick source file and parses the specially formatted comment blocks which precede each function and writes the information obtained from the comment block into a reStructuredText file. Usage: format_c_api_docs.py [options] SRCFILE OUTFILE SRCFILE is the path to a Graphicsmagick API .c file. For example: ./magick/animate.c OUTFILE is the path where the reStructuredText file is written. Options: -h --help -- Print this help message -w --whatis-file -- The path to a file containing "whatis" information for the source files. The format of this file is: * one line per source file * source filename (without directory paths) and whatis text are separated by whitespace * blank lines are ignored * lines starting with '#' are ignored -i --include-rst -- Comma-separated list of file paths to be objects of reST ..include:: directives inserted in OUTFILE. The default is the single file 'api_hyperlinks.rst' Example of whatis file format: animate.c Interactively animate an image sequence annotate.c Annotate an image with text """ __copyright__ = "2008, Mark Mitchell" __license__ = """ Copyright 2008, Mark Mitchell Permission is hereby granted, free of charge, to any person obtaining a copy of this Software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with Software or the use or other dealings in the Software. """ import sys import getopt import os, os.path import re import textwrap # Key words to replace with HTML links keywords = { 'AffineMatrix' : '`AffineMatrix`_', 'BlobInfo' : '`BlobInfo`_', 'Cache' : '`Cache`_', 'ChannelType' : '`ChannelType`_', 'ChromaticityInfo' : '`ChromaticityInfo`_', 'ClassType' : '`ClassType`_', 'ClipPathUnits' : '`ClipPathUnits`_', 'ColorPacket' : '`ColorPacket`_', 'ColorspaceType' : '`ColorspaceType`_', 'ComplianceType' : '`ComplianceType`_', 'CompositeOperator' : '`CompositeOperator`_', 'CompressionType' : '`CompressionType`_', 'DecorationType' : '`DecorationType`_', 'DrawContext' : '`DrawContext`_', 'DrawInfo' : '`DrawInfo`_', 'ErrorHandler' : '`ErrorHandler`_', 'ExceptionInfo' : '`ExceptionInfo`_', 'ExceptionType' : '`ExceptionType`_', 'FillRule' : '`FillRule`_', 'FilterTypes' : '`FilterTypes`_', 'FrameInfo' : '`FrameInfo`_', 'GravityType' : '`GravityType`_', 'Image' : '`Image`_', 'ImageInfo' : '`ImageInfo`_', 'ImageType' : '`ImageType`_', 'InterlaceType' : '`InterlaceType`_', 'LayerType' : '`LayerType`_', 'MagickInfo' : '`MagickInfo`_', 'MonitorHandler' : '`MonitorHandler`_', 'MontageInfo' : '`MontageInfo`_', 'NoiseType' : '`NoiseType`_', 'PaintMethod' : '`PaintMethod`_', 'PixelPacket' : '`PixelPacket`_', 'PointInfo' : '`PointInfo`_', 'ProfileInfo' : '`ProfileInfo`_', 'QuantizeInfo' : '`QuantizeInfo`_', 'Quantum' : '`Quantum`_', 'QuantumType' : '`QuantumType`_', 'RectangleInfo' : '`RectangleInfo`_', 'RegistryType' : '`RegistryType`_', 'RenderingIntent' : '`RenderingIntent`_', 'ResolutionType' : '`ResolutionType`_', 'ResourceType' : '`ResourceType`_', 'SegmentInfo' : '`SegmentInfo`_', 'SignatureInfo' : '`SignatureInfo`_', 'StorageType' : '`StorageType`_', 'StreamHandler' : '`StreamHandler`_', 'StretchType' : '`StretchType`_', 'StyleType' : '`StyleType`_', 'TypeMetric' : '`TypeMetric`_', 'ViewInfo' : '`ViewInfo`_', 'VirtualPixelMethod' : '`VirtualPixelMethod`_', 'MagickXResourceInfo' : '`MagickXResourceInfo`_', } state_init = 0 state_found_fcncomment = 1 state_found_fcntitle = 2 state_found_fcndoc = 3 state_more_prototype = 4 state_found_prototype = 5 state_found_private = 6 state_parmdescr = 7 def warn(msg): print >> sys.stderr, msg def debugtrace(msg): print >> sys.stdout, msg def nodebugtrace(msg): pass dtrace = nodebugtrace #dtrace = debugtrace # extract and save function title. example: # + X M a g i c k C o m m a n d % # % X A n i m a t e B a c k g r o u n d I m a g e % # Lines starting with '+' are private APIs which should not appear in # in the output. re_func_title = re.compile(r'^[+|%]\s+((\w )+)\s*%') def proto_pretty(line): """fixes up inconsistent spaces in C function prototypes""" line = re.sub(r',', ' , ', line) line = re.sub(r'\(', ' ( ', line) line = re.sub(r'\)', ' ) ', line) line = re.sub(r'\*', ' * ', line) line = re.sub(r'\s+', ' ', line) line = re.sub(r'\(\s+\*', '(*', line) line = re.sub(r' ,', ',', line) line = re.sub(r' \(', '(', line) line = re.sub(r'\) ', ')', line) line = re.sub(r' \* ', ' *', line) line = re.sub('^\s*', '', line) return line class Paragraph: "Paragraphs consist of one or more lines of text." def __init__(self): self.lines = [] def __str__(self): #return '\n'.join(self.lines) return '\n'.join([line.strip() for line in self.lines]) class Prototype: def __init__(self): self.lines = [] def __str__(self): proto = ' '.join(self.lines) proto = proto_pretty(proto) # escape all the '*' chars proto = re.sub(r'\*', '\\*', proto) # escape all the '_' chars proto = re.sub(r'_', '\\_', proto) # now replace keywords with hyperlinks for k,v in keywords.iteritems(): proto = re.sub(r'^%s ' % k, '%s ' % v, proto) proto = re.sub(r' %s ' % k, ' %s ' % v, proto) # make some attempt to wrap the text nicely openparen_index = proto.find('(') if openparen_index > 0: fcn = proto[:openparen_index+1] indent_len = len(fcn) + 3 toomuch = (2 * fcn.count('\\')) + (3 * fcn.count('`_')) if toomuch > 0: # account for the space following the opening paren toomuch -= 1 indent_len -= toomuch params = proto[openparen_index+1:].split(',') params = [p.strip() for p in params] max_param_len = 0 for x in params: if len(x) > max_param_len: max_param_len = len(x) wrap_width = max(96, max_param_len + indent_len) proto_lines = [] line = fcn + ' ' while params: x = params.pop(0) if len(line) + len(x) > wrap_width: proto_lines.append(line) line = ' ' * indent_len line += x if params: line += ', ' proto_lines.append(line) proto = '\n '.join(proto_lines) return ".. parsed-literal::\n\n %s" % proto class ListItem: """List items are used for parameter descriptions, and consist of the parameter name and one or more lines of description text.""" def __init__(self, name): self.name = name self.lines = [] def __str__(self): s = [] s.append('%s:' % self.name) for line in self.lines: s.append(' %s' % line.strip()) return '\n'.join(s) class Function: def __init__(self, name): self.name = name self.prototype = None # Description is a list, the items of which are either Paragraph or # ListItem or Prototype instances. self.description = [] def __str__(self): lines = [] lines.append('') lines.append('') lines.append(self.name) lines.append('=' * len(self.name)) lines.append('') lines.append('Synopsis') lines.append('--------') lines.append(str(self.prototype)) lines.append('') lines.append('Description') lines.append('-----------') for item in self.description: lines.append(str(item)) lines.append('') return '\n'.join(lines) def parse(srcfilepath): list_item = None proto = None para = None func = None functions = [] state = state_init linecnt = 0 ftitle = None f = file(srcfilepath, 'r') for line in f: linecnt += 1 if not (line.startswith('%') or line.startswith('+') or re.search(r'\*/', line)): continue line = line.strip() if state == state_init: # Find first line of function title/comment block if line.startswith('%%%%%%%%'): dtrace('Line %d: start of function comment block ############' % linecnt) state = state_found_fcncomment continue elif state == state_found_fcncomment: # Search for the function name, with spaces between each letter if line.startswith('%%%%%%%%'): warn('Line %d: WARNING: no function name found, found start of function comment block instead.' % linecnt) state = state_init continue m = re_func_title.search(line) if m: if line.startswith('+'): dtrace('Line %d: private API' % linecnt) # private API, skip it state = state_found_private else: # public API, process it ftitle = re.sub(' ', '', m.group(1)) dtrace('Line %d: public API %s' % (linecnt, ftitle)) func = Function(ftitle) functions.append(func) state = state_found_fcntitle continue elif state == state_found_private: # skip to end of function title block if line.startswith('%%%%%%%%'): dtrace('Line %d: end of private function comment block' % linecnt) state = state_init continue elif state == state_found_fcntitle: # skip to first line following end of function title block. # lines of the function title block start with and end with '%'. if not re.match(r'%.+%', line): dtrace('Line %d: end of public function comment block %s' % (linecnt, ftitle)) state = state_found_fcndoc # fall through elif state == state_found_fcndoc: # extract function prototype if line.startswith('% '): line = re.sub(r'^%\s{0,2}', '', line, 1) # if empty args (), it's not the prototype, but the one-line summary if re.search(r'%s\(\)' % ftitle, line): if para is None: dtrace('Line %d: found_fcndoc start paragraph ()' % linecnt) para = Paragraph() func.description.append(para) para.lines.append(line) # is this only line of prototype? elif re.search(r'%s\([^)]+\)$' % ftitle, line): if para: dtrace('Line %d: found_fcndoc end paragraph by proto ()' % linecnt) para = None dtrace('Line %d: one-line prototype' % linecnt) proto = Prototype() proto.lines.append(line) func.description.append(proto) func.prototype = proto proto = None state = state_found_prototype # is this first line of multiline prototype? elif re.search(r'%s\([^)]*$' % ftitle, line): if para: dtrace('Line %d: found_fcndoc end paragraph by proto (' % linecnt) para = None dtrace('Line %d: first line of multi-line prototype' % linecnt) proto = Prototype() proto.lines.append(line) func.description.append(proto) func.prototype = proto state = state_more_prototype else: if para is None: dtrace('Line %d: found_fcndoc start paragraph' % linecnt) para = Paragraph() func.description.append(para) para.lines.append(line) else: if line.startswith('%%%%%%%%'): warn('Line %d: WARNING: no prototype found for %s, found start of function comment block instead.' % (linecnt, ftitle)) state = state_found_fcncomment continue if line.strip() == '%': # empty line terminates paragraph if para: dtrace('Line %d: found_fcndoc end paragraph by blank line' % linecnt) para = None if proto: dtrace('Line %d: found_fcndoc end proto by blank line' % linecnt) proto = None continue elif state == state_more_prototype: if re.match(r'%.+%', line): # really this should raise a warning of "incomplete prototype" continue line = re.sub(r'^%\s{0,2}', '', line, 1) if re.search(r'^\s*$', line): dtrace('Line %d: end of more prototype' % linecnt) state = state_found_prototype else: func.prototype.lines.append(line) continue elif state == state_found_prototype: dtrace('Line %d: found prototype of function %s' % (linecnt, ftitle)) func.prototype.lines.append(';') #print 'Function %s' % func.name #print 'Synopsis' #print ' '.join(func.prototype) #print # Process parm description. # Description consists of two kinds of texts: paragraphs, and lists. # Lists consist of list items. List items are one or more lines. # List items are separated by blank lines. The first line of a list # item starts with 'o '. # Paragraphs consist of one or more lines which don't start with 'o '. # Paragraphs are separated from each other and from adjacent list items # by blank lines. # In theory, a line which starts with 'o ' which is not preceded by a # blank line is illegal syntax. para = None state = state_parmdescr # fall through elif state == state_parmdescr: if line.endswith('*/'): # end of function comment block dtrace('Line %d: end of parmdescr ************' % linecnt) if list_item: func.description.append(list_item) list_item = None if para: func.description.append(para) dtrace('Line %d: parmdescr end paragraph ()' % linecnt) para = None func = None state = state_init continue line = re.sub(r'^%\s{0,2}', '', line, 1) if line: # look for list item, which starts with 'o' m = re.search(r'^\s+o\s+([^:]+:|o|[0-9]\.)\s(.*)', line) if m: # first line of list item if list_item: # if blank lines separate list items, this should never evaluate true dtrace('Line %d: surprising end of list item' % linecnt) func.description.append(list_item) list_item = None dtrace('Line %d: start list item' % linecnt) list_item = ListItem(m.group(1).strip().rstrip(':')) list_item.lines.append(m.group(2)) else: # either a line of paragraph or subsequent line of list item if list_item: # subsequent line of list item list_item.lines.append(line) else: # line of paragraph if list_item: # if blank lines after list items, this should never evaluate true dtrace('Line %d: end of list item, end of list' % linecnt) func.description.append(list_item) list_item = None if para is None: dtrace('Line %d: parmdescr start paragraph' % linecnt) para = Paragraph() para.lines.append(line) else: # empty line, two cases: # 1. terminate multi-line list item # 2. terminate multi-line paragraph if list_item: dtrace('Line %d: parmdescr end of list item by blank line' % linecnt) func.description.append(list_item) list_item = None elif para: # terminate any paragraph dtrace('Line %d: parmdescr end of paragraph by blank line' % linecnt) func.description.append(para) para = None continue f.close() return functions def process_srcfile(srcfilepath, basename, whatis, outfile, include_rst): """outfile is a file object open for writing""" functions = parse(srcfilepath) print >> outfile, "=" * len(basename) print >> outfile, basename print >> outfile, "=" * len(basename) if whatis: print >> outfile, "-" * len(whatis) print >> outfile, whatis print >> outfile, "-" * len(whatis) print >> outfile print >> outfile, '.. contents:: :depth: 1' print >> outfile for x in include_rst: print >> outfile, '.. include:: %s' % x print >> outfile # print all functions found in this source file for func in functions: print >> outfile, func #para = para.strip() # trim leading and trailing whitespace #para = re.sub(r'\s+', ' ', para) # canonicalize inner whitespace #para = re.sub(r"""([a-zA-Z0-9][.!?][)'"]*) """, '\1 ', para) # Fix sentence ends def find_val(key, keyval_file): val = None f = file(keyval_file, 'r') cnt = 0 for line in f: cnt += 1 if not line.strip(): continue if line.startswith('#'): continue try: k, v = line.split(None, 1) except ValueError: print >> sys.stderr, "Line %u of %s: improper format" % (cnt, keyval_file) return None if k == key: val = v break f.close() return val.strip() def main(argv=None): if argv is None: argv = sys.argv[1:] # parse command line options try: opts, posn_args = getopt.getopt(argv, 'hw:i:', ['help', 'whatis-file=', 'include-rst=', ]) except getopt.GetoptError, msg: print msg print __doc__ return 1 # process options whatis_file = None include_rst = ['api_hyperlinks.rst'] for opt, val in opts: if opt in ("-h", "--help"): print __doc__ return 0 if opt in ("-w", "--whatis-file"): whatis_file = val if opt in ("-i", "--include-rst"): include_rst = [x for x in val.split(',') if x] if len(posn_args) != 2: print >> sys.stderr, 'Missing arguments' print >> sys.stderr, __doc__ return 1 srcfile_path = posn_args[0] outfile_path = posn_args[1] srcfile = os.path.basename(srcfile_path) base, ext = os.path.splitext(srcfile) if whatis_file: whatis = find_val(srcfile, whatis_file) else: whatis = None fout = file(outfile_path, 'w') process_srcfile(srcfile_path, base, whatis, fout, include_rst) fout.close() return 0 if __name__ == '__main__': sys.exit(main())
kazuyaujihara/osra_vs
GraphicsMagick/scripts/format_c_api_doc.py
Python
gpl-2.0
21,967
showWord(["n.","pwèl. Cheve tou kout ki sou po , anbabra epi sou pibis moun. Gason gen pwal sou lestomak yo men fi pa genyen." ])
georgejhunt/HaitiDictionary.activity
data/words/pwal.js
JavaScript
gpl-2.0
130
import sys def bye(): sys.exit(40) # Crucial error: abort now! try: bye() except Exception: print('got it') # Oops--we ignored the exit print('continuing...')
simontakite/sysadmin
pythonscripts/learningPython/exiter2.py
Python
gpl-2.0
208
<?php // No direct access to this file defined('_JEXEC') or die('Restricted access'); // import the Joomla modellist library jimport('joomla.application.component.modeladmin'); /** * HelloWorldList Model */ class RealEstateModelPayment extends JModelAdmin { /* * param JForm $form The JForm instance for the view being edited * param array $data The form data as derived from the view (may be empty) * * @return void * */ protected function preprocessForm(JForm $form, $data) { // Get the input form data $input = JFactory::getApplication()->input; // And tease out whether the use_invoice_address field is ticked or not $formData = $input->get('jform', array(), 'array'); $filter = JFilterInput::getInstance(); $use_invoice_address = $filter->clean($formData['use_invoice_address'], 'int'); if ($use_invoice_address) { // Make the billing details optional $fieldset = $form->getFieldset('billing-details'); foreach ($fieldset as $field) { $form->setFieldAttribute($field->fieldname, 'required', 'false'); } } } /* * Method to get the payment form * */ public function getPaymentForm($data = array(), $loadData = true) { JForm::addFormPath(JPATH_LIBRARIES . '/frenchconnections/forms'); $form = $this->loadForm('com_realestate', 'payment', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } $data = JFactory::getApplication()->getUserState('com_realestate.renewal.data', array()); $data['id'] = $id = $this->getState($this->getName() . '.id', ''); $form->bind($data); return $form; } public function getForm($data = array(), $loadData = true) { JForm::addFormPath(JPATH_LIBRARIES . '/frenchconnections/forms'); $form = $this->loadForm('account', 'account', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } return $form; } public function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_realestate.edit.listing.data', array()); // Which layout are we working on? $layout = JFactory::getApplication()->input->get('layout', '', 'string'); // If this is a the payment layout/view then we need to pre-load some data into the form. // In particular, we need the property listing id. if (empty($data) && $layout == 'payment') { // Not sure what this is doing! } return $data; } public function getTable($type = 'Property', $prefix = 'RealEstateTable', $options = array()) { return JTable::getInstance($type, $prefix, $options); } public function getBillingDetails($data = array()) { $model = JModelLegacy::getInstance('Property', 'RealEstateModel', array('ignore_request' => true)); $property_id = $data['id']; $property = $model->getItem($property_id); $owner_id = $property->created_by; $user = JFactory::getUser($owner_id); // Get the dispatcher and load the user's plugins. $dispatcher = JEventDispatcher::getInstance(); JPluginHelper::importPlugin('user'); $user_data = new JObject; $user_data->id = $owner_id; // Trigger the data preparation event. $dispatcher->trigger('onContentPrepareData', array('com_users.user', &$user_data)); $data['BillingFirstnames'] = $user_data->firstname; $data['BillingSurname'] = $user_data->surname; $data['BillingAddress1'] = $user_data->address1; $data['BillingAddress2'] = $user_data->address2; $data['BillingCity'] = $user_data->city; $data['BillingPostCode'] = $user_data->postal_code; $data['BillingEmailAddress'] = $user->email; $data['BillingCountry'] = $user_data->country; $data['BillingState'] = $user_data->state; return $data; } }
adster101/French-Connections-
administrator/components/com_realestate/models/payment.php
PHP
gpl-2.0
3,928
package com.neusoft.pm.model; import java.sql.Date; public class Lib { private int id; private String name; private String sex; private String birthday; private String idcard; private String politics; private String nation; private String phone; private String email; private String height; private String bloodtype; private String marriage; private String hometown; private String birthland; private String school; private String graduationdate; private String major; private String edubackground; private String degree; public Lib() { super(); // TODO Auto-generated constructor stub } public Lib(int id, String name, String sex, String birthday, String idcard, String politics, String nation, String phone, String email, String height, String bloodtype, String marriage, String hometown, String birthland, String school, String graduationdate, String major, String edubackground, String degree) { super(); this.id = id; this.name = name; this.sex = sex; this.birthday = birthday; this.idcard = idcard; this.politics = politics; this.nation = nation; this.phone = phone; this.email = email; this.height = height; this.bloodtype = bloodtype; this.marriage = marriage; this.hometown = hometown; this.birthland = birthland; this.school = school; this.graduationdate = graduationdate; this.major = major; this.edubackground = edubackground; this.degree = degree; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getIdcard() { return idcard; } public void setIdcard(String idcard) { this.idcard = idcard; } public String getPolitics() { return politics; } public void setPolitics(String politics) { this.politics = politics; } public String getNation() { return nation; } public void setNation(String nation) { this.nation = nation; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } public String getBloodtype() { return bloodtype; } public void setBloodtype(String bloodtype) { this.bloodtype = bloodtype; } public String getMarriage() { return marriage; } public void setMarriage(String marriage) { this.marriage = marriage; } public String getHometown() { return hometown; } public void setHometown(String hometown) { this.hometown = hometown; } public String getBirthland() { return birthland; } public void setBirthland(String birthland) { this.birthland = birthland; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public String getGraduationdate() { return graduationdate; } public void setGraduationdate(String graduationdate) { this.graduationdate = graduationdate; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getEdubackground() { return edubackground; } public void setEdubackground(String edubackground) { this.edubackground = edubackground; } public String getDegree() { return degree; } public void setDegree(String degree) { this.degree = degree; } }
treejames/HRS
src/com/neusoft/pm/model/Lib.java
Java
gpl-2.0
3,748
<?php return [ /* |-------------------------------------------------------------------------- | Head Page |-------------------------------------------------------------------------- | | It is specified in which view the html codes in the [head] tags will be | placed. | */ 'headPage' => '', # string or array /* |-------------------------------------------------------------------------- | Head Page |-------------------------------------------------------------------------- | | It is specified in which view the html codes in the [body] tags will be | placed. | */ 'bodyPage' => '', /* |-------------------------------------------------------------------------- | Document Type |-------------------------------------------------------------------------- | | The type of document to use. | | Types: html5 , html4Frameset , html4Transitional , html4Strict | xhtml11, xhtml1Frameset, xhtml1Transitional, xhtml1Strict | */ 'docType' => 'html5', /* |-------------------------------------------------------------------------- | Title |-------------------------------------------------------------------------- | | Edit the [title] tag. | */ 'title' => '', /* |-------------------------------------------------------------------------- | Content |-------------------------------------------------------------------------- | | The language and charset of your content. | */ 'content' => [ 'language' => 'tr', 'charset' => ['utf-8'] ], /* |-------------------------------------------------------------------------- | Resources |-------------------------------------------------------------------------- | | The settings below are just like using the | Import::theme/plugin/font/style/script() method. | */ 'theme' => [ 'name' => [], 'recursive' => false ], 'plugin' => [ 'name' => '', 'recursive' => false ], /* |-------------------------------------------------------------------------- | Browser Icon |-------------------------------------------------------------------------- | | The browser icon to be used. | */ 'browserIcon' => FILES_DIR . 'favicon.ico', /* |-------------------------------------------------------------------------- | Background Image |-------------------------------------------------------------------------- | | The background image to be used. | */ 'backgroundImage' => '', /* |-------------------------------------------------------------------------- | Attributes |-------------------------------------------------------------------------- | | Adds a property value pair to the [html], [head] and [body] tags. | | ['id' => 'body', 'name' => 'Body'] <body id="body" name="Body"> | */ 'attributes' => [ 'html' => [], 'head' => [], 'body' => [] ], /* |-------------------------------------------------------------------------- | Meta |-------------------------------------------------------------------------- | | Used to edit meta tags. | */ 'meta' => [ 'name:description' => '', 'name:author' => '', 'name:designer' => '', 'name:distribution' => '', 'name:keywords' => '', 'name:abstract' => '', 'name:copyright' => '', 'name:expires' => '', 'name:pragma' => '', 'name:revisit-after' => '', 'http:cache-control' => '', 'http:refresh' => '', 'name:robots' => [] ] ];
SAFAKAYDIN/DenemeSafak
Config/Masterpage.php
PHP
gpl-2.0
3,903
/** * Name: base.css * * T.O.C * * #CssReset * #Typography * #Links * #Lists * #Images * #Tables * #Forms * #Misc */ /* ========================================================================== #CssReset ========================================================================== */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } /* HTML5 display-role reset for older browsers */ article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; } /** * 1. Always force vertical scroll * 2. Prevent iOS text size adjust after orientation change, without disabling user zoom. * 3. For animations */ html { font-size: 100%; overflow-y: scroll; /* 1 */ -ms-text-size-adjust: 100%; /* 2 */ -webkit-text-size-adjust: 100%; /* 2 */ -webkit-font-smoothing: antialiased; overflow-x: hidden; /* 3 */ } /* ========================================================================== #Typography ========================================================================== */ /** * 1. For animations */ body { overflow-x: hidden; /* 1 */ background-color: #fff; color: #5e5e5e; font: 14px 'Open Sans', Arial, sans-serif; line-height: 24px; font-weight: 300; } h1, h2, h3, h4, h5, h6 { color: #5e5e5e; font-family: 'Open Sans', Arial, sans-serif; font-weight: 400; } h1 a, h2 a, h3 a, h4 a, h5 a, h6 a { font-weight: inherit; } h1 { margin-bottom: 14px; font-size: 30px; line-height: 36px; } h2 { margin-bottom: 10px; font-size: 24px; line-height: 40px; } h3 { margin-bottom: 8px; font-size: 18px; line-height: 24px; } h4 { margin-bottom: 4px; font-size: 16px; line-height: 30px; } h5 { font-size: 14px; line-height: 24px; } h6 { font-size: 12px; line-height: 21px; } p { margin-bottom: 20px; } em { font-style: italic; } strong { font-weight: 600; } small { font-size: 70%; } sub { vertical-align: sub; font-size: 75%; } sup { vertical-align: super; font-size: 75%; } abbr[title] { border-bottom: 1px dotted #999; cursor: help; } address { display: block; margin-bottom: 20px; } blockquote {} blockquote p { font-style: italic; } blockquote span { display: block; margin-top: 5px; color: #999999; } blockquote span:before { content: "\2013 \00A0"; } hr { height: 0; border: solid #efefef; border-width: 1px 0 0 0; margin: 30px 0; } code, pre { -webkit-border-radius: 3px; border-radius: 3px; font-family: Monaco, Menlo, Consolas, "Courier New", monospace; } code { padding: 1px 4px; border: 1px solid #e1e1e8; background-color: #f7f7f7; color: #d14; } pre { overflow-x: auto; display: block; padding: 20px; border: 1px solid #e1e1e8; margin-bottom: 20px; white-space: pre-wrap; background-color: #f7f7f7; } /* Typography Helper Classes */ /** * <div class="hr"></div> acts like an <hr /> */ .hr { border-top: 1px solid #efefef; margin: 30px 0; } .text-left { text-align: left; } .text-right { text-align: right; } .text-center { text-align: center; } .text-highlight { color: #ea6872; } .text-uppercase { text-transform: uppercase; } .mute{ color: #aaa; } p.last, h1.last, h2.last, h3.last, h4.last, h5.last, address.last { margin-bottom: 0; } /* #Links ========================================================================== */ a, a:visited { color: #ea6872; text-decoration: none; } /** * 1. Remove the gray background color from active links in IE 10. */ a:active { background: transparent; /* 1 */ } a:hover, a:focus { outline: 0; text-decoration: underline; } /* #Lists ========================================================================== */ ul, ol { margin-bottom: 20px; list-style-position: inside; } ul ul, ul ol, ol ol, ol ul { margin-bottom: 0; margin-left: 30px; } li {} ul { list-style-type: disc; } ol { list-style-type: decimal; } /* List Helper Classes */ ul.last, ol.last { margin-bottom: 0; } /* #Images ========================================================================== */ img { border: none; } /* Images Helper Classes */ .img-align-left { float: left; margin: 5px 10px 0 0; } .img-align-right { float: right; margin: 5px 0 0 10px; } /* #Tables ========================================================================== */ table { width: 100%; margin-bottom: 20px; border-collapse: collapse; border-spacing: 0; background-color: transparent; } caption { margin: 20px 0; text-align: center; } table th, table td { padding: 15px 8px; border-top: 1px solid #acacac; text-align: center; vertical-align: top; } table th { border-top: none; background-color: #ea6872; color: #fff; font-size: 16px; font-weight: 700; } table thead th { vertical-align: bottom; } /* #Forms ========================================================================== */ form {} fieldset {} form p {} label { display: block; margin-bottom: 5px; } label span { color: #ff0000; } select, button, input[type="button"], input[type="reset"], input[type="submit"], input[type="radio"], input[type="checkbox"] { cursor: pointer; } /* * 1. stop safari from overwriting input styles */ input, textarea, select { -webkit-appearance: none; /* 1 */ display: block; max-width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 10px; border: 1px solid #acacac; -webkit-border-radius: 10px; border-radius: 10px; margin-bottom: 10px; background: transparent; color: #666; font: 12px 'Open Sans', Arial, sans-serif; } input[type="text"]:focus, input[type="email"]:focus, input[type="url"]:focus, textarea:focus { border-color: #888; outline: 0; } select { height: 40px; border-radius: 5px; } select:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } textarea { min-height: 100px; overflow: auto; } .radio, .checkbox { min-height: 18px; padding-left: 18px; } .radio input[type="radio"], .checkbox input[type="checkbox"] { float: left; margin-left: -18px; } input:-moz-placeholder, textarea:-moz-placeholder { color: #ccc; } input:-ms-input-placeholder, textarea:-ms-input-placeholder { color: #ccc; } input::-webkit-input-placeholder, textarea::-webkit-input-placeholder { color: #ccc; } /* #Misc ========================================================================== */ .javascript-required { padding: 15px 0; background-color: #f00; color: #fff; text-align:center; font-weight: bold; }
olabimaker/siteolabi
doc/themeforest/pearl/01.html-website/_layout/css/base.css
CSS
gpl-2.0
7,876
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="x-ua-compatible" content="IE=edge,chrome=1"> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="author" content="Sheryl van Heerden"> <meta name="keywords" content=""> <meta name="description" content="Sunshine Coast Wedding"> <meta name="robots" content="all"> <link href="../favicon.ico" rel="shortcut icon" type="image/x-icon" /> <?php echo html::style(CLIENTPATH . "css" . DIRECTORY_SEPARATOR . JsonApiApplication::$config -> load("application") -> as_array()["default"]["theme"] . DIRECTORY_SEPARATOR . "app.css"); ?> <title></title> </head> <body> <div data-ui-google-analytics></div> <div data-ui-main-menu data-ng-cloak></div> <div data-ui-overlay data-ng-cloak></div> <div class="wrapper"> <div data-ui-carousel data-ng-if="IsHomePage"></div> <div class="hide-on-all show-on-large" data-ui-breadcrumbs data-displayname-property="data.displayName" data-abstract-proxy-property="data.proxy"></div> <div data-ui-view="content" id="contentUI" data-ng-cloak></div> <div id="root_footer"></div> </div> <div data-ui-footer data-ng-cloak></div> <?php if (count(get_included_files()) == 1) exit("Direct access not permitted."); $attributes = []; if (JsonApiApplication::$environment == JsonApiApplication::DEVELOPMENT) { $attributes["data-main"] = "/JsonApiApplication/client/app/main.js"; $src = "JsonApiApplication/client/lib/requirejs/require.js"; } else { $src = "JsonApiApplication/client/app/main-built.js"; } echo html::script($src, $attributes); ?> </body> </html>
benshez/DreamWeddingCeremomies
JsonApiApplication/server/application/views/Welcome.php
PHP
gpl-2.0
1,934
<?php /** * * info_acp_donation.php [French] * * @package PayPal Donation MOD * @copyright (c) 2013 Skouat * @license http://opensource.org/licenses/gpl-license.php GNU Public License * */ /** * DO NOT CHANGE */ if (!defined('IN_PHPBB')) { exit; } if (empty($lang) || !is_array($lang)) { $lang = array(); } // DEVELOPERS PLEASE NOTE // // All language files should use UTF-8 as their encoding and the files must not contain a BOM. // // Placeholders can now contain order information, e.g. instead of // 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows // translators to re-order the output of data while ensuring it remains correct // // You do not need this where single placeholders are used, e.g. 'Message %d' is fine // equally where a string contains only two placeholders which are used to wrap text // in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine // // Some characters you may want to copy&paste: // ’ « » “ ” … // /** * mode: main */ $lang = array_merge($lang, array( 'ACP_DONATION_MOD' => 'PayPal Donation', )); /** * mode: overview */ $lang = array_merge($lang, array( 'DONATION_OVERVIEW' => 'Général', 'DONATION_WELCOME' => 'Bienvenue sur PayPal Donation MOD', 'DONATION_WELCOME_EXPLAIN' => '', 'DONATION_STATS' => 'Statistics des dons', 'DONATION_INSTALL_DATE' => 'Date d’installation de <strong>PayPal Donation</strong>', 'DONATION_VERSION' => 'Version de <strong>PayPal Donation</strong>', 'INFO_FSOCKOPEN' => 'Fsockopen', 'INFO_CURL' => 'cURL', 'INFO_DETECTED' => 'Détecté', 'INFO_NOT_DETECTED' => 'Non détecté', 'DONATION_VERSION_NOT_UP_TO_DATE_TITLE' => 'Votre installation de PayPal Donation n’est pas à jour.', 'STAT_RESET_DATE' => 'Réinitialiser la date d’installation du MOD', 'STAT_RESET_DATE_EXPLAIN' => 'La réinitialisation de la date d’installation affecte les statistiques du MOD', 'STAT_RESET_DATE_CONFIRM' => 'Etes-vous sûr de vouloir réinitialiser la data d’installation du MOD ?', )); /** * mode: configuration */ $lang = array_merge($lang, array( 'DONATION_CONFIG' => 'Configuration', 'DONATION_CONFIG_EXPLAIN' => '', 'DONATION_SAVED' => 'Les paramètres de PayPal Donation ont été sauvegardés', 'MODE_CURRENCY' => 'devise', 'MODE_DONATION_PAGES' => 'pages de dons', // Global Donation settings 'DONATION_ENABLE' => 'Activer PayPal Donation', 'DONATION_ENABLE_EXPLAIN' => 'Active ou désactive le MOD PayPal Donation.', 'DONATION_ACCOUNT_ID' => 'ID du compte PayPal', 'DONATION_ACCOUNT_ID_EXPLAIN' => 'Saisir l’adresse email ou l’ID de compte marchand.', 'DONATION_DEFAULT_CURRENCY' => 'Devise par défaut', 'DONATION_DEFAULT_CURRENCY_EXPLAIN' => 'Défini quelle devise sera sélectionnée par défaut.', 'DONATION_DEFAULT_VALUE' => 'Valeur de don par défaut', 'DONATION_DEFAULT_VALUE_EXPLAIN' => 'Défini quelle valeur de don sera suggérée par défaut.', 'DONATION_DROPBOX_ENABLE' => 'Activer la liste déroulante', 'DONATION_DROPBOX_ENABLE_EXPLAIN' => 'Si activée, elle remplacera la zonte de texte par un menu déroulant.', 'DONATION_DROPBOX_VALUE' => 'Valeurs de la liste déroulante', 'DONATION_DROPBOX_VALUE_EXPLAIN' => 'Définissez les nombres que vous voulez voir dans la liste déroulante.<br />Séparez chaques valeurs par une virgule (",") et sans espaces.', // PayPal sandbox settings 'SANDBOX_SETTINGS' => 'Paramètres PayPal Sandbox', 'SANDBOX_ENABLE' => 'Tester avec PayPal Sandbox', 'SANDBOX_ENABLE_EXPLAIN' => 'Activez cette option si vous voulez utiliser PayPal Sandbox au lieu des services PayPal.<br />Pratique pour les développeurs/testeurs. Toutes les transactions sont fictives.', 'SANDBOX_FOUNDER_ENABLE' => 'Sandbox pour les fondateurs', 'SANDBOX_FOUNDER_ENABLE_EXPLAIN' => 'Si activé, PayPal Sandbox ne sera visible que par les fondateurs du forum.', 'SANDBOX_ADDRESS' => 'Adresse PayPal Sandbox', 'SANDBOX_ADDRESS_EXPLAIN' => 'Inscrire votre addresse e-mail de vendeur PayPal Sandbox', // Stats Donation settings 'DONATION_STATS_SETTINGS' => 'Paramètres des statistiques', 'DONATION_STATS_INDEX_ENABLE' => 'Statistiques des dons sur l’index', 'DONATION_STATS_INDEX_ENABLE_EXPLAIN' => 'Activez cette option si vous voulez afficher les statistiques des dons sur l’index du forum', 'DONATION_RAISED_ENABLE' => 'Activer dons recueillis', 'DONATION_RAISED' => 'Dons recueillis', 'DONATION_RAISED_EXPLAIN' => 'Inscrire le montant total des dons actuellement reçus', 'DONATION_GOAL_ENABLE' => 'Activer Objectif des dons', 'DONATION_GOAL' => 'Objectif des dons', 'DONATION_GOAL_EXPLAIN' => 'Inscrire le montant total des dons à atteindre', 'DONATION_USED_ENABLE' => 'Activer dons utilisés', 'DONATION_USED' => 'Dons Utilisés', 'DONATION_USED_EXPLAIN' => 'Inscrire le montant des dons déjà utilisés', 'DONATION_CURRENCY_ENABLE' => 'Activer Devise des dons', 'DONATION_CURRENCY_ENABLE_EXPLAIN' => 'Activez cette option, pour rendre visible le Code ISO 4217 de la devise défini par défaut dans les statistiques des dons', )); /** * mode: donation pages * Info: language keys are prefixed with 'DONATION_DP_' for 'DONATION_DONATION_PAGES_' */ $lang = array_merge($lang, array( // Donation Page settings 'DONATION_DP_CONFIG' => 'Donation pages', 'DONATION_DP_CONFIG_EXPLAIN' => 'Permet d’améliorer le rendu des pages personalisables du MOD.', 'DONATION_DP_PAGE' => 'Type de page', 'DONATION_DP_LANG' => 'Langue', // Donation Page Body settings 'DONATION_BODY_SETTINGS' => 'Paramètres de la page principale', 'DONATION_BODY' => 'Page principale', 'DONATION_BODY_EXPLAIN' => 'Saisir le texte que vous souhaitez afficher sur la page principale.', // Donation Success settings 'DONATION_SUCCESS_SETTINGS' => 'Paramètres de la page des dons validés', 'DONATION_SUCCESS' => 'Page des dons validés', 'DONATION_SUCCESS_EXPLAIN' => 'Saisir le texte que vous souhaitez afficher sur la page des dons validés.', // Donation Cancel settings 'DONATION_CANCEL_SETTINGS' => 'Paramètres de la page des dons annulés', 'DONATION_CANCEL' => 'Page des dons annulés', 'DONATION_CANCEL_EXPLAIN' => 'Saisir le texte que vous souhaitez afficher sur la page des dons annulés.', // Donation Page Template vars 'DONATION_DP_PREDEFINED_VARS' => 'Variables prédéfinies', 'DONATION_DP_VAR_EXAMPLE' => 'Exemple', 'DONATION_DP_VAR_NAME' => 'Nom', 'DONATION_DP_VAR_VAR' => 'Variable', 'DONATION_DP_BOARD_CONTACT' => 'E-mail de contact', 'DONATION_DP_BOARD_EMAIL' => 'E-mail du forum', 'DONATION_DP_BOARD_SIG' => 'Signature du forum', 'DONATION_DP_SITE_DESC' => 'Description du site', 'DONATION_DP_SITE_NAME' => 'Nom du site', 'DONATION_DP_USER_ID' => 'ID de l’utilisateur', 'DONATION_DP_USERNAME' => 'Nom de l’utilisateur', )); /** * mode: currency * Info: language keys are prefixed with 'DONATION_DC_' for 'DONATION_DONATION_CURRENCY_' */ $lang = array_merge($lang, array( // Currency Management 'DONATION_DC_CONFIG' => 'Gestion des devises', 'DONATION_DC_CONFIG_EXPLAIN' => 'Permet de gérer les devises pour faire un don', 'DONATION_DC_NAME' => 'Nom de la devise', 'DONATION_DC_NAME_EXPLAIN' => 'Exemple : Euro', 'DONATION_DC_ISO_CODE' => 'Code ISO 4217', 'DONATION_DC_ISO_CODE_EXPLAIN' => 'Code alpabetique de la devise.<br />En savoir plus sur la norme ISO 4217… reportez-vous à la <a href="http://www.phpbb.com/customise/db/mod/paypal_donation_mod/faq/f_746" title="FAQ du MOD PayPal Donation">FAQ du MOD PayPal Donation</a> (lien externe en anglais)', 'DONATION_DC_SYMBOL' => 'Symbole de la devise', 'DONATION_DC_SYMBOL_EXPLAIN' => 'Inscire le symbole de la devise.<br />Exemple : <strong>€</strong> pour Euro', 'DONATION_DC_ENABLED' => 'Activer la devise', 'DONATION_DC_ENABLED_EXPLAIN' => 'Si activée, la devise sera disponible dans les listes de sélection', 'DONATION_DC_CREATE_CURRENCY' => 'Ajouter une nouvelle devise', )); /** * logs */ $lang = array_merge($lang, array( //logs 'LOG_DONATION_UPDATED' => '<strong>PayPal Donation: Configuration mise à jour.</strong>', 'LOG_DONATION_PAGES_UPDATED' => '<strong>PayPal Donation: Pages de dons mises à jour.</strong>', 'LOG_ITEM_ADDED' => '<strong>PayPal Donation: %1$s ajouté(e)</strong><br />» %2$s', 'LOG_ITEM_UPDATED' => '<strong>PayPal Donation: %1$s ajouté(e)</strong><br />» %2$s', 'LOG_ITEM_REMOVED' => '<strong>PayPal Donation: %1$s supprimé(e)</strong>', 'LOG_ITEM_MOVE_DOWN' => '<strong>PayPal Donation: Déplacement de la %1$s. </strong> %2$s <strong>après</strong> %3$s', 'LOG_ITEM_MOVE_UP' => '<strong>PayPal Donation: Déplacement de la %1$s. </strong> %2$s <strong>avant</strong> %3$s', 'LOG_ITEM_ENABLED' => '<strong>PayPal Donation: %1$s activé(e)</strong><br />» %2$s', 'LOG_ITEM_DISABLED' => '<strong>PayPal Donation: %1$s désactivé(e)</strong><br />» %2$s', 'LOG_STAT_RESET_DATE' => '<strong>PayPal Donation: Data d’installation réinitialisée</strong>', // Confirm box 'DONATION_DC_ENABLED' => 'Une devise a été activée', 'DONATION_DC_DISABLED' => 'Une devise a été désactivée.', 'DONATION_DC_ADDED' => 'Une nouvelle devise a été ajoutée.', 'DONATION_DC_UPDATED' => 'Une devise a été mise à jour.', 'DONATION_DC_REMOVED' => 'Une devise a été supprimée.', 'DONATION_DP_LANG_ADDED' => 'Une langue de page de dons a été ajoutée', 'DONATION_DP_LANG_UPDATED' => 'Une langue de page de dons a été mise à jour', 'DONATION_DP_LANG_REMOVED' => 'Une langue de page de dons a été supprimée', // Errors 'MUST_SELECT_ITEM' => 'L’objet sélectionné n’existe pas', 'DONATION_DC_ENTER_NAME' => 'Entrez un nom de devise', )); ?>
Skouat/mod_paypal_donation
root/language/fr/mods/info_acp_donation.php
PHP
gpl-2.0
9,873
class AddIssueStatusPosition < ActiveRecord::Migration def self.up add_column :issue_statuses, :position, :integer, :default => 1 IssueStatus.all.each_with_index {|status, i| status.update_attribute(:position, i+1)} end def self.down remove_column :issue_statuses, :position end end
alejandrok5/Redmine-for-heroku
db/migrate/019_add_issue_status_position.rb
Ruby
gpl-2.0
314
# # Makefile for the kernel block device drivers. # # 12 June 2000, Christoph Hellwig <hch@infradead.org> # Rewritten to use lists instead of if-statements. # obj-$(CONFIG_MAC_FLOPPY) += swim3.o obj-$(CONFIG_BLK_DEV_SWIM) += swim_mod.o obj-$(CONFIG_BLK_DEV_FD) += floppy.o obj-$(CONFIG_AMIGA_FLOPPY) += amiflop.o obj-$(CONFIG_PS3_DISK) += ps3disk.o obj-$(CONFIG_PS3_VRAM) += ps3vram.o obj-$(CONFIG_ATARI_FLOPPY) += ataflop.o obj-$(CONFIG_AMIGA_Z2RAM) += z2ram.o obj-$(CONFIG_GAMECUBE_SD) += gcn-sd.o obj-$(CONFIG_GAMECUBE_ARAM) += gcn-aram.o obj-$(CONFIG_GAMECUBE_DI) += gcn-di/ obj-$(CONFIG_WII_MEM2) += rvl-mem2.o obj-$(CONFIG_WII_SD) += rvl-stsd.o obj-$(CONFIG_WII_DI) += rvl-di.o obj-$(CONFIG_BLK_DEV_RAM) += brd.o obj-$(CONFIG_BLK_DEV_LOOP) += loop.o obj-$(CONFIG_BLK_DEV_XD) += xd.o obj-$(CONFIG_BLK_CPQ_DA) += cpqarray.o obj-$(CONFIG_BLK_CPQ_CISS_DA) += cciss.o obj-$(CONFIG_BLK_DEV_DAC960) += DAC960.o obj-$(CONFIG_XILINX_SYSACE) += xsysace.o obj-$(CONFIG_CDROM_PKTCDVD) += pktcdvd.o obj-$(CONFIG_MG_DISK) += mg_disk.o obj-$(CONFIG_SUNVDC) += sunvdc.o obj-$(CONFIG_BLK_DEV_OSD) += osdblk.o obj-$(CONFIG_BLK_DEV_UMEM) += umem.o obj-$(CONFIG_BLK_DEV_NBD) += nbd.o obj-$(CONFIG_BLK_DEV_CRYPTOLOOP) += cryptoloop.o obj-$(CONFIG_VIRTIO_BLK) += virtio_blk.o obj-$(CONFIG_VIODASD) += viodasd.o obj-$(CONFIG_BLK_DEV_SX8) += sx8.o obj-$(CONFIG_BLK_DEV_UB) += ub.o obj-$(CONFIG_BLK_DEV_HD) += hd.o obj-$(CONFIG_XEN_BLKDEV_FRONTEND) += xen-blkfront.o obj-$(CONFIG_XEN_BLKDEV_BACKEND) += xen-blkback/ obj-$(CONFIG_BLK_DEV_DRBD) += drbd/ obj-$(CONFIG_BLK_DEV_RBD) += rbd.o swim_mod-y := swim.o swim_asm.o
crowell/gbadev.kernel
drivers/block/Makefile
Makefile
gpl-2.0
1,623
<!-- saved from url=(0107)https://www.naylornetwork.com/absolutebm/abmw_ssl.aspx?a=ASQ-WEB-VerticalBanner03&K=Sub%20Page&isframe=true --> <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Advertisement</title> <meta name="ROBOTS" content="NOINDEX, NOFOLLOW"> <style>img{max-width: 100%;}</style> <!-- Copyright(c)2004 By XIGLA SOFTWARE : http://www.xigla.com --> </head><body leftmargin="0" topmargin="0" marginwidth="0" bottommargin="0" rightmargin="0" marginheight="0"> <!--<base target="_top">--><base href="." target="_top"><div id="ABMbanner" style="position:absolute;"><a href="https://www.naylornetwork.com/absolutebm/abmc.aspx?b=27666&z=2410" target="_blank"><img src="579104_Quality_CVB.gif" border="0" alt="Quality Council of Indiana" name="Quality Council of Indiana"></a></div> </body></html>
bladerunner92/web-tutorial
spc/Statistical Process Control and Process Control Tools ASQ_files/abmw_ssl(1).html
HTML
gpl-2.0
841
#!/usr/bin/env python ################################################################################ # # Project Euler - Problem 6 # # The sum of the squares of the first ten natural numbers is, # # 1^2 + 2^2 + ... + 10^2 = 385 # The square of the sum of the first ten natural numbers is, # # (1 + 2 + ... + 10)^2 = 552 = 3025 # Hence the difference between the sum of the squares of the first ten natural # numbers and the square of the sum is 3025 - 385 = 2640 # # Find the difference between the sum of the squares of the first one hundred # natural numbers and the square of the sum. # # Joaquin Derrac - carrdelling@gmail.com # ################################################################################ if __name__ == "__main__": sum_one_hundred = sum([x for x in range(1, 101)]) sum_one_hundred_squared = sum_one_hundred * sum_one_hundred sum_squared = sum([x ** 2 for x in range(1, 101)]) solution = sum_one_hundred_squared - sum_squared print(solution)
carrdelling/project_euler
problem6.py
Python
gpl-2.0
996
<?php session_start(); require($_SERVER['DOCUMENT_ROOT'] . '/auth/config.php'); require($_SERVER['DOCUMENT_ROOT'] . '/content/functions.php'); $outp = '[{}]'; if (isset($_SESSION["id"])) { $snmp_storage_row = ''; # $snmp_storage_query = " SELECT a.rdate, a.idate, a.Serial_Number, a.Description, free_percentage AS store_free_per FROM tbl_summary_snmp_common_storage_5min a WHERE RDate > NOW() - INTERVAL 7 DAY AND a.Serial_Number = :rb_sn AND a.Description IS NOT NULL ORDER BY a.RDate;"; // Check if the site_name supplied has not already been used $snmp_storage_query_params = array( ':rb_sn' => $_SESSION["rb_sn"] ); $snmp_storage_stmt = $db->prepare($snmp_storage_query); if ($snmp_storage_stmt->execute($snmp_storage_query_params)) { $snmp_storage_row = $snmp_storage_stmt->fetchAll(); } $series1 = array(); // $result = array(); if ($snmp_storage_row) { $rows = array(); $d = array(); foreach ($snmp_storage_row as $x) { $res[$x['Description']][] = array( $x['idate'], $x['store_free_per'] ); } foreach ($res as $k => $i) { $tmp['name'] = $k; $tmp['data'] = $i; $result[] = $tmp; } /* post the data */ print json_encode($result, JSON_NUMERIC_CHECK); } /* Send default output */ } else { echo $outp; } ?>
jawug/wugms
web/ms/content/snmp_storage_data2.php
PHP
gpl-2.0
1,586
/*************************************************************************** sndhrdw/sblaster.c Soundblaster code ****************************************************************************/ #include "includes/sblaster.h" #include "sound/dac.h" /* operation modes 0x10 output 8 bit direct 0x14 output 8 bit with dma 0x16 output 2 bit compression with dma 0x17 output 2 bit compression with dma and reference byte 0x74 output 4 bit compression with dma 0x75 output 4 bit compression with dma with reference byte 0x76 output 2.6 bit compression with dma 0x77 output 2.7 bit compression with dma and reference byte 0x20 input 8 bit direct 0x24 input 8 bit with dma 0xd1 speaker on 0xd3 speaker off 0xd8 read speaker 0x40 samplerate adjust 0x48 blockgroesse einstellen 0x80 interrupt after xx samples 0xd0 end dma 0xd4 continue dma 0xe1 read version 0x30 midi input 0x31 midi input with irq generation 0x32 midi input with time stamp 0x33 midi input with irq and time stamp 0x34 midi output mode 0x35 midi output with irq 0x37 midi output with time stamp and irq 0x38 midi output direct pro 0x48, 0x91 output 8 bit high speed 8bit with dma 0x48, 0x99 input 8 bit high speed 8bit with dma */ typedef enum { OFF, INPUT, OUTPUT } MODE; static struct { SOUNDBLASTER_CONFIG config; /* int channel; */ MODE mode; int on; int dma; int frequency; int count; int input_state; int output_state; void *timer; } blaster={ {0} } ; void soundblaster_config(const SOUNDBLASTER_CONFIG *config) { blaster.config = *config; } void soundblaster_reset(void) { if (blaster.timer) blaster.timer = NULL; blaster.on=0; blaster.mode=OFF; blaster.input_state=0; blaster.output_state=0; blaster.frequency=0; } #if 0 int soundblaster_start(void) { channel = stream_init("PC speaker", 50, Machine->sample_rate, 0, pc_sh_update); return 0; } void soundblaster_stop(void) {} void soundblaster_update(void) {} #endif READ8_HANDLER( soundblaster_r ) { int data=0; switch (offset) { case 0xa: /*data input */ switch (blaster.input_state) { case 0: data=0xaa; break; case 1: /* version high */ data=blaster.config.version.major; blaster.input_state++; break; case 2: /* version low */ data=blaster.config.version.minor; blaster.input_state=0; break; case 3: /* speaker state */ data=blaster.on?0xff:0; blaster.input_state=0; break; } break; case 0xc: /*status */ break; case 0xe: /* busy */ data=0x80; break; } return data; } static int soundblaster_operation(int data) { switch (data) { case 0x10: /*play*/ return 1; case 0x40: /* set samplerate */ return 1; case 0xd0: /* dma break */ break; case 0xd4: /* dma continue */ break; case 0xd1: blaster.on=1; break; case 0xd3: blaster.on=0; break; case 0xd8: /* read speaker */ blaster.input_state=3; break; case 0xe1: /* read version */ blaster.input_state=1; break; } return 0; } WRITE8_HANDLER( soundblaster_w ) { switch (offset) { case 6: if (data!=0) { /*reset */ } else { /* reset off */ } break; case 0xc: /*operation, data */ switch (blaster.output_state) { case 0: blaster.output_state=soundblaster_operation(data); break; case 1: blaster.frequency=(int)(1000000.0/(256-data)); blaster.output_state=0; break; case 10: DAC_data_w(0, data); blaster.output_state=0; break; } break; } } #if 0 struct CustomSound_interface soundblaster_interface = { soundblaster_start, soundblaster_stop, soundblaster_update }; #endif
scs/uclinux
user/games/xmame/xmame-0.106/mess/sndhrdw/sblaster.c
C
gpl-2.0
3,607
--- layout: post title: One paper got accepted at Conference on Neural Information Processing Systems (NeurIPS), 2021. date: 2021-09-29 16:11:00-0400 inline: true selected: true --- One paper got accepted in Conference on Neural Information Processing Systems - [NeurIPS, 2021](https://nips.cc/).
awaisrauf/awaisrauf.github.io
_news/news_12.md
Markdown
gpl-2.0
301
<?php /* * @package MijoShop * @copyright 2009-2013 Miwisoft LLC, miwisoft.com * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html * @license GNU/GPL based on AceShop www.joomace.net */ // No Permission defined('_JEXEC') or die('Restricted access'); class Template { public $data = array(); public function fetch($filename) { $file = DIR_TEMPLATE . $filename; if (file_exists($file)) { extract($this->data); ob_start(); include($file); $content = ob_get_contents(); ob_end_clean(); return $content; } else { trigger_error('Error: Could not load template ' . $file . '!'); exit(); } } } ?>
eugeneuskov/modna
components/com_mijoshop/opencart/system/library/template.php
PHP
gpl-2.0
689
/* * Defs.h * * Created on: 2014-10-21 * Author: Etienne Dupéré Larivière */ #ifndef DEFS_H_INCLUDED #define DEFS_H_INCLUDED #include "Util/EnumString.h" // note: all times are in milliseconds static const int deviceAckTimeout = 4000; // timeout to receive expected ACK reply from a device static const int deviceCommandRetries = 3; // number of times to retry sending a device command (if no ACK was received from the device within deviceAckTimeout time) static const int deviceCommandWaitTime = 200; // minimum time between to wait between sending two different device commands static const int duplicateInterval = 1000; // interval within which to treat multiple matching messages received from a device as duplicates, where matching is defined as all message bytes are the same except for the hop-count bits static const int echoTimeout = 1000; // time to wait for echo response after sending data static const int negotiateRetries = 5; // number of times to retry negotiating with a serial device static const unsigned int openTimeout = 1000; // time to wait for initial response after opening port static const int readDataRetries = 5; // number of times to retry reading data from the serial port static const int readDataRetryTime = 5; // time to wait between retries when reading data from the serial port static const int readDataTimeout = 1000; // maximum amount of time to wait for additional data when reading data from the serial port static const int sendMessageRetries = 5; // number of times to retry sending a message static const int sendMessageWaitTime = 100; // amount of time to wait after failing to send a message before retrying, note time is multiplied on each retry 1x, 2x, 3x, ... up to sendMessageRetries times static const int sendReceiveTimeout = 2000; // timeout to receive expected reply from a blocking send/receive message such as a Controller.GetLinks or a Device.GetOnLevel static const int webRequestTimeout = 5000; // timeout for web requests to smartlinc.smarthome.com and for accessing SmartLinc devices over the local network // Basic types typedef signed char int8; typedef unsigned char uint8; typedef signed short int16; typedef unsigned short uint16; typedef signed int int32; typedef unsigned int uint32; typedef signed long long int64; typedef unsigned long long uint64; typedef float float32; typedef double float64; enum InsteonDeviceCommands { DeviceCommandNull = -1, EnterLinkingMode = 0x09, EnterUnlinkingMode = 0x0A, IDRequest = 0x10, DeviceOn = 0x11, DeviceFastOn = 0x12, DeviceOff = 0x13, DeviceFastOff = 0x14, DeviceBrighten = 0x15, DeviceDim = 0x16, DeviceStartDimming = 0x17, DeviceStopDimming = 0x18, StatusRequest = 0x19 }; // String support for InsteonDeviceCommands Begin_Enum_String(InsteonDeviceCommands) { Enum_String( DeviceCommandNull ); Enum_String( EnterLinkingMode ); Enum_String( EnterUnlinkingMode ); Enum_String( IDRequest ); Enum_String( DeviceOn ); Enum_String( DeviceFastOn ); Enum_String( DeviceOff ); Enum_String( DeviceFastOff ); Enum_String( DeviceBrighten ); Enum_String( DeviceDim ); Enum_String( DeviceStartDimming ); Enum_String( DeviceStopDimming ); Enum_String( StatusRequest ); } End_Enum_String; InsteonDeviceCommands const deviceCommandsValues[] = { DeviceCommandNull, EnterLinkingMode, EnterUnlinkingMode, IDRequest, DeviceOn, DeviceFastOn, DeviceOff, DeviceFastOff, DeviceBrighten, DeviceDim, DeviceStartDimming, DeviceStopDimming, StatusRequest }; // Represents the various device states for an INSTEON device. enum InsteonDeviceStatus { DeviceStatusUnknown = 0, DeviceStatusOn = 1, DeviceStatusOff = 2, DeviceStatusFastOn = 3, DeviceStatusFastOff = 4, DeviceStatusBrighten = 5, DeviceStatusDim = 6 }; // String support for InsteonDeviceStatus Begin_Enum_String(InsteonDeviceStatus) { Enum_String( DeviceStatusUnknown ); Enum_String( DeviceStatusOn ); Enum_String( DeviceStatusOff ); Enum_String( DeviceStatusFastOn ); Enum_String( DeviceStatusFastOff ); Enum_String( DeviceStatusBrighten ); Enum_String( DeviceStatusDim ); } End_Enum_String; // Represents the type of link record. enum InsteonDeviceLinkRecordType { Empty = 0, DeviceResponder, DeviceController }; // String support for InsteonDeviceLinkRecordType Begin_Enum_String(InsteonDeviceLinkRecordType) { Enum_String( Empty ); Enum_String( DeviceResponder ); Enum_String( DeviceController ); } End_Enum_String; // Represents the set of commands that can be sent to all INSTEON devices linked to a controller in the specified group. enum InsteonControllerGroupCommands { On = 0x11, FastOn = 0x12, Off = 0x13, FastOff = 0x14, Brighten = 0x15, Dim = 0x16, StartDimming = 0x17, StopDimming = 0x18 }; // String support for InsteonControllerGroupCommands Begin_Enum_String(InsteonControllerGroupCommands) { Enum_String( On ); Enum_String( FastOn ); Enum_String( Off ); Enum_String( FastOff ); Enum_String( Brighten ); Enum_String( Dim ); Enum_String( StartDimming ); Enum_String( StopDimming ); } End_Enum_String; // Determines the linking mode for the EnterLinkMode method of the INSTEON controller device. enum InsteonLinkMode { Null = -1, Responder = 0x00, Controller = 0x01, Either = 0x03, Delete = 0xFF }; // String support for InsteonLinkMode Begin_Enum_String(InsteonLinkMode) { Enum_String( Null ); Enum_String( Responder ); Enum_String( Controller ); Enum_String( Either ); Enum_String( Delete ); } End_Enum_String; // Represents the status of the serial message echoed from the controller. enum EchoStatus { None = 0, // No response Unknown = 1, // Unknown acknowledgment response (i.e. not a 0x06 or a 0x15) ACK = 0x06, // Acknowledge (OK) NAK = 0x15 // Negative Acknowledge (ERROR) }; // String support for EchoStatus Begin_Enum_String(EchoStatus) { Enum_String( None ); Enum_String( Unknown ); Enum_String( ACK ); Enum_String( NAK ); } End_Enum_String; // Represents the type of an INSTEON connection enum InsteonConnectionType { Net, Serial }; // String support for ConnectionType Begin_Enum_String(InsteonConnectionType) { Enum_String( Net ); Enum_String( Serial ); } End_Enum_String; // A list of defined keys for the property list. enum PropertyKey { Address, Cmd1, Cmd2, Data1, Data2, Data3, Data4, Data5, Data6, Data7, Data8, Data9, Data10, Data11, Data12, Data13, Data14, DevCat, FirmwareVersion, FromAddress, Group, IncrementDirection, LinkAddress, LinkData1, LinkData2, LinkData3, LinkGroup, LinkRecordFlags, LinkStatus, LinkType, MessageFlagsMaxHops, MessageFlagsRemainingHops, MessageFlagsExtendedFlag, MessageFlagsAck, MessageFlagsAllLink, MessageFlagsBroadcast, ResponderCmd1, ResponderCount, ResponderGroup, ResponderErrorCount, SubCat, ToAddress }; // String support for PropertyKey Begin_Enum_String(PropertyKey) { Enum_String( Address ); Enum_String( Cmd1 ); Enum_String( Cmd2 ); Enum_String( Data1 ); Enum_String( Data2 ); Enum_String( Data3 ); Enum_String( Data4 ); Enum_String( Data5 ); Enum_String( Data6 ); Enum_String( Data7 ); Enum_String( Data8 ); Enum_String( Data9 ); Enum_String( Data10 ); Enum_String( Data11 ); Enum_String( Data12 ); Enum_String( Data13 ); Enum_String( Data14 ); Enum_String( DevCat ); Enum_String( FirmwareVersion ); Enum_String( FromAddress ); Enum_String( Group ); Enum_String( IncrementDirection ); Enum_String( LinkAddress ); Enum_String( LinkData1 ); Enum_String( LinkData2 ); Enum_String( LinkData3 ); Enum_String( LinkGroup ); Enum_String( LinkRecordFlags ); Enum_String( LinkStatus ); Enum_String( LinkType ); Enum_String( MessageFlagsMaxHops ); Enum_String( MessageFlagsRemainingHops ); Enum_String( MessageFlagsExtendedFlag ); Enum_String( MessageFlagsAck ); Enum_String( MessageFlagsAllLink ); Enum_String( MessageFlagsBroadcast ); Enum_String( ResponderCmd1 ); Enum_String( ResponderCount ); Enum_String( ResponderGroup ); Enum_String( ResponderErrorCount ); Enum_String( SubCat ); Enum_String( ToAddress ); } End_Enum_String; // Identfies the type of INSTEON message. enum InsteonMessageType { Other = 0, Ack, DeviceLink, DeviceLinkCleanup, DeviceLinkRecord, FastOffBroadcast, FastOffCleanup, FastOnBroadcast, FastOnCleanup, GetIMInfo, IncrementBeginBroadcast, IncrementEndBroadcast, OffBroadcast, OffCleanup, OnBroadcast, OnCleanup, SetButtonPressed, SuccessBroadcast }; // String support for MessageType Begin_Enum_String(InsteonMessageType) { Enum_String( Other ); Enum_String( Ack ); Enum_String( DeviceLink ); Enum_String( DeviceLinkCleanup ); Enum_String( DeviceLinkRecord ); Enum_String( FastOffBroadcast ); Enum_String( FastOffCleanup ); Enum_String( FastOnBroadcast ); Enum_String( FastOnCleanup ); Enum_String( GetIMInfo ); Enum_String( IncrementBeginBroadcast ); Enum_String( IncrementEndBroadcast ); Enum_String( OffBroadcast ); Enum_String( OffCleanup ); Enum_String( OnBroadcast ); Enum_String( OnCleanup ); Enum_String( SetButtonPressed ); Enum_String( SuccessBroadcast ); } End_Enum_String; #endif
EtienneDupereLariviere/OpenInsteon
src/Defs.h
C
gpl-2.0
9,354
var std = std || {}; std.vm = function () { var studies = ko.observableArray([]), defaultStudyId = 0, studyitem = ko.observable(), getstudies = function () { $.ajax({ url: "/Json/GetStudies", dataType: 'json', cache: false, success: function (d) { studies([]); $.each(d, function (i, data) { studies.push(ko.mapping.fromJS(data)); }); } }); }, sortBy = function (field) { if (field) { studies.sort(function (a, b) { try { return eval('a.' + field)() < eval('b.' + field)() ? -1 : 1; } catch (e) { return eval('a.' + field) < eval('b.' + field) ? -1 : 1; } }); } }, gridViewModel = new ko.simpleGrid.viewModel({ data: studies, columns: [ { headerText: "Controls", rowText: function (item) { return '<button class="btn btn-mini edit" data-id=' + item.Id() + '><i class="icon-pencil"></i> Edit</button>'; }, sortColumnName: '' }, { headerText: "Name", rowText: function (item) { return item.Name(); }, sortColumnName: 'Name' }, { headerText: "Description", rowText: function (item) { return item.Description(); }, sortColumnName: 'Description' }, { headerText: "Targets", rowText: function (item) { return item.Target(); }, sortColumnName: 'Target' }, { headerText: "Goals", rowText: function (item) { return item.Goal(); }, sortColumnName: 'Goal' }, { headerText: "Budget", rowText: function (item) { return item.Budget(); }, sortColumnName: 'Budget' }, { headerText: "Start Date", rowText: function (item) { try { var dt = eval('new ' + item.StartDate().replace("/", '').replace("/", '')); item.StartDate(dt.toDateString()); return dt.toDateString(); }catch (e) { return 'N/A'; } }, sortColumnName: 'StartDate' }, { headerText: "End Date", rowText: function (item) { try { if (item.EndDate()) { var dt = eval('new ' + item.EndDate().replace("/", '').replace("/", '')); item.EndDate(dt.toDateString()); var enddate = dt.toDateString(); return enddate; } } catch (e) { return 'N/A'; } }, sortColumnName: 'EndDate' }, { headerText: "State", rowText: function (item) { if (item.IsActive()) { return '<span class=\"span1 userstatus label label-success\" data-id=\"' + item.Id() + '\">Active</span>'; } else { return '<span class=\"span1 userstatus label label-important\" data-id=\"' + item.Id() + '\">Inactive</span>'; } return ''; }, sortColumnName: 'IsActive' } ], pageSize: 10 }), newStudy = function () { return { Name: ko.observable(), Description: ko.observable(), StartDate: ko.observable(), EndDate: ko.observable(), Target: ko.observable(), Goal: ko.observable(), Budget: ko.observable(), SortOrder: ko.observable(), Status: ko.observable(1), CreatedOn: ko.observable(), UpdatedOn: ko.observable(), CreatedBy: ko.observable(), UpdatedBy: ko.observable(), IsActive: ko.observable(true), Arms: ko.observable(), Drugs: ko.observable(), Forms: ko.observable(), Sites: ko.observable(), Id: ko.observable(0), }; }; return { studies: studies, defaultStudyId: defaultStudyId, studyitem: studyitem, newStudy: newStudy, getstudies: getstudies, sortBy: sortBy, gridViewModel: gridViewModel }; }(); $(document).ready(function () { window.setTimeout(function () { init(); std.vm.getstudies(); ko.applyBindings(std.vm); }, 300); }); function init() { $("body").on("click", ".edit", function () { var sid = $(this).attr('data-id'); var data = ko.utils.arrayFirst(std.vm.studies(), function (item) { return item.Id() == sid; }); $("#newstudy-modal").modal('show'); std.vm.studyitem(data); }); $("#modellink").on("click", function () { std.vm.studyitem(std.vm.newStudy()); }); $("body").on("click", ".userstatus", function () { toastr.error($(this).data('id')); }); $("body").on('click', ".sortableHead", function () { var field = $(this).attr('sortname'); std.vm.sortBy(field); }); }
odesuk/clires
src/Tateeda.Clires/Tateeda.Clires/Scripts/app/Admin/Study/study.js
JavaScript
gpl-2.0
4,243
/*************************************************************************** * 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. * * * * copyright (C) 2005-2012 * * Umbrello UML Modeller Authors <uml-devel@uml.sf.net> * ***************************************************************************/ // own header #include "adaimport.h" // app includes #include "association.h" #include "attribute.h" #include "classifier.h" #include "debug_utils.h" #include "enum.h" #include "folder.h" #include "import_utils.h" #include "operation.h" #include "package.h" #include "uml.h" #include "umldoc.h" // qt includes #include <QRegExp> #include <stdio.h> /** * Constructor. */ AdaImport::AdaImport(CodeImpThread* thread) : NativeImportBase("--", thread) { initVars(); } /** * Destructor. */ AdaImport::~AdaImport() { } /** * Reimplement operation from NativeImportBase. */ void AdaImport::initVars() { m_inGenericFormalPart = false; m_classesDefinedInThisScope.clear(); m_renaming.clear(); } /** * Split the line so that a string is returned as a single element of the list. * When not in a string then split at white space. * Reimplementation of method from NativeImportBase is required because of * Ada's tic which is liable to be confused with the beginning of a character * constant. */ QStringList AdaImport::split(const QString& lin) { QStringList list; QString listElement; bool inString = false; bool seenSpace = false; QString line = lin.trimmed(); uint len = line.length(); for (uint i = 0; i < len; ++i) { const QChar& c = line[i]; if (inString) { listElement += c; if (c == '"') { if (i < len - 1 && line[i + 1] == '"') { i++; // escaped quotation mark continue; } list.append(listElement); listElement.clear(); inString = false; } } else if (c == '"') { inString = true; if (!listElement.isEmpty()) list.append(listElement); listElement = QString(c); seenSpace = false; } else if (c == '\'') { if (i < len - 2 && line[i + 2] == '\'') { // character constant if (!listElement.isEmpty()) list.append(listElement); listElement = line.mid(i, 3); i += 2; list.append(listElement); listElement.clear(); continue; } listElement += c; seenSpace = false; } else if (c.isSpace()) { if (seenSpace) continue; seenSpace = true; if (!listElement.isEmpty()) { list.append(listElement); listElement.clear(); } } else { listElement += c; seenSpace = false; } } if (!listElement.isEmpty()) list.append(listElement); return list; } /** * Implement abstract operation from NativeImportBase. */ void AdaImport::fillSource(const QString& word) { QString lexeme; const uint len = word.length(); for (uint i = 0; i < len; ++i) { QChar c = word[i]; if (c.isLetterOrNumber() || c == '_' || c == '.' || c == '#') { lexeme += c; } else { if (!lexeme.isEmpty()) { m_source.append(lexeme); lexeme.clear(); } if (c == ':' && word[i + 1] == '=') { m_source.append(":="); i++; } else { m_source.append(QString(c)); } } } if (!lexeme.isEmpty()) m_source.append(lexeme); } /** * Apply package renamings to the given name. * @return expanded name */ QString AdaImport::expand(const QString& name) { QRegExp pfxRegExp("^(\\w+)\\."); pfxRegExp.setCaseSensitivity(Qt::CaseInsensitive); int pos = pfxRegExp.indexIn(name); if (pos == -1) return name; QString result = name; QString pfx = pfxRegExp.cap(1); if (m_renaming.contains(pfx)) { result.remove(pfxRegExp); result.prepend(m_renaming[pfx] + '.'); } return result; } /** * Parse all files that can be formed by concatenation of the given stems. */ void AdaImport::parseStems(const QStringList& stems) { if (stems.isEmpty()) return; QString base = stems.first(); int i = 0; while (1) { QString filename = base + ".ads"; if (! m_parsedFiles.contains(filename)) { // Save current m_source and m_srcIndex. QStringList source(m_source); uint srcIndex = m_srcIndex; m_source.clear(); parseFile(filename); // Restore m_source and m_srcIndex. m_source = source; m_srcIndex = srcIndex; // Also reset m_currentAccess. // CHECK: need to reset more stuff? m_currentAccess = Uml::Visibility::Public; } if (++i >= stems.count()) break; base += '-' + stems[i]; } } /** * Implement abstract operation from NativeImportBase. */ bool AdaImport::parseStmt() { const int srcLength = m_source.count(); QString keyword = m_source[m_srcIndex]; UMLDoc *umldoc = UMLApp::app()->document(); //uDebug() << '"' << keyword << '"'; if (keyword == "with") { if (m_inGenericFormalPart) { // mapping of generic formal subprograms or packages is not yet implemented return false; } while (++m_srcIndex < srcLength && m_source[m_srcIndex] != ";") { QStringList components = m_source[m_srcIndex].toLower().split('.'); const QString& prefix = components.first(); if (prefix == "system" || prefix == "ada" || prefix == "gnat" || prefix == "interfaces" || prefix == "text_io" || prefix == "unchecked_conversion" || prefix == "unchecked_deallocation") { if (advance() != ",") break; continue; } parseStems(components); if (advance() != ",") break; } return true; } if (keyword == "generic") { m_inGenericFormalPart = true; return true; } if (keyword == "package") { const QString& name = advance(); QStringList parentPkgs = name.toLower().split('.'); parentPkgs.pop_back(); // exclude the current package parseStems(parentPkgs); UMLObject *ns = NULL; if (advance() == "is") { ns = Import_Utils::createUMLObject(UMLObject::ot_Package, name, m_scope[m_scopeIndex], m_comment); if (m_source[m_srcIndex + 1] == "new") { m_srcIndex++; QString pkgName = advance(); UMLObject *gp = Import_Utils::createUMLObject(UMLObject::ot_Package, pkgName, m_scope[m_scopeIndex]); gp->setStereotype("generic"); // Add binding from instantiator to instantiatee UMLAssociation *assoc = new UMLAssociation(Uml::AssociationType::Dependency, ns, gp); assoc->setUMLPackage(umldoc->rootFolder(Uml::ModelType::Logical)); assoc->setStereotype("bind"); // Work around missing display of stereotype in AssociationWidget: assoc->setName(assoc->stereotype(true)); umldoc->addAssociation(assoc); skipStmt(); } else { m_scope[++m_scopeIndex] = static_cast<UMLPackage*>(ns); } } else if (m_source[m_srcIndex] == "renames") { m_renaming[name] = advance(); } else { uError() << "unexpected: " << m_source[m_srcIndex]; skipStmt("is"); } if (m_inGenericFormalPart) { ns->setStereotype("generic"); m_inGenericFormalPart = false; } return true; } if (m_inGenericFormalPart) return false; // skip generic formal parameter (not yet implemented) if (keyword == "subtype") { QString name = advance(); advance(); // "is" QString base = expand(advance()); base.remove("Standard.", Qt::CaseInsensitive); UMLObject *type = umldoc->findUMLObject(base, UMLObject::ot_UMLObject, m_scope[m_scopeIndex]); if (type == NULL) { type = Import_Utils::createUMLObject(UMLObject::ot_Datatype, base, m_scope[m_scopeIndex]); } UMLObject *subtype = Import_Utils::createUMLObject(type->baseType(), name, m_scope[m_scopeIndex], m_comment); UMLAssociation *assoc = new UMLAssociation(Uml::AssociationType::Dependency, subtype, type); assoc->setUMLPackage(umldoc->rootFolder(Uml::ModelType::Logical)); assoc->setStereotype("subtype"); // Work around missing display of stereotype in AssociationWidget: assoc->setName(assoc->stereotype(true)); umldoc->addAssociation(assoc); skipStmt(); return true; } if (keyword == "type") { QString name = advance(); QString next = advance(); if (next == "(") { uDebug() << name << ": discriminant handling is not yet implemented"; // @todo Find out how to map discriminated record to UML. // For now, we just create a pro forma empty record. Import_Utils::createUMLObject(UMLObject::ot_Class, name, m_scope[m_scopeIndex], m_comment, "record"); skipStmt("end"); if ((next = advance()) == "case") m_srcIndex += 2; // skip "case" ";" skipStmt(); return true; } if (next == ";") { // forward declaration Import_Utils::createUMLObject(UMLObject::ot_Class, name, m_scope[m_scopeIndex], m_comment); return true; } if (next != "is") { uError() << "expecting \"is\""; return false; } next = advance(); if (next == "(") { // enum type UMLObject *ns = Import_Utils::createUMLObject(UMLObject::ot_Enum, name, m_scope[m_scopeIndex], m_comment); UMLEnum *enumType = static_cast<UMLEnum*>(ns); while ((next = advance()) != ")") { Import_Utils::addEnumLiteral(enumType, next, m_comment); m_comment.clear(); if (advance() != ",") break; } skipStmt(); return true; } bool isTaggedType = false; if (next == "abstract") { m_isAbstract = true; next = advance(); } if (next == "tagged") { isTaggedType = true; next = advance(); } if (next == "limited" || next == "task" || next == "protected" || next == "synchronized") { next = advance(); // we can't (yet?) represent that } if (next == "private" || next == "interface" || next == "record" || (next == "null" && m_source[m_srcIndex+1] == "record")) { UMLObject::ObjectType t = (next == "interface" ? UMLObject::ot_Interface : UMLObject::ot_Class); UMLObject *ns = Import_Utils::createUMLObject(t, name, m_scope[m_scopeIndex], m_comment); if (t == UMLObject::ot_Interface) { while ((next = advance()) == "and") { UMLClassifier *klass = static_cast<UMLClassifier*>(ns); QString base = expand(advance()); UMLObject *p = Import_Utils::createUMLObject(UMLObject::ot_Interface, base, m_scope[m_scopeIndex]); UMLClassifier *parent = static_cast<UMLClassifier*>(p); Import_Utils::createGeneralization(klass, parent); } } else { ns->setAbstract(m_isAbstract); } m_isAbstract = false; if (isTaggedType) { if (! m_classesDefinedInThisScope.contains(ns)) m_classesDefinedInThisScope.append(ns); } else { ns->setStereotype("record"); } if (next == "record") m_klass = static_cast<UMLClassifier*>(ns); else skipStmt(); return true; } if (next == "new") { QString base = expand(advance()); QStringList baseInterfaces; while ((next = advance()) == "and") { baseInterfaces.append(expand(advance())); } const bool isExtension = (next == "with"); UMLObject::ObjectType t; if (isExtension || m_isAbstract) { t = UMLObject::ot_Class; } else { base.remove("Standard.", Qt::CaseInsensitive); UMLObject *known = umldoc->findUMLObject(base, UMLObject::ot_UMLObject, m_scope[m_scopeIndex]); t = (known ? known->baseType() : UMLObject::ot_Datatype); } UMLObject *ns = Import_Utils::createUMLObject(t, base, NULL); UMLClassifier *parent = static_cast<UMLClassifier*>(ns); ns = Import_Utils::createUMLObject(t, name, m_scope[m_scopeIndex], m_comment); if (isExtension) { next = advance(); if (next == "null" || next == "record") { UMLClassifier *klass = static_cast<UMLClassifier*>(ns); Import_Utils::createGeneralization(klass, parent); if (next == "record") { // Set the m_klass for attributes. m_klass = klass; } if (baseInterfaces.count()) { t = UMLObject::ot_Interface; QStringList::Iterator end(baseInterfaces.end()); for (QStringList::Iterator bi(baseInterfaces.begin()); bi != end; ++bi) { ns = Import_Utils::createUMLObject(t, *bi, m_scope[m_scopeIndex]); parent = static_cast<UMLClassifier*>(ns); Import_Utils::createGeneralization(klass, parent); } } } } skipStmt(); return true; } // Datatypes: TO BE DONE return false; } if (keyword == "private") { m_currentAccess = Uml::Visibility::Private; return true; } if (keyword == "end") { if (m_klass) { if (advance() != "record") { uError() << "end: expecting \"record\" at " << m_source[m_srcIndex]; } m_klass = NULL; } else if (m_scopeIndex) { if (advance() != ";") { QString scopeName = m_scope[m_scopeIndex]->fullyQualifiedName(); if (scopeName.toLower() != m_source[m_srcIndex].toLower()) uError() << "end: expecting " << scopeName << ", found " << m_source[m_srcIndex]; } m_scopeIndex--; m_currentAccess = Uml::Visibility::Public; // @todo make a stack for this } else { uError() << "importAda: too many \"end\""; } skipStmt(); return true; } // subprogram if (keyword == "not") keyword = advance(); if (keyword == "overriding") keyword = advance(); if (keyword == "function" || keyword == "procedure") { const QString& name = advance(); QString returnType; if (advance() != "(") { // Unlike an Ada package, a UML package does not support // subprograms. // In order to map those, we would need to create a UML // class with stereotype <<utility>> for the Ada package. uDebug() << "ignoring parameterless " << keyword << " " << name; skipStmt(); return true; } UMLClassifier *klass = NULL; UMLOperation *op = NULL; const uint MAX_PARNAMES = 16; while (m_srcIndex < srcLength && m_source[m_srcIndex] != ")") { QString parName[MAX_PARNAMES]; uint parNameCount = 0; do { if (parNameCount >= MAX_PARNAMES) { uError() << "MAX_PARNAMES is exceeded at " << name; break; } parName[parNameCount++] = advance(); } while (advance() == ","); if (m_source[m_srcIndex] != ":") { uError() << "importAda: expecting ':'"; skipStmt(); break; } const QString &direction = advance(); QString typeName; Uml::Parameter_Direction dir = Uml::pd_In; if (direction == "access") { // Oops, we have to improvise here because there // is no such thing as "access" in UML. // So we use the next best thing, "inout". // Better ideas, anyone? dir = Uml::pd_InOut; typeName = advance(); } else if (direction == "in") { if (m_source[m_srcIndex + 1] == "out") { dir = Uml::pd_InOut; m_srcIndex++; } typeName = advance(); } else if (direction == "out") { dir = Uml::pd_Out; typeName = advance(); } else { typeName = direction; // In Ada, the default direction is "in" } typeName.remove("Standard.", Qt::CaseInsensitive); typeName = expand(typeName); if (op == NULL) { // In Ada, the first parameter indicates the class. UMLObject *type = Import_Utils::createUMLObject(UMLObject::ot_Class, typeName, m_scope[m_scopeIndex]); UMLObject::ObjectType t = type->baseType(); if ((t != UMLObject::ot_Interface && (t != UMLObject::ot_Class || type->stereotype() == "record")) || !m_classesDefinedInThisScope.contains(type)) { // Not an instance bound method - we cannot represent it. skipStmt(")"); break; } klass = static_cast<UMLClassifier*>(type); op = Import_Utils::makeOperation(klass, name); // The controlling parameter is suppressed. parNameCount--; if (parNameCount) { for (uint i = 0; i < parNameCount; ++i) { parName[i] = parName[i + 1]; } } } for (uint i = 0; i < parNameCount; ++i) { UMLAttribute *att = Import_Utils::addMethodParameter(op, typeName, parName[i]); att->setParmKind(dir); } if (advance() != ";") break; } if (keyword == "function") { if (advance() != "return") { if (klass) uError() << "importAda: expecting \"return\" at function " << name; return false; } returnType = expand(advance()); returnType.remove("Standard.", Qt::CaseInsensitive); } bool isAbstract = false; if (advance() == "is" && advance() == "abstract") isAbstract = true; if (klass != NULL && op != NULL) Import_Utils::insertMethod(klass, op, m_currentAccess, returnType, false, isAbstract, false, false, m_comment); skipStmt(); return true; } if (keyword == "task" || keyword == "protected") { // Can task and protected objects/types be mapped to UML? QString name = advance(); if (name == "type") { name = advance(); } QString next = advance(); if (next == "(") { skipStmt(")"); // skip discriminant next = advance(); } if (next == "is") skipStmt("end"); skipStmt(); return true; } if (keyword == "for") { // rep spec QString typeName = advance(); QString next = advance(); if (next == "'") { advance(); // skip qualifier next = advance(); } if (next == "use") { if (advance() == "record") skipStmt("end"); } else { uError() << "importAda: expecting \"use\" at rep spec of " << typeName; } skipStmt(); return true; } // At this point we're only interested in attribute declarations. if (m_klass == NULL || keyword == "null") { skipStmt(); return true; } const QString& name = keyword; if (advance() != ":") { uError() << "adaImport: expecting \":\" at " << name << " " << m_source[m_srcIndex]; skipStmt(); return true; } QString nextToken = advance(); if (nextToken == "aliased") nextToken = advance(); QString typeName = expand(nextToken); QString initialValue; if (advance() == ":=") { initialValue = advance(); QString token; while ((token = advance()) != ";") { initialValue.append(' ' + token); } } UMLObject *o = Import_Utils::insertAttribute(m_klass, m_currentAccess, name, typeName, m_comment); UMLAttribute *attr = static_cast<UMLAttribute*>(o); attr->setInitialValue(initialValue); skipStmt(); return true; }
Elv13/Umbrello-ng2
umbrello/codeimport/adaimport.cpp
C++
gpl-2.0
22,908
/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. Copyright (c) 2008, 2017, MariaDB Corporation. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file Optimising of MIN(), MAX() and COUNT(*) queries without 'group by' clause by replacing the aggregate expression with a constant. Given a table with a compound key on columns (a,b,c), the following types of queries are optimised (assuming the table handler supports the required methods) @verbatim SELECT COUNT(*) FROM t1[,t2,t3,...] SELECT MIN(b) FROM t1 WHERE a=const SELECT MAX(c) FROM t1 WHERE a=const AND b=const SELECT MAX(b) FROM t1 WHERE a=const AND b<const SELECT MIN(b) FROM t1 WHERE a=const AND b>const SELECT MIN(b) FROM t1 WHERE a=const AND b BETWEEN const AND const SELECT MAX(b) FROM t1 WHERE a=const AND b BETWEEN const AND const @endverbatim Instead of '<' one can use '<=', '>', '>=' and '=' as well. Instead of 'a=const' the condition 'a IS NULL' can be used. If all selected fields are replaced then we will also remove all involved tables and return the answer without any join. Thus, the following query will be replaced with a row of two constants: @verbatim SELECT MAX(b), MIN(d) FROM t1,t2 WHERE a=const AND b<const AND d>const @endverbatim (assuming a index for column d of table t2 is defined) */ #include "mariadb.h" #include "sql_priv.h" #include "key.h" // key_cmp_if_same #include "sql_select.h" static bool find_key_for_maxmin(bool max_fl, TABLE_REF *ref, Field* field, COND *cond, uint *range_fl, uint *key_prefix_length); static int reckey_in_range(bool max_fl, TABLE_REF *ref, Field* field, COND *cond, uint range_fl, uint prefix_len); static int maxmin_in_range(bool max_fl, Field* field, COND *cond); /* Get exact count of rows in all tables SYNOPSIS get_exact_records() tables List of tables NOTES When this is called, we know all table handlers supports HA_HAS_RECORDS or HA_STATS_RECORDS_IS_EXACT RETURN ULONGLONG_MAX Error: Could not calculate number of rows # Multiplication of number of rows in all tables */ static ulonglong get_exact_record_count(List<TABLE_LIST> &tables) { ulonglong count= 1; TABLE_LIST *tl; List_iterator<TABLE_LIST> ti(tables); while ((tl= ti++)) { ha_rows tmp= tl->table->file->records(); if (tmp == HA_POS_ERROR) return ULONGLONG_MAX; count*= tmp; } return count; } /** Use index to read MIN(field) value. @param table Table object @param ref Reference to the structure where we store the key value @item_field Field used in MIN() @range_fl Whether range endpoint is strict less than @prefix_len Length of common key part for the range @retval 0 No errors HA_ERR_... Otherwise */ static int get_index_min_value(TABLE *table, TABLE_REF *ref, Item_field *item_field, uint range_fl, uint prefix_len) { int error; if (!ref->key_length) error= table->file->ha_index_first(table->record[0]); else { /* Use index to replace MIN/MAX functions with their values according to the following rules: 1) Insert the minimum non-null values where the WHERE clause still matches, or 2) a NULL value if there are only NULL values for key_part_k. 3) Fail, producing a row of nulls Implementation: Read the smallest value using the search key. If the interval is open, read the next value after the search key. If read fails, and we're looking for a MIN() value for a nullable column, test if there is an exact match for the key. */ if (!(range_fl & NEAR_MIN)) /* Closed interval: Either The MIN argument is non-nullable, or we have a >= predicate for the MIN argument. */ error= table->file->ha_index_read_map(table->record[0], ref->key_buff, make_prev_keypart_map(ref->key_parts), HA_READ_KEY_OR_NEXT); else { /* Open interval: There are two cases: 1) We have only MIN() and the argument column is nullable, or 2) there is a > predicate on it, nullability is irrelevant. We need to scan the next bigger record first. Open interval is not used if the search key involves the last keypart, and it would not work. */ DBUG_ASSERT(prefix_len < ref->key_length); error= table->file->ha_index_read_map(table->record[0], ref->key_buff, make_prev_keypart_map(ref->key_parts), HA_READ_AFTER_KEY); /* If the found record is outside the group formed by the search prefix, or there is no such record at all, check if all records in that group have NULL in the MIN argument column. If that is the case return that NULL. Check if case 1 from above holds. If it does, we should read the skipped tuple. */ if (item_field->field->real_maybe_null() && ref->key_buff[prefix_len] == 1 && /* Last keypart (i.e. the argument to MIN) is set to NULL by find_key_for_maxmin only if all other keyparts are bound to constants in a conjunction of equalities. Hence, we can detect this by checking only if the last keypart is NULL. */ (error == HA_ERR_KEY_NOT_FOUND || key_cmp_if_same(table, ref->key_buff, ref->key, prefix_len))) { DBUG_ASSERT(item_field->field->real_maybe_null()); error= table->file->ha_index_read_map(table->record[0], ref->key_buff, make_prev_keypart_map(ref->key_parts), HA_READ_KEY_EXACT); } } } return error; } /** Use index to read MAX(field) value. @param table Table object @param ref Reference to the structure where we store the key value @range_fl Whether range endpoint is strict greater than @retval 0 No errors HA_ERR_... Otherwise */ static int get_index_max_value(TABLE *table, TABLE_REF *ref, uint range_fl) { return (ref->key_length ? table->file->ha_index_read_map(table->record[0], ref->key_buff, make_prev_keypart_map(ref->key_parts), range_fl & NEAR_MAX ? HA_READ_BEFORE_KEY : HA_READ_PREFIX_LAST_OR_PREV) : table->file->ha_index_last(table->record[0])); } /** Substitutes constants for some COUNT(), MIN() and MAX() functions. @param thd thread handler @param tables list of leaves of join table tree @param all_fields All fields to be returned @param conds WHERE clause @note This function is only called for queries with aggregate functions and no GROUP BY part. This means that the result set shall contain a single row only @retval 0 no errors @retval 1 if all items were resolved @retval HA_ERR_KEY_NOT_FOUND on impossible conditions @retval HA_ERR_... if a deadlock or a lock wait timeout happens, for example @retval ER_... e.g. ER_SUBQUERY_NO_1_ROW */ int opt_sum_query(THD *thd, List<TABLE_LIST> &tables, List<Item> &all_fields, COND *conds) { List_iterator_fast<Item> it(all_fields); List_iterator<TABLE_LIST> ti(tables); TABLE_LIST *tl; int const_result= 1; bool recalc_const_item= 0; ulonglong count= 1; bool is_exact_count= TRUE, maybe_exact_count= TRUE; table_map removed_tables= 0, outer_tables= 0, used_tables= 0; table_map where_tables= 0; Item *item; int error= 0; DBUG_ENTER("opt_sum_query"); thd->lex->current_select->min_max_opt_list.empty(); if (conds) where_tables= conds->used_tables(); /* Analyze outer join dependencies, and, if possible, compute the number of returned rows. */ while ((tl= ti++)) { TABLE_LIST *embedded; for (embedded= tl ; embedded; embedded= embedded->embedding) { if (embedded->on_expr) break; } if (embedded) /* Don't replace expression on a table that is part of an outer join */ { outer_tables|= tl->table->map; /* We can't optimise LEFT JOIN in cases where the WHERE condition restricts the table that is used, like in: SELECT MAX(t1.a) FROM t1 LEFT JOIN t2 join-condition WHERE t2.field IS NULL; */ if (tl->table->map & where_tables) DBUG_RETURN(0); } else used_tables|= tl->table->map; /* If the storage manager of 'tl' gives exact row count as part of statistics (cheap), compute the total number of rows. If there are no outer table dependencies, this count may be used as the real count. Schema tables are filled after this function is invoked, so we can't get row count */ if (!(tl->table->file->ha_table_flags() & HA_STATS_RECORDS_IS_EXACT) || tl->schema_table) { maybe_exact_count&= MY_TEST(!tl->schema_table && (tl->table->file->ha_table_flags() & HA_HAS_RECORDS)); is_exact_count= FALSE; count= 1; // ensure count != 0 } else if (tl->is_materialized_derived() || tl->jtbm_subselect) { /* Can't remove a derived table as it's number of rows is just an estimate. */ DBUG_RETURN(0); } else { error= tl->table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK); if (unlikely(error)) { tl->table->file->print_error(error, MYF(ME_FATAL)); DBUG_RETURN(error); } count*= tl->table->file->stats.records; } } /* Iterate through all items in the SELECT clause and replace COUNT(), MIN() and MAX() with constants (if possible). */ while ((item= it++)) { if (item->type() == Item::SUM_FUNC_ITEM) { Item_sum *item_sum= (((Item_sum*) item)); switch (item_sum->sum_func()) { case Item_sum::COUNT_FUNC: /* If the expr in COUNT(expr) can never be null we can change this to the number of rows in the tables if this number is exact and there are no outer joins. */ if (!conds && !((Item_sum_count*) item)->get_arg(0)->maybe_null && !outer_tables && maybe_exact_count && ((item->used_tables() & OUTER_REF_TABLE_BIT) == 0)) { if (!is_exact_count) { if ((count= get_exact_record_count(tables)) == ULONGLONG_MAX) { /* Error from handler in counting rows. Don't optimize count() */ const_result= 0; continue; } is_exact_count= 1; // count is now exact } ((Item_sum_count*) item)->make_const((longlong) count); recalc_const_item= 1; } else const_result= 0; break; case Item_sum::MIN_FUNC: case Item_sum::MAX_FUNC: { int is_max= MY_TEST(item_sum->sum_func() == Item_sum::MAX_FUNC); /* If MIN/MAX(expr) is the first part of a key or if all previous parts of the key is found in the COND, then we can use indexes to find the key. */ Item *expr=item_sum->get_arg(0); if (((expr->used_tables() & OUTER_REF_TABLE_BIT) == 0) && expr->real_item()->type() == Item::FIELD_ITEM) { uchar key_buff[MAX_KEY_LENGTH]; TABLE_REF ref; uint range_fl, prefix_len; ref.key_buff= key_buff; Item_field *item_field= (Item_field*) (expr->real_item()); TABLE *table= item_field->field->table; /* Look for a partial key that can be used for optimization. If we succeed, ref.key_length will contain the length of this key, while prefix_len will contain the length of the beginning of this key without field used in MIN/MAX(). Type of range for the key part for this field will be returned in range_fl. */ if (table->file->inited || (outer_tables & table->map) || !find_key_for_maxmin(is_max, &ref, item_field->field, conds, &range_fl, &prefix_len)) { const_result= 0; break; } longlong info_limit= 1; error= 0; table->file->info_push(INFO_KIND_FORCE_LIMIT_BEGIN, &info_limit); if (!table->const_table) { if (likely(!(error= table->file->ha_index_init((uint) ref.key, 1)))) error= (is_max ? get_index_max_value(table, &ref, range_fl) : get_index_min_value(table, &ref, item_field, range_fl, prefix_len)); } /* Verify that the read tuple indeed matches the search key */ if (!error && reckey_in_range(is_max, &ref, item_field->field, conds, range_fl, prefix_len)) error= HA_ERR_KEY_NOT_FOUND; if (!table->const_table) { table->file->ha_end_keyread(); table->file->ha_index_end(); } table->file->info_push(INFO_KIND_FORCE_LIMIT_END, NULL); if (error) { if (error == HA_ERR_KEY_NOT_FOUND || error == HA_ERR_END_OF_FILE) DBUG_RETURN(HA_ERR_KEY_NOT_FOUND); // No rows matching WHERE /* HA_ERR_LOCK_DEADLOCK or some other error */ table->file->print_error(error, MYF(0)); DBUG_RETURN(error); } removed_tables|= table->map; } else if (!expr->const_item() || !is_exact_count || conds) { /* The optimization is not applicable in both cases: (a) 'expr' is a non-constant expression. Then we can't replace 'expr' by a constant. (b) 'expr' is a costant. According to ANSI, MIN/MAX must return NULL if the query does not return any rows. Thus, if we are not able to determine if the query returns any rows, we can't apply the optimization and replace MIN/MAX with a constant. (c) there is a WHERE clause. The WHERE conditions may result in an empty result, but the clause cannot be taken into account here. */ const_result= 0; break; } item_sum->set_aggregator(item_sum->has_with_distinct() ? Aggregator::DISTINCT_AGGREGATOR : Aggregator::SIMPLE_AGGREGATOR); /* If count == 0 (so is_exact_count == TRUE) and there're no outer joins, set to NULL, otherwise set to the constant value. */ if (!count && !outer_tables) { item_sum->aggregator_clear(); } else { item_sum->reset_and_add(); /* Save a reference to the item for possible rollback of the min/max optimizations for this select */ thd->lex->current_select->min_max_opt_list.push_back(item_sum); } item_sum->make_const(); recalc_const_item= 1; break; } default: const_result= 0; break; } } else if (const_result) { if (recalc_const_item) item->update_used_tables(); if (!item->const_item() && item->type() != Item::WINDOW_FUNC_ITEM) const_result= 0; } } if (unlikely(thd->is_error())) DBUG_RETURN(thd->get_stmt_da()->sql_errno()); /* If we have a where clause, we can only ignore searching in the tables if MIN/MAX optimisation replaced all used tables We do not use replaced values in case of: SELECT MIN(key) FROM table_1, empty_table removed_tables is != 0 if we have used MIN() or MAX(). */ if (removed_tables && used_tables != removed_tables) const_result= 0; // We didn't remove all tables DBUG_RETURN(const_result); } /* Check if both item1 and item2 are strings, and item1 has fewer characters than item2. */ static bool check_item1_shorter_item2(Item *item1, Item *item2) { if (item1->cmp_type() == STRING_RESULT && item2->cmp_type() == STRING_RESULT) { int len1= item1->max_length / item1->collation.collation->mbmaxlen; int len2= item2->max_length / item2->collation.collation->mbmaxlen; return len1 < len2; } return false; /* When the check is not applicable, it means "not bigger" */ } /** Test if the predicate compares a field with constants. @param func_item Predicate item @param[out] args Here we store the field followed by constants @param[out] inv_order Is set to 1 if the predicate is of the form 'const op field' @retval 0 func_item is a simple predicate: a field is compared with a constant whose length does not exceed the max length of the field values @retval 1 Otherwise */ bool simple_pred(Item_func *func_item, Item **args, bool *inv_order) { Item *item; *inv_order= 0; switch (func_item->argument_count()) { case 0: /* MULT_EQUAL_FUNC */ { Item_equal *item_equal= (Item_equal *) func_item; if (!(args[1]= item_equal->get_const())) return 0; Item_equal_fields_iterator it(*item_equal); if (!(item= it++)) return 0; args[0]= item->real_item(); if (check_item1_shorter_item2(args[0], args[1])) return 0; if (it++) return 0; } break; case 1: /* field IS NULL */ item= func_item->arguments()[0]->real_item(); if (item->type() != Item::FIELD_ITEM) return 0; args[0]= item; break; case 2: /* 'field op const' or 'const op field' */ item= func_item->arguments()[0]->real_item(); if (item->type() == Item::FIELD_ITEM) { args[0]= item; item= func_item->arguments()[1]->real_item(); if (!item->const_item()) return 0; args[1]= item; } else if (item->const_item()) { args[1]= item; item= func_item->arguments()[1]->real_item(); if (item->type() != Item::FIELD_ITEM) return 0; args[0]= item; *inv_order= 1; } else return 0; if (check_item1_shorter_item2(args[0], args[1])) return 0; break; case 3: /* field BETWEEN const AND const */ item= func_item->arguments()[0]->real_item(); if (item->type() == Item::FIELD_ITEM) { args[0]= item; for (int i= 1 ; i <= 2; i++) { item= func_item->arguments()[i]->real_item(); if (!item->const_item()) return 0; args[i]= item; if (check_item1_shorter_item2(args[0], args[i])) return 0; } } else return 0; } return 1; } /** Check whether a condition matches a key to get {MAX|MIN}(field):. For the index specified by the keyinfo parameter and an index that contains the field as its component (field_part), the function checks whether - the condition cond is a conjunction, - all of its conjuncts refer to columns of the same table, and - each conjunct is on one of the following forms: - f_i = const_i or const_i = f_i or f_i IS NULL, where f_i is part of the index - field {<|<=|>=|>|=} const - const {<|<=|>=|>|=} field - field BETWEEN const_1 AND const_2 As a side-effect, the key value to be used for looking up the MIN/MAX value is actually stored inside the Field object. An interesting feature is that the function will find the most restrictive endpoint by over-eager evaluation of the @c WHERE condition. It continually stores the current endpoint inside the Field object. For a query such as @code SELECT MIN(a) FROM t1 WHERE a > 3 AND a > 5; @endcode the algorithm will recurse over the conjuction, storing first a 3 in the field. In the next recursive invocation the expression a > 5 is evaluated as 3 > 5 (Due to the dual nature of Field objects as value carriers and field identifiers), which will obviously fail, leading to 5 being stored in the Field object. @param[in] max_fl Set to true if we are optimizing MAX(), false means we are optimizing %MIN() @param[in, out] ref Reference to the structure where the function stores the key value @param[in] keyinfo Reference to the key info @param[in] field_part Pointer to the key part for the field @param[in] cond WHERE condition @param[in,out] key_part_used Map of matchings parts. The function will output the set of key parts actually being matched in this set, yet it relies on the caller to initialize the value to zero. This is due to the fact that this value is passed recursively. @param[in,out] range_fl Says whether endpoints use strict greater/less than. @param[out] prefix_len Length of common key part for the range where MAX/MIN is searched for @retval false Index can't be used. @retval true We can use the index to get MIN/MAX value */ static bool matching_cond(bool max_fl, TABLE_REF *ref, KEY *keyinfo, KEY_PART_INFO *field_part, COND *cond, key_part_map *key_part_used, uint *range_fl, uint *prefix_len) { DBUG_ENTER("matching_cond"); if (!cond) DBUG_RETURN(TRUE); Field *field= field_part->field; table_map cond_used_tables= cond->used_tables(); if (cond_used_tables & OUTER_REF_TABLE_BIT) { DBUG_RETURN(FALSE); } if (!(cond_used_tables & field->table->map) && MY_TEST(cond_used_tables & ~PSEUDO_TABLE_BITS)) { /* Condition doesn't restrict the used table */ DBUG_RETURN(!cond->const_item()); } else if (cond->is_expensive()) DBUG_RETURN(FALSE); if (cond->type() == Item::COND_ITEM) { if (((Item_cond*) cond)->functype() == Item_func::COND_OR_FUNC) DBUG_RETURN(FALSE); /* AND */ List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list()); Item *item; while ((item= li++)) { if (!matching_cond(max_fl, ref, keyinfo, field_part, item, key_part_used, range_fl, prefix_len)) DBUG_RETURN(FALSE); } DBUG_RETURN(TRUE); } if (cond->type() != Item::FUNC_ITEM) DBUG_RETURN(FALSE); // Not operator, can't optimize bool eq_type= 0; // =, <=> or IS NULL bool is_null_safe_eq= FALSE; // The operator is NULL safe, e.g. <=> bool noeq_type= 0; // < or > bool less_fl= 0; // < or <= bool is_null= 0; // IS NULL bool between= 0; // BETWEEN ... AND ... switch (((Item_func*) cond)->functype()) { case Item_func::ISNULL_FUNC: is_null= 1; /* fall through */ case Item_func::EQ_FUNC: eq_type= TRUE; break; case Item_func::EQUAL_FUNC: eq_type= is_null_safe_eq= TRUE; break; case Item_func::LT_FUNC: noeq_type= 1; /* fall through */ case Item_func::LE_FUNC: less_fl= 1; break; case Item_func::GT_FUNC: noeq_type= 1; /* fall through */ case Item_func::GE_FUNC: break; case Item_func::BETWEEN: if (((Item_func_between*) cond)->negated) DBUG_RETURN(FALSE); between= 1; break; case Item_func::MULT_EQUAL_FUNC: eq_type= 1; break; default: DBUG_RETURN(FALSE); // Can't optimize function } Item *args[3]; bool inv; /* Test if this is a comparison of a field and constant */ if (!simple_pred((Item_func*) cond, args, &inv)) DBUG_RETURN(FALSE); if (!is_null_safe_eq && !is_null && (args[1]->is_null() || (between && args[2]->is_null()))) DBUG_RETURN(FALSE); if (inv && !eq_type) less_fl= 1-less_fl; // Convert '<' -> '>' (etc) /* Check if field is part of the tested partial key */ uchar *key_ptr= ref->key_buff; KEY_PART_INFO *part; for (part= keyinfo->key_part; ; key_ptr+= part++->store_length) { if (part > field_part) DBUG_RETURN(FALSE); // Field is beyond the tested parts if (part->field->eq(((Item_field*) args[0])->field)) break; // Found a part of the key for the field } bool is_field_part= part == field_part; if (!(is_field_part || eq_type)) DBUG_RETURN(FALSE); key_part_map org_key_part_used= *key_part_used; if (eq_type || between || max_fl == less_fl) { uint length= (uint)(key_ptr-ref->key_buff)+part->store_length; if (ref->key_length < length) { /* Ultimately ref->key_length will contain the length of the search key */ ref->key_length= length; ref->key_parts= (uint)(part - keyinfo->key_part) + 1; } if (!*prefix_len && part+1 == field_part) *prefix_len= length; if (is_field_part && eq_type) *prefix_len= ref->key_length; *key_part_used|= (key_part_map) 1 << (part - keyinfo->key_part); } if (org_key_part_used == *key_part_used && /* The current search key is not being extended with a new key part. This means that the a condition is added a key part for which there was a previous condition. We can only overwrite such key parts in some special cases, e.g. a > 2 AND a > 1 (here range_fl must be set to something). In all other cases the WHERE condition is always false anyway. */ (eq_type || *range_fl == 0)) DBUG_RETURN(FALSE); if (org_key_part_used != *key_part_used || (is_field_part && (between || eq_type || max_fl == less_fl) && !cond->val_int())) { /* It's the first predicate for this part or a predicate of the following form that moves upper/lower bounds for max/min values: - field BETWEEN const AND const - field = const - field {<|<=} const, when searching for MAX - field {>|>=} const, when searching for MIN */ if (is_null || (is_null_safe_eq && args[1]->is_null())) { /* If we have a non-nullable index, we cannot use it, since set_null will be ignored, and we will compare uninitialized data. */ if (!part->field->real_maybe_null()) DBUG_RETURN(FALSE); part->field->set_null(); *key_ptr= (uchar) 1; } else { /* Update endpoints for MAX/MIN, see function comment. */ Item *value= args[between && max_fl ? 2 : 1]; value->save_in_field_no_warnings(part->field, 1); if (part->null_bit) *key_ptr++= (uchar) MY_TEST(part->field->is_null()); part->field->get_key_image(key_ptr, part->length, Field::itRAW); } if (is_field_part) { if (between || eq_type) *range_fl&= ~(NO_MAX_RANGE | NO_MIN_RANGE); else { *range_fl&= ~(max_fl ? NO_MAX_RANGE : NO_MIN_RANGE); if (noeq_type) *range_fl|= (max_fl ? NEAR_MAX : NEAR_MIN); else *range_fl&= ~(max_fl ? NEAR_MAX : NEAR_MIN); } } } else if (eq_type) { if ((!is_null && !cond->val_int()) || (is_null && !MY_TEST(part->field->is_null()))) DBUG_RETURN(FALSE); // Impossible test } else if (is_field_part) *range_fl&= ~(max_fl ? NO_MIN_RANGE : NO_MAX_RANGE); DBUG_RETURN(TRUE); } /** Check whether we can get value for {max|min}(field) by using a key. If where-condition is not a conjunction of 0 or more conjuct the function returns false, otherwise it checks whether there is an index including field as its k-th component/part such that: -# for each previous component f_i there is one and only one conjunct of the form: f_i= const_i or const_i= f_i or f_i is null -# references to field occur only in conjucts of the form: field {<|<=|>=|>|=} const or const {<|<=|>=|>|=} field or field BETWEEN const1 AND const2 -# all references to the columns from the same table as column field occur only in conjucts mentioned above. -# each of k first components the index is not partial, i.e. is not defined on a fixed length proper prefix of the field. If such an index exists the function through the ref parameter returns the key value to find max/min for the field using the index, the length of first (k-1) components of the key and flags saying how to apply the key for the search max/min value. (if we have a condition field = const, prefix_len contains the length of the whole search key) @param[in] max_fl 0 for MIN(field) / 1 for MAX(field) @param[in,out] ref Reference to the structure we store the key value @param[in] field Field used inside MIN() / MAX() @param[in] cond WHERE condition @param[out] range_fl Bit flags for how to search if key is ok @param[out] prefix_len Length of prefix for the search range @note This function may set field->table->key_read to true, which must be reset after index is used! (This can only happen when function returns 1) @retval 0 Index can not be used to optimize MIN(field)/MAX(field) @retval 1 Can use key to optimize MIN()/MAX(). In this case ref, range_fl and prefix_len are updated */ static bool find_key_for_maxmin(bool max_fl, TABLE_REF *ref, Field* field, COND *cond, uint *range_fl, uint *prefix_len) { if (!(field->flags & PART_KEY_FLAG)) return FALSE; // Not key field DBUG_ENTER("find_key_for_maxmin"); TABLE *table= field->table; uint idx= 0; KEY *keyinfo,*keyinfo_end; for (keyinfo= table->key_info, keyinfo_end= keyinfo+table->s->keys ; keyinfo != keyinfo_end; keyinfo++,idx++) { KEY_PART_INFO *part,*part_end; key_part_map key_part_to_use= 0; /* Perform a check if index is not disabled by ALTER TABLE or IGNORE INDEX. */ if (!table->keys_in_use_for_query.is_set(idx)) continue; uint jdx= 0; *prefix_len= 0; part_end= keyinfo->key_part+table->actual_n_key_parts(keyinfo); for (part= keyinfo->key_part ; part != part_end ; part++, jdx++, key_part_to_use= (key_part_to_use << 1) | 1) { if (!(table->file->index_flags(idx, jdx, 0) & HA_READ_ORDER)) DBUG_RETURN(FALSE); /* Check whether the index component is partial */ Field *part_field= table->field[part->fieldnr-1]; if ((part_field->flags & BLOB_FLAG) || part->length < part_field->key_length()) break; if (field->eq(part->field)) { ref->key= idx; ref->key_length= 0; ref->key_parts= 0; key_part_map key_part_used= 0; *range_fl= NO_MIN_RANGE | NO_MAX_RANGE; if (matching_cond(max_fl, ref, keyinfo, part, cond, &key_part_used, range_fl, prefix_len) && !(key_part_to_use & ~key_part_used)) { if (!max_fl && key_part_used == key_part_to_use && part->null_bit) { /* The query is on this form: SELECT MIN(key_part_k) FROM t1 WHERE key_part_1 = const and ... and key_part_k-1 = const If key_part_k is nullable, we want to find the first matching row where key_part_k is not null. The key buffer is now {const, ..., NULL}. This will be passed to the handler along with a flag indicating open interval. If a tuple is read that does not match these search criteria, an attempt will be made to read an exact match for the key buffer. */ /* Set the first byte of key_part_k to 1, that means NULL */ ref->key_buff[ref->key_length]= 1; ref->key_length+= part->store_length; ref->key_parts++; DBUG_ASSERT(ref->key_parts == jdx+1); *range_fl&= ~NO_MIN_RANGE; *range_fl|= NEAR_MIN; // Open interval } /* The following test is false when the key in the key tree is converted (for example to upper case) */ if (field->part_of_key.is_set(idx)) table->file->ha_start_keyread(idx); DBUG_RETURN(TRUE); } } } } DBUG_RETURN(FALSE); } /** Check whether found key is in range specified by conditions. @param[in] max_fl 0 for MIN(field) / 1 for MAX(field) @param[in] ref Reference to the key value and info @param[in] field Field used the MIN/MAX expression @param[in] cond WHERE condition @param[in] range_fl Says whether there is a condition to to be checked @param[in] prefix_len Length of the constant part of the key @retval 0 ok @retval 1 WHERE was not true for the found row */ static int reckey_in_range(bool max_fl, TABLE_REF *ref, Field* field, COND *cond, uint range_fl, uint prefix_len) { if (key_cmp_if_same(field->table, ref->key_buff, ref->key, prefix_len)) return 1; if (!cond || (range_fl & (max_fl ? NO_MIN_RANGE : NO_MAX_RANGE))) return 0; return maxmin_in_range(max_fl, field, cond); } /** Check whether {MAX|MIN}(field) is in range specified by conditions. @param[in] max_fl 0 for MIN(field) / 1 for MAX(field) @param[in] field Field used the MIN/MAX expression @param[in] cond WHERE condition @retval 0 ok @retval 1 WHERE was not true for the found row */ static int maxmin_in_range(bool max_fl, Field* field, COND *cond) { /* If AND/OR condition */ if (cond->type() == Item::COND_ITEM) { List_iterator_fast<Item> li(*((Item_cond*) cond)->argument_list()); Item *item; while ((item= li++)) { if (maxmin_in_range(max_fl, field, item)) return 1; } return 0; } if (cond->used_tables() != field->table->map) return 0; bool less_fl= 0; switch (((Item_func*) cond)->functype()) { case Item_func::BETWEEN: return cond->val_int() == 0; // Return 1 if WHERE is false case Item_func::LT_FUNC: case Item_func::LE_FUNC: less_fl= 1; /* fall through */ case Item_func::GT_FUNC: case Item_func::GE_FUNC: { Item *item= ((Item_func*) cond)->arguments()[1]; /* In case of 'const op item' we have to swap the operator */ if (!item->const_item()) less_fl= 1-less_fl; /* We only have to check the expression if we are using an expression like SELECT MAX(b) FROM t1 WHERE a=const AND b>const not for SELECT MAX(b) FROM t1 WHERE a=const AND b<const */ if (max_fl != less_fl) return cond->val_int() == 0; // Return 1 if WHERE is false return 0; } default: break; // Ignore } return 0; }
ottok/mariadb
sql/opt_sum.cc
C++
gpl-2.0
37,064
# enw
nicofisch5/enw
README.md
Markdown
gpl-2.0
6
<?php /* You may not change or alter any portion of this comment or credits of supporting developers from this source code or any supporting source code which is considered copyrighted (c) material of the original comment or credit authors. 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. */ /** * Module: randomquote * * @category Module * @package randomquote * @author XOOPS Development Team <name@site.com> - <https://xoops.org> * @copyright {@link https://xoops.org/ XOOPS Project} * @license GPL 2.0 or later * @link https://xoops.org/ * @since 1.0.0 */ use Xmf\Request; use Xoopsmodules\randomquote; $GLOBALS['xoopsOption']['template_main'] = 'randomquote_category_list.tpl'; require_once __DIR__ . '/header.php'; $start = Request::getInt('start', 0); $categoryPaginationLimit = $GLOBALS['xoopsModuleConfig']['userpager']; $criteria = new CriteriaCompo(); $criteria->setOrder('DESC'); $criteria->setLimit($categoryPaginationLimit); $criteria->setStart($start); $categoryCount = $categoryHandler->getCount($criteria); $categoryArray = $categoryHandler->getAll($criteria); if ($categoryCount > 0) { foreach (array_keys($categoryArray) as $i) { $category['id'] = $categoryArray[$i]->getVar('id'); $category['pid'] = $categoryArray[$i]->getVar('pid'); $category['title'] = $categoryArray[$i]->getVar('title'); $category['description'] = $categoryArray[$i]->getVar('description'); $category['image'] = $categoryArray[$i]->getVar('image'); $category['weight'] = $categoryArray[$i]->getVar('weight'); $category['color'] = $categoryArray[$i]->getVar('color'); $category['online'] = $categoryArray[$i]->getVar('online'); $GLOBALS['xoopsTpl']->append('category', $category); $keywords[] = $categoryArray[$i]->getVar('title'); unset($category); } // Display Navigation if ($categoryCount > $categoryPaginationLimit) { require_once XOOPS_ROOT_PATH . '/class/pagenav.php'; $pagenav = new \XoopsPageNav($categoryCount, $categoryPaginationLimit, $start, 'start'); $GLOBALS['xoopsTpl']->assign('pagenav', $pagenav->renderNav(4)); } } //keywords if (isset($keywords)) { $utility::meta_keywords(xoops_getModuleOption('keywords', $moduleDirName) . ', ' . implode(', ', $keywords)); } //description $utility::meta_description(MD_RANDOMQUOTE_CATEGORY_DESC); // $GLOBALS['xoopsTpl']->assign('xoops_mpageurl', RANDOMQUOTE_URL . '/category.php'); $GLOBALS['xoopsTpl']->assign('randomquote_url', RANDOMQUOTE_URL); $GLOBALS['xoopsTpl']->assign('adv', xoops_getModuleOption('advertise', $moduleDirName)); // $GLOBALS['xoopsTpl']->assign('bookmarks', xoops_getModuleOption('bookmarks', $moduleDirName)); $GLOBALS['xoopsTpl']->assign('fbcomments', xoops_getModuleOption('fbcomments', $moduleDirName)); // $GLOBALS['xoopsTpl']->assign('admin', MD_RANDOMQUOTE_ADMIN); //$GLOBALS['xoopsTpl']->assign('copyright', $copyright); // require_once XOOPS_ROOT_PATH . '/footer.php';
mambax7/randomquote
category.php
PHP
gpl-2.0
3,246
package testcases.postgresql; import org.junit.Test; import constants.DatabaseName; import databases.PostgreSQLDatabase; public class PostgreSqlToMySqlTest { @Test public void test() { PostgreSQLDatabase postgres = new PostgreSQLDatabase(); postgres.parse(DatabaseName.MY_SQL, ""); } }
luanamartins/ConvertQueries
ConvertQueries/test/testcases/postgresql/PostgreSqlToMySqlTest.java
Java
gpl-2.0
297
<?php /* Plugin Name: mywidget Plugin URI: localhost Description: Author: April Hodge Silver Version: 1.0 Author URI: localhost */ class Posts_From_Category extends WP_Widget { function Posts_From_Category() { $widget_ops = array( 'classname' => 'postsfromcat', 'description' => 'Allows you to display a list of recent posts within a particular category.'); $control_ops = array( 'width' => 250, 'height' => 250, 'id_base' => 'postsfromcat-widget'); $this->WP_Widget('postsfromcat-widget', 'Posts from a Category', $widget_ops, $control_ops ); } function form ($instance) { $defaults = array('numberposts' => '4'); $instance = wp_parse_args( (array) $instance, $defaults ); ?> <p> <label for="<?php echo $this->get_field_id('title'); ?>">Title:</label> <input type="text" name="<?php echo $this->get_field_name('title') ?>" id="<?php echo $this->get_field_id('title') ?> " value="<?php echo $instance['title'] ?>" size="20"> </p> <p> <label for="<?php echo $this->get_field_id('catid'); ?>">Category:</label> <?php wp_dropdown_categories('hide_empty=0&hierarchical=1&id='.$this->get_field_id('catid').'&name='.$this->get_field_name('catid').'&selected='.$instance['catid']); ?> </p> <p> <label for="<?php echo $this->get_field_id('numberposts'); ?>">Number of posts:</label> <select id="<?php echo $this->get_field_id('numberposts'); ?>" name="<?php echo $this->get_field_name('numberposts'); ?>"> <?php for ($i=1;$i<=20;$i++) { echo '<option value="'.$i.'"'; if ($i==$instance['numberposts']) echo ' selected="selected"'; echo '>'.$i.'</option>'; } ?> </select> </p> <p> <input type="checkbox" id="<?php echo $this->get_field_id('rss'); ?>" name="<?php echo $this->get_field_name('rss'); ?>" <?php if ($instance['rss']) echo 'checked="checked"' ?> /> <label for="<?php echo $this->get_field_id('rss'); ?>">Show RSS feed link?</label> </p> <?php } function update ($new_instance, $old_instance) { $instance = $old_instance; $instance['catid'] = $new_instance['catid']; $instance['numberposts'] = $new_instance['numberposts']; $instance['title'] = $new_instance['title']; $instance['rss'] = $new_instance['rss']; return $instance; } function widget ($args,$instance) { extract($args); $title = $instance['title']; $catid = $instance['catid']; $numberposts = $instance['numberposts']; $rss = $instance['rss']; // retrieve posts information from database global $wpdb; echo $before_widget; echo $before_title.$title.$after_title; echo $after_widget; $out = '<ul>'; $posts = get_posts('numberposts='.$numberposts.'&category='.$catid); ?> <li style="clear: both"> <ul id="lastest_events"> <?php foreach ($posts as $posts): ?> <li> <?php echo get_the_post_thumbnail($posts->ID, array(50,50)); ?> <a href="<?php the_permalink() ?>"><?php echo $posts->post_title; ?></a> </li> <?php endforeach; ?> </ul> </li> <?php if ($rss) $out .= '<li><a href="'.get_category_link($catid).'feed/" class="rss">Category RSS</a></li>'; $out .= '</ul>'; echo $out; } } function ahspfc_load_widgets() { register_widget('Posts_From_Category'); } add_action('widgets_init', 'ahspfc_load_widgets'); ?>
daitran1104/wordpress
wp-content/plugins/ahswidget_postfromcat.php
PHP
gpl-2.0
3,426
#include "botpch.h" #include "../../playerbot.h" #include "EmoteAction.h" using namespace ai; map<string, uint32> EmoteAction::emotes; bool EmoteAction::Execute(Event event) { if (emotes.empty()) { InitEmotes(); } uint32 emote = 0; string param = event.getParam(); if (param.empty() || emotes.find(param) == emotes.end()) { int index = rand() % emotes.size(); for (map<string, uint32>::iterator i = emotes.begin(); i != emotes.end() && index; ++i, --index) { emote = i->second; } } else { emote = emotes[param]; } bot->CastStop(); ai->InterruptSpell(); bot->SetStandState(UNIT_STAND_STATE_STAND); Player* master = GetMaster(); if (master) { ObjectGuid masterSelection = master->GetSelectionGuid(); if (masterSelection) { ObjectGuid oldSelection = bot->GetSelectionGuid(); bot->SetSelectionGuid(masterSelection); bot->HandleEmoteCommand(emote); bot->SetSelectionGuid(oldSelection); return true; } } bot->HandleEmoteCommand(emote); return true; } void EmoteAction::InitEmotes() { emotes["dance"] = EMOTE_ONESHOT_DANCE; emotes["drown"] = EMOTE_ONESHOT_DROWN; emotes["land"] = EMOTE_ONESHOT_LAND; emotes["laugh_nosheathe"] = EMOTE_ONESHOT_LAUGH_NOSHEATHE; emotes["liftoff"] = EMOTE_ONESHOT_LIFTOFF; emotes["loot"] = EMOTE_ONESHOT_LOOT; emotes["no"] = EMOTE_ONESHOT_NO; emotes["point_nosheathe"] = EMOTE_ONESHOT_POINT_NOSHEATHE; emotes["roar"] = EMOTE_STATE_ROAR; emotes["salute"] = EMOTE_ONESHOT_SALUTE; emotes["stomp"] = EMOTE_ONESHOT_STOMP; emotes["train"] = EMOTE_ONESHOT_TRAIN; emotes["yes"] = EMOTE_ONESHOT_YES; emotes["applaud"] = EMOTE_ONESHOT_APPLAUD; emotes["battleroar"] = EMOTE_ONESHOT_BATTLEROAR; emotes["beg"] = EMOTE_ONESHOT_BEG; emotes["bow"] = EMOTE_ONESHOT_BOW; emotes["cheer"] = EMOTE_ONESHOT_CHEER; emotes["chicken"] = EMOTE_ONESHOT_CHICKEN; emotes["cry"] = EMOTE_ONESHOT_CRY; emotes["dance"] = EMOTE_STATE_DANCE; emotes["eat"] = EMOTE_ONESHOT_EAT; emotes["exclamation"] = EMOTE_ONESHOT_EXCLAMATION; emotes["flex"] = EMOTE_ONESHOT_FLEX; emotes["kick"] = EMOTE_ONESHOT_KICK; emotes["kiss"] = EMOTE_ONESHOT_KISS; emotes["kneel"] = EMOTE_ONESHOT_KNEEL; emotes["laugh"] = EMOTE_ONESHOT_LAUGH; emotes["parryshield"] = EMOTE_ONESHOT_PARRYSHIELD; emotes["parryunarmed"] = EMOTE_ONESHOT_PARRYUNARMED; emotes["point"] = EMOTE_ONESHOT_POINT; emotes["question"] = EMOTE_ONESHOT_QUESTION; emotes["ready1h"] = EMOTE_ONESHOT_READY1H; emotes["readybow"] = EMOTE_ONESHOT_READYBOW; emotes["readyunarmed"] = EMOTE_ONESHOT_READYUNARMED; emotes["roar"] = EMOTE_ONESHOT_ROAR; emotes["rude"] = EMOTE_ONESHOT_RUDE; emotes["shout"] = EMOTE_ONESHOT_SHOUT; emotes["shy"] = EMOTE_ONESHOT_SHY; emotes["sleep"] = EMOTE_STATE_SLEEP; emotes["talk"] = EMOTE_ONESHOT_TALK; emotes["wave"] = EMOTE_ONESHOT_WAVE; emotes["woundcritical"] = EMOTE_ONESHOT_WOUNDCRITICAL; emotes["wound"] = EMOTE_ONESHOT_WOUND; }
mangoszero/server
src/modules/Bots/playerbot/strategy/actions/EmoteAction.cpp
C++
gpl-2.0
3,205
! ! Copyright (C) 2009 A. Smogunov ! This file is distributed under the terms of the ! GNU General Public License. See the file `License' ! in the root directory of the present distribution, ! or http://www.gnu.org/copyleft/gpl.txt . ! ! MODULE realus_scatt ! ! Some extra subroutines to the module realus ! needed for the scattering problem ! INTEGER, ALLOCATABLE :: orig_or_copy(:,:) CONTAINS SUBROUTINE realus_scatt_0() ! ! Calculates orig_or_copy array ! USE kinds, ONLY : dp USE constants, ONLY : pi USE ions_base, ONLY : nat, tau, ityp USE cell_base, ONLY : at, bg USE realus, ONLY : qpointlist, tabp, boxrad USE uspp, ONLY : okvan USE uspp_param, ONLY : upf USE mp_global, ONLY : me_pool USE fft_base, ONLY : dfftp IMPLICIT NONE INTEGER :: ia, ir, mbia, roughestimate, j0, k0, idx, i, j, k, i_lr, ipol REAL(DP) :: mbr, mbx, mby, mbz, dmbx, dmby, dmbz, distsq REAL(DP) :: inv_nr1, inv_nr2, inv_nr3, boxradsq_ia, posi(3) IF ( .NOT. okvan ) RETURN CALL qpointlist(dfftp, tabp) !-- Finds roughestimate mbr = MAXVAL( boxrad(:) ) mbx = mbr*SQRT( bg(1,1)**2 + bg(1,2)**2 + bg(1,3)**2 ) mby = mbr*SQRT( bg(2,1)**2 + bg(2,2)**2 + bg(2,3)**2 ) mbz = mbr*SQRT( bg(3,1)**2 + bg(3,2)**2 + bg(3,3)**2 ) dmbx = 2*ANINT( mbx*dfftp%nr1x ) + 2 dmby = 2*ANINT( mby*dfftp%nr2x ) + 2 dmbz = 2*ANINT( mbz*dfftp%nr3x ) + 2 roughestimate = ANINT( DBLE( dmbx*dmby*dmbz ) * pi / 6.D0 ) !-- IF (ALLOCATED(orig_or_copy)) DEALLOCATE( orig_or_copy ) ALLOCATE( orig_or_copy( roughestimate, nat ) ) inv_nr1 = 1.D0 / DBLE( dfftp%nr1 ) inv_nr2 = 1.D0 / DBLE( dfftp%nr2 ) inv_nr3 = 1.D0 / DBLE( dfftp%nr3 ) DO ia = 1, nat IF ( .NOT. upf(ityp(ia))%tvanp ) CYCLE mbia = 0 boxradsq_ia = boxrad(ityp(ia))**2 j0 = dfftp%my_i0r2p ; k0 = dfftp%my_i0r3p DO ir = 1, dfftp%nr1x*dfftp%my_nr2p*dfftp%my_nr3p ! ! ... three dimensional indices (i,j,k) ! idx = ir -1 k = idx / (dfftp%nr1x*dfftp%my_nr2p) idx = idx - (dfftp%nr1x*dfftp%my_nr2p)*k k = k + k0 j = idx / dfftp%nr1x idx = idx - dfftp%nr1x * j j = j + j0 i = idx ! ! ... do not include points outside the physical range ! IF ( i >= dfftp%nr1 .OR. j >= dfftp%nr2 .OR. k >= dfftp%nr3 ) CYCLE DO ipol = 1, 3 posi(ipol) = DBLE( i )*inv_nr1*at(ipol,1) + & DBLE( j )*inv_nr2*at(ipol,2) + & DBLE( k )*inv_nr3*at(ipol,3) END DO posi(:) = posi(:) - tau(:,ia) CALL cryst_to_cart( 1, posi, bg, -1 ) IF ( abs(ANINT(posi(3))).gt.1.d-6 ) THEN i_lr = 0 ELSE i_lr = 1 END IF posi(:) = posi(:) - ANINT( posi(:) ) CALL cryst_to_cart( 1, posi, at, 1 ) distsq = posi(1)**2 + posi(2)**2 + posi(3)**2 IF ( distsq < boxradsq_ia ) THEN mbia = mbia + 1 orig_or_copy(mbia,ia) = i_lr END IF END DO END DO RETURN END SUBROUTINE realus_scatt_0 SUBROUTINE realus_scatt_1(becsum_orig) ! ! Augments the charge and spin densities. ! USE kinds, ONLY : dp USE ions_base, ONLY : nat, ityp USE lsda_mod, ONLY : nspin USE scf, ONLY : rho USE realus, ONLY : tabp USE uspp, ONLY : okvan, becsum, ijtoh USE uspp_param, ONLY : upf, nhm, nh USE noncollin_module, ONLY : noncolin USE spin_orb, ONLY : domag IMPLICIT NONE INTEGER :: ia, nt, ir, irb, ih, jh, ijh, is, nspin0, mbia, nhnt, iqs REAL(DP) :: becsum_orig(nhm*(nhm+1)/2,nat,nspin) IF (.NOT.okvan) RETURN nspin0 = nspin IF (noncolin.AND..NOT.domag) nspin0 = 1 DO is = 1, nspin0 iqs = 0 DO ia = 1, nat mbia = tabp(ia)%maxbox IF ( mbia == 0 ) CYCLE nt = ityp(ia) IF ( .NOT. upf(nt)%tvanp ) CYCLE nhnt = nh(nt) ijh = 0 DO ih = 1, nhnt DO jh = ih, nhnt ijh = ijh + 1 DO ir = 1, mbia irb = tabp(ia)%box(ir) iqs = iqs + 1 if(orig_or_copy(ir,ia).eq.1) then rho%of_r(irb,is) = rho%of_r(irb,is) + tabp(ia)%qr(ir,ijtoh(ih,jh,nt))*becsum_orig(ijh,ia,is) else rho%of_r(irb,is) = rho%of_r(irb,is) + tabp(ia)%qr(ir,ijtoh(ih,jh,nt))*becsum(ijh,ia,is) endif ENDDO ENDDO ENDDO ENDDO ENDDO RETURN END SUBROUTINE realus_scatt_1 END MODULE realus_scatt
dceresoli/ce-espresso
PWCOND/src/realus_scatt.f90
FORTRAN
gpl-2.0
4,755
# # Cookbook Name:: lxc_manage # Providers:: manage_node # # Copyright (C) 2015 Chris Hammer <chris@thezengarden.net> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/gpl-2.0.txt>. action :create do # Some vars to increase code readability def_domain = node["lxc_container"]["def_domain"] lxc_base = node["lxc_container"]["path"] + "/" + new_resource.lxc_name lxc_type = new_resource.lxc_vars['type'] || "centos" lxc_ver = new_resource.lxc_vars['version'] || false rootfs = lxc_base + "/rootfs" lxc_conf = lxc_base + "/config" lxc_opts = '' autostart = new_resource.lxc_vars['autostart'] startdelay = new_resource.lxc_vars['startdelay'] || 0 startorder = new_resource.lxc_vars['startorder'] || 1 lxcgroup = new_resource.lxc_vars['group'] || "ungrouped" limit_cpu = new_resource.lxc_vars['limit_cpu'] || false if (lxc_ver) lxc_opts = "-- --release=#{lxc_ver}" end execute "create-lxc-#{new_resource.lxc_name}" do command "lxc-create -t #{lxc_type} -n #{new_resource.lxc_name} #{lxc_opts}" not_if "lxc-ls | grep #{new_resource.lxc_name}" end # Create a backup of the LXC generated config: execute "backup-#{lxc_conf}" do command "mv #{lxc_conf} #{lxc_conf}.dist" not_if { ::File.exist?("#{lxc_conf}.dist") } end ruby_block "mac_addr_#{new_resource.name}" do block do if (new_resource.lxc_vars.has_key?("network")) new_resource.lxc_vars['network'].each do |dev,_vars| gen_mac = generate_mac node.normal['lxc_container']['node'][new_resource.lxc_name]['network'][dev]['hwaddr'] = gen_mac end else gen_mac = generate_mac node.normal["lxc_container"]["node"][new_resource.lxc_name]["network"]["eth0"]["hwaddr"] = gen_mac end end end if (new_resource.lxc_vars.has_key?("network")) new_resource.lxc_vars['network'].each do |dev,vars| template "#{lxc_base}/rootfs/etc/sysconfig/network-scripts/ifcfg-#{dev}" do source "ifcfg.erb" variables( lazy { { :network_device => dev, :hwaddr => node["lxc_container"]["node"][new_resource.lxc_name]["network"][dev]["hwaddr"], :ipaddr => vars['ip'], :ipcidr => vars['cidr'], :ipgateway => vars['gw'] } }) end end cookbook_file "#{lxc_base}/rootfs/etc/sysctl.d/99-rp_filter.conf" do source "99-rp_filter.conf" owner "root" group "root" mode "0644" only_if { lxc_type == "centos" && (lxc_ver == false || lxc_ver == "7") } end end template lxc_conf do source "container_config.erb" variables( lazy { { :rootfs => rootfs, :utsname_pre => new_resource.lxc_name, :utsname_post => def_domain, :network => new_resource.lxc_vars['network'], :autostart => autostart, :start_delay => startdelay, :start_order => startorder, :group => lxcgroup, :limit_cpu => limit_cpu, :cpu_cores => new_resource.lxc_vars['cpu_cores'], :cpu_shares => new_resource.lxc_vars['cpu_shares'] } }) only_if { ::File.exist?("#{lxc_conf}.dist") } end end action :update_conf do def_domain = node["lxc_container"]["def_domain"] lxc_base = node["lxc_container"]["path"] + "/" + new_resource.lxc_name lxc_type = new_resource.lxc_vars['type'] || "centos" lxc_ver = new_resource.lxc_vars['version'] || false rootfs = lxc_base + "/rootfs" lxc_conf = lxc_base + "/config" autostart = new_resource.lxc_vars['autostart'] startdelay = new_resource.lxc_vars['startdelay'] || 0 startorder = new_resource.lxc_vars['startorder'] || 1 lxcgroup = new_resource.lxc_vars['group'] || "ungrouped" limit_cpu = new_resource.lxc_vars['limit_cpu'] || false if (new_resource.lxc_vars.has_key?("network")) new_resource.lxc_vars['network'].each do |dev,vars| template "#{lxc_base}/rootfs/etc/sysconfig/network-scripts/ifcfg-#{dev}" do source "ifcfg.erb" variables( lazy { { :network_device => dev, :hwaddr => node["lxc_container"]["node"][new_resource.lxc_name]["network"][dev]["hwaddr"], :ipaddr => vars['ip'], :ipcidr => vars['cidr'], :ipgateway => vars['gw'] } }) end end else template "#{lxc_base}/rootfs/etc/sysconfig/network-scripts/ifcfg-eth0" do source "ifcfg.erb" variables({ :lxc_name => new_resource.lxc_name }) end end cookbook_file "#{lxc_base}/rootfs/etc/sysctl.d/99-rp_filter.conf" do source "99-rp_filter.conf" owner "root" group "root" mode "0644" only_if { lxc_type == "centos" && (lxc_ver == false || lxc_ver == "7") } end template lxc_conf do source "container_config.erb" variables( lazy { { :rootfs => rootfs, :utsname_pre => new_resource.lxc_name, :utsname_post => def_domain, :network => new_resource.lxc_vars['network'], :autostart => autostart, :start_delay => startdelay, :start_order => startorder, :group => lxcgroup, :limit_cpu => limit_cpu, :cpu_cores => new_resource.lxc_vars['cpu_cores'], :cpu_shares => new_resource.lxc_vars['cpu_shares'] } }) only_if { ::File.exist?("#{lxc_conf}.dist") } end end action :stop do execute "stopping-lxc-#{new_resource.name}" do command "lxc-stop -n #{new_resource.lxc_name}" end end action :start do execute "starting-lxc-#{new_resource.name}" do command "lxc-start -n #{new_resource.lxc_name} -d" end end action :destroy do execute "destroy-lxc-#{new_resource.lxc_name}" do command "lxc-stop -n #{new_resource.lxc_name}; lxc-destroy -n #{new_resource.lxc_name}" only_if "lxc-ls | grep #{new_resource.lxc_name}" end node.rm("lxc_container", "node", new_resource.lxc_name) end
jchristianh/lxc_manage
providers/node.rb
Ruby
gpl-2.0
6,746
#!/bin/bash ## ## Time-stamp: <2017-06-13 22:44:11 katsu> ## ## Some program were needed for this script ## "curl" ## "jq or python" ## "base64" #DEBUG="on" DEBUG="off" #CURL="curl -s -x http://your.proxy:80" CURL="curl -s" #JQ="jq . " JQ="python -m json.tool " ## ## parameters ## ADJ_TIME=9000 DIRNAME=`dirname $0` . $DIRNAME/opc_init.sh # Bash 4 has Associative array. # But Mac OS X has bash ver.3. So we do not use associative array. declare -a HOST_UUID_ASSOC # host name(uuid) in ipassociation declare -a VCABLE_UUID_ASSOC # vcable (uuid) in instance and ipassociation declare -a GIP_USE_ASSOC # Global IPs in ipassociation declare -a GIP_INSTANCE # Global IPs in instance declare -a GIP_FREE_UUID_RE # unused IP address name on ipreservation declare -a GIP_FREE_RESERV # unused IP address on ipreservation declare -a INSTANCE_UUID # instance name(uuid) declare -a SECRULE # secrule name declare -a SECLIST # seclist name declare -a SSHKEY # sshkey name declare -a ORCHESTRATION # orchestration name declare -a IPNETWORK # ipnetwork name declare -a VIRTUALNIC # virtualnic name declare -a VIRTUALNICSET # virtualnic set name declare -a ROUTES # Routes name declare -a VPN # VPN Gateway name SESSION_ID="$CONF_DIR/tmp-compute.$$" # temporary text file for auth info COOKIE_FILE="$CONF_DIR/tmp-compute_cookie-$OPC_DOMAIN" COMPUTE_COOKIE="" ## ## Authentication function ## get_cookie() { if [ -f "$COOKIE_FILE" ]; then epoch_date=$(date '+%s') epoch_cookie=$( sed 's/^nimbula=//' $COOKIE_FILE | base64 --decode \ | LANG=C sed 's/\(.*\)expires\(.*\)expires\(.*\)/\2/' \ | sed -e 's/\(.*\) \([0-9]\{10,\}.[0-9]\{3,\}\)\(.*\)/\2/' \ | sed -e 's/\(.*\)\.\(.*\)/\1/') # echo "$epoch_cookie" # echo "$epoch_date" ## If you use gnu date, it works # date --date="$epoch_cookie" # date --date="$epoch_date" # check $epoch_cookie value is valid ret=$(echo $epoch_cookie | sed -e 's/[0-9]\{10,\}/OK/') if [ "$ret" != OK ]; then echo "Authentication has been failed" echo "Please delete the file (COOKIE_FILE) $COOKIE_FILE" exit 1 fi # compare authenticate life time on cookie file and date command if [ $(($epoch_cookie-$epoch_date)) -gt $ADJ_TIME ]; then COMPUTE_COOKIE=$(cat $COOKIE_FILE) cache_file=`basename $COOKIE_FILE` status="Authenticated with cache file $cache_file" else _get_cookie fi else _get_cookie fi # uncomment next line for no caching $COOKIE_FILE if [ $DEBUG != "on" ]; then rm $COOKIE_FILE fi } _get_cookie() { ret=$($CURL -X POST \ -H "Content-Type: application/oracle-compute-v3+json" \ -w '%{http_code}' \ -d "{\"user\":\"/Compute-$OPC_DOMAIN/$OPC_ACCOUNT\",\ \"password\":\"$OPC_PASS\"}" \ $IAAS_URL/authenticate/ -D $SESSION_ID ) COMPUTE_COOKIE=$( grep -i Set-cookie $SESSION_ID | cut -d';' -f 1 \ | cut -d' ' -f 2 | tee $COOKIE_FILE ) status=$(echo $ret | sed -e 's/.*\([0-9][0-9][0-9]$\)/\1/') if [ "$status" = 204 ]; then status="Authenticated" elif [ "$status" = 401 ]; then echo "Incorrect username or password" exit 1 else echo "IAAS_URL on CONFIG_FILE could not be reached." echo echo "IAAS_URL=$IAAS_URL" echo echo "Please check IAAS_URL on the web dashboard." echo "It is the REST Endpoint." fi if [ $DEBUG != "on" ]; then rm $SESSION_ID fi } ## ## functions ## account() { $CURL -X GET -H "Cookie: $COMPUTE_COOKIE" \ -H "Accept: application/oracle-compute-v3+directory+json"\ $IAAS_URL/account/Compute-$OPC_DOMAIN/ | $JQ } delete(){ echo "Which object do you want to delete ?" echo echo " 1: instance" echo " 2: storage volume" echo " 3: global IP address" echo " 4: above all, seclist, secrule, sshkey, orchestration, ipnetwork" echo echo -n "Choose 1,2,3,4: " read ans1 case $ans1 in 1) # delete Instances get_cookie ipassociation_list instances_list v if [ -z ${INSTANCE_UUID[0]} ]; then echo echo "There is no instance." echo exit 1 fi echo echo "----------------" echo "Do you want to delete these instance?" echo -n "(1:Yes / 2:Only $OPC_ACCOUNT's / 3:No): " read ans2 case $ans2 in 1 | [Yy]* ) for ((i = 0 ; i < ${#INSTANCE_UUID[@]};++i )) do instance_delete ${INSTANCE_UUID[$i]} done ;; 2 | [Oo]* ) for ((i = 0 ; i < ${#INSTANCE_UUID[@]};++i )) do user1=$(echo ${INSTANCE_UUID[$i]} \ | sed -n -e 's/\/[^/]*\/\([^/]*\)\/.*/\1/p') if [ "$user1" = "$OPC_ACCOUNT" ]; then instance_delete ${INSTANCE_UUID[$i]} fi done ;; *) exit 1 ;; esac ;; 2) # delete Storage Volume get_cookie storage_volume_list if [ -z ${vol_name[0]} ]; then echo echo "There is no Storage Volume." echo exit 1 fi echo echo "Do you want to delete these storage volume?" echo -n "(1:Yes / 2:Only $OPC_ACCOUNT's / 3:No): " read ans2 case $ans2 in 1 | [Yy]* ) echo for ((i = 0 ; i < ${#vol_name[@]}; ++i )) do storage_volume_delete ${vol_name[$i]} done ;; 2 | [Oo]* ) for ((i = 0 ; i < ${#vol_name[@]};++i )) do user1=$(echo ${vol_name[$i]} \ | sed -n -e 's/[^/]*\/\([^/]*\)\/.*/\1/p') if [ "$user1" = "$OPC_ACCOUNT" ]; then storage_volume_delete ${vol_name[$i]} fi done ;; *) exit 1 ;; esac ;; 3) # delete global IP address reservation get_cookie ipassociation_list instances_list ipreservation_list if [ -z ${GIP_FREE_RESERV[0]} ]; then echo echo "There is no unused global IP address." echo exit 1 fi echo echo "global address that is not used" echo "----------------------------------" echo -e "IP ADDRESS\tFREE OBJECT NAME" for ((i = 0 ; i < ${#GIP_FREE_RESERV[$i]};++i )) do echo -e "${GIP_FREE_RESERV[$i]}\t${GIP_FREE_UUID_RE[$i]}" done echo "----------------------------------" echo "Do you want to delete these addresses?" echo -n "(1:Yes / 2:Only $OPC_ACCOUNT's / 3:No): " read ans2 case $ans2 in 1 | [Yy]* ) for ((i = 0 ; i < ${#GIP_FREE_RESERV[@]};++i )) do ipreservation_delete ${GIP_FREE_UUID_RE[$i]} done ;; 2 | [Oo]* ) for ((i = 0 ; i < ${#GIP_FREE_RESERV[@]};++i )) do user1=$(echo ${GIP_FREE_UUID_RE[$i]} \ | sed -n -e 's/\([^/]*\)\/.*/\1/p') if [ "$user1" = "$OPC_ACCOUNT" ]; then ipreservation_delete ${GIP_FREE_UUID_RE[$i]} fi done ;; *) exit 1 ;; esac ;; 4) # delete Everything get_cookie ipassociation_list instances_list list ipreservation_list storage_volume_list DEFAULT_SECLIST=0 seclist_list DEFAULT_SECRULE=0 secrule_list sshkey_list orchestration_list route_list ipexchange_list ipnetwork_list echo echo "Do you want to delete these on $OPC_DOMAIN site?" echo -n "(1:Yes / 2:Only $OPC_ACCOUNT's / 3:No): " read ans2 case $ans2 in 1 | [Yy]* ) # orchestration for ((i = 0 ; i < ${#ORCHESTRATION[@]}; ++i )) do orchestration_delete ${ORCHESTRATION[$i]} done # route for ((i = 0 ; i < ${#ROUTE[@]}; ++i )) do route_delete ${ROUTE[$i]} done # ipexchange for ((i = 0 ; i < ${#IPEXCHANGE[@]}; ++i )) do ipexchange_delete ${IPEXCHANGE[$i]} done # ipnetwork for ((i = 0 ; i < ${#IPNETWORK[@]}; ++i )) do ipnetwork_delete ${IPNETWORK[$i]} done # instance for ((i = 0 ; i < ${#INSTANCE_UUID[@]};++i )) do instance_delete ${INSTANCE_UUID[$i]} done # storage for ((i = 0 ; i < ${#vol_name[@]}; ++i )) do storage_volume_delete ${vol_name[$i]} done # global IP address for ((i = 0 ; i < ${#GIP_FREE_RESERV[@]};++i )) do ipreservation_delete ${GIP_FREE_UUID_RE[$i]} done # secrule for ((i = 0 ; i < ${#SECRULE[@]}; ++i )) do secrule_delete ${SECRULE[$i]} done if [ "$DEFAULT_SECRULE" = 0 ];then secrule_default_create fi # seclist for ((i = 0 ; i < ${#SECLIST[@]}; ++i )) do seclist_delete ${SECLIST[$i]} done if [ "DEFAULT_SECLIST" = 0 ];then seclist_create default fi # sshkey for ((i = 0 ; i < ${#SSHKEY[@]}; ++i )) do sshkey_delete ${SSHKEY[$i]} done ;; 2 | [Oo]* ) # orchestration for ((i = 0 ; i < ${#ORCHESTRATION[@]}; ++i )) do echo $i user1=$(echo ${ORCHESTRATION[$i]} \ | sed -n -e 's/\([^/]*\)\/.*/\1/p') echo yyy $user1 if [ "$user1" = "$OPC_ACCOUNT" ]; then orchestration_delete ${ORCHESTRATION[$i]} fi done # instance for ((i = 0 ; i < ${#INSTANCE_UUID[@]};++i )) do user1=$(echo ${INSTANCE_UUID[$i]} \ | sed -n -e 's/\/[^/]*\/\([^/]*\)\/.*/\1/p') if [ "$user1" = "$OPC_ACCOUNT" ]; then instance_delete ${INSTANCE_UUID[$i]} fi done # storage for ((i = 0 ; i < ${#vol_name[@]};++i )) do user1=$(echo ${vol_name[$i]} \ | sed -n -e 's/\([^/]*\)\/.*/\1/p') if [ "$user1" = "$OPC_ACCOUNT" ]; then storage_volume_delete ${vol_name[$i]} fi done # global IP address for ((i = 0 ; i < ${#GIP_FREE_RESERV[@]};++i )) do user1=$(echo ${GIP_FREE_UUID_RE[$i]} \ | sed -n -e 's/\([^/]*\)\/.*/\1/p') if [ "$user1" = "$OPC_ACCOUNT" ]; then ipreservation_delete ${GIP_FREE_UUID_RE[$i]} fi done # secrule for ((i = 0 ; i < ${#SECRULE[@]}; ++i )) do user1=$(echo ${SECRULE[$i]} \ | sed -n -e 's/\([^/]*\)\/.*/\1/p') if [ "$user1" = "$OPC_ACCOUNT" ]; then secrule_delete ${SECRULE[$i]} fi done if [ "$DEFAULT_SECRULE" = 0 ];then secrule_default_create fi # seclist for ((i = 0 ; i < ${#SECLIST[@]}; ++i )) do user1=$(echo ${SECLIST[$i]} \ | sed -n -e 's/\([^/]*\)\/.*/\1/p') if [ "$user1" = "$OPC_ACCOUNT" ]; then seclist_delete ${SECLIST[$i]} fi done if [ "DEFAULT_SECLIST" = 0 ];then seclist_create default fi # sshkey for ((i = 0 ; i < ${#SSHKEY[@]}; ++i )) do user1=$(echo ${SSHKEY[$i]} \ | sed -n -e 's/\([^/]*\)\/.*/\1/p') if [ "$user1" = "$OPC_ACCOUNT" ]; then sshkey_delete ${SSHKEY[$i]} fi done ;; *) exit 1 ;; esac ;; esac } imagelist_info() { imagelist=$CONF_DIR/tmp-imagelist-$OPC_DOMAIN imagename=($($CURL -X GET -H "Cookie:$COMPUTE_COOKIE" \ $IAAS_URL/imagelist/oracle/public/ | $JQ | tee $imagelist \ | sed -n -e 's/.*\"name\": \"\/oracle\/public\/\(.*\)\",/\1/p')) _IFS=$IFS IFS=$'\n' imagedesc=($(sed -n -e 's/.*\"description\": \(.*\),/\1/p' $imagelist )) echo " SHAPE \"DESCRIPTION\"" echo "-------------------------------------------------------------" for ((i = 0 ; i < ${#imagedesc[@]};++i )) do printf "%-35s %s\n" ${imagename[$i]} ${imagedesc[$i]} done IFS=$_IFS if [ $DEBUG != "on" ]; then rm $imagelist fi } imagelist_user_defined_info() { $CURL -X GET -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/imagelist/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/ | $JQ } imagelistentry_info() { test_image=oel_6.4_2GB_v1 $CURL -X GET -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/imagelist/oracle/public/$test_image/entry/1 | $JQ } instance() { echo "What instance/uuid do you want to show ?" read ans $CURL -X GET -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/instance/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans | $JQ } instances() { $CURL -X GET -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/instance/Compute-$OPC_DOMAIN/ | $JQ } instance_delete() { if [ "$1" = "" ]; then echo "What instance/uuid do you want to delete ?" read ans ret=$($CURL -X DELETE -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/instance/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans) else ret=$($CURL -X DELETE \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/instance$1) fi status=$(echo $ret | sed -n -e 's/.*\([0-9][0-9][0-9]$\)/\1/p') # If successful, "HTTP/1.1 204 No Content" is returned. if [ "$status" = 204 ]; then echo "$1""$ans"" deleted" else echo $ret fi } instances_list() { instance=$CONF_DIR/tmp-instance-$OPC_DOMAIN if [ "$1" == list ]; then echo echo " OBJECT list for the Domain $OPC_DOMAIN" echo "-------------------------------------------------------------" echo " ### INSTANCE ###" echo "-------------------------------------------------------------" if [ "$1" == list ]; then echo "Host Status "\ "Private IP Global IP" elif [ "$1" == v ]; then echo "User Host MAC "\ "Private IP Global IP" fi fi # sed:1 pick up object "name" # sed:2 omit storage attachment uuid by "uniq" # sed:3 choose object with uuid # get INSTANCE uuid INSTANCE_UUID=($($CURL -X GET -H "Cookie:$COMPUTE_COOKIE" \ $IAAS_URL/instance/Compute-$OPC_DOMAIN/ | $JQ | tee $instance \ | sed -n -e 's/.*\"name\".*\(\/Compute-.*\)\".*/\1/p' \ | sed -e 's/\(\/Compute-.*\/.*\/.*\/.*\)\/.*/\1/' | uniq \ | sed -n -e '/[0-9a-z]\{8\}-[0-9a-z]\{4\}-.*-.*-[0-9a-z]\{12\}/p' )) # get eth0 MAC address mac_address=($(grep -A1 '\"address\":' $instance \ | sed -n -e 's/.*\"\(.*:.*:.*\)\",/\1/p')) # get private IP address private_ip=($(sed -n -e 's/.*\"ip\": \"\(.*\)\",/\1/p' $instance )) # get vcable id vcable_uuid_instance=($(sed \ -n -e 's/.*\"vcable_id\".*\/.*\/.*\/\(.*\)\",/\1/p' $instance )) state=($(sed -n -e 's/.*\"state\": "\(.*\)\",/\1/p' $instance)) shape=($(sed -n -e 's/.*\"shape\": "\(.*\)\",/\1/p' $instance)) # Now INSTANCE_UUID,MAC_ADDRESS,private_ip,vcable_uuid_instance has # same index in row. # Because they are in same block in $INSTANCE file. # Next "for loop" use $i to pick up the factor. # view like web console declare -a host_name for ((i = 0 ; i < ${#INSTANCE_UUID[@]};++i )) do user1=$( echo ${INSTANCE_UUID[$i]} \ | sed -e "s/\/Compute-$OPC_DOMAIN\/\([^/]*\).*/\1/" ) # get hostname/uuid host_uuid=$( echo ${INSTANCE_UUID[$i]} \ | sed -e "s/\/Compute-$OPC_DOMAIN\/[^/]*\(.*\)/\1/" \ -e 's/^\///' ) # get hostname host_name[${#host_name[@]}]=$( echo $host_uuid \ | sed -e 's/\(.*\)[/].*/\1/' ) for ((m = 0 ; m < ${#VCABLE_UUID_ASSOC[@]}; ++m )) do if [[ ${vcable_uuid_instance[$i]} = ${VCABLE_UUID_ASSOC[$m]} ]]; then GIP_INSTANCE[$i]=${GIP_USE_ASSOC[$m]} if [ "$1" == list ]; then printf "%-16s " ${host_name[$i]} printf "%8s " $state printf "%-16s" ${private_ip[$i]} printf "%-16s" ${GIP_USE_ASSOC[$m]} printf "\n" elif [ "$1" == v ]; then printf "%-16s " $user1 printf "%-12s " ${host_name[$i]} printf "%17s " ${mac_address[$i]} printf "%-16s" ${private_ip[$i]} printf "%-16s" ${GIP_USE_ASSOC[$m]} printf "\n" fi HOST_UUID_ASSOC[$m]=$host_uuid break fi done done # view for /etc/hosts file if [ "$1" == list ]; then echo "-------------------------------------------------------------" echo "hosts for private network" echo "-------------------------------------------------------------" for ((i = 0 ; i < ${#INSTANCE_UUID[@]};++i )) do printf "%-16s" ${private_ip[$i]} printf "%-16s " ${host_name[$i]} printf "\n" done echo "-------------------------------------------------------------" echo "hosts for global network" echo "-------------------------------------------------------------" for ((i = 0 ; i < ${#INSTANCE_UUID[@]};++i )) do if [[ ${GIP_INSTANCE[$i]} != "" ]]; then printf "%-16s" ${GIP_INSTANCE[$i]} printf "%-16s " ${host_name[$i]} printf "\n" fi done fi if [ $DEBUG != "on" ]; then rm $instance fi } ipassociation() { # connect vcable and ipreservation $CURL -X GET -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/ip/association/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/ | $JQ } ipassociation_list() { # instance: "vcable_uuid_instance(uuid)" # ipassociation: "name"(uuid),"reservation"(uuid),"vcable"(uuid) # ipreservation: "name"(uuid),"ip"(uuid) ip_assoc=$CONF_DIR/tmp-ipassociation-$OPC_DOMAIN # get user account name user_id_assoc=($($CURL -X GET \ -H "Accept: application/oracle-compute-v3+directory+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/ip/association/Compute-$OPC_DOMAIN/ | $JQ \ | sed -n -e 's/.*\/Compute-.*\/\(.*\)\/.*/\1/p')) # get the object from all users account # objects into $user_id_assoc[$i]/$OBJECT[$j] # $OBJECT is array of ipassociation name and ip address # get all user_id_assoc's information from ip_assoc for ((m = 0 ; m < ${#user_id_assoc[@]};++m )) do echo checking ${user_id_assoc[$m]}, # get global IP address global_ip_assoc=($($CURL -X GET \ -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/ip/association/Compute-$OPC_DOMAIN/${user_id_assoc[$m]}/ \ | $JQ | tee $ip_assoc-${user_id_assoc[$m]} \ | sed -n -e 's/.*\"ip\": \"\(.*\)\",/\1/p' )) # get vcable uuid vcable_assoc=($(sed -n -e 's/.*\"vcable\": \"\/.*\/.*\/\(.*\)\"/\1/p' \ $ip_assoc-${user_id_assoc[$m]})) # set global IP address into VCABLE_GIP # "${#global_ip[@]}" is total number of global_ip # make VCABLE_UUID_ASSOC[j] and GIP_USE_ASSOC[j] in same index row for ((n = 0 ; n < ${#global_ip_assoc[@]}; ++n )) do VCABLE_UUID_ASSOC[${#VCABLE_UUID_ASSOC[@]}]=${vcable_assoc[$n]} GIP_USE_ASSOC[${#GIP_USE_ASSOC[@]}]=${global_ip_assoc[$n]} done if [ $DEBUG != "on" ]; then rm $ip_assoc-${user_id_assoc[$m]} fi done } ipnetwork_list() { I_FILE=$CONF_DIR/tmp-ipnetwork-$OPC_DOMAIN IPNETWORK=($($CURL -X GET \ -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/network/v1/ipnetwork/Compute-$OPC_DOMAIN/ \ | $JQ | tee $I_FILE \ | sed -n -e 's/.*\"name\": \"\/[^/]*\/\(.*\)\",/\1/p')) echo echo IPNETWORK echo "-------------------------------------" for (( i=0 ; i < ${#IPNETWORK[@]}; i++ )) do echo "${IPNETWORK[$i]}" done echo "-------------------------------------" if [ $DEBUG != "on" ]; then rm $I_FILE fi } ipnetwork_delete() { if [ "$1" = "" ]; then echo "What is the name of ipnetwork to delete ?" read ans ret=$($CURL -X DELETE \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/network/v1/ipnetwork/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans) else ret=$($CURL -X DELETE \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/network/v1/ipnetwork/Compute-$OPC_DOMAIN/$1) fi status=$(echo $ret | sed -n -e 's/.*\([0-9][0-9][0-9]$\)/\1/p') # If successful, "HTTP/1.1 204 No Content" is returned. if [ "$status" = 204 ]; then echo "$1""$ans"" deleted" else echo $ret fi } ipexchange_list() { IE_FILE=$CONF_DIR/tmp-ipexchange-$OPC_DOMAIN IPEXCHANGE=($($CURL -X GET \ -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/network/v1/ipnetworkexchange/Compute-$OPC_DOMAIN/ \ | $JQ | tee $IE_FILE \ | sed -n -e 's/.*\"name\": \"\/[^/]*\/\(.*\)\",/\1/p')) echo echo IPEXCHANGE echo "-------------------------------------" for (( i=0 ; i < ${#IPEXCHANGE[@]}; i++ )) do echo "${IPEXCHANGE[$i]}" done echo "-------------------------------------" if [ $DEBUG != "on" ]; then rm $IE_FILE fi } ipexchange_delete() { if [ "$1" = "" ]; then echo "What is the name of ipexchange to delete ?" read ans ret=$($CURL -X DELETE \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/network/v1/ipnetworkexchange/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans) else ret=$($CURL -X DELETE \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/network/v1/ipnetworkexchange/Compute-$OPC_DOMAIN/$1) fi status=$(echo $ret | sed -n -e 's/.*\([0-9][0-9][0-9]$\)/\1/p') # If successful, "HTTP/1.1 204 No Content" is returned. if [ "$status" = 204 ]; then echo "$1""$ans"" deleted" else echo $ret fi } ipreservation() { # Global IP address $CURL -X GET \ -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/ip/reservation/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/ | $JQ } ipreservation_create() { if [ "$1" = "" ]; then echo "What is the name of ipreservation to create ?" read ans ret=$($CURL -X POST \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ -d "{\"parentpool\":\"/oracle/public/ippool\", \ \"account\":\"/Compute-$OPC_DOMAIN/default\",\ \"permanent\": true, \ \"name\": \"/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans\"}"\ $IAAS_URL/ip/reservation/ ) else ret=$($CURL -X POST \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ -d "{\"parentpool\":\"/oracle/public/ippool\", \ \"account\":\"/Compute-$OPC_DOMAIN/default\",\ \"permanent\": true, \ \"name\": \"/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$1\"}"\ $IAAS_URL/ip/reservation/ ) fi status=$(echo $ret | sed -n -e 's/.*\([0-9][0-9][0-9]$\)/\1/p') if [ "$status" = 201 ]; then echo "$ans""$1"" created" else echo $ret fi } ipreservation_delete() { if [ "$1" = "" ]; then echo "What is the name of ipreservation to delete ?" read ans ret=$($CURL -X DELETE \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/ip/reservation/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans) else ret=$($CURL -X DELETE \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/ip/reservation/Compute-$OPC_DOMAIN/$1) fi status=$(echo $ret | sed -n -e 's/.*\([0-9][0-9][0-9]$\)/\1/p') # If successful, "HTTP/1.1 204 No Content" is returned. if [ "$status" = 204 ]; then echo "$1""$ans"" deleted" else echo $ret fi } ipreservation_list() { # There is 3 containers. # instance: "vcable"(uuid) # ipassociation: "name"(uuid),"reservation"(uuid),"vcable"(uuid) # ipreservation: "name"(uuid),"ip"(uuid) # We have to link host id to ipreservation id with ipassociation_list(). # Some time ipreservation id has no linkage with any instance id. ip_reserv="$CONF_DIR"/tmp-ipreservation-"$OPC_DOMAIN" # get account name which use global IP address # using "Accept: application/oracle-compute-v3+directory+json", # we could get not only $OPC_ACCOUNT but another account name. # And ipreservation objects are only being showed on owner account's # sub object with "Accept: application/oracle-compute-v3+json". # That is why trying to get user_id_re first and to get each sub # objects. # get user account name user_id_re=($($CURL -X GET \ -H "Accept: application/oracle-compute-v3+directory+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/ip/reservation/Compute-$OPC_DOMAIN/ | $JQ \ | sed -n -e 's/.*\/Compute-.*\/\(.*\)\/.*/\1/p' )) # get the object from all users account # objects into $user_id_re[$i]/$OBJECT[$j] echo "-------------------------------------------------------------" echo " ### GLOBAL IP ADDRESS (IP RESERVATION) ###" echo "-------------------------------------------------------------" echo -e "User IP ADDRESS Host" # pick up every user's global IP address for ((m = 0 ; m < ${#user_id_re[@]};++m )) do gip_reserv=($($CURL -X GET \ -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/ip/reservation/Compute-$OPC_DOMAIN/${user_id_re[$m]}/ \ | $JQ | tee $ip_reserv-${user_id_re[$m]} \ | sed -n -e 's/.*\"ip\": \"\(.*\)\",/\1/p' )) resv_name=($(sed -n \ -e "s/.*\"name\": \"\/Compute-$OPC_DOMAIN\/\(.*\)\",/\1/p" \ $ip_reserv-${user_id_re[$m]} )) # gip_reserv is from ipreservation # GIP_USE_ASSOC is from ipassociation # get unused Global IP address # if there is no global IP address on ipassociation, # all gip_reserv on ipreservation must be unused. if [ "${#GIP_USE_ASSOC[@]}" == 0 ]; then for ((k = 0 ; k < ${#gip_reserv[@]}; ++k )) do echo "${gip_reserv[$k]}" # pickup no use IP address using in delete() GIP_FREE_RESERV[${#GIP_FREE_RESERV[@]}]=${gip_reserv[$k]} GIP_FREE_UUID_RE[${#GIP_FREE_UUID_RE[@]}]=${resv_name[$k]} done else for ((i = 0 ; i < ${#gip_reserv[@]}; ++i )) do for ((j = 0 ; j < ${#GIP_USE_ASSOC[@]}; ++j )) do if [ "${gip_reserv[$i]}" = "${GIP_USE_ASSOC[$j]}" ]; then # instance_list() to ipreservation_list() hostname_reserv=$( echo ${HOST_UUID_ASSOC[$j]} \ | sed -e 's/\(.*\)[/].*/\1/' ) printf "%-16s " ${user_id_re[$m]} printf "%-16s" ${GIP_USE_ASSOC[$j]} printf "%-12s " $hostname_reserv printf "\n" break elif [ $(($j+1)) = "${#GIP_USE_ASSOC[@]}" ];then # it must be without INSTANCE printf "%-16s " ${user_id_re[$m]} printf "%-16s" ${gip_reserv[$i]} printf "\n" # pickup no use IP address using in delete() GIP_FREE_RESERV[${#GIP_FREE_RESERV[@]}]="${gip_reserv[$i]}" GIP_FREE_UUID_RE[${#GIP_FREE_UUID_RE[@]}]="${resv_name[$i]}" fi done done if [ $DEBUG != "on" ]; then rm $ip_reserv-${user_id_re[$m]} fi fi done } launchplan() { echo "What is the name of new host ?" read host_name echo "What is the sshkey ? (you must upload sshkey first.)" read SSHKEY ret=$($CURL -X POST \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ -d "{\"instances\": [ \ {\"shape\": \"oc3\",\ \"imagelist\": \"/oracle/public/OL_6.7_3GB-1.3.0-20160411\",\ \"sshkeys\": [\"/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$SSHKEY\"],\ \"name\": \"/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$host_name\",\ \"label\": \"$host_name\",\ \"attributes\": {\"userdata\": \ {\"corente-tunnel-args\": \"--local-tunnel-address=172.16.21.3 --csg-hostname=csg.compute-gse00000626.oraclecloud.internal --csg-tunnel-address=172.16.254.1 --onprem-subnets=192.168.0.0/24\"} },\ \"networking\":{\"eth0\": \ {\"dns\": [\"$host_name\"], \ \"seclists\": [\"/Compute-$OPC_DOMAIN/default/default\"], \ \"nat\":\"ippool:/oracle/public/ippool\"} }\ } ] }" \ $IAAS_URL/launchplan/) status=$(echo $ret | sed -e 's/.*\([0-9][0-9][0-9]$\)/\1/') if [ "$status" = 201 ]; then echo "$host_name created" else echo $ret fi } # uploaded images machineimage() { $CURL -X GET -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/machineimage/Compute-$OPC_DOMAIN/ \ | $JQ echo } # Under construction # POST /machineimage/, POST /imagelist/, and POST /imagelistentry/ methods machineimage_create(){ # echo "What is the name of machineimage on storage cloud ?" # read FILE_NAME FILE_NAME="CentOS-7-x86_64-OracleCloud.raw.tar.gz" IMAGE_NAME=centos7-cui # opc_storage.sh -l $OPC_DOMAIN _upload compute_images $FILE_NAME SIZE=`opc_storage.sh -l $OPC_DOMAIN _metadata $FILE_NAME` SIZE_TOTAL=`echo $SIZE | tr -d '\r\n'` echo $SIZE_TOTAL $CURL -X POST -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -d "{\"account\":\"/Compute-$OPC_DOMAIN/cloud_storage\",\ \"name\":\"/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$IMAGE_NAME\",\ \"no_upload\":true,\ \"file\":\"compute_images/$FILE_NAME\",\ \"sizes\":{\"upload\":$SIZE_TOTAL,\ \"total\":$SIZE_TOTAL}}" \ $IAAS_URL/machineimage/ echo } machineimage_info(){ $CURL -X GET -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/machineimage/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/ | $JQ echo } nic() { $CURL -X GET -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/network/v1/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/ | $JQ echo } orchestration(){ O_FILE=/tmp/orchestration-$OPC_DOMAIN $CURL -X GET \ -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/orchestration/Compute-$OPC_DOMAIN/ \ | $JQ | tee $O_FILE \ | sed -n -e 's/.*\"name\": \"\/[^/]*\/\(.*\)\",/\1/p' } orchestration_container(){ O_FILE=/tmp/orchestration-$OPC_DOMAIN $CURL -X GET \ -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/orchestration/Compute-$OPC_DOMAIN/default } orchestration_delete(){ O_FILE=/tmp/orchestration-$OPC_DOMAIN if [ "$1" = "" ]; then echo "Which orchestration do you want to delete ?" read ans ret=$($CURL -X DELETE \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/orchestration/Compute-$OPC_DOMAIN/$ans ) else $CURL -X PUT \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/orchestration/Compute-$OPC_DOMAIN/$1?action=STOP ret=$($CURL -X DELETE \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/orchestration/Compute-$OPC_DOMAIN/$1 ) fi status=$(echo $ret | sed -n -e 's/.*\([0-9][0-9][0-9]$\)/\1/p') # If successful, "HTTP/1.1 204 No Content" is returned. if [ "$status" = 204 ]; then echo "$1""$ans"" deleted" else echo $ret fi } orchestration_list(){ O_FILE=$CONF_DIR/orchestration-$OPC_DOMAIN ORCHESTRATION=($($CURL -X GET \ -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/orchestration/Compute-$OPC_DOMAIN/ \ | $JQ | tee $O_FILE \ | grep -B 1 "oplans\":" \ | sed -n -e 's/.*\"name\": \"\/[^/]*\/\(.*\)\",/\1/p')) echo echo ORCHESTRATION echo "-------------------------------------" for (( i=0 ; i < ${#ORCHESTRATION[@]}; i++ )) do echo "${ORCHESTRATION[$i]}" done echo "-------------------------------------" if [ $DEBUG != "on" ]; then rm $O_FILE fi } role() { sed -e 's/nimbula=//' $COOKIE_FILE | base64 -d \ | sed -e 's/Compute-$OPC_DOMAIN\/\(.*\)/\1/' echo } route_list() { R_FILE=$CONF_DIR/tmp-route-$OPC_DOMAIN ROUTE=($($CURL -X GET \ -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/network/v1/route/Compute-$OPC_DOMAIN/ \ | $JQ | tee $R_FILE \ | sed -n -e 's/.*\"name\": \"\/[^/]*\/\(.*\)\",/\1/p')) echo echo ROUTE echo "-------------------------------------" for (( i=0 ; i < ${#ROUTE[@]}; i++ )) do echo "${ROUTE[$i]}" done echo "-------------------------------------" if [ $DEBUG != "on" ]; then rm $R_FILE fi } route_delete() { if [ "$1" = "" ]; then echo "What is the name of route to delete ?" read ans ret=$($CURL -X DELETE \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/network/v1/route/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans) else ret=$($CURL -X DELETE \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/network/v1/route/Compute-$OPC_DOMAIN/$1) fi status=$(echo $ret | sed -n -e 's/.*\([0-9][0-9][0-9]$\)/\1/p') # If successful, "HTTP/1.1 204 No Content" is returned. if [ "$status" = 204 ]; then echo "$1""$ans"" deleted" else echo $ret fi } secassociation() { # endpoint: secassociation/vcable_uuid/secassociation_uuid $CURL -X GET -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/secassociation/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/ | $JQ } secassociation_create() { # endpoint: secassociation/vcable_uuid/secassociation_uuid $CURL -X GET -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/secassociation/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/ | $JQ } seclist() { echo default: $CURL -X GET -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/seclist/Compute-$OPC_DOMAIN/default/ | $JQ echo echo user: $CURL -X GET -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/seclist/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/ | $JQ echo } seclist_create(){ echo -n "What is the name of container do you create ? " read ans if [[ "$ans" =~ ^default$|^default/default$ ]]; then $CURL -X POST -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -d "{\"name\": \"/Compute-$OPC_DOMAIN/default/default\", \"outbound_cidr_policy\": \"PERMIT\", \"policy\": \"DENY\" }" \ $IAAS_URL/seclist/Compute-$OPC_DOMAIN/$ans else echo -n "Which is JSON file ? " read json $CURL -X POST -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -d @"$json" \ $IAAS_URL/seclist/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans fi echo } seclist_delete(){ if [ "$1" = "" ]; then echo "What is the name of seclist you want to delete ?" read ans ret=$($CURL -X DELETE -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/seclist/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans ) elif [ "$1" != default/default ]; then ret=$($CURL -X DELETE -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/seclist/Compute-$OPC_DOMAIN/$1 ) # If successful, "HTTP/1.1 204 No Content" is returned. if [ "$status" = 204 ]; then echo "$1""$ans"" deleted" else echo $ret fi fi } seclist_list() { SECLIST=($($CURL -X GET \ -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/seclist/Compute-$OPC_DOMAIN/ | $JQ \ | sed -n -e 's/.*\"name\": \"\/[^/]*\/\(.*\)\"\,/\1/p' )) echo echo SECLIST echo "-------------------------------------" for (( i=0 ; i < ${#SECLIST[@]}; i++ )) do echo "${SECLIST[$i]}" if [ "${SECLIST[$i]}" = 'default/default' ]; then DEFAULT_SECLIST=1 fi done echo "-------------------------------------" } secrule() { $CURL -X GET -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/secrule/Compute-$OPC_DOMAIN/ | $JQ echo } secrule_list() { SECRULE=($($CURL -X GET \ -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/secrule/Compute-$OPC_DOMAIN/ | $JQ \ | sed -n -e 's/.*\"name\": \"\/[^/]*\/\(.*\)\"\,/\1/p' )) echo echo SECRULE echo "-------------------------------------" for (( i=0 ; i < ${#SECRULE[@]}; i++ )) do echo "${SECRULE[$i]}" if [ "${SECRULE[$i]}" = 'DefaultPublicSSHAccess' ]; then DEFAULT_SECRULE=1 fi done echo "-------------------------------------" } secrule_default_create() { ret=$($CURL -X POST -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ -d "{ \"action\": \"PERMIT\", \"application\": \"/oracle/public/ssh\", \"description\": \"Default security rule for public SSH access to instances in the default security list.\", \"disabled\": false, \"dst_is_ip\": "false", \"dst_list\": \"seclist:/Compute-$OPC_DOMAIN/default/default\", \"name\": \"/Compute-$OPC_DOMAIN/DefaultPublicSSHAccess\", \"src_is_ip\": \"true\", \"src_list\": \"seciplist:/oracle/public/public-internet\" }" \ $IAAS_URL/secrule/ ) status=$(echo $ret | sed -e 's/.*\([0-9][0-9][0-9]$\)/\1/') if [ "$status" = 201 ]; then echo "default secrule created" else echo $ret fi } secrule_default() { ret=$($CURL -X GET -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/secrule/Compute-$OPC_DOMAIN/DefaultPublicSSHAccess ) status=$(echo $ret | sed -e 's/.*\([0-9][0-9][0-9]$\)/\1/') if [ "$status" = 200 ]; then echo "DefaultPublicSSHAccess exists" else echo "Try to make DefaultPublicSSHAccess rule" secrule_default_create fi } secrule_delete(){ if [ "$1" = "" ]; then echo "What is the name of secrule you want to delete ?" read ans ret=$($CURL -X DELETE -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/secrule/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans ) elif [ "$1" != DefaultPublicSSHAccess ]; then ret=$($CURL -X DELETE -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/secrule/Compute-$OPC_DOMAIN/$1 ) status=$(echo $ret | sed -n -e 's/.*\([0-9][0-9][0-9]$\)/\1/p') # If successful, "HTTP/1.1 204 No Content" is returned. if [ "$status" = 204 ]; then echo "$1""$ans"" deleted" else echo $ret fi fi } shape() { shape_list=/tmp/shape-$OPC_DOMAIN shape=($($CURL -X GET -H "Cookie:$COMPUTE_COOKIE" \ $IAAS_URL/shape/ | $JQ | tee $shape_list \ | sed -n -e 's/.*\"name\": \"\(.*\)\",/\1/p')) core=($(sed -n -e 's/.*\"cpus\": \(.*\)\.0,/\1/p' $shape_list )) ram=($(sed -n -e 's/.*\"ram\": \(.*\),/\1/p' $shape_list )) _IFS=$IFS IFS=$'\n' echo "----------------------------------------" echo -e "SHAPE\t CORE\t oCPU\t RAM(GB)" echo "----------------------------------------" for ((i = 0 ; i < ${#shape[@]};++i )) do ram_gb=$(( ${ram[$i]} / 1024 )) ocpu=$((${core[$i]} / 2)) printf "%s \t %5d\t" ${shape[$i]} ${core[$i]} printf "%5d %5d\n" $ocpu $ram_gb done IFS=$_IFS if [ $DEBUG != "on" ]; then rm $shape_list fi } sshkey(){ echo "It will upload $HOME/.ssh/id_rsa.pub to the cloud" echo -n "What is the name of the new sshkey ? " read ans key=$(cat $HOME/.ssh/id_rsa.pub) ret=$($CURL -X POST -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ -d "{ \"enabled\": true,\ \"key\": \"$key\",\ \"name\": \"/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans\"}" \ $IAAS_URL/sshkey/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans) status=$(echo $ret | sed -n -e 's/.*\([0-9][0-9][0-9]$\)/\1/p') # If successful, "HTTP/1.1 201 Created." is returned. if [ "$status" = 201 ]; then echo "$ans"" created" else echo $ret fi } sshkey_info(){ $CURL -X GET -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/sshkey/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/ | $JQ } sshkey_list(){ SSHKEY=($($CURL -X GET \ -H "Content-Type: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/sshkey/Compute-$OPC_DOMAIN/ | $JQ \ | sed -n -e 's/.*\"name\": \"\/[^/]*\/\(.*\)\"\,/\1/p' )) echo echo SSHKEY echo "-------------------------------------" for (( i=0 ; i < ${#SSHKEY[@]}; i++ )) do echo "${SSHKEY[$i]}" done echo "-------------------------------------" } sshkey_delete(){ if [ "$1" = "" ]; then echo "What is the name of sshkey you want to delete ?" read ans ret=$($CURL -X DELETE -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/sshkey/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans ) else ret=$($CURL -X DELETE -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ -w '%{http_code}' \ $IAAS_URL/sshkey/Compute-$OPC_DOMAIN/$1 ) status=$(echo $ret | sed -n -e 's/.*\([0-9][0-9][0-9]$\)/\1/p') # If successful, "HTTP/1.1 204 No Content" is returned. if [ "$status" = 204 ]; then echo "$1""$ans"" deleted" else echo $ret fi fi } storage_attachment_info() { $CURL -X GET -H "Cookie: $COMPUTE_COOKIE" \ -H "Accept: application/oracle-compute-v3+json" \ $IAAS_URL/storage/attachment/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/ echo } storage_volume_create() { echo "What name of the volume do you want to create ?" read ans echo "How much size of volume do you want ?" read SIZE $CURL -X POST -H "Cookie: $COMPUTE_COOKIE" \ -H "Content-Type: application/oracle-compute-v3+json" \ -d "{ \"name\": \"/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans\",\ \"properties\": [\"/oracle/public/storage/default\"],\ \"size\": \"$SIZE\"}"\ $IAAS_URL/storage/volume/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/ | $JQ } storage_volume_delete() { if [ "$1" = "" ];then echo "Which Storage Volume do you want to delete ?" read ans ret=$($CURL -X DELETE -H "Cookie: $COMPUTE_COOKIE" \ -H "Content-Type: application/oracle-compute-v3+json" \ -w '%{http_code}' \ -d "{ \"name\": \"/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans\"}" \ $IAAS_URL/storage/volume/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$ans ) else ret=$($CURL -X DELETE -H "Cookie: $COMPUTE_COOKIE" \ -H "Content-Type: application/oracle-compute-v3+json" \ -w '%{http_code}' \ -d "{ \"name\": \"Compute-$OPC_DOMAIN/$1\"}" \ $IAAS_URL/storage/volume/Compute-$OPC_DOMAIN/$1 ) fi status=$(echo $ret | sed -n -e 's/.*\([0-9][0-9][0-9]$\)/\1/p') # If successful, "HTTP/1.1 204 No Content" is returned. if [ "$status" = 204 ]; then echo "$1""$ans"" deleted" else echo $ret fi } storage_volume_info() { $CURL -X GET -H "Cookie: $COMPUTE_COOKIE" \ -H "Accept: application/oracle-compute-v3+json" \ $IAAS_URL/storage/volume/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/$1 | $JQ } storage_volume_list() { storage_vol_list=$CONF_DIR/tmp-storage_vol_list-$OPC_DOMAIN echo "-------------------------------------------------------------" echo " ### STORAGE VOLUME ###" echo "-------------------------------------------------------------" vol_name=($($CURL -X GET -H "Cookie: $COMPUTE_COOKIE" \ -H "Accept: application/oracle-compute-v3+json" \ $IAAS_URL/storage/volume/Compute-$OPC_DOMAIN/ \ | $JQ \ | tee $storage_vol_list \ | sed -n -e 's/.*\"name\":.*\/\(.*\/.*\)\",/\1/p' )) status=($(sed -n -e 's/.*\"status\": \"\(.*\)\",/\1/p' $storage_vol_list)) size=($(sed -n -e 's/.*\"size\": \"\(.*\)\",/\1/p' $storage_vol_list)) for ((i = 0 ; i < ${#vol_name[@]}; ++i )) do printf "%-16s" ${vol_name[$i]} printf "%8s " ${status[$i]} printf "%8s " "$((${size[$i]} / 1024 ** 3 ))" # show Byte to GB printf GB printf "\n" done if [ $DEBUG != "on" ]; then rm $storage_vol_list fi } storage_attachment() { $CURL -X POST -H "Cookie: $COMPUTE_COOKIE" \ -H "Content-Type: application/oracle-compute-v3+json" \ $IAAS_URL/storage/attachment/Compute-$OPC_DOMAIN/$OPC_ACCOUNT/ } vnic_list() { V_FILE=$CONF_DIR/tmp-vnic-$OPC_DOMAIN VIRTUALNIC=($($CURL -X GET \ -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/network/v1/vnic/Compute-$OPC_DOMAIN/ \ | $JQ | tee $V_FILE \ | sed -n -e 's/.*\"name\": \"\/[^/]*\/\(.*\)\",/\1/p')) echo echo VIRTUALNIC echo "-------------------------------------" for (( i=0 ; i < ${#VIRTUALNIC[@]}; i++ )) do echo "${VIRTUALNIC[$i]}" done echo "-------------------------------------" if [ $DEBUG != "on" ]; then rm $V_FILE fi } vnicset_list() { VS_FILE=$CONF_DIR/tmp-vnicset-$OPC_DOMAIN VIRTUALNIC=($($CURL -X GET \ -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/network/v1/vnicset/Compute-$OPC_DOMAIN/ \ | $JQ | tee $VS_FILE \ | sed -n -e 's/.*\"name\": \"\/[^/]*\/\(.*\)\",/\1/p')) echo echo VIRTUALNICSET echo "-------------------------------------" for (( i=0 ; i < ${#VIRTUALNIC[@]}; i++ )) do echo "${VIRTUALNIC[$i]}" done echo "-------------------------------------" if [ $DEBUG != "on" ]; then rm $VS_FILE fi } vpn_list() { VPN_FILE=$CONF_DIR/vpn-$OPC_DOMAIN VPN=($($CURL -X GET \ -H "Accept: application/oracle-compute-v3+json" \ -H "Cookie: $COMPUTE_COOKIE" \ $IAAS_URL/Compute-$OPC_DOMAIN/ \ | $JQ | tee $VPN_FILE \ | sed -n -e 's/.*\"name\": \"\/[^/]*\/\(.*\)\",/\1/p')) echo echo VPN echo "-------------------------------------" for (( i=0 ; i < ${#VPN[@]}; i++ )) do echo "${VPN[$i]}" done echo "-------------------------------------" if [ $DEBUG != "on" ]; then rm $VPN_FILE fi } case "$ARG" in account) get_cookie account ;; auth) get_cookie echo $status ;; config) config ;; delete) delete ;; delete-instance) get_cookie instance_delete ;; imagelist) get_cookie imagelist_info ;; imagelistentry) get_cookie imagelistentry_info ;; imagelist-user-defined) get_cookie imagelist_user_defined_info ;; ipassociation) get_cookie ipassociation ;; ipassociation-list) get_cookie ipassociation_list ;; ipreservation) get_cookie ipreservation ;; ipreservation-list) get_cookie ipassociation_list instances_list ipreservation_list ;; ipreservation-create) get_cookie ipreservation_create ;; ipreservation-delete) get_cookie ipreservation_delete ;; ipnetwork) get_cookie ipexchange_list ipnetwork_list route_list ;; ipnetwork-delete) get_cookie ipnetwork_delete ;; instance) get_cookie instance ;; instances) get_cookie instances ;; launchplan) get_cookie launchplan ;; list) get_cookie ipassociation_list instances_list list ipreservation_list storage_volume_list ;; machineimage-create) get_cookie machineimage_create ;; machineimage-info) get_cookie machineimage_info ;; machineimage) get_cookie machineimage ;; nic) get_cookie vnic_list vnicset_list ;; orchestration) get_cookie orchestration ;; orchestration-container) get_cookie orchestration_container ;; orchestration-delete) get_cookie orchestration_delete ;; role) get_cookie role ;; secassociation) get_cookie secassociation ;; seclist) get_cookie seclist ;; seclist-create) get_cookie seclist_create ;; seclist_delete) get_cookie seclist_delete ;; secrule) get_cookie secrule ;; secrule-default) get_cookie secrule_default ;; shape) get_cookie shape ;; show) get_cookie ipassociation_list instances_list list ;; sshkey) get_cookie sshkey ;; sshkey-info) get_cookie sshkey_info ;; sshkey-list) get_cookie sshkey_list ;; storage-attachment) get_cookie storage_attachment_info ;; storage-volume-info) get_cookie storage_volume_info ;; storage-volume-create) get_cookie storage_volume_create ;; storage-volume-delete) get_cookie storage_volume_delete ;; vpn) get_cookie vpn_list ;; vpn-delete) get_cookie vpn_delete ;; # Under construction create-minimal) get_cookie sshkey storage_volume_create seclist_add ipreservation ;; secrule-list) get_cookie secrule_list ;; *) cat <<-EOF Usage: opc_compute.sh [-l "your domain" ] [ options ] options: auth -- authentication with Oracle Cloud show -- show compute instance sshkey -- upload ssh-key shape -- show oCPU + Memory size template imagelist -- show OS and disk size template launchplan -- make an instance for temporary list -- list all instance,ipreservation,storage volume delete -- delete objects except JCS,DBCS auto making objects config -- make new configuration or change default setting nic -- show vNIC EOF exit 1 esac exit 0
kkoj/oracle_cloud
opc_compute.sh
Shell
gpl-2.0
49,837
/** * @file * Menu Link Weight Javascript functionality. */ (function ($) { /** * Automatically update the current link title in the menu link weight list. */ Drupal.behaviors.menuLinkWeightAutomaticTitle = { attach: function (context) { $('fieldset.menu-link-form', context).each(function () { var $checkbox = $('.form-item-menu-enabled input', this); var $link_title = $('.form-item-menu-link-title input', context); var $current_selection = $('.menu-link-weight-link-current', context); var $node_title = $(this).closest('form').find('.form-item-title input'); // If there is no title, take over the title of the link. if ($current_selection.html() == '') { $current_selection.html($link_title.val().substring(0, 30)); } // Take over any link title change. $link_title.keyup(function () { $current_selection.html($link_title.val().substring(0, 30)); }); // Also update on node title change, as this may update the link title. $node_title.keyup(function () { $current_selection.html($link_title.val().substring(0, 30)); }); }); } }; })(jQuery);
andrysobolev/Drupal-Base
sites/all/modules/contrib/menu_link_weight/js/menu_link_weight.js
JavaScript
gpl-2.0
1,218
data: The server time is: Fri, 23 Jan 2015 02:20:56 -0500
platinhom/ManualHom
Coding/W3School/W3Schools_Offline_2015/www.w3schools.com/html/demo_sse.php
PHP
gpl-2.0
59
/* * A simple reboot and halt */ #include <stdio.h> #include <string.h> #include <unistd.h> int main(int argc, char *argv[]) { char *p = strchr(argv[0], '/'); if (p) p++; else p = argv[0]; if (strcmp(p, "halt") == 0) uadmin(A_SHUTDOWN,0,0); else uadmin(A_REBOOT,0,0); /* If we get here there was an error! */ perror(argv[0]); }
geijoenr/FUZIX
Applications/util/reboot.c
C
gpl-2.0
361
// main48.cc is a part of the PYTHIA event generator. // Copyright (C) 2020 Torbjorn Sjostrand. // PYTHIA is licenced under the GNU GPL v2 or later, see COPYING for details. // Please respect the MCnet Guidelines, see GUIDELINES for details. // Authors: Philip Ilten <philten@cern.ch>. // Keywords: B decays; external decays; EvtGen; // An example where decays are performed with EvtGen. See the // documentation in Pythia8Plugins/EvtGen.h for further details on the // EvtGenDecays class. In this example the decay B0 -> nu_e e+ D*-[-> // gamma D-[-> nu_ebar e- pi0]] is forced. The invariant mass spectrum // of the final state electron and pion is then plotted. // The syntax to run this example is: // ./main48 <EvtGen decay file> <EvtGen particle data> <PYTHIA8DATA> // <flag to use EvtGen> // This example has only been tested with EvtGen version 1.3.0. The // EvtGen package is designed to use Pythia 8 for any decays that it // cannot perform. For this to be possible, EvtGen must be linked // against the Pythia 8 shared library. To build EvtGen 1.3.0 with // Pythia 8.2 the "-llhapdfdummy" library requirement must be // removed. Prior to running "./configure" for EvtGen this can be // accomplished via: // sed -i "s/-llhapdfdummy//g" configure // To modify how this example program is compiled (i.e to remove // linking against the EvtGenExternal library) change the main48 rule // in the Makefile of this directory. #include "Pythia8/Pythia.h" #include "Pythia8Plugins/EvtGen.h" using namespace Pythia8; int main(int argc, char* argv[]) { // Check arguments. if (argc != 5) { cerr << " Unexpected number of command-line arguments. \n You are" << " expected to provide the arguments \n" << " 1. EvtGen decay file (e.g. DECAY_2010.DEC) \n" << " 2. EvtGen particle data (e.g. evt.pdl) \n" << " 3. PYTHIA8DATA path \n" << " 4. Flag to use EvtGen (true or false) \n" << " Program stopped. " << endl; return 1; } bool use(string(argv[4]) == "true"); // Intialize Pythia. Pythia pythia; pythia.readString("Print:quiet = on"); pythia.readString("HardQCD:hardbbbar = on"); if (!use) { cout << "Not using EvtGen." << endl; pythia.readString("511:onMode = off"); pythia.readString("511:onIfMatch = 12 -11 -413"); pythia.readString("413:onMode = off"); pythia.readString("413:onIfMatch = 411 22"); pythia.readString("411:onMode = off"); pythia.readString("411:onIfMatch = -11 12 111"); } else cout << "Using EvtGen." << endl; pythia.init(); // Initialize EvtGen. EvtGenDecays *evtgen = 0; if (use) { setenv("PYTHIA8DATA", argv[3], 1); evtgen = new EvtGenDecays(&pythia, argv[1], argv[2]); evtgen->readDecayFile("main48.dec"); } // The event loop. Hist mass("m(e, pi0) [GeV]", 100, 0., 2.); for (int iEvent = 0; iEvent < 1000; ++iEvent) { // Generate the event. if (!pythia.next()) continue; // Perform the decays with EvtGen. if (evtgen) evtgen->decay(); // Analyze the event. Event &event = pythia.event; for (int iPrt = 0; iPrt < (int)event.size(); ++iPrt) { if (event[iPrt].idAbs() != 511) continue; int iB0(event[iPrt].iBotCopyId()), iDsm(-1), iDm(-1), iE(-1), iPi0(-1); for (int iDtr = event[iB0].daughter1(); iDtr <= event[iB0].daughter2(); ++ iDtr) { if (event[iDtr].idAbs() == 413) { iDsm = event[iDtr].iBotCopyId(); continue; } } if (iDsm == -1) continue; for (int iDtr = event[iDsm].daughter1(); iDtr <= event[iDsm].daughter2(); ++ iDtr) { if (event[iDtr].idAbs() == 411) { iDm = event[iDtr].iBotCopyId(); continue; } } if (iDm == -1) continue; for (int iDtr = event[iDm].daughter1(); iDtr <= event[iDm].daughter2(); ++ iDtr) { if (event[iDtr].idAbs() == 11) iE = event[iDtr].iBotCopyId(); if (event[iDtr].idAbs() == 111) iPi0 = event[iDtr].iBotCopyId(); } if (iE == -1 || iPi0 == -1) continue; mass.fill((event[iE].p() + event[iPi0].p()).mCalc()); } } // Print the statistics and histogram. pythia.stat(); mass /= mass.getEntries(); cout << mass; if (evtgen) delete evtgen; return 0; }
alisw/pythia8
examples/main48.cc
C++
gpl-2.0
4,310