content
stringlengths
10
4.9M
<reponame>apcs-assignments-fall2020/s00-shuffle-magiccoder890 public class MyMain { // Shuffles an array, using the perfect shuffle algorithm public static int[] perfectShuffle(int[] arr) { int[] mylist = new int[arr.length]; int start = 0; for (int i = 0; i < arr.length; i++){ if (i % 2 == 0){ mylist[i] = arr[start]; start++; } if (i % 2 == 1){ mylist[i] = arr[arr.length/2 + start - 1]; } } return mylist; } public static boolean ifrepeat(int[] arr,int random,int time,int[] random_list,int zerotime){ int num = 0; for (int random_repeat = 0; random_repeat < random_list.length; random_repeat++){ if (random_list[random_repeat] == random && random != 0){ num++; } } if (num > 0 ){ return true; } else{ random_list[time] = random; return false; } } // Shuffles an array, using the selection shuffle algorithm public static int[] selectionShuffle(int[] arr) { int zerotime = 0; int[] extra_list = new int[arr.length]; int[] mylist = new int[arr.length]; int random_num = 0; for (int i = 0; i < arr.length; i++){ random_num = (int) (Math.random() * arr.length); while(ifrepeat(arr,random_num,i,extra_list,zerotime)) { random_num = (int) (Math.random() * arr.length); } mylist[i] = arr[random_num]; } return mylist; } public static void main(String[] args) { // Write some code here to test your methods! int[] list = {1,2,3,4,5,21,22,23,24,25}; System.out.print(selectionShuffle(list)); } }
/** * Pokes the given url with the given JSON data. */ public class HttpPoker { private static final String TAG = "HttpPoker"; private String mUrl; public HttpPoker(String url) { mUrl = url; } public HttpResponse doPut(JSONObject json) { return doPut(json.toString()); } public HttpResponse doPut(String json) { Log.d(TAG, mUrl+" : "+json); try{ URI url = new URI(mUrl); HttpClient httpClient = new DefaultHttpClient(); HttpPut put= new HttpPut(url); put.setEntity(new StringEntity(json,"UTF-8")); put.setHeader("Content-type", "application/json"); put.setHeader("charset", "utf-8"); put.addHeader("Accept-Language", Locale.getDefault().toString().replace("_", "-")); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "ADDM v0.1 "+android.os.Build.MODEL); HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 60 * 1000); // 1min HttpConnectionParams.setSoTimeout(httpClient.getParams(), 5 * 60 * 1000); // 5min HttpResponse response = httpClient.execute(put); return response; } catch(Exception e) { Log.e(TAG, "Failed to PUT: "+e); } return null; } }
package io.kuo.tahoe; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; import io.kuo.support.jersey.JsonObjectMapperProvider; import io.kuo.support.jersey.filter.CORSResponseFilter; import org.glassfish.jersey.filter.LoggingFilter; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.spring.scope.RequestContextFilter; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; /** * Created by nikog on 1/30/2015. */ public class TahoeApplication extends ResourceConfig { public TahoeApplication() { super.setApplicationName("tahoe"); register(RequestContextFilter.class); register(CORSResponseFilter.class); register(LoggingFilter.class); register(JsonObjectMapperProvider.class); register(JacksonJaxbJsonProvider.class, new Class[]{MessageBodyReader.class, MessageBodyWriter.class}); packages("io.kuo.tahoe.resource,io.kuo.support.jersey,com.fasterxml.jackson.jaxrs.base"); } }
/** * @author Pierre Sutra */ public class Utils { private static Random rand = new Random(System.currentTimeMillis()); public static final long YEAR_IN_MS = 365L * 24L * 60L * 60L * 1000L; public static Employee createEmployee(int i) { Employee employee = Employee.newBuilder().build(); employee.setSsn(Long.toString(i)); employee.setName(Long.toString(rand.nextLong())); employee.setDateOfBirth(rand.nextLong() - 20L * YEAR_IN_MS); employee.setSalary(rand.nextInt()); return employee; } public static <T extends CharSequence> void populateEmployeeStore(DataStore<T, Employee> dataStore, int n) { for(int i=0; i<n; i++) { Employee e = createEmployee(i); dataStore.put((T)e.getSsn(),e); } dataStore.flush(); } }
/* * Copyright 2014 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package shillelagh.test; public final class LotsOfParamConstructor { private final byte testByte; private final short testShort; private final int testInt; private final long testLong; private final float testFloat; private final double testDouble; private final char testChar; private final boolean testBool; private final String testString; public LotsOfParamConstructor(byte testByte, short testShort, int testInt, long testLong, float testFloat, double testDouble, char testChar, boolean testBool, String testString) { this.testByte = testByte; this.testShort = testShort; this.testInt = testInt; this.testLong = testLong; this.testFloat = testFloat; this.testDouble = testDouble; this.testChar = testChar; this.testBool = testBool; this.testString = testString; } public byte getTestByte() { return testByte; } public short getTestShort() { return testShort; } public int getTestInt() { return testInt; } public long getTestLong() { return testLong; } public float getTestFloat() { return testFloat; } public double getTestDouble() { return testDouble; } public char getTestChar() { return testChar; } public boolean isTestBool() { return testBool; } public String getTestString() { return testString; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LotsOfParamConstructor that = (LotsOfParamConstructor) o; if (testBool != that.testBool) return false; if (testByte != that.testByte) return false; if (testChar != that.testChar) return false; if (Double.compare(that.testDouble, testDouble) != 0) return false; if (Float.compare(that.testFloat, testFloat) != 0) return false; if (testInt != that.testInt) return false; if (testLong != that.testLong) return false; if (testShort != that.testShort) return false; if (testString != null ? !testString.equals(that.testString) : that.testString != null) { return false; } return true; } @Override public int hashCode() { int result; long temp; result = (int) testByte; result = 31 * result + (int) testShort; result = 31 * result + testInt; result = 31 * result + (int) (testLong ^ (testLong >>> 32)); result = 31 * result + (testFloat != +0.0f ? Float.floatToIntBits(testFloat) : 0); temp = Double.doubleToLongBits(testDouble); result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + (int) testChar; result = 31 * result + (testBool ? 1 : 0); result = 31 * result + (testString != null ? testString.hashCode() : 0); return result; } @Override public String toString() { return "LotsOfParamConstructor{" + "testByte=" + testByte + ", testShort=" + testShort + ", testInt=" + testInt + ", testLong=" + testLong + ", testFloat=" + testFloat + ", testDouble=" + testDouble + ", testChar=" + testChar + ", testBool=" + testBool + ", testString='" + testString + '\'' + '}'; } }
<reponame>rstyro/AQS-demo package top.lrshuai.aqs.semaphore; import top.lrshuai.aqs.commons.ThreadPool; import java.util.Vector; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; public class SemaphoreDemo { public static void main(String[] args) throws InterruptedException { //厕所坑位 int count = 2; // 人数 int peopleNum = 8; CountDownLatch countDownLatch = new CountDownLatch(peopleNum); Semaphore semaphore = new Semaphore(count); ThreadPoolExecutor pool = ThreadPool.getPool(); Vector<String> vector = new Vector(peopleNum); System.out.println("目前有厕所位置:"+count); for (int i = 0; i < peopleNum; i++) { String name = "编号:"+(i+1); Thread thread = new Thread(new RunTask(name,semaphore, countDownLatch,vector),name); vector.add(name); pool.execute(thread); } countDownLatch.await(); pool.shutdown(); } }
/** * This factory is used to test if a string is a valid JSON string. * <p>No actual object is created by this factory.</p> * * @ibm-api */ public class JsonEmptyFactory implements JsonFactory { public static final JsonEmptyFactory instance = new JsonEmptyFactory(); public boolean supportFeature(int feature) throws JsonException { return true; } public boolean isValidValue(Object value) throws JsonException { return true; } public Object createNull() { return null; } public Object createUndefined() { return null; } public Object createString(String value) { return null; } public Object createJavaScriptCode(String code) throws JsonException { return null; } public Object createNumber(double value) { return null; } public Object createBoolean(boolean value) { return null; } public Object createObject(Object parent, String propertyName) { return null; } public Object createArray(Object parent, String propertyName, List<Object> values) { return null; } public void setProperty(Object parent, String propertyName, Object value) { } public Object getProperty(Object parent, String propertyName) throws JsonException { return null; } // Not used... public boolean isNull(Object value) throws JsonException { return false; } public boolean isUndefined(Object value) throws JsonException { return false; } public boolean isString(Object value) throws JsonException { return false; } public String getString(Object value) throws JsonException { return null; } public boolean isJavaScriptCode(Object value) throws JsonException { return false; } public String getJavaScriptCode(Object value) throws JsonException { return null; } public boolean isNumber(Object value) throws JsonException { return false; } public double getNumber(Object value) throws JsonException { return 0; } public boolean isBoolean(Object value) throws JsonException { return false; } public boolean getBoolean(Object value) throws JsonException { return false; } public boolean isObject(Object value) throws JsonException { return false; } @SuppressWarnings("unchecked") //$NON-NLS-1$ public Iterator<String> iterateObjectProperties(Object object) throws JsonException { return EmptyIterator.getInstance(); } public boolean isArray(Object value) throws JsonException { return false; } public int getArrayCount(Object value) throws JsonException { return 0; } @SuppressWarnings("unchecked") public Iterator<Object> iterateArrayValues(Object array) throws JsonException { return EmptyIterator.getInstance(); } public List<Object> createTemporaryArray(Object parent) throws JsonException { return new ArrayList<Object>(); } }
/** * Returns the immediate mode of the component. * <p> * Since Vaadin 8, the default mode is immediate. * * @return true if the component is in immediate mode (explicitly or * implicitly set), false if the component if not in immediate mode */ public boolean isImmediate() { if (explicitImmediateValue != null) { return explicitImmediateValue; } else { return true; } }
We all saw “Free Willy,” we all loved “Free Willy.” But what happened to the real Willy? In a tragic, confounding dose of irony, Keiko, the whale-actor who played Willy, was languising in a marine park in Mexico after filming. He was underweight, covered in skin lesions, suffering a drooping dorsal fin and predicted to die within months from poor health. “Freeing Willy,” a new 12-minute mini-documentary from Retro Report and The New York Times, recounts the global campaign to “Free Keiko.” Thanks mostly to a huge donation from billionaire Craig McCaw, a $7.3 million rehabilitation tank was built for Keiko in Oregon, intended as a center where the orca whale could learn how to survive in the wild, a process Susan Orlean (who wrote about Keiko’s journey in the New Yorker) called “human beings teaching a whale to be a whale.” Born in Icelandic waters but caught captive as a baby, Keiko may have known how to star in a movie, but he didn’t know how to hold his breath for long periods, catch his own food, or swim in harsh waters.
package utils import ( "github.com/magiconair/properties/assert" "testing" ) func TestSnakeString(t *testing.T) { assert.Equal(t, "snake_string", SnakeString("SnakeString")) } func TestCamelString(t *testing.T) { assert.Equal(t, "SnakeString", CamelString("snake_string")) }
<gh_stars>0 /* * The MIT License * * Copyright (c) 2018-2022, qinglangtech Ltd * * 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. */ package com.qlangtech.tis.hdfs.client.data; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import javax.sql.DataSource; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.qlangtech.tis.exception.SourceDataReadException; import com.qlangtech.tis.hdfs.client.data.sql.JDBCProperties; import com.qlangtech.tis.hdfs.client.data.sql.JDBCPropertiesSupport; import com.qlangtech.tis.hdfs.client.data.sql.SqlFunctionCollectors; import com.qlangtech.tis.hdfs.util.FormatTool; /* * @description 对于一个表的SQL操作,如果本表操作完毕则依次执行 nextDataProvider的表SQL操作<br> * 【注意】该类不适用多线程操作<br> * * @author 百岁(<EMAIL>) * @date 2019年1月17日 */ public class SingleTableSqlExcuteProvider extends AbstractSourceDataProvider { protected static Log log = LogFactory.getLog(SingleTableSqlExcuteProvider.class); private final AtomicLong dbReaderCounter; // 需要导入的表的名称 private String tableName; /** * @param dbReaderCounter */ public SingleTableSqlExcuteProvider(AtomicLong dbReaderCounter) { super(); this.dbReaderCounter = dbReaderCounter; } @Override public String getDsName() { return this.dsName; } // public SingleTableSqlExcuteProvider nextDataProvider; public String dsName; public String dbHost; public String suffixTableName; protected DataSource dataSource; protected Connection connection; protected Statement statement; protected ResultSetMetaData metaData; protected ResultSet resultSet; protected Map<String, String> row; protected int columCount; private String sql; // protected boolean mustNext = false; protected SqlFunctionCollectors sqlFuncs; protected JDBCProperties jdbcProperties; protected String selfFlag; protected int executeRowCount = 0; // protected boolean isTest; protected String shardKey = "id"; @Override public String getDbHost() { return this.dbHost; } public final CurrentOperatorLocation currentOperatorLocation = new CurrentOperatorLocation(); @Override public boolean hasNext() throws SourceDataReadException { // boolean flag = false; try { // if (resultSet != null && resultSet.next()) { dbReaderCounter.incrementAndGet(); return true; } return false; // if (isTest && executeRowCount++ > 2) { // flag = false; // } // } catch (SQLException e) { throw new SourceDataReadException("【注意】操作数据源:" + dsName + ",表后缀为: " + suffixTableName + "出现错误:", e); } // if (!flag) { // if (this.hasNextDatProvider()) { // if (!mustNext) { // /** // * 进入下一个Provider,那么打开下一个Provider的资源连接, 同时关闭当前Provider的资源连接 // */ // this.getNextDataProvider().openResource(); // this.closeResource(false); // mustNext = true; // } // flag = this.getNextDataProvider().hasNext(); // } // //} // // return flag; } public void openResource() throws SourceDataReadException { try { this.connection = this.dataSource.getConnection(); this.currentOperatorLocation.dsName = dsName; this.currentOperatorLocation.suffixTableName = suffixTableName; this.currentOperatorLocation.shardKey = shardKey; if (this.jdbcProperties == null && this.dataSource instanceof JDBCPropertiesSupport) { this.jdbcProperties = ((JDBCPropertiesSupport) dataSource).getJdbcProperties(); } this.statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); if (this.jdbcProperties != null) { this.setPropertiesBeforeQuery(this.statement, this.jdbcProperties); } String executeSql = this.getFinalSql(getSql()); if (statement.execute(executeSql)) { resultSet = statement.getResultSet(); } else { log.fatal("执行SQL失败,sql ==> \n" + executeSql); resultSet = null; } // // connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); // resultSet.last(); // resultSet.getRow(); // resultSet.first(); 移动到第一条 metaData = resultSet.getMetaData(); columCount = metaData.getColumnCount(); } catch (Exception e) { this.closeResource(false); throw new SourceDataReadException("can not create connection:[" + this.getDbHost() + "," + this.getDsName() + "," + this.tableName + this.suffixTableName + "],\n" + ToStringBuilder.reflectionToString(this.dataSource, ToStringStyle.MULTI_LINE_STYLE), e); } } /** * 针对一些JDBC的参数,可在这里实现,用户可覆盖这个方法,想做什么都在这里做吧 * * * @param statement * @param jdbcProperties * @throws SQLException */ protected void setPropertiesBeforeQuery(Statement statement, JDBCProperties jdbcProperties) throws SQLException { // log.warn("设置JDBC的相关属性 ==> " + jdbcProperties.toString()); statement.setFetchSize(jdbcProperties.getStatementFetchSize()); } private String getFinalSql(String sql) { // sqlFuncs.register( sqlFuncs.new StartDateFunction(isInrc)); return sqlFuncs.parseSql(sql); } public List<RowMetaData> getMetaData() { List<RowMetaData> result = new ArrayList<RowMetaData>(); try { for (int i = 1; i <= columCount; i++) { result.add(new RowMetaData((i - 1), metaData.getColumnLabel(i), metaData.getColumnType(i))); } return result; } catch (SQLException e) { throw new RuntimeException(e); } } public class RowMetaData { private final String key; private final int type; private final int index; /** * @param key * @param type */ public RowMetaData(int index, String key, int type) { super(); this.key = key; this.type = type; this.index = index; } public int getIndex() { return index; } public String getKey() { return key; } public int getType() { return type; } } @Override public Map<String, String> next() throws SourceDataReadException { // if (row != null) // row = null; // // if (!mustNext) { // row = new LinkedHashMap<String, String>(columCount); for (int i = 1; i <= columCount; i++) { String key = null; String value = null; try { key = metaData.getColumnLabel(i); // 防止特殊字符造成HDFS文本文件出现错误 value = FormatTool.filter(resultSet, i); // value= resultSet.getString(i); } catch (SQLException e) { // if (ignoreIllFieldRow) { throw new SourceDataReadException("出现错误,table:" + this.tableName, e); // } else { // row.put(key, defaultIllFiledValue); // continue; // } } // 在数据来源为数据库情况下,客户端提供一行的数据对于Solr来说是一个Document row.put(key, value != null ? value : ""); } return row; // } else { // // return nextDataProvider.next(); // } } // private boolean ignoreIllFieldRow = true; // private String defaultIllFiledValue = null; public void closeResource(boolean isIterator) throws SourceDataReadException { // if (isIterator) // log.warn("嵌套关闭后缀名为" + this.suffixTableName + "的数据库资源"); // else { // log.warn("关闭本Provider后缀名为" + this.suffixTableName + "的数据库资源"); // } log.info("db:" + this.getDsName() + ",table:" + this.tableName + ",import:" + this.dbReaderCounter.get()); try { if (resultSet != null) resultSet.close(); if (statement != null) statement.close(); if (connection != null) connection.close(); } catch (SQLException e) { log.error("关闭本Provider后缀名为" + this.suffixTableName + "的数据库资源出现致命错误", e); throw new SourceDataReadException("释放数据库连接资源失败", e); } finally { resultSet = null; statement = null; connection = null; metaData = null; columCount = 0; executeRowCount = 0; } } public static class CurrentOperatorLocation { public String dsName; public String suffixTableName; public String shardKey; } public static void main(String[] args) { } @Override public String getShardKey() { return this.shardKey; } @Override public void closeResource() throws SourceDataReadException { this.closeResource(true); } @Override public void init() throws SourceDataReadException { if (dbReaderCounter == null) { throw new IllegalStateException("dbReaderCounter can not be null"); } } protected String getSql() { return sql; } protected void setSql(String sql) { try { this.tableName = StringUtils.substringAfterLast(sql.toLowerCase(), "from"); this.tableName = StringUtils.trim(StringUtils.substringBefore(this.tableName, "where")); } catch (Throwable e) { } this.sql = sql; } }
<reponame>PrabhuLoganathan/Collection-of-Python-Scripts import twitter import json import re # replace 'default' with twitter user user = 'default' # path to json file with your twitter credentials (see https://python-twitter.readthedocs.io/en/latest/) creds = 'creds.json' file_name = 'tweets.txt' def init_twitter(): # load twitter API tokens with open(creds) as data_file: data = json.load(data_file) api = twitter.Api(consumer_key=data["consumer_key"], consumer_secret=data["consumer_secret"], access_token_key=data["access_token_key"], access_token_secret=data["access_token_secret"]) return api def main(): if user == 'default': print("Please define the twitter user's screenname to download content from in source code.") return api = init_twitter() # get up to 4000 latest tweets tweets = api.GetUserTimeline(screen_name=user, count=200) curr_id = tweets[-1].id for i in range(19): tweets = tweets + api.GetUserTimeline(screen_name=user, count=200, max_id=curr_id) curr_id = tweets[-1].id print("Tweets: " + str(len(tweets))) # write tweets to file with open(file_name, 'w') as file_o: for tweet in tweets: tweet_cont = tweet.text # strip links tweet_cont = re.sub(r'http\S+', '', tweet_cont) # strip mentions tweet_cont = re.sub(r'@\S+', '', tweet_cont) # strip hashtags tweet_cont = re.sub(r'#\S+', '', tweet_cont) tweet_cont = tweet_cont.replace('RT: ', '') tweet_cont = tweet_cont.replace('RT', '') file_o.write(tweet_cont + '\n') if __name__ == "__main__": main()
/** * @author Jose Molina Colmenero */ public class LaunchFS { public static void main(String[] args) throws FuseException { if (args.length < 2) { System.err.println("Please specify url of the repository " + "and the mount point"); } String repoUrl = args[0]; String mountpoint = args[1]; String repoCache = "/tmp/cvmfs-java-client-cache"; if (args.length > 2) repoCache = args[2]; CvmfsFileSystem fs = new CvmfsFileSystem(repoUrl, repoCache); File mountpointFile = new File(mountpoint); if (mountpointFile.exists() && mountpointFile.isDirectory()) { fs.mount(mountpointFile); } else { System.err.println("Cannot mount the file system in " + mountpointFile.getAbsolutePath()); } } }
import { expect } from 'chai' import { Scanner } from '../../../src/parser/scanner/Scanner' import { TokenKind } from '../../../src/parser/tokens' import { token } from '../utils' export function keywords () { it('keywords', () => { const keywords: [TokenKind, string][] = [ [TokenKind.FUNCTION, 'function'], [TokenKind.EVENT, 'event'], [TokenKind.STORAGE, 'storage'], [TokenKind.CONTRACT, 'contract'], [TokenKind.LET, 'let'], [TokenKind.USE, 'use'], [TokenKind.FOR, 'for'], [TokenKind.WHILE, 'while'], [TokenKind.IF, 'if'], [TokenKind.ELSE, 'else'], [TokenKind.ZERO, 'zero'], [TokenKind.RETURN, 'return'], [TokenKind.BOOLEAN, 'true'], [TokenKind.BOOLEAN, 'false'], [TokenKind.IDENTIFIER, 'blah'] ] const source = keywords.map(([, value]) => value).join(' ') const tokens = Scanner.scan(source) let i = 0 let last = 0 function t (kind: TokenKind, value: string) { i += last last = value.length + 1 return token(kind, value, i) } expect(tokens).to.deep.equal([ ...keywords.map(([kind, value]) => t(kind, value)), token(TokenKind.EOF, '', source.length) ]) }) }
<filename>realbrowserlocusts/core.py # pylint:disable=too-few-public-methods """ Core Selenium wrapping functionality """ import time from selenium.webdriver.support.ui import WebDriverWait from locust import events from locust.exception import StopUser def wrap_for_locust(request_type, name, func, *args, **kwargs): """ Wrap Selenium activity function with Locust's event fail/success method :param request_type: the type of request :param name: name to be reported to events.request_*.fire :param func: callable to be timed and logged :return result: Result of the provided function if doesn't raise exception """ try: start_time = time.time() result = func(*args, **kwargs) except Exception as event_exception: total_time = int((time.time() - start_time) * 1000) events.request_failure.fire( request_type=request_type, name=name, response_time=total_time, response_length=0, exception=event_exception ) raise StopUser() else: total_time = int((time.time() - start_time) * 1000) events.request_success.fire( request_type=request_type, name=name, response_time=total_time, response_length=0 ) return result class RealBrowserClient(object): """ Web Driver client with Locust functionality """ def __init__(self, driver, wait_time_to_finish, screen_width, screen_height, set_window=True): self.driver = driver if set_window: self.driver.set_window_size(screen_width, screen_height) self.wait = WebDriverWait(self.driver, wait_time_to_finish) @staticmethod def timed_event_for_locust(request_type, message, func, *args, **kwargs): """ Use this method whenever you have a logical sequence of browser steps that you would like to time. Group these in a seperate, not @task method and call them using this method. These will show up in the locust web interface with timings Args: request_type (str): the type of request message (str): name to be reported to events.request_*.fire func (Function): callable to be timed and logged *args: arguments to be used when calling func **kwargs: Arbitrary keyword args used for calling func Returns: func(*args, **kwargs) if this function invocation does not raise an exception Raises: StopUser: whenever func raises an exception, this exception is catched, logged to locust as a failure and a StopUser (formerly StopLocust) exception is raised. """ return wrap_for_locust(request_type, message, func, *args, **kwargs) def __getattr__(self, attr): """ Forward all messages this client doesn't understand to it's webdriver """ return getattr(self.driver, attr)
/** * Parameters definitions for Elasticsearch. */ public class ElasticsearchParameters { /** * Elasticsearch server host. */ private String host; /** * Elasticsearch server port. */ private int port; /** * Elasticsearch server scheme. * Optional. If not provided, defaults to http. */ private String scheme; /** * Authentication type to connect to the server. * Can be BASIC, TOKEN or APIKEY. */ private AuthenticationType authenticationType; /** * Username to use for server authentication. * Required for BASIC authentication to connect to the server. */ private String username; /** * Password to use for server authentication. * Required for BASIC authentication to connect to the server. */ private String password; /** * Authorization token to use for server authentication. * Required for TOKEN authentication to connect to the server. */ private String authorizationToken; /** * API Key ID to use for server authentication. * Required for APIKEY authentication to connect to the server. */ private String apiKeyId; /** * API Key Secret to use for server authentication. * Required for APIKEY authentication to connect to the server. */ private String apiKeySecret; /** * Timeout in milliseconds used for establishing the connection to the server. * Optional. If not provided, defaults to 5000s. */ private int connectTimeout; /** * Timeout in milliseconds used for waiting for data – after establishing the connection to the server. * Optional. If not provided, defaults to 60000s. */ private int socketTimeout; /** * Number of worker threads used by the connection manager. * Optional. If not provided, defaults to 1. */ private int ioThreadCount; public ElasticsearchParameters(String host, int port) { this.host = host; this.port = port; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getScheme() { return scheme; } public void setScheme(String scheme) { this.scheme = scheme; } public AuthenticationType getAuthenticationType() { return authenticationType; } public void setAuthenticationType(AuthenticationType authenticationType) { this.authenticationType = authenticationType; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAuthorizationToken() { return authorizationToken; } public void setAuthorizationToken(String authorizationToken) { this.authorizationToken = authorizationToken; } public String getApiKeyId() { return apiKeyId; } public void setApiKeyId(String apiKeyId) { this.apiKeyId = apiKeyId; } public String getApiKeySecret() { return apiKeySecret; } public void setApiKeySecret(String apiKeySecret) { this.apiKeySecret = apiKeySecret; } public int getConnectTimeout() { return connectTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public int getSocketTimeout() { return socketTimeout; } public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } public int getIoThreadCount() { return ioThreadCount; } public void setIoThreadCount(int ioThreadCount) { this.ioThreadCount = ioThreadCount; } /** * Reads Elasticsearch parameters from a properties list. * * @param properties Properties list * @return Elasticsearch parameters instance */ public static ElasticsearchParameters load(Properties properties, Configuration conf) { ElasticsearchParameters elasticsearchParameters; if (!Boolean.parseBoolean(properties.getProperty(ElasticsearchConstants.PROP_OVERRIDING))) { elasticsearchParameters = new ElasticsearchParameters( conf.get(ElasticsearchConstants.PROP_HOST, ElasticsearchConstants.DEFAULT_HOST), conf.getInt(ElasticsearchConstants.PROP_PORT, ElasticsearchConstants.DEFAULT_PORT)); } else { elasticsearchParameters = new ElasticsearchParameters( properties.getProperty(ElasticsearchConstants.PROP_HOST, ElasticsearchConstants.DEFAULT_HOST), Integer.parseInt(properties.getProperty(ElasticsearchConstants.PROP_PORT, String.valueOf(ElasticsearchConstants.DEFAULT_PORT)))); } String schemeProperty = properties.getProperty(ElasticsearchConstants.PROP_SCHEME); if (schemeProperty != null) { elasticsearchParameters.setScheme(schemeProperty); } AuthenticationType authenticationTypeProperty = AuthenticationType.valueOf(properties.getProperty(ElasticsearchConstants.PROP_AUTHENTICATIONTYPE)); if (authenticationTypeProperty != null) { elasticsearchParameters.setAuthenticationType(authenticationTypeProperty); } String usernameProperty = properties.getProperty(ElasticsearchConstants.PROP_USERNAME); if (usernameProperty != null) { elasticsearchParameters.setUsername(usernameProperty); } String passwordProperty = properties.getProperty(ElasticsearchConstants.PROP_PASSWORD); if (passwordProperty != null) { elasticsearchParameters.setPassword(passwordProperty); } String authorizationTokenProperty = properties.getProperty(ElasticsearchConstants.PROP_AUTHORIZATIONTOKEN); if (authorizationTokenProperty != null) { elasticsearchParameters.setAuthorizationToken(authorizationTokenProperty); } String apiKeyIdProperty = properties.getProperty(ElasticsearchConstants.PROP_APIKEYID); if (apiKeyIdProperty != null) { elasticsearchParameters.setApiKeyId(apiKeyIdProperty); } String apiKeySecretProperty = properties.getProperty(ElasticsearchConstants.PROP_APIKEYSECRET); if (apiKeySecretProperty != null) { elasticsearchParameters.setApiKeySecret(apiKeySecretProperty); } String connectTimeoutProperty = properties.getProperty(ElasticsearchConstants.PROP_CONNECTTIMEOUT); if (connectTimeoutProperty != null) { elasticsearchParameters.setConnectTimeout(Integer.parseInt(connectTimeoutProperty)); } String socketTimeoutProperty = properties.getProperty(ElasticsearchConstants.PROP_SOCKETTIMEOUT); if (socketTimeoutProperty != null) { elasticsearchParameters.setSocketTimeout(Integer.parseInt(socketTimeoutProperty)); } String ioThreadCountProperty = properties.getProperty(ElasticsearchConstants.PROP_IOTHREADCOUNT); if (ioThreadCountProperty != null) { elasticsearchParameters.setIoThreadCount(Integer.parseInt(ioThreadCountProperty)); } return elasticsearchParameters; } }
/** * Converts a 4-byte array into an int32 * * @param src Source array * @param byteOrder Byte order * @return Integer result */ public static int byteToInt(byte[] src, ByteOrder byteOrder) { if (src.length != 4) { throw new IllegalArgumentException("Attempted to convert size " + src.length + " to int (invalid size)"); } return ByteBuffer.wrap(src).order(byteOrder).getInt(); }
/* * Compares one file path to another. */ int osys_path_cmp(const char *path1, const char *path2) { #if defined OSYS_DOS_OS2 return stricmp(path1, path2); #elif defined OSYS_WINDOWS return lstrcmpiA(path1, path2); #elif OSYS_PATH_ICASE return strcasecmp(path1, path2); #else return strcmp(path1, path2); #endif }
<filename>test/Benchmarking/CrossPlatform/src/ntakl.java // NTAKL -- The TAKeuchi function using lists as counters, // rewriting the boolean expression as statements. class Pair { // A Java compiler ought to generate inline code for these. public static Pair cons (int n, Pair y) { return new Pair(n, y); } public static int car (Pair x) { return x.hd; } public static Pair cdr (Pair x) { return x.tl; } // If it doesn't, then we'll inline them by hand. // That's why the following are public. // (But Sun's Java 1.2 does the inlining ok.) public Pair (int n, Pair y) { hd = n; tl = y; } public int hd; public Pair tl; } class ntakl { static Pair listn (int n) { if (n != 0) return Pair.cons (n, listn (n - 1)); else return null; } // The boolean expression below comes from the original TAKL // benchmark, and remains because it is fun to see which compilers // can generate good code from it. See NTAKL for a version in // which this mess has been cleaned up. static boolean shorterp (Pair x, Pair y) { while ((x != null) && (y != null)) { x = Pair.cdr (x); y = Pair.cdr (y); } if (y == null) return false; else return true; } static Pair mas (Pair x, Pair y, Pair z) { if (! shorterp (y, x)) return z; else return mas( mas( Pair.cdr(x), y, z ), mas( Pair.cdr(y), z, x ), mas( Pair.cdr(z), x, y ) ); } static Pair l18 = listn(18); static Pair l12 = listn(12); static Pair l6 = listn(6); static int result; static void test_takl() { result = Pair.car( mas( l18, l12, l6 ) ); } /*===========================================================================*/ public static void main (String args[]) { int i; for (i=0; i<200; i++) test_takl(); if (result != 7) System.out.println ("*** wrong result ***"); } }
While toddling through Shawlands this week, I chanced across the Labour's Glasgow South candidate, Tom Harris, campaigning outside the local Co-op. Having politely explained that I wasn't with him in this election, I took the opportunity to ask him about a letter which has been circulating in the constituency, inviting folk who voted No on the 18th of September 2014 to save his bacon on the 7th of May. "I thought Jim had said that Scottish Labour isn't a unionist party?" I enquired. "But I'm a unionist," he said. In his affably bluff way, Tom explained that he needed every vote going, and if that involved putting the fear of god up the Tories of Newlands, he'd make no apology for doing so. "And I suppose you're pretty right-wing too, so - " I quipped, for villainy - "I suppose I am," he responded, with unexpected candour. I sidled on. Good luck to him. He'll need it. "55% of people voted no, back me to stop the Nationalist juggernaut." John Curtice has been pouring But the encounter made me think a wee bit about the assumptions lying behind Tom's letter, and being pushed nationally by Liberal Democrats in tight spots, that the Better Together alliance can be cobbled back together to save their skins.John Curtice has been pouring buckets of icy water over the idea that tactical voting represents an effective anti-Nationalist strategy over most of the country, arguing that the sums just don't add up. As Professor Curtice points out, there aren't enough Labour, Tories or Liberal Democrat voters in the overwhelming majority of seats to make a decisive difference, even if folk were inclined to lend their vote to a Better Together ally. numerically problematic - it also flies in the face of what the referendum taught us about the reasons and attitudes lying behind the No vote. Tom and the Liberal Democrats seem to have forgotten who the 55% are, and why they voted against independence last September. The recent findings of the But the thinking behind this isn't justproblematic - it also flies in the face of what the referendum taught us about the reasons and attitudes lying behind the No vote. Tom and the Liberal Democrats seem to have forgotten who the 55% are, and why they voted against independence last September. The recent findings of the Scottish Election Study suggest that the No lead did not come down to British identities, or optimism about the Union, nor widespread pessimism about independence, but fear, risk and uncertainty. 29.5% of the No vote. To put a more concrete number on that, just 590,568 of the 2,001,926 votes attracted by the No campaign seem to have hinged to any significant extent on British identities. The study concludes that identities - Scottish and British - provided core support for both Yes and No campaigns, the outcome was decided by perceptions of economic risk. The most recent tranche of survey data from the study suggested that feelings of Britishness or attachment to the Union account for justof the No vote. To put a more concrete number on that, just 590,568 of the 2,001,926 votes attracted by the No campaign seem to have hinged to any significant extent on British identities. This chimes with my own experiences. If this referendum has revealed one thing, it is that Scots allegiance to the British state is - perhaps disturbingly - provisional. A popular, winning, organic unionism has not emerged. If anything, the Conservative and Unionist Party seems hell-bent on salting the earth across the border, to ensure no sprouts grow.
/** * @author Max Bechtold * */ public class FunctionTest extends XQueryBaseTest { private DBCompileChain chain = new DBCompileChain(metaDataMgr, tx); @Test public void createPathIdxTestOneArg() throws QueryException { Sequence result = new XQuery(chain, "bdb:create-path-index('test.xml')").execute(ctx); assertTrue(result != null); checkPathIndex(); } @Test public void createPathIdxTestTwoArg() throws QueryException { Sequence result = new XQuery(chain, "bdb:create-path-index('test.xml', ('//Member', '//Title'))") .execute(ctx); assertTrue(result != null); checkPathIndex(); } @Test public void createNameIdxTestOneArg() throws QueryException { Sequence result = new XQuery(chain, "bdb:create-name-index('test.xml')").execute(ctx); assertTrue(result != null); checkNameIndex(); } @Test public void createNameIdxTestTwoArg() throws QueryException { XQuery.DEBUG = true; Sequence result = new XQuery(chain, "bdb:create-name-index('test.xml', " + "(fn:QName((), 'Title'), " + "fn:QName('http://brackit.org', 'Title')))") .execute(ctx); assertTrue(result != null); checkNameIndex(); } @Test public void createCASIdxTestOneArg() throws QueryException { Sequence result = new XQuery(chain, "bdb:create-cas-index('test.xml')").execute(ctx); assertTrue(result != null); checkCASIndex(); } @Test public void createCASIdxTestTwoArg() throws QueryException { Sequence result = new XQuery(chain, "bdb:create-cas-index('test.xml', 'string')").execute(ctx); assertTrue(result != null); checkCASIndex(); } @Test public void createCASIdxTestThreeArg() throws QueryException { Sequence result = new XQuery(chain, "bdb:create-cas-index('test.xml', 'string'," + "('//Member', '//Title'))") .execute(ctx); assertTrue(result != null); checkCASIndex(); } @Test public void createCASIdxTestTwoAndAHalfArg() throws QueryException { Sequence result = new XQuery(chain, "bdb:create-cas-index('test.xml', ()," + "('//Member', '//Title'))") .execute(ctx); assertTrue(result != null); checkCASIndex(); } protected void checkCASIndex() throws DocumentException, ItemNotFoundException, QueryException { IndexDef index = metaDataMgr.lookup(tx, "test.xml").get(Indexes.class) .findCASIndex(Path.parse("//Title")); Una key = new Una("XML-DB"); Stream<?> stream = metaDataMgr.lookup(tx, "test.xml") .getIndexController().openCASIndex(index.getID(), null, key, key, true, true, SearchMode.GREATER_OR_EQUAL); Object o = stream.next(); int c = 0; while (o != null) { o = stream.next(); c++; } assertEquals(1, c); } protected void checkNameIndex() throws DocumentException, ItemNotFoundException, QueryException { QNm title = new QNm("Title"); IndexDef index = metaDataMgr.lookup(tx, "test.xml").get(Indexes.class) .findNameIndex(title); Stream<?> stream = metaDataMgr.lookup(tx, "test.xml") .getIndexController().openNameIndex(index.getID(), title, SearchMode.FIRST); Object o = stream.next(); int c = 0; while (o != null) { o = stream.next(); c++; } assertEquals(4, c); stream = metaDataMgr.lookup(tx, "test.xml").getIndexController() .openNameIndex(index.getID(), new QNm("http://brackit.org", "Title"), SearchMode.FIRST); o = stream.next(); c = 0; while (o != null) { o = stream.next(); c++; } assertEquals(0, c); } protected void checkPathIndex() throws DocumentException, ItemNotFoundException, QueryException { IndexDef index = metaDataMgr.lookup(tx, "test.xml").get(Indexes.class) .findPathIndex(Path.parse("//Title")); Filter<Node<?>> f = new Filter<Node<?>>() { @Override public boolean filter(Node<?> element) throws DocumentException { return !element.getName().equals(new QNm("Title")); } }; Stream<?> stream = metaDataMgr.lookup(tx, "test.xml") .getIndexController().openPathIndex(index.getID(), f, SearchMode.FIRST); Object o = stream.next(); int c = 0; while (o != null) { o = stream.next(); c++; } assertEquals(4, c); f = new Filter<Node<?>>() { @Override public boolean filter(Node<?> element) throws DocumentException { QNm qnm; try { qnm = new QNm("http://brackit.org", "Title"); } catch (QueryException e) { qnm = null; } return !element.getName().equals(qnm); } }; stream = metaDataMgr.lookup(tx, "test.xml") .getIndexController().openPathIndex(index.getID(), f, SearchMode.FIRST); o = stream.next(); c = 0; while (o != null) { o = stream.next(); c++; } assertEquals(0, c); } @Override public void setUp() throws Exception, FileNotFoundException { super.setUp(); XQuery.DEBUG = false; storeFile("test.xml", "/docs/orga.xml"); } }
n = input() cards = map(int, raw_input().split()) pos = {} for i in xrange(n): card = cards[i] pos[card] = pos.get(card, []) + [i+1] cards.sort() for i in xrange(n/2): first = cards.pop(0) last = cards.pop() print pos[first].pop(0), pos[last].pop(0) if first in pos and len(pos[first]) == 0: pos.pop(first) if last in pos and len(pos[last]) == 0: pos.pop(last)
def log_contains_count(self, msg, logfile=None, ignore_case=False): is_regexp = isinstance(msg, REGEXP_TYPE) counter = 0 if ignore_case: msg = msg.lower() if logfile is None: logfile = self.beat_name + "-" + self.today + ".ndjson" print("logfile", logfile, self.working_dir) try: with open(os.path.join(self.working_dir, logfile), "r", encoding="utf_8") as f: for line in f: if is_regexp: if msg.search(line) is not None: counter = counter + 1 continue if ignore_case: line = line.lower() if line.find(msg) >= 0: counter = counter + 1 except IOError as ioe: print(ioe) counter = -1 return counter
High nitrogen atom yield downstream of an atmospheric pressure flowing Ar-N2 microwave discharge A large yield of nitrogen atoms can be achieved at atmospheric pressure, from an Ar-N2 surface-wave-induced microwave discharge with half the microwave power needed with a pure N2 discharge. The dissociation of N2 molecules into atomic nitrogen in this Ar-N2 discharge is close to 22% at 0.3% N2 concentration and decreases with increasing nitrogen concentration. The maximum nitrogen atom yield per watt is reached at 3% of N2. Such a low power and simple nitrogen atom source, with a typical flow rate of 10 l min-1, is of interest for achieving metal nitriding at atmospheric pressure.
def func_lookup(type='device', action='list'): if action == 'query': func = action else: func = '_'.join((type, action)) try: return func_map[func]() except: print('Error: invalid argument combination: -t {}, -a {}'.format( arguments['type'], arguments['action'])) sys.exit(1) return None
/** * The download state should trigger changes in the UI --- it may be useful * to show the state as being indeterminate at times. This sample can be * considered a guideline. */ @Override public void onDownloadStateChanged(int newState) { if (mState != newState) { mState = newState; KrollDict evtObj = new KrollDict(); evtObj.put("state", newState); Log.d(TAG, "downloaderStateChanged to " + newState); fireEvent("downloaderStateChanged", evtObj); } }
AT&T, Whose Ex-CEO Promised To Wreck Net Neutrality, Insists It Won't Do Anything To Net Neutrality from the yeah,-nice-try dept AT&T is the latest big broadband player to try to suggest that everyone just calm down a little about this whole thing where the FCC destroys net neutrality. And, sure, some of the reports out there and some of the predictions being made about the impending death of net neutrality are fairly exaggerated. But, there are serious concerns, and AT&T's decision to set up some strawmen to knock over ignores the importance of the issue. Also, while AT&T ignores this, let's bring up a bit of history. Because it was former AT&T CEO Ed Whitacre who kicked off much of this debate back in 2005 when he declared that he was going to start charging successful internet sites to reach "his" customers over "his" pipes: "Now what they would like to do is use my pipes free, but I ain't going to let them do that because we have spent this capital and we have to have a return on it. So there's going to have to be some mechanism for these people who use these pipes to pay for the portion they're using. Why should they be allowed to use my pipes? The Internet can't be free in that sense, because we and the cable companies have made an investment and for a Google or Yahoo! or Vonage or anybody to expect to use these pipes [for] free is nuts!" As we pointed out at the time, this statement is incredibly misleading. Everyone -- especially those companies -- pay for their own bandwidth. And when AT&T's customers connect to the internet, the reasons it's worth it to them to pay AT&T for internet access is because they can access the entire internet, and not just the parts that AT&T gets to charge companies double for. So, with that in mind, let's take a look at the nonsense AT&T's top lobbyist, Bob Quinn, posted to AT&T's blog. AT&T intends to operate its network the same way AT&T operates its network today: in an open and transparent manner. We will not block websites, we will not throttle or degrade internet traffic based on content, and we will not unfairly discriminate in our treatment of internet traffic (all consistent with the rules that were adopted – and that we supported – in 2010, and the rules in place today). These commitments are laid out in the broadband details section of AT&T’s main website. They represent a guarantee to our customers that we will provide service in an open and transparent way. They have been, and will continue to be, enforceable commitments. We will not remove that language and we will continue to update any changes we make to our network management practices. Those commitments are not new. They have been formally in place in one form or another at AT&T since 2005, and we have also publicly disclosed how we manage internet traffic with a version of our current broadband details description on our website since 2010. If AT&T is making no changes and intends to operate the same way, why has AT&T been pushing so hard against the 2015 rules and for this repeal? And, again, it was the company's former CEO who made those statements above about how it's "nuts" that all these internet companies get to ride "his pipes... for free." Does that really sound like a company that has no intention of doing paid prioritization or fast lanes and slow lanes? Yes, Whitacre is no longer CEO, but the current CEO, Randall Stephenson, worked for Whitacre for many, many years and was his handpicked successor. So it's not as if AT&T has some new, more enlightened management. What is different is that AT&T has learned that being so blatant and so upfront about their plan to screw over internet users and websites goes over poorly in the press. So they figured out a while back how to make the behavior sneakier. They can play around with interconnection. They can dabble in zero rating. And, as some will no doubt point out, the 2015 open internet order did not explicitly deal with either of these loopholes (which was one of our biggest complaints with the order). But it did signal an FCC that wouldn't allow such bad actions (which is why interconnection fights all disappeared almost within seconds of the order being approved). In short: AT&T will seek to use whatever power it can to extract rents from the internet. Remember, this is a company that has been fined over and over and over again by the FCC for a variety of bad, anti-consumer behavior. And, remember, some of those fines (for SMS cramming) were under Title II. Do we magically think that AT&T is going to suddenly stop fucking over its users once the FCC has publicly stated "do whatever the fuck you want, we no longer care." We not only have enforceable commitments on blocking, throttling and discrimination on our own network, we also have incentives to ensure that other ISPs adhere to these same open internet principles. Take, for example, DIRECTV NOW, our over-the-top video service that travels over broadband connections whether owned by AT&T or someone else. We depend on an open internet for this service, and we accordingly conduct ourselves – and will continue to conduct ourselves – in the same manner we expect to be treated when we rely on the infrastructure of others to provide services to our customers. This sounds nice, doesn't it? Except, should we forget that the previous FCC actually found that AT&T abused its relationship with DirecTV in a way that violated its net neutrality rules? I mean, does Quinn just hope that people reading his blog post don't remember what happened less than a year ago? Besides, AT&T knows damn well that, as large as it is, it can easily negotiate good terms for competitors to carry DirecTV Now, while at the same time it has the leverage to fuck over smaller competitors. The day after the FCC’s decision, consumers are going to see no changes to how their internet works. Everyone will be able to access their favorite websites; no one’s traffic will be throttled based on content; and the consumer internet is going to work the same way it did the day before the FCC order is adopted. Well, sure. The day after the FCC's decision nothing is going to change because AT&T knows that a bunch of lawsuits will be filed, and it's not stupid enough to do something so blatant that it will be used as fodder in that lawsuit. It'll wait. And if the rules are upheld, you'll then suddenly start to notice little changes here and there. And, frequently, they'll be couched and framed in ways to look supportive of the consumer, rather than anti-consumer. They'll be things like zero rating, where AT&T will pretend that it's giving you "free data" even though it's really only "free" from the arbitrarily low and onerous caps that it sets itself. Consumers will, however, see enormous benefits from the FCC’s actions. Utility regulation over broadband can only inhibit incentives for network investment. They keep saying this, but this is hogwash. Again, the net neutrality rules was not "utility regulation." It was a basic framework that said you can't fuck over users. It was only a burden if your intent was to fuck over users. So if AT&T claims it was a burden... it was because it intended to fuck over users. By lifting that cloud here, the FCC will restore the bi-partisan, light-touch regulatory structure that made the United States the world leader in mobile broadband infrastructure. Hogwash. This is the same AT&T that bid billions last year under Title II in the big FCC spectrum auction. If it really felt hamstrung over the rules, why would it have invested so much in that spectrum? The doomsayers, of course, have a different view, conspicuously colored by a litany of hypotheticals and hyperbole, and generally devoid of facts. Some are calling this the death of the internet as we know it. The doomsayers, however, have been making these and similar dire predictions for years. In 2010, in response to the first FCC Open Internet rules, Free Press warned: “These rules don’t do enough to stop the phone and cable companies from dividing the Internet into fast and slow lanes, and they fail to protect wireless users from discrimination. No longer can you get to the same Internet via your mobile device as you can via your laptop. The rules pave the way for AT&T to block your access to third-party applications and to require you to use its own preferred applications.” Of course, none of those predictions ever came true then and they won’t come true after the FCC acts here either. There will be a lot of talk over the next two weeks on what the FCC’s net neutrality order means. The truth is that, at first, no one will notice a difference in how their internet works. But when the removal of utility regulation translates into greater broadband investment and increased innovation on the internet…well, everyone will eventually notice that. Actually... the one who is "devoid of facts" here is Bob Quinn at AT&T. Because under those rules, what Free Press predicted did happen. Remember when AT&T blocked Google Hangouts on mobile? Or when it blocked Facetime? Both of those happened under the weak 2010 rules, just like Free Press predicted. And, I should note, this seems like another reason not to trust AT&T here. It's directly denying it had done the very thing... it did. I know in this age of alternative facts some powerful folks believe that if you just say you didn't do the thing you absolutely did, many people will believe that you never actually did it. But the facts are here. Furthermore, AT&T's statement is even more disingenuous, because the 2010 rules were fought over in court for many years, which again was a reason why AT&T and others didn't go all out in implementing really bad behavior, so as not to give an assist to the courts. Either way, AT&T's statement is extremely misleading, ignores significant history from AT&T in both what its execs have said it intends to do and the company's actual actions. AT&T's Bob Quinn is spewing alternative facts here, and the public shouldn't accept his lies. Filed Under: ajit pai, bob quinn, ed whitacre, fcc, net neutrality Companies: at&t
/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*- */ /* vi: set ts=4 sw=4 expandtab: (add to ~/.vimrc: set modeline modelines=5) */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is [Open Source Virtual Machine]. * * The Initial Developer of the Original Code is * Adobe System Incorporated. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adobe AS3 Team * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "nanojit.h" #if defined FEATURE_NANOJIT && defined NANOJIT_PPC namespace nanojit { const Register Assembler::retRegs[] = { R3, R4 }; // high=R3, low=R4 const Register Assembler::argRegs[] = { R3, R4, R5, R6, R7, R8, R9, R10 }; const Register Assembler::savedRegs[] = { #if !defined NANOJIT_64BIT R13, #endif R14, R15, R16, R17, R18, R19, R20, R21, R22, R23, R24, R25, R26, R27, R28, R29, R30 }; const char *regNames[] = { "r0", "sp", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31" }; const char *bitNames[] = { "lt", "gt", "eq", "so" }; #define TODO(x) do{ avmplus::AvmLog(#x); NanoAssertMsgf(false, "%s", #x); } while(0) /* * see http://developer.apple.com/documentation/developertools/Conceptual/LowLevelABI/index.html * stack layout (higher address going down) * sp -> out linkage area * out parameter area * local variables * saved registers * sp' -> in linkage area * in parameter area * * linkage area layout: * PPC32 PPC64 * sp+0 sp+0 saved sp * sp+4 sp+8 saved cr * sp+8 sp+16 saved lr * sp+12 sp+24 reserved */ const int min_param_area_size = 8*sizeof(void*); // r3-r10 const int linkage_size = 6*sizeof(void*); const int lr_offset = 2*sizeof(void*); // linkage.lr const int cr_offset = 1*sizeof(void*); // linkage.cr NIns* Assembler::genPrologue() { // mflr r0 // stw r0, lr_offset(sp) // stwu sp, -framesize(sp) // param_area must be at least large enough for r3-r10 to be saved, // regardless of whether we think the callee needs less: e.g., the callee // might tail-call to a function that uses varargs, which could flush // r3-r10 to the parameter area. uint32_t param_area = (max_param_size > min_param_area_size) ? max_param_size : min_param_area_size; // activation frame is 4 bytes per entry even on 64bit machines uint32_t stackNeeded = param_area + linkage_size + _activation.stackSlotsNeeded() * 4; uint32_t aligned = alignUp(stackNeeded, NJ_ALIGN_STACK); UNLESS_PEDANTIC( if (isS16(aligned)) { STPU(SP, -aligned, SP); // *(sp-aligned) = sp; sp -= aligned } else ) { STPUX(SP, SP, R0); asm_li(R0, -aligned); } NIns *patchEntry = _nIns; MR(FP,SP); // save SP to use as a FP STP(FP, cr_offset, SP); // cheat and save our FP in linkage.cr STP(R0, lr_offset, SP); // save LR in linkage.lr MFLR(R0); return patchEntry; } NIns* Assembler::genEpilogue() { BLR(); MTLR(R0); LP(R0, lr_offset, SP); LP(FP, cr_offset, SP); // restore FP from linkage.cr MR(SP,FP); return _nIns; } void Assembler::asm_load32(LIns *ins) { LIns* base = ins->oprnd1(); int d = ins->disp(); Register rr = deprecated_prepResultReg(ins, GpRegs); Register ra = getBaseReg(base, d, GpRegs); switch(ins->opcode()) { case LIR_lduc2ui: if (isS16(d)) { LBZ(rr, d, ra); } else { LBZX(rr, ra, R0); // rr = [ra+R0] asm_li(R0,d); } return; case LIR_ldus2ui: // these are expected to be 2 or 4-byte aligned if (isS16(d)) { LHZ(rr, d, ra); } else { LHZX(rr, ra, R0); // rr = [ra+R0] asm_li(R0,d); } return; case LIR_ldi: // these are expected to be 4-byte aligned if (isS16(d)) { LWZ(rr, d, ra); } else { LWZX(rr, ra, R0); // rr = [ra+R0] asm_li(R0,d); } return; case LIR_ldc2i: case LIR_lds2i: NanoAssertMsg(0, "NJ_EXPANDED_LOADSTORE_SUPPORTED not yet supported for this architecture"); return; default: NanoAssertMsg(0, "asm_load32 should never receive this LIR opcode"); return; } } void Assembler::asm_store32(LOpcode op, LIns *value, int32_t dr, LIns *base) { switch (op) { case LIR_sti: case LIR_sti2c: // handled by mainline code below for now break; case LIR_sti2s: NanoAssertMsg(0, "NJ_EXPANDED_LOADSTORE_SUPPORTED not yet supported for this architecture"); return; default: NanoAssertMsg(0, "asm_store32 should never receive this LIR opcode"); return; } Register rs = findRegFor(value, GpRegs); Register ra = value == base ? rs : getBaseReg(base, dr, GpRegs & ~rmask(rs)); #if !PEDANTIC if (isS16(dr)) { switch (op) { case LIR_sti: STW(rs, dr, ra); break; case LIR_sti2c: STB(rs, dr, ra); break; } return; } #endif // general case store, any offset size switch (op) { case LIR_sti: STWX(rs, ra, R0); break; case LIR_sti2c: STBX(rs, ra, R0); break; } asm_li(R0, dr); } void Assembler::asm_load64(LIns *ins) { switch (ins->opcode()) { case LIR_ldd: CASE64(LIR_ldq:) // handled by mainline code below for now break; case LIR_ldf2d: NanoAssertMsg(0, "NJ_EXPANDED_LOADSTORE_SUPPORTED not yet supported for this architecture"); return; default: NanoAssertMsg(0, "asm_load64 should never receive this LIR opcode"); return; } LIns* base = ins->oprnd1(); #ifdef NANOJIT_64BIT Register rr = ins->deprecated_getReg(); if (deprecated_isKnownReg(rr) && (rmask(rr) & FpRegs)) { // FPR already assigned, fine, use it deprecated_freeRsrcOf(ins); } else { // use a GPR register; its okay to copy doubles with GPR's // but *not* okay to copy non-doubles with FPR's rr = deprecated_prepResultReg(ins, GpRegs); } #else Register rr = deprecated_prepResultReg(ins, FpRegs); #endif int dr = ins->disp(); Register ra = getBaseReg(base, dr, GpRegs); #ifdef NANOJIT_64BIT if (rmask(rr) & GpRegs) { #if !PEDANTIC if (isS16(dr)) { LD(rr, dr, ra); return; } #endif // general case 64bit GPR load LDX(rr, ra, R0); asm_li(R0, dr); return; } #endif // FPR #if !PEDANTIC if (isS16(dr)) { LFD(rr, dr, ra); return; } #endif // general case FPR load LFDX(rr, ra, R0); asm_li(R0, dr); } void Assembler::asm_li(Register r, int32_t imm) { #if !PEDANTIC if (isS16(imm)) { LI(r, imm); return; } if ((imm & 0xffff) == 0) { imm = uint32_t(imm) >> 16; LIS(r, imm); return; } #endif asm_li32(r, imm); } void Assembler::asm_li32(Register r, int32_t imm) { // general case // TODO use ADDI instead of ORI if r != r0, impl might have 3way adder ORI(r, r, imm); LIS(r, imm>>16); // on ppc64, this sign extends } void Assembler::asm_li64(Register r, uint64_t imm) { underrunProtect(5*sizeof(NIns)); // must be contiguous to be patchable ORI(r,r,uint16_t(imm)); // r[0:15] = imm[0:15] ORIS(r,r,uint16_t(imm>>16)); // r[16:31] = imm[16:31] SLDI(r,r,32); // r[32:63] = r[0:31], r[0:31] = 0 asm_li32(r, int32_t(imm>>32)); // r[0:31] = imm[32:63] } void Assembler::asm_store64(LOpcode op, LIns *value, int32_t dr, LIns *base) { NanoAssert(value->isQorD()); switch (op) { case LIR_std: CASE64(LIR_stq:) // handled by mainline code below for now break; case LIR_std2f: NanoAssertMsg(0, "NJ_EXPANDED_LOADSTORE_SUPPORTED not yet supported for this architecture"); return; default: NanoAssertMsg(0, "asm_store64 should never receive this LIR opcode"); return; } Register ra = getBaseReg(base, dr, GpRegs); // general case for any value #if !defined NANOJIT_64BIT // on 32bit cpu's, we only use store64 for doubles Register rs = findRegFor(value, FpRegs); #else // if we have to choose a register, use a GPR Register rs = ( !value->isInReg() ? findRegFor(value, GpRegs & ~rmask(ra)) : value->deprecated_getReg() ); if (rmask(rs) & GpRegs) { #if !PEDANTIC if (isS16(dr)) { // short offset STD(rs, dr, ra); return; } #endif // general case store 64bit GPR STDX(rs, ra, R0); asm_li(R0, dr); return; } #endif // NANOJIT_64BIT #if !PEDANTIC if (isS16(dr)) { // short offset STFD(rs, dr, ra); return; } #endif // general case for any offset STFDX(rs, ra, R0); asm_li(R0, dr); } void Assembler::asm_cond(LIns *ins) { LOpcode op = ins->opcode(); LIns *a = ins->oprnd1(); LIns *b = ins->oprnd2(); ConditionRegister cr = CR7; Register r = deprecated_prepResultReg(ins, GpRegs); switch (op) { case LIR_eqi: case LIR_eqd: CASE64(LIR_eqq:) EXTRWI(r, r, 1, 4*cr+COND_eq); // extract CR7.eq MFCR(r); break; case LIR_lti: case LIR_ltui: case LIR_ltd: case LIR_led: CASE64(LIR_ltq:) CASE64(LIR_ltuq:) EXTRWI(r, r, 1, 4*cr+COND_lt); // extract CR7.lt MFCR(r); break; case LIR_gti: case LIR_gtui: case LIR_gtd: case LIR_ged: CASE64(LIR_gtq:) CASE64(LIR_gtuq:) EXTRWI(r, r, 1, 4*cr+COND_gt); // extract CR7.gt MFCR(r); break; case LIR_lei: case LIR_leui: CASE64(LIR_leq:) CASE64(LIR_leuq:) EXTRWI(r, r, 1, 4*cr+COND_eq); // extract CR7.eq MFCR(r); CROR(CR7, eq, lt, eq); break; case LIR_gei: case LIR_geui: CASE64(LIR_geq:) CASE64(LIR_geuq:) EXTRWI(r, r, 1, 4*cr+COND_eq); // select CR7.eq MFCR(r); CROR(CR7, eq, gt, eq); break; default: debug_only(outputf("%s",lirNames[ins->opcode()]);) TODO(asm_cond); break; } asm_cmp(op, a, b, cr); } void Assembler::asm_condd(LIns *ins) { asm_cond(ins); } // cause sign extension to test bits. ptrdiff_t is a signed, // pointer-sized int static inline bool isS14(ptrdiff_t d) { const int shift = sizeof(ptrdiff_t) * 8 - 14; // 18 or 50 return ((d << shift) >> shift) == d; } NIns* Assembler::asm_branch(bool onfalse, LIns *cond, NIns * const targ) { LOpcode condop = cond->opcode(); NanoAssert(cond->isCmp()); // powerpc offsets are based on the address of the branch instruction NIns *patch; #if !PEDANTIC ptrdiff_t bd = targ - (_nIns-1); if (targ && isS24(bd)) patch = asm_branch_near(onfalse, cond, targ); else #endif patch = asm_branch_far(onfalse, cond, targ); asm_cmp(condop, cond->oprnd1(), cond->oprnd2(), CR7); return patch; } NIns* Assembler::asm_branch_near(bool onfalse, LIns *cond, NIns * const targ) { NanoAssert(targ != 0); underrunProtect(4); ptrdiff_t bd = targ - (_nIns-1); NIns *patch = 0; if (!isS14(bd)) { underrunProtect(8); bd = targ - (_nIns-1); if (isS24(bd)) { // can't fit conditional branch offset into 14 bits, but // we can fit in 24, so invert the condition and branch // around an unconditional jump verbose_only(verbose_outputf("%p:", _nIns);) NIns *skip = _nIns; B(bd); patch = _nIns; // this is the patchable branch to the given target onfalse = !onfalse; bd = skip - (_nIns-1); NanoAssert(isS14(bd)); verbose_only(verbose_outputf("branch24");) } else { // known far target return asm_branch_far(onfalse, cond, targ); } } ConditionRegister cr = CR7; switch (cond->opcode()) { case LIR_eqi: case LIR_eqd: CASE64(LIR_eqq:) if (onfalse) BNE(cr,bd); else BEQ(cr,bd); break; case LIR_lti: case LIR_ltui: case LIR_ltd: case LIR_led: CASE64(LIR_ltq:) CASE64(LIR_ltuq:) if (onfalse) BNL(cr,bd); else BLT(cr,bd); break; case LIR_lei: case LIR_leui: CASE64(LIR_leq:) CASE64(LIR_leuq:) if (onfalse) BGT(cr,bd); else BLE(cr,bd); break; case LIR_gti: case LIR_gtui: case LIR_gtd: case LIR_ged: CASE64(LIR_gtq:) CASE64(LIR_gtuq:) if (onfalse) BNG(cr,bd); else BGT(cr,bd); break; case LIR_gei: case LIR_geui: CASE64(LIR_geq:) CASE64(LIR_geuq:) if (onfalse) BLT(cr,bd); else BGE(cr,bd); break; default: debug_only(outputf("%s",lirNames[cond->opcode()]);) TODO(unknown_cond); } if (!patch) patch = _nIns; return patch; } // general case branch to any address (using CTR) NIns *Assembler::asm_branch_far(bool onfalse, LIns *cond, NIns * const targ) { LOpcode condop = cond->opcode(); ConditionRegister cr = CR7; underrunProtect(16); switch (condop) { case LIR_eqi: case LIR_eqd: CASE64(LIR_eqq:) if (onfalse) BNECTR(cr); else BEQCTR(cr); break; case LIR_lti: case LIR_ltui: CASE64(LIR_ltq:) CASE64(LIR_ltuq:) case LIR_ltd: case LIR_led: if (onfalse) BNLCTR(cr); else BLTCTR(cr); break; case LIR_lei: case LIR_leui: CASE64(LIR_leq:) CASE64(LIR_leuq:) if (onfalse) BGTCTR(cr); else BLECTR(cr); break; case LIR_gti: case LIR_gtui: CASE64(LIR_gtq:) CASE64(LIR_gtuq:) case LIR_gtd: case LIR_ged: if (onfalse) BNGCTR(cr); else BGTCTR(cr); break; case LIR_gei: case LIR_geui: CASE64(LIR_geq:) CASE64(LIR_geuq:) if (onfalse) BLTCTR(cr); else BGECTR(cr); break; default: debug_only(outputf("%s",lirNames[condop]);) TODO(unknown_cond); } #if !defined NANOJIT_64BIT MTCTR(R0); asm_li32(R0, (int)targ); #else MTCTR(R0); if (!targ || !isU32(uintptr_t(targ))) { asm_li64(R0, uint64_t(targ)); } else { asm_li32(R0, uint32_t(uintptr_t(targ))); } #endif return _nIns; } NIns* Assembler::asm_branch_ov(LOpcode, NIns*) { TODO(asm_branch_ov); return _nIns; } void Assembler::asm_cmp(LOpcode condop, LIns *a, LIns *b, ConditionRegister cr) { RegisterMask allow = isCmpDOpcode(condop) ? FpRegs : GpRegs; Register ra = findRegFor(a, allow); #if !PEDANTIC if (b->isImmI()) { int32_t d = b->immI(); if (isS16(d)) { if (isCmpSIOpcode(condop)) { CMPWI(cr, ra, d); return; } #if defined NANOJIT_64BIT if (isCmpSQOpcode(condop)) { CMPDI(cr, ra, d); TODO(cmpdi); return; } #endif } if (isU16(d)) { if (isCmpUIOpcode(condop)) { CMPLWI(cr, ra, d); return; } #if defined NANOJIT_64BIT if (isCmpUQOpcode(condop)) { CMPLDI(cr, ra, d); TODO(cmpldi); return; } #endif } } #endif // general case Register rb = b==a ? ra : findRegFor(b, allow & ~rmask(ra)); if (isCmpSIOpcode(condop)) { CMPW(cr, ra, rb); } else if (isCmpUIOpcode(condop)) { CMPLW(cr, ra, rb); } #if defined NANOJIT_64BIT else if (isCmpSQOpcode(condop)) { CMPD(cr, ra, rb); } else if (isCmpUQOpcode(condop)) { CMPLD(cr, ra, rb); } #endif else if (isCmpDOpcode(condop)) { // set the lt/gt bit for fle/fge. We don't do this for // int/uint because in those cases we can invert the branch condition. // for float, we can't because of unordered comparisons if (condop == LIR_led) CROR(cr, lt, lt, eq); // lt = lt|eq else if (condop == LIR_ged) CROR(cr, gt, gt, eq); // gt = gt|eq FCMPU(cr, ra, rb); } else { TODO(asm_cmp); } } void Assembler::asm_ret(LIns *ins) { genEpilogue(); releaseRegisters(); assignSavedRegs(); LIns *value = ins->oprnd1(); Register r = ins->isop(LIR_retd) ? F1 : R3; findSpecificRegFor(value, r); } void Assembler::asm_nongp_copy(Register r, Register s) { // PPC doesn't support any GPR<->FPR moves NanoAssert((rmask(r) & FpRegs) && (rmask(s) & FpRegs)); FMR(r, s); } bool Assembler::canRemat(LIns* ins) { return ins->isImmI() || ins->isop(LIR_allocp); } void Assembler::asm_restore(LIns *i, Register r) { int d; if (i->isop(LIR_allocp)) { d = deprecated_disp(i); ADDI(r, FP, d); } else if (i->isImmI()) { asm_li(r, i->immI()); } else { d = findMemFor(i); if (IsFpReg(r)) { NanoAssert(i->isQorD()); LFD(r, d, FP); } else if (i->isQorD()) { NanoAssert(IsGpReg(r)); LD(r, d, FP); } else { NanoAssert(i->isI()); NanoAssert(IsGpReg(r)); LWZ(r, d, FP); } } } void Assembler::asm_immi(LIns *ins) { Register rr = deprecated_prepResultReg(ins, GpRegs); asm_li(rr, ins->immI()); } void Assembler::asm_fneg(LIns *ins) { Register rr = deprecated_prepResultReg(ins, FpRegs); Register ra = findRegFor(ins->oprnd1(), FpRegs); FNEG(rr,ra); } void Assembler::asm_param(LIns *ins) { uint32_t a = ins->paramArg(); uint32_t kind = ins->paramKind(); if (kind == 0) { // ordinary param // first eight args always in R3..R10 for PPC if (a < 8) { // incoming arg in register deprecated_prepResultReg(ins, rmask(argRegs[a])); } else { // todo: support stack based args, arg 0 is at [FP+off] where off // is the # of regs to be pushed in genProlog() TODO(asm_param_stk); } } else { // saved param deprecated_prepResultReg(ins, rmask(savedRegs[a])); } } void Assembler::asm_call(LIns *ins) { if (!ins->isop(LIR_callv)) { Register retReg = ( ins->isop(LIR_calld) ? F1 : retRegs[0] ); deprecated_prepResultReg(ins, rmask(retReg)); } // Do this after we've handled the call result, so we don't // force the call result to be spilled unnecessarily. evictScratchRegsExcept(0); const CallInfo* call = ins->callInfo(); ArgType argTypes[MAXARGS]; uint32_t argc = call->getArgTypes(argTypes); bool indirect; if (!(indirect = call->isIndirect())) { verbose_only(if (_logc->lcbits & LC_Native) outputf(" %p:", _nIns); ) br((NIns*)call->_address, 1); } else { // Indirect call: we assign the address arg to R11 since it's not // used for regular arguments, and is otherwise scratch since it's // clobberred by the call. underrunProtect(8); // underrunProtect might clobber CTR BCTRL(); MTCTR(R11); asm_regarg(ARGTYPE_P, ins->arg(--argc), R11); } int param_size = 0; Register r = R3; Register fr = F1; for(uint32_t i = 0; i < argc; i++) { uint32_t j = argc - i - 1; ArgType ty = argTypes[j]; LIns* arg = ins->arg(j); NanoAssert(ty != ARGTYPE_V); if (ty != ARGTYPE_D) { // GP arg if (r <= R10) { asm_regarg(ty, arg, r); r = r + 1; param_size += sizeof(void*); } else { // put arg on stack TODO(stack_int32); } } else { // double if (fr <= F13) { asm_regarg(ty, arg, fr); fr = fr + 1; #ifdef NANOJIT_64BIT r = r + 1; #else r = r + 2; // Skip 2 GPRs. #endif param_size += sizeof(double); } else { // put arg on stack TODO(stack_double); } } } if (param_size > max_param_size) max_param_size = param_size; } void Assembler::asm_regarg(ArgType ty, LIns* p, Register r) { NanoAssert(r != deprecated_UnknownReg); NanoAssert(ty != ARGTYPE_V); if (ty != ARGTYPE_D) { #ifdef NANOJIT_64BIT if (ty == ARGTYPE_I) { // sign extend 32->64 EXTSW(r, r); } else if (ty == ARGTYPE_UI) { // zero extend 32->64 CLRLDI(r, r, 32); } #endif // arg goes in specific register if (p->isImmI()) { asm_li(r, p->immI()); } else { if (p->isExtant()) { if (!p->deprecated_hasKnownReg()) { // load it into the arg reg int d = findMemFor(p); if (p->isop(LIR_allocp)) { NanoAssert(isS16(d)); ADDI(r, FP, d); } else if (p->isQorD()) { LD(r, d, FP); } else { LWZ(r, d, FP); } } else { // it must be in a saved reg MR(r, p->deprecated_getReg()); } } else { // this is the last use, so fine to assign it // to the scratch reg, it's dead after this point. findSpecificRegFor(p, r); } } } else { if (p->isExtant()) { Register rp = p->deprecated_getReg(); if (!deprecated_isKnownReg(rp) || !IsFpReg(rp)) { // load it into the arg reg int d = findMemFor(p); LFD(r, d, FP); } else { // it must be in a saved reg NanoAssert(IsFpReg(r) && IsFpReg(rp)); FMR(r, rp); } } else { // this is the last use, so fine to assign it // to the scratch reg, it's dead after this point. findSpecificRegFor(p, r); } } } void Assembler::asm_spill(Register rr, int d, bool quad) { (void)quad; NanoAssert(d); if (IsFpReg(rr)) { NanoAssert(quad); STFD(rr, d, FP); } #ifdef NANOJIT_64BIT else if (quad) { STD(rr, d, FP); } #endif else { NanoAssert(!quad); STW(rr, d, FP); } } void Assembler::asm_arith(LIns *ins) { LOpcode op = ins->opcode(); LIns* lhs = ins->oprnd1(); LIns* rhs = ins->oprnd2(); RegisterMask allow = GpRegs; Register rr = deprecated_prepResultReg(ins, allow); Register ra = findRegFor(lhs, GpRegs); if (rhs->isImmI()) { int32_t rhsc = rhs->immI(); if (isS16(rhsc)) { // ppc arith immediate ops sign-exted the imm16 value switch (op) { case LIR_addi: CASE64(LIR_addq:) ADDI(rr, ra, rhsc); return; case LIR_subi: SUBI(rr, ra, rhsc); return; case LIR_muli: MULLI(rr, ra, rhsc); return; } } if (isU16(rhsc)) { // ppc logical immediate zero-extend the imm16 value switch (op) { CASE64(LIR_orq:) case LIR_ori: ORI(rr, ra, rhsc); return; CASE64(LIR_andq:) case LIR_andi: ANDI(rr, ra, rhsc); return; CASE64(LIR_xorq:) case LIR_xori: XORI(rr, ra, rhsc); return; } } // LIR shift ops only use last 5bits of shift const switch (op) { case LIR_lshi: SLWI(rr, ra, rhsc&31); return; case LIR_rshui: SRWI(rr, ra, rhsc&31); return; case LIR_rshi: SRAWI(rr, ra, rhsc&31); return; } } // general case, put rhs in register Register rb = rhs==lhs ? ra : findRegFor(rhs, GpRegs&~rmask(ra)); switch (op) { CASE64(LIR_addq:) case LIR_addi: ADD(rr, ra, rb); break; CASE64(LIR_andq:) case LIR_andi: AND(rr, ra, rb); break; CASE64(LIR_orq:) case LIR_ori: OR(rr, ra, rb); break; CASE64(LIR_xorq:) case LIR_xori: XOR(rr, ra, rb); break; case LIR_subi: SUBF(rr, rb, ra); break; case LIR_lshi: SLW(rr, ra, R0); ANDI(R0, rb, 31); break; case LIR_rshi: SRAW(rr, ra, R0); ANDI(R0, rb, 31); break; case LIR_rshui: SRW(rr, ra, R0); ANDI(R0, rb, 31); break; case LIR_muli: MULLW(rr, ra, rb); break; #ifdef NANOJIT_64BIT case LIR_lshq: SLD(rr, ra, R0); ANDI(R0, rb, 63); break; case LIR_rshuq: SRD(rr, ra, R0); ANDI(R0, rb, 63); break; case LIR_rshq: SRAD(rr, ra, R0); ANDI(R0, rb, 63); TODO(qirsh); break; #endif default: debug_only(outputf("%s",lirNames[op]);) TODO(asm_arith); } } void Assembler::asm_fop(LIns *ins) { LOpcode op = ins->opcode(); LIns* lhs = ins->oprnd1(); LIns* rhs = ins->oprnd2(); RegisterMask allow = FpRegs; Register rr = deprecated_prepResultReg(ins, allow); Register ra, rb; findRegFor2(allow, lhs, ra, allow, rhs, rb); switch (op) { case LIR_addd: FADD(rr, ra, rb); break; case LIR_subd: FSUB(rr, ra, rb); break; case LIR_muld: FMUL(rr, ra, rb); break; case LIR_divd: FDIV(rr, ra, rb); break; default: debug_only(outputf("%s",lirNames[op]);) TODO(asm_fop); } } void Assembler::asm_i2d(LIns *ins) { Register r = deprecated_prepResultReg(ins, FpRegs); Register v = findRegFor(ins->oprnd1(), GpRegs); const int d = 16; // natural aligned #if defined NANOJIT_64BIT && !PEDANTIC FCFID(r, r); // convert to double LFD(r, d, SP); // load into fpu register STD(v, d, SP); // save int64 EXTSW(v, v); // extend sign destructively, ok since oprnd1 only is 32bit #else FSUB(r, r, F0); LFD(r, d, SP); // scratch area in outgoing linkage area STW(R0, d+4, SP); XORIS(R0, v, 0x8000); LFD(F0, d, SP); STW(R0, d+4, SP); LIS(R0, 0x8000); STW(R0, d, SP); LIS(R0, 0x4330); #endif } void Assembler::asm_ui2d(LIns *ins) { Register r = deprecated_prepResultReg(ins, FpRegs); Register v = findRegFor(ins->oprnd1(), GpRegs); const int d = 16; #if defined NANOJIT_64BIT && !PEDANTIC FCFID(r, r); // convert to double LFD(r, d, SP); // load into fpu register STD(v, d, SP); // save int64 CLRLDI(v, v, 32); // zero-extend destructively #else FSUB(r, r, F0); LFD(F0, d, SP); STW(R0, d+4, SP); LI(R0, 0); LFD(r, d, SP); STW(v, d+4, SP); STW(R0, d, SP); LIS(R0, 0x4330); #endif } void Assembler::asm_d2i(LIns*) { NanoAssertMsg(0, "NJ_F2I_SUPPORTED not yet supported for this architecture"); } #if defined NANOJIT_64BIT // XXX: this is sub-optimal, see https://bugzilla.mozilla.org/show_bug.cgi?id=540368#c7. void Assembler::asm_q2i(LIns *ins) { Register rr = deprecated_prepResultReg(ins, GpRegs); int d = findMemFor(ins->oprnd1()); LWZ(rr, d+4, FP); } void Assembler::asm_ui2uq(LIns *ins) { LOpcode op = ins->opcode(); Register r = deprecated_prepResultReg(ins, GpRegs); Register v = findRegFor(ins->oprnd1(), GpRegs); switch (op) { default: debug_only(outputf("%s",lirNames[op])); TODO(asm_ui2uq); case LIR_ui2uq: CLRLDI(r, v, 32); // clears the top 32 bits break; case LIR_i2q: EXTSW(r, v); break; } } void Assembler::asm_dasq(LIns*) { TODO(asm_dasq); } void Assembler::asm_qasd(LIns*) { TODO(asm_qasd); } #endif #ifdef NANOJIT_64BIT void Assembler::asm_immq(LIns *ins) { Register r = ins->deprecated_getReg(); if (deprecated_isKnownReg(r) && (rmask(r) & FpRegs)) { // FPR already assigned, fine, use it deprecated_freeRsrcOf(ins); } else { // use a GPR register; its okay to copy doubles with GPR's // but *not* okay to copy non-doubles with FPR's r = deprecated_prepResultReg(ins, GpRegs); } if (rmask(r) & FpRegs) { union { double d; struct { int32_t hi, lo; // Always assuming big-endian in NativePPC.cpp } w; }; d = ins->immD(); LFD(r, 8, SP); STW(R0, 12, SP); asm_li(R0, w.lo); STW(R0, 8, SP); asm_li(R0, w.hi); } else { int64_t q = ins->immQ(); if (isS32(q)) { asm_li(r, int32_t(q)); return; } RLDIMI(r,R0,32,0); // or 32,32? asm_li(R0, int32_t(q>>32)); // hi bits into R0 asm_li(r, int32_t(q)); // lo bits into dest reg } } #endif void Assembler::asm_immd(LIns *ins) { #ifdef NANOJIT_64BIT Register r = ins->deprecated_getReg(); if (deprecated_isKnownReg(r) && (rmask(r) & FpRegs)) { // FPR already assigned, fine, use it deprecated_freeRsrcOf(ins); } else { // use a GPR register; its okay to copy doubles with GPR's // but *not* okay to copy non-doubles with FPR's r = deprecated_prepResultReg(ins, GpRegs); } #else Register r = deprecated_prepResultReg(ins, FpRegs); #endif if (rmask(r) & FpRegs) { union { double d; struct { int32_t hi, lo; // Always assuming big-endian in NativePPC.cpp } w; }; d = ins->immD(); LFD(r, 8, SP); STW(R0, 12, SP); asm_li(R0, w.lo); STW(R0, 8, SP); asm_li(R0, w.hi); } else { int64_t q = ins->immDasQ(); if (isS32(q)) { asm_li(r, int32_t(q)); return; } RLDIMI(r,R0,32,0); // or 32,32? asm_li(R0, int32_t(q>>32)); // hi bits into R0 asm_li(r, int32_t(q)); // lo bits into dest reg } } void Assembler::br(NIns* addr, int link) { // destination unknown, then use maximum branch possible if (!addr) { br_far(addr,link); return; } // powerpc offsets are based on the address of the branch instruction underrunProtect(4); // ensure _nIns is addr of Bx ptrdiff_t offset = addr - (_nIns-1); // we want ptr diff's implicit >>2 here #if !PEDANTIC if (isS24(offset)) { Bx(offset, 0, link); // b addr or bl addr return; } ptrdiff_t absaddr = addr - (NIns*)0; // ptr diff implies >>2 if (isS24(absaddr)) { Bx(absaddr, 1, link); // ba addr or bla addr return; } #endif // !PEDANTIC br_far(addr,link); } void Assembler::br_far(NIns* addr, int link) { // far jump. // can't have a page break in this sequence, because the break // would also clobber ctr and r2. We use R2 here because it's not available // to the register allocator, and we use R0 everywhere else as scratch, so using // R2 here avoids clobbering anything else besides CTR. #ifdef NANOJIT_64BIT if (addr==0 || !isU32(uintptr_t(addr))) { // really far jump to 64bit abs addr underrunProtect(28); // 7 instructions BCTR(link); MTCTR(R2); asm_li64(R2, uintptr_t(addr)); // 5 instructions return; } #endif underrunProtect(16); BCTR(link); MTCTR(R2); asm_li32(R2, uint32_t(uintptr_t(addr))); // 2 instructions } void Assembler::underrunProtect(int bytes) { NanoAssertMsg(bytes<=LARGEST_UNDERRUN_PROT, "constant LARGEST_UNDERRUN_PROT is too small"); int instr = (bytes + sizeof(NIns) - 1) / sizeof(NIns); NIns *pc = _nIns; NIns *top = codeStart; // this may be in a normal code chunk or an exit code chunk #if PEDANTIC // pedanticTop is based on the last call to underrunProtect; any time we call // underrunProtect and would use more than what's already protected, then insert // a page break jump. Sometimes, this will be to a new page, usually it's just // the next instruction and the only effect is to clobber R2 & CTR NanoAssert(pedanticTop >= top); if (pc - instr < pedanticTop) { // no page break required, but insert a far branch anyway just to be difficult #ifdef NANOJIT_64BIT const int br_size = 7; #else const int br_size = 4; #endif if (pc - instr - br_size < top) { // really do need a page break verbose_only(if (_logc->lcbits & LC_Native) outputf("newpage %p:", pc);) codeAlloc(); } // now emit the jump, but make sure we won't need another page break. // we're pedantic, but not *that* pedantic. pedanticTop = _nIns - br_size; br(pc, 0); pedanticTop = _nIns - instr; } #else if (pc - instr < top) { verbose_only(if (_logc->lcbits & LC_Native) outputf("newpage %p:", pc);) // This may be in a normal code chunk or an exit code chunk. codeAlloc(codeStart, codeEnd, _nIns verbose_only(, codeBytes)); // This jump will call underrunProtect again, but since we're on a new // page, nothing will happen. br(pc, 0); } #endif } void Assembler::asm_cmov(LIns* ins) { LIns* condval = ins->oprnd1(); LIns* iftrue = ins->oprnd2(); LIns* iffalse = ins->oprnd3(); #ifdef NANOJIT_64BIT NanoAssert((ins->opcode() == LIR_cmovi && iftrue->isI() && iffalse->isI()) || (ins->opcode() == LIR_cmovq && iftrue->isQ() && iffalse->isQ())); #else NanoAssert((ins->opcode() == LIR_cmovi && iftrue->isI() && iffalse->isI())); #endif Register rr = prepareResultReg(ins, GpRegs); Register rf = findRegFor(iffalse, GpRegs & ~rmask(rr)); // If 'iftrue' isn't in a register, it can be clobbered by 'ins'. Register rt = iftrue->isInReg() ? iftrue->getReg() : rr; underrunProtect(16); // make sure branch target and branch are on same page and thus near NIns *after = _nIns; verbose_only(if (_logc->lcbits & LC_Native) outputf("%p:",after);) MR(rr,rf); NanoAssert(isS24(after - (_nIns-1))); asm_branch_near(false, condval, after); if (rr != rt) MR(rr, rt); freeResourcesOf(ins); if (!iftrue->isInReg()) { NanoAssert(rt == rr); findSpecificRegForUnallocated(iftrue, rr); } asm_cmp(condval->opcode(), condval->oprnd1(), condval->oprnd2(), CR7); } RegisterMask Assembler::nHint(LIns* ins) { NanoAssert(ins->isop(LIR_paramp)); RegisterMask prefer = 0; if (ins->paramKind() == 0) if (ins->paramArg() < 8) prefer = rmask(argRegs[ins->paramArg()]); return prefer; } void Assembler::asm_neg_not(LIns *ins) { Register rr = deprecated_prepResultReg(ins, GpRegs); Register ra = findRegFor(ins->oprnd1(), GpRegs); if (ins->isop(LIR_negi)) { NEG(rr, ra); } else { NOT(rr, ra); } } void Assembler::nInit(AvmCore*) { nHints[LIR_calli] = rmask(R3); #ifdef NANOJIT_64BIT nHints[LIR_callq] = rmask(R3); #endif nHints[LIR_calld] = rmask(F1); nHints[LIR_paramp] = PREFER_SPECIAL; } void Assembler::nBeginAssembly() { max_param_size = 0; } void Assembler::nativePageSetup() { NanoAssert(!_inExit); if (!_nIns) { codeAlloc(codeStart, codeEnd, _nIns verbose_only(, codeBytes)); IF_PEDANTIC( pedanticTop = _nIns; ) } } void Assembler::nativePageReset() {} // Increment the 32-bit profiling counter at pCtr, without // changing any registers. verbose_only( void Assembler::asm_inc_m32(uint32_t* /*pCtr*/) { } ) void Assembler::nPatchBranch(NIns *branch, NIns *target) { // ppc relative offsets are based on the addr of the branch instruction ptrdiff_t bd = target - branch; if (branch[0] == PPC_b) { // unconditional, 24bit offset. Whoever generated the unpatched jump // must have known the final size would fit in 24bits! otherwise the // jump would be (lis,ori,mtctr,bctr) and we'd be patching the lis,ori. NanoAssert(isS24(bd)); branch[0] |= (bd & 0xffffff) << 2; } else if ((branch[0] & PPC_bc) == PPC_bc) { // conditional, 14bit offset. Whoever generated the unpatched jump // must have known the final size would fit in 14bits! otherwise the // jump would be (lis,ori,mtctr,bcctr) and we'd be patching the lis,ori below. NanoAssert(isS14(bd)); NanoAssert(((branch[0] & 0x3fff)<<2) == 0); branch[0] |= (bd & 0x3fff) << 2; TODO(patch_bc); } #ifdef NANOJIT_64BIT // patch 64bit branch else if ((branch[0] & ~(31<<21)) == PPC_addis) { // general branch, using lis,ori,sldi,oris,ori to load the const 64bit addr. Register rd = { (branch[0] >> 21) & 31 }; NanoAssert(branch[1] == PPC_ori | GPR(rd)<<21 | GPR(rd)<<16); NanoAssert(branch[3] == PPC_oris | GPR(rd)<<21 | GPR(rd)<<16); NanoAssert(branch[4] == PPC_ori | GPR(rd)<<21 | GPR(rd)<<16); uint64_t imm = uintptr_t(target); uint32_t lo = uint32_t(imm); uint32_t hi = uint32_t(imm>>32); branch[0] = PPC_addis | GPR(rd)<<21 | uint16_t(hi>>16); branch[1] = PPC_ori | GPR(rd)<<21 | GPR(rd)<<16 | uint16_t(hi); branch[3] = PPC_oris | GPR(rd)<<21 | GPR(rd)<<16 | uint16_t(lo>>16); branch[4] = PPC_ori | GPR(rd)<<21 | GPR(rd)<<16 | uint16_t(lo); } #else // NANOJIT_64BIT // patch 32bit branch else if ((branch[0] & ~(31<<21)) == PPC_addis) { // general branch, using lis,ori to load the const addr. // patch a lis,ori sequence with a 32bit value Register rd = { (branch[0] >> 21) & 31 }; NanoAssert(branch[1] == PPC_ori | GPR(rd)<<21 | GPR(rd)<<16); uint32_t imm = uint32_t(target); branch[0] = PPC_addis | GPR(rd)<<21 | uint16_t(imm >> 16); // lis rd, imm >> 16 branch[1] = PPC_ori | GPR(rd)<<21 | GPR(rd)<<16 | uint16_t(imm); // ori rd, rd, imm & 0xffff } #endif // !NANOJIT_64BIT else { TODO(unknown_patch); } } static int cntzlw(int set) { // On PowerPC, prefer higher registers, to minimize // size of nonvolatile area that must be saved. register uint32_t i; #ifdef __GNUC__ asm ("cntlzw %0,%1" : "=r" (i) : "r" (set)); #else // __GNUC__ # error("unsupported compiler") #endif // __GNUC__ return 31-i; } Register Assembler::nRegisterAllocFromSet(RegisterMask set) { uint32_t i; // note, deliberate truncation of 64->32 bits if (set & 0xffffffff) { i = cntzlw(int(set)); // gp reg } else { i = 32 + cntzlw(int(set>>32)); // fp reg } Register r = { i }; _allocator.free &= ~rmask(r); return r; } void Assembler::nRegisterResetAll(RegAlloc &regs) { regs.clear(); regs.free = SavedRegs | 0x1ff8 /* R3-12 */ | 0x3ffe00000000LL /* F1-13 */; } #ifdef NANOJIT_64BIT void Assembler::asm_qbinop(LIns *ins) { LOpcode op = ins->opcode(); switch (op) { case LIR_orq: case LIR_andq: case LIR_rshuq: case LIR_rshq: case LIR_lshq: case LIR_xorq: case LIR_addq: asm_arith(ins); break; default: debug_only(outputf("%s",lirNames[op])); TODO(asm_qbinop); } } #endif // NANOJIT_64BIT void Assembler::nFragExit(LIns*) { TODO(nFragExit); } void Assembler::asm_jtbl(LIns* ins, NIns** native_table) { // R0 = index*4, R2 = table, CTR = computed address to jump to. // must ensure no page breaks in here because R2 & CTR can get clobbered. Register indexreg = findRegFor(ins->oprnd1(), GpRegs); #ifdef NANOJIT_64BIT underrunProtect(9*4); BCTR(0); // jump to address in CTR MTCTR(R2); // CTR = R2 LDX(R2, R2, R0); // R2 = [table + index*8] SLDI(R0, indexreg, 3); // R0 = index*8 asm_li64(R2, uint64_t(native_table)); // R2 = table (5 instr) #else // 64bit underrunProtect(6*4); BCTR(0); // jump to address in CTR MTCTR(R2); // CTR = R2 LWZX(R2, R2, R0); // R2 = [table + index*4] SLWI(R0, indexreg, 2); // R0 = index*4 asm_li(R2, int32_t(native_table)); // R2 = table (up to 2 instructions) #endif // 64bit } void Assembler::swapCodeChunks() { if (!_nExitIns) { codeAlloc(exitStart, exitEnd, _nExitIns verbose_only(, exitBytes)); } SWAP(NIns*, _nIns, _nExitIns); SWAP(NIns*, codeStart, exitStart); SWAP(NIns*, codeEnd, exitEnd); verbose_only( SWAP(size_t, codeBytes, exitBytes); ) } void Assembler::asm_insert_random_nop() { NanoAssert(0); // not supported } } // namespace nanojit #endif // FEATURE_NANOJIT && NANOJIT_PPC
package main import ( "bufio" "flag" "fmt" "log" "os" "regexp" "strings" ) var ( getURL = flag.Bool("c", false, "get novel url to a file.") getNovel = flag.Bool("n", false, "get novel content from files.") modNovel = flag.Bool("m", false, "modify novel title.") ) func main() { chapterURL := config.URL + config.Chapter flag.Parse() flag.Usage = myUsage if *getURL == false && *getNovel == false && *modNovel == false { fmt.Printf("Usage: %s [OPTIONS] argument ...\n", os.Args[0]) flag.PrintDefaults() os.Exit(1) } if *getURL { println("start to download") writeNovelToFile(chapterURL, config.URLFile) } if *getNovel { downloadNovel(config.URLFile, config.NovelFile, config.StartPage, GetNovelByParam) } if *modNovel { handleText(config.NovelFile, "tmp.txt") } } func myUsage() { fmt.Printf("Usage: %s [OPTIONS] argument ...\n", os.Args[0]) flag.PrintDefaults() } func writeNovelToFile(url, filename string) { pages := GetPages(url) var str string for _, page := range pages { str += fmt.Sprintf("[%s %s/%s]\n", page.Title, url, page.URL) } WriteToFile(filename, str) } func downloadNovel(src, dest string, firstChapter int, f func(string) []Novel) { outFile, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY, 0600) if err != nil { fmt.Printf("Cannot open file %s", dest) } bWriter := bufio.NewWriter(outFile) pages := getNovelFromFile(src, firstChapter) for _, page := range pages { novel := f(page.URL)[0] novel.Title = page.Title novelText := novel.Title + "\n\n " + strings.TrimSpace(novel.Content) + "\n\n" bWriter.WriteString(novelText) } bWriter.Flush() outFile.Close() } func getNovelFromFile(filename string, firstChapter int) (pages []Page) { novelStr := ReadFromFile(filename) for i, novelLine := range strings.Split(novelStr, "\n") { if novelLine == "" { break } novelLine = strings.TrimPrefix(novelLine, "[") novelLine = strings.TrimRight(novelLine, "]") log.Println(novelLine) novelSplit := strings.Split(novelLine, " ") chapter := fmt.Sprintf("第%d章 %s", i+firstChapter, novelSplit[1]) page := Page{ Title: chapter, URL: novelSplit[2], } pages = append(pages, page) } return pages } func handleText(inputFileName, outputFileName string) error { var re *regexp.Regexp var count int = 0 inFile, err := os.Open(inputFileName) if err != nil { log.Printf("Cannot open text file: %s, err: [%v]", inputFileName, err) return err } defer inFile.Close() outFile, err := os.OpenFile(outputFileName, os.O_CREATE|os.O_WRONLY, 0600) if err != nil { fmt.Printf("Cannot open file %s", outputFileName) } bWriter := bufio.NewWriter(outFile) scanner := bufio.NewScanner(inFile) for scanner.Scan() { line := scanner.Text() // 更改章节 re = regexp.MustCompile("^[\u7b2c](.*)[\u7ae0] ") matched := re.MatchString(line) if matched { println(line) replaceString := fmt.Sprintf("第%d章 ", config.StartPage+count) line = re.ReplaceAllString(line, replaceString) count++ } bWriter.WriteString(line + "\n") } bWriter.Flush() if err := scanner.Err(); err != nil { log.Printf("Cannot scanner text file: %s, err: [%v]", inputFileName, err) return err } return nil }
import { ICommandHandlerRegister, ICommandService } from "./command"; import { CommandHandlerRegister } from "./command/model/CommandHandlerRegister"; import { CommandService } from "./command/model/CommandService"; import { IEventHandlerRegister, IEventService } from "./event"; import { StandardEventHandlerRegister } from "./event/model/StandardEventHandlerRegister"; import { StandardEventService } from "./event/model/StandardEventService"; import { IGuid } from "./guid/IGuid"; import { GuidImpl } from "./guid/impl/GuidImpl"; import { setDefaultResourceBundle } from "./i18n/I18nServices"; import { IIndexPool } from "./index/IIndexPool"; import { IndexPool } from "./index/impl/IndexPool"; import { createSingletonService } from "./ioc"; import { createSingletonServiceFactory } from "./ioc/create/CreateSingletonServiceFactory"; import { ILoggerFactory } from "./logger"; import { StandardLoggerFactory } from "./logger/factory/StandardLoggerFactory"; import { IQueryHandlerRegister, IQueryService } from "./query"; import { StandardQueryHandlerRegister } from "./query/model/StandardQueryHandlerRegister"; import { StandardQueryService } from "./query/model/StandardQueryService"; import { ISystemWindow } from "./window"; import { SystemWindow } from "./window/model/SystemWindow"; let initialized: boolean = false; export const setupCoreServices = () => { if (initialized) { return; } createSingletonServiceFactory( ISystemWindow, () => new SystemWindow(window) ); createSingletonService(ILoggerFactory, StandardLoggerFactory); createSingletonService(IIndexPool, IndexPool); createSingletonService(IGuid, GuidImpl); createSingletonService(IEventService, StandardEventService); createSingletonService(ICommandService, CommandService); createSingletonService(IQueryService, StandardQueryService); createSingletonService(IEventHandlerRegister, StandardEventHandlerRegister); createSingletonService(ICommandHandlerRegister, CommandHandlerRegister); createSingletonService(IQueryHandlerRegister, StandardQueryHandlerRegister); setDefaultResourceBundle(); initialized = true; };
// used in place of assert.Equal(t, want, actual) to avoid failures due to // scheduler.lastAdvanced timestamp inequalities. func checkSameScheduler(t *testing.T, want *scheduler, actual *scheduler) { assert.Equal(t, want.initHeight, actual.initHeight) assert.Equal(t, want.height, actual.height) assert.Equal(t, want.peers, actual.peers) assert.Equal(t, want.blockStates, actual.blockStates) assert.Equal(t, want.pendingBlocks, actual.pendingBlocks) assert.Equal(t, want.pendingTime, actual.pendingTime) assert.Equal(t, want.blockStates, actual.blockStates) assert.Equal(t, want.receivedBlocks, actual.receivedBlocks) assert.Equal(t, want.blockStates, actual.blockStates) }
// NewHandler creates an sdk.Handler for all bitcoin type messages func NewHandler(k types.BTCKeeper, v types.Voter, signer types.Signer, n types.Nexus, snapshotter types.Snapshotter) sdk.Handler { server := keeper.NewMsgServerImpl(k, signer, n, v, snapshotter) h := func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { ctx = ctx.WithEventManager(sdk.NewEventManager()) switch msg := msg.(type) { case *types.LinkRequest: res, err := server.Link(sdk.WrapSDKContext(ctx), msg) result, err := sdk.WrapServiceResult(ctx, res, err) if err == nil { result.Log = fmt.Sprintf("successfully linked deposit %s to recipient %s", res.DepositAddr, msg.RecipientAddr) } return result, err case *types.ConfirmOutpointRequest: res, err := server.ConfirmOutpoint(sdk.WrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) case *types.VoteConfirmOutpointRequest: res, err := server.VoteConfirmOutpoint(sdk.WrapSDKContext(ctx), msg) if err == nil { k.Logger(ctx).Debug(res.Status) } return sdk.WrapServiceResult(ctx, res, err) case *types.CreatePendingTransfersTxRequest: res, err := server.CreatePendingTransfersTx(sdk.WrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) case *types.CreateMasterTxRequest: res, err := server.CreateMasterTx(sdk.WrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) case *types.CreateRescueTxRequest: res, err := server.CreateRescueTx(sdk.WrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) case *types.SignTxRequest: res, err := server.SignTx(sdk.WrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) case *types.SubmitExternalSignatureRequest: res, err := server.SubmitExternalSignature(sdk.WrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) default: return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, fmt.Sprintf("unrecognized %s message type: %T", types.ModuleName, msg)) } } return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { res, err := h(ctx, msg) if err != nil { k.Logger(ctx).Debug(err.Error()) return nil, sdkerrors.Wrap(types.ErrBitcoin, err.Error()) } return res, nil } }
package com.general.service; import com.general.dto.ErrorDTO; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class ApplicationServiceImpl implements ApplicationService { //postApplication public ErrorDTO submitTopicApplication(String json){ return null; } //putApplication public ErrorDTO reviewApplication(String json,String applicationToken){ return null; } }
<reponame>johnhenry/std export default (path: string, append: boolean = false) => (data: string) => Deno.writeTextFileSync(path, data, { append });
/** * R905 [Element] Connect Specification */ public void connect_spec(Token id) { FortranTree id_Node = new FortranTree(0, "NULL"); FortranTree connect_spec_Node = new FortranTree(905, "ConnSpec"); if (id != null) id_Node = new FortranTree("ConnID", getCToken(id)); connect_spec_Node.addChild(id_Node); assert !stack.isEmpty(); assert isExpression(stack.peek().rule()); connect_spec_Node.addChild(stack.pop()); stack.push(connect_spec_Node); }
/** * Batch delete dictionary data * * @param ids the data to be deleted * @return result */ @Override public int deleteDictDataByIds(String ids) { int row = dictDataMapper.deleteDictDataByIds(Convert.toStrArray(ids)); if (row > 0) { DictUtils.clearDictCache(); } return row; }
<filename>receiver.go<gh_stars>1-10 package opinionatedevents import "fmt" type OnMessageHandler func(msg *Message) error type Receiver struct { onMessage map[string]OnMessageHandler } func (r *Receiver) Receive(data []byte) error { msg, err := ParseMessage(data) if err != nil { return err } if onMessageHandler, ok := r.onMessage[msg.name]; ok { return onMessageHandler(msg) } return nil } func (r *Receiver) On(name string, onMessage OnMessageHandler) error { if _, ok := r.onMessage[name]; ok { return fmt.Errorf("only one handler per message type is allowed") } r.onMessage[name] = onMessage return nil } func NewReceiver() (*Receiver, error) { receiver := &Receiver{ onMessage: map[string]OnMessageHandler{}, } return receiver, nil }
def categoriesCountPlot(self): for folder in self.classes: path = os.path.join(self.dataset_dir ,self.data_dir, folder) count = len(os.listdir(path)) self.class_counts[folder] = count print("Counts per each category") for key in self.class_counts.keys(): print(f"Category {key}: {self.class_counts[key]}") min_class = min(self.class_counts.values()) max_class = max(self.class_counts.values()) total_images = sum(self.class_counts.values()) if max_class - min_class >= 0.5 * total_images: create_countplot = input("Class imbalance present. Do you want to continue? (y/n): ") if create_countplot.upper() != "Y": return plt.bar(self.class_counts.keys(), self.class_counts.values()) plt.title('Countplot of categories') plt.xlabel('Class') plt.ylabel('Number of images') plt.savefig(os.path.join(self.results_path, "categoriesCountPlot.png")) try: doc = Document() doc.add_heading('Categories Countplot') doc.add_picture(os.path.join(self.results_path, "categoriesCountPlot.png")) doc.save(os.path.join(self.results_path, "categories_countplot.docx")) except Exception as e: print(f"Unable to create categories countplot document due to {e}") os.remove(os.path.join(self.results_path, "categoriesCountPlot.png"))
/******************************************************************************* * tests/sort_parallel_mergesort_test.cpp * * String sorting test program * * Part of tlx - http://panthema.net/tlx * * Copyright (C) 2014-2018 <NAME> <<EMAIL>> * * All rights reserved. Published under the Boost Software License, Version 1.0 ******************************************************************************/ #include <functional> #include <iostream> #include <random> #include <vector> #include <tlx/die.hpp> #include <tlx/logger.hpp> #include <tlx/sort/parallel_mergesort.hpp> struct Something { int a, b; explicit Something(int x = 0) : a(x), b(x * x) { } bool operator < (const Something& other) const { return a < other.a; } friend std::ostream& operator << (std::ostream& os, const Something& s) { return os << '(' << s.a << ',' << s.b << ')'; } }; template <bool Stable> void test_size(unsigned int size, tlx::MultiwayMergeSplittingAlgorithm mwmsa) { // std::cout << "testing parallel_mergesort with " << size << " items.\n"; std::vector<Something> v(size); std::less<Something> cmp; std::mt19937 randgen(123456); std::uniform_int_distribution<unsigned int> distr; for (unsigned int i = 0; i < size; ++i) v[i] = Something(distr(randgen)); if (Stable) { tlx::stable_parallel_mergesort( v.begin(), v.end(), cmp, /* num_threads */ 8, mwmsa); } else { tlx::parallel_mergesort( v.begin(), v.end(), cmp, /* num_threads */ 8, mwmsa); } die_unless(std::is_sorted(v.cbegin(), v.cend(), cmp)); } int main() { // run multiway mergesort tests for 0..256 sequences for (unsigned int i = 0; i < 256; ++i) { test_size<false>(i, tlx::MWMSA_SAMPLING); test_size<true>(i, tlx::MWMSA_SAMPLING); test_size<false>(i, tlx::MWMSA_EXACT); test_size<true>(i, tlx::MWMSA_EXACT); } // run multiway mergesort tests for 0..256 sequences for (unsigned int i = 256; i <= 16 * 1024 * 1024; i = 2 * i - i / 2) { test_size<false>(i, tlx::MWMSA_SAMPLING); test_size<true>(i, tlx::MWMSA_SAMPLING); test_size<false>(i, tlx::MWMSA_EXACT); test_size<true>(i, tlx::MWMSA_EXACT); } return 0; } /******************************************************************************/
Collins Need to Know? Kama Sutra Dr J Rogiere Contents Cover Title Page Introduction Getting in the Mood Kama Sutra Positions Tantra and You Tantra and the Single Person Pleasure Enhancers Sharing Kama Sutra Sex Safer Sex Glossary of terms Need to Know More? Searchable Terms _Copyright_ _About the Publisher_ Kama Sutra 'If all science is founded more or less on a stratus of facts there can be no harm in making known to mankind generally certain matters intimately connected with their private, domestic and social life. Alas! complete ignorance of them has unfortunately wrecked many a man and many woman...' Preface to the original Burton translation of the Kama Sutra, 1883 Why learn about the _Kama Sutra_? **'... while a little knowledge of a subject generally ignored by the masses would have enabled numbers of people to have understood many things which they believed to be quite incomprehensible, or which where not thought worthy of their consideration.'** Preface to the original Burton translation of the Kama Sutra, 1883 Recently there's been an upsurge of interest in books, videos and courses describing the _Kama Sutra_ and also tantric sex practices. So, what is it that these very ancient ideas have to offer us in the 21st century? One answer may be that while our Western society inherited religious traditions in which the body and even sensuality were as seen as potentially shameful, the East celebrated these things. The good news for people wanting to see their sexual lives in a new way is that, through the Eastern traditions of tantra and the _Kama Sutra_ , for the first time in a few millennia, sexuality is being seen in a positive, even spiritual, way. Sex is really coming out of the 'naughty' closet. Most of us would like to have an interesting and emotionally satisfying sex life. The fact is a lot of us don't. Surrounded by images of sex and sexuality in advertising, on TV and in film, many people find that sex is not the wonderful, exciting part of life that magazines, novels and the media suggest it ought to be. We may wonder why this is, or maybe we just put it to the back of our minds and get on with our day-to-day lives. However, if the sales of guides and handbooks to sex and sexual pleasure are anything to judge by, today's men and women want to change things for the better and this book will give you a great place to start. The origin of the _Kama Sutra_ **The Kama Sutra reached the West through the work of 19th century British explorer and diplomat, Sir Richard Burton.** He had spent many years in India where he was shown ancient Indian erotic texts. He subsequently had these texts translated from the Sanskrit in which they were written and distributed them privately through the London Anthropological Society. Today, thanks to Sir Richard Burton and adventurers like him, anyone can access and enjoy texts like the _Kama Sutra_ and benefit from the experience and wisdom of the East. Is it really a sex guide? **So what is the** _**Kama Sutra**_ **?** _**Kama Sutra**_ **translates as 'rules of pleasure' and it's one of the earliest surviving examples of a lifestyle manual and sex guide. It is thought to have been written between the second and fourth centuries AD by the Hindu sage, Mallanaga Vatsyayana who drew on much earlier Kama Shastras or 'Rules of Love', some of them almost a thousand years old in his own time.** The book was intended as much more than just a sex guide as we understand it today – it was a guide to a whole way of life. Contrary to what most people imagine, the _Kama Sutra_ is not simply about exotic sexual positions but gives guidance on how a wealthy, middle-class man should live his life in the most general sense. **'Man ... should practise Dharma, Artha and Kama at different times and in such a manner that they may harmonise together and not clash in any way.... Dharma is obedience to the command of the Shastras or Holy Writ of the Hindus... Artha is the acquisition of arts, land, gold, cattle, wealth, equipages and friends... Kama is the enjoyment of appropriate objects by the five senses of hearing feeling, seeing, tasting and smelling, assisted by the mind together with the soul.'** The text has seven parts: general observations, how to make amorous advances, finding a wife, the duties and privileges of a wife, how to behave with other men's wives, information on consorting with courtesans and eunuchs, occult spells and rituals and a section on herbs and potions to promote libido and virility. The book covers everything the wealthy Hindu man might have needed to know about conducting his personal relationships nearly two millennia ago, but Vatsyayana makes it plain that Kama – the pursuit of sensual pleasure – comes after Artha and Dharma and that it is the harmonious balance of these three that results in a 'good life'. There are two main differences between the original _Kama Sutra_ and modern texts. First, Vatsyayana's book was never meant as a manual for everyone; his readers were wealthy, urban men to whom he offered guidance on the social norms and sexual customs of the patriarchal North Indian society in which they lived. Secondly, as with the much later love and sex manuals the _Ananga Ranga_ and the _Perfumed Garden_ , the _Kama Sutra_ described women and men as unequal partners socially and therefore sexually, something no modern writer of sex books could possibly do. But what Vatsyayana does do, which in western terms puts him nearly two millennia ahead of his time, is to place great emphasis on the equality of sexual pleasure between men and women, and the man's responsibility and duty to ensure that the woman's pleasure is as great as his own. Vatsyayana also advises women to study the _Kama Sutra_ , albeit privately, in order to learn how to present themselves, how to please their partner and even how to subject a man to their will. He clearly had a great respect and affection for high-class courtesans – **'... a Ganika ... (is) always respected by the king and praised by learned men and her favour being sought for by all, she becomes an object of universal regard.'** The _Kama Sutra_ and spirituality **The** _**Kama Sutra**_ **doesn't really address the spiritual aspects of sex between men and women – in fact it might be more accurate to describe the** _**Kama Sutra**_ **as the 'game of love', rather than the 'rules', as much of the advice given by Vatsyayana is about turning sexual relations into an elaborate social artifice in which wealth and security are significant factors – not so different from today!** Many modern readers would consider much of the original text boring or even incomprehensible; so why is it still so popular? The reason, quite simply, is the number and variety of sexual positions that Vatsyayana describes so eloquently for his readers. So, we've found the social and erotic aspects of the ancient Hindu tradition, where do we look for the spiritual aspects of sexuality? Tantra and sacred sexuality When he wrote the _Kama Sutra_ , Vatsyayana was aware of much older Sanskrit writings that dealt with the same subjects. Unlike his book, which focused on the social and interpersonal aspects of love and sex, Sanskrit tantric texts examined the spiritual nature of sex. Tantra offered practices designed to use the natural energy of the physical body to raise the kundalini (spiritual energy), allowing a deep union between sexual partners and between the individual and the 'infinite'. In the West, the body and spirit have been seen as separate and even contradictory for at least 1500 years. Hinduism, on the other hand, historically saw body and spirit as inseparable, which made sex an important part of spiritual life, a means of expressing our God-nature. Tantra particularly offers a way of satisfying both our desire for an ecstatic, long-lasting and joyful sex life and our spiritual side. In an increasingly sophisticated and technology-driven world, sex remains one of the few free, natural pleasures left us. More than that, sex is just about the only way in which we can express every single aspect of our human nature: animal, emotional and spiritual. Tantra offers a key to opening these possibilities. One simple way of describing tantric sex is that it's the absolute opposite of a quick fix. With practice, tantra can help you to turn orgasm into a whole body experience, creating a holistic union of mind, body and spirit through a combination of breathing techniques, simple meditations and delayed orgasm. Aims of _Need to Know Kama Sutra_ **What this book aims to do is bring together the sophisticated sensuality of the** _**Kama Sutra**_ **with some of the profound, spiritual practices of tantra, to offer a new way of looking at sex and love, at your partner or partners and ultimately, at yourself. Despite occasionally strange and exotic suggestions, what you will find in this book is actually something universal, something common to every one of us, a birthright of physical and spiritual power, which we each have within us and which, with practice, we can rediscover.** **I hope that you will find something personally useful in this book, whether that's fun and exotic new positions from the Kama Sutra, or the more profound lessons of Tantra. Whatever you search for, may all your efforts bring pleasure!** Dr Jean Rogiere WATCH OUT **Starting Out** **If you're in a relationship and become interested in the** _**Kama Sutra**_ **or in tantra, mention the subject to your partner gently. Be aware that what you find an exciting or novel prospect could seem threatening or weird to someone else. He or she may take your new interest as evidence that you aren't into 'normal' sex, or maybe are bored with them, or even that they aren't good enough in bed. Your partner may think it's bizarre or a turn-off to discuss sex-based spirituality, or imagine that sex that requires effort or practice is less natural or spontaneous than your usual lovemaking. If these things do happen, listen to your partner's concerns, perhaps show her or him this book or some of thesuggested books and let them see what it is you found so interesting and exciting so they can perhaps share that feeling with you.** Getting in the Mood Contrary to what popular mythology would have us believe, we are not born great lovers. We all learn lots of different things at school or college, but nothing we discover there teaches us about how to behave in a loving relationship and there is definitely nothing on the school curriculum about the art of sensual loving! Getting in the mood **Many of us grow up feeling confused or ignorant about how to really please a partner and, more importantly, how we ourselves would like to experience pleasure.** Most people over 50 lived through the sexual revolution of the 1960s, which radically changed the way sex was seen in our society. But the feelings of guilt, shame and insecurity, which many people still feel today as a result of their beliefs or upbringing, did not disappear. Vatsyayana's readers were not restricted by an unhappy and contradictory relation between body and soul; properly conducted sexual relations with appropriate partners were actually seen as spiritually elevating, a way of balancing Artha and Dharma, while promoting social harmony. In Vatsyayana's time a person's choice of partner, even a non-marriage partner, would have been socially engineered. Today most of us choose our own partners and this means that getting to know someone and feeling comfortable with them is particularly important if we are looking for a happy and relaxed emotional and physical relationship. So, whether you have just met a new person and want to impress, or you want to entertain your husband, wife or long-time lover, getting into the right mood is a key part of lovemaking, for everyone. Sex on the brain Many of us spend quite a lot of time thinking idly about sex, fantasizing about real or imagined experiences, remembering past encounters. One of the things this book will ask you to do, if you want to change your sex life from mundane or even quite good, to something ecstatic and life enhancing, is to start thinking about sex in a completely different way. One of the many things the _Kama Sutra_ and tantric practice focus on is the ritual nature of lovemaking. But what does ritual mean? Simply put, it means thinking about sex as a 'ceremony', a ceremony that is conducted with the intention of pleasuring and honouring your partner and yourself. Ritual can lead you away from a simple physical act and take what you do together into the realm of the divine. If this sounds bizarre or unlikely, remember that the tantric practices described later in this book have been studied throughout the Hindu world for millennia but have only been available here in the West for a relatively short time; hardly surprising then if we feel a bit dubious of such extravagant claims. Dramatically improving your experience of sex and love starts by learning to think about lovemaking in terms of 'ritual' or 'ceremony', rather than as a 'quickie', or even something just done purely for physical pleasure. As you become more comfortable with the idea of ceremony, you will begin to experience the unique 'specialness' of your partner and yourself. This in turn can bring you closer to your partner in all aspects of your life, not just in the bedroom. MUST KNOW **Something most people know, but few of us really pay attention to, is that the biggest and most important sex organ is the brain. Pleasure begins and ends in the head.** MUST KNOW **Having a good sexual relationship is about much, much more than what you do with your body, it's a whole attitude of mind, a new way of looking at your partner, yourself and the world around you. It's this attitude which can keep partners deeply in love and sexually attracted to each other throughout their lives.** Making time **'Going to Gardens or Picnics: In the forenoon, men, having dressed themselves, should to gardens on horseback, accompanied by public women and followed by servants. And having done there all the duties of the day, and passed the time in various agreeable diversions... they should return home in the afternoon in the same manner bringing with them bunches of flowers etc.'** MUST KNOW **Relaxation is key to truly satisfying sex and it's no good worrying about who's going to be walking in on you, or being in a sumptuous location and thinking about what's happening at home.** The society described in the _Kama Sutra_ is one of high culture in which pleasure, relaxation and the pursuit of sensuality were considered acceptable and worthy. Today we live in a world full of stress and pressures that would have been completely alien to readers of the original _Kama Sutra_. Finding the time to relax and try anything new seems to get more difficult as our lives get busier, and, for many people, making the time and space to really enjoy lovemaking is no easy thing. Part of ritual is setting aside time for what you want to do – the opposite of snatching a few minutes between TV and sleep. Location, location So, you're planning a spectacular sex ceremony – an hour, a night, a long weekend. Where will it be? Some people feel more relaxed in their own homes; others find the unknown space of a hotel or rented apartment, where friends and family won't phone or drop in, more conducive to relaxation. Perhaps it needs some serious planning if you have children or other responsibilities. Whatever you do, make sure this is what both of you want and feel good about. Food and drink **'When the girl accepts the embrace, the man should put a tambula or screw of betel nut and betel leaves in her mouth... At the time of giving this tambula he should kiss her mouth softly and gracefully without making any sound.'** One of the many social etiquettes mentioned in the _Kama Sutra_ is the role of food and drink in sensual enjoyment. Today, too, we often prepare for lovemaking by eating and drinking. How many of us have met a partner in a restaurant or a bar and eaten a three course meal complete with large quantities of alcohol before going home and falling into bed bloated and tired? A full stomach is not conducive to sexual pleasure and we all know the old adage about alcohol increasing the desire and reducing the ability. Our bodies respond best when they don't have to multi-task. Digesting a heavy meal takes a great deal of energy, energy that might be better spent giving and experiencing pleasure. The _Kama Sutra_ and tantric texts advise that eating and drinking – like sex itself – should bring a sense of satisfaction without excess. (Moderation was clearly considered a virtue in ancient India!) With this advice in mind, consider incorporating food and drink into setting the mood for lovemaking. In some exclusive Japanese restaurants it's possible to eat sushi (raw fish and rice) that has been carefully positioned on the body of a naked woman. While this may not be at all your thing, it does hint at the possibilities of combining the human body with food. Do you know what your partner's favourite foods are? Perhaps it's chocolate, or strawberries, toffee or peaches, Parma ham or oysters. Many foods are considered to be 'aphrodisiacs', passion stimulators, and sharing any food while naked can be very stimulating. Try feeding each other delicious titbits – run juicy strawberries over each other's skin; pass small pieces of dark, dark chocolate with your lips. Having these things to hand requires a little planning, so try making it all part of preparing the ritual. Setting the scene **'... balmy with rich perfumes, [the room] should contain a bed, soft, agreeable to the sight, covered with a clean white cloth, low in the middle part, having garlands and bunches of flowers upon it... and two pillows, one at the top and another at the bottom. [A stool] on which should be placed the fragrant ointments for the night, pots containing collyrium and other fragrant substances, things used to perfume the mouth, and the bark of the common citron tree.'** MUST KNOW **Fragrance is a very important part of sensuality, and while we know that** _**we** _**should smell good, it's easy to forget our surroundings.** The space in which you make love with your partner is extremely important. The rumpled bed covered with last week's linen or with dirty laundry strewn around the room is not the best way to create a sensual and seductive atmosphere. One of the simplest ways to enhance the celebration of your sexuality is to create a special area in which it can be expressed. Try making the space in which you make love a beautiful place. The _Kama Sutra_ advises decorating the room with many flowers and surrounding the bed with fragrant substances, which could be a bunch of lilies, simple sticks of incense or pure essential oils warmed in a burner. Whether you are making love in the bedroom, in front of an open fire, or in your garden, make the space a special one in ways that suit you and your partner. The _Kama Sutra_ suggests that the bed should be covered with a clean, white cloth and strewn with petals and flowers. Such simple but effective things immediately change the nature of your lovemaking from the mundane into something special. Lighting is also very important for mood and candles are a perennial favourite, casting a soft, romantic glow that can make every man and woman feel attractive. These days it's easily possible to combine fragrance with subtle lighting in a scented candle. You and your partner can decide in advance what kind of lighting you would like in your special place. Some people feel more comfortable making love in darkness, which can greatly enhance tactile experience – though the visual side of things will be missing. Try experimenting with very, very low light, gradually increasing it so that a single candle lights the room. If you can only relax in total blackness, give some thought to why this is: how you feel about being looked at, or looking at your partner. Much of the information and advice offered by tantric texts and the _Kama Sutra_ focus on honouring each partner's individuality and totality – not an easy thing to do in the dark. One advantage that we have over Hindu ancients is the ready availability of pleasing music. Sound is very important for relaxation and relief of stress and can greatly enhance any lovemaking experience. Bearing in mind that you are creating what is in effect a sacred space for you and your lover, choose your music with care. A thumping rock beat may be fun at times, but on this occasion you are trying to create a mood of mellow, seductive relaxation. Find something unusual, something you wouldn't usually listen to, which has no history or meaning for either of you. Whether it's classical, jazz or chill-out music, remember its purpose is to enhance the celebration of your physical union, not to get your feet tapping! Preparing the body **'Men should bathe daily, anointing the body with oil every other day, apply a lathering substance to the body every three days, get the head and face shaved every four days, and the other parts of the body every five to ten days. All these things should be done without fail, and the sweat of the armpit should also be removed.'** Cleanliness was clearly an extremely important part, not only of lovemaking, but also of everyday life in ancient India, very much as it is today. The idea of washing every day and frequently removing all body hair is something many modern people would find extreme. Just like their Roman contemporaries, the lovers of Vatsyayana's time realised that hygiene is extremely important in sexual intimacy. Preparing your body for lovemaking is something that you can do alone or with your partner. The advantage of sharing bathing and grooming is that it can enhance closeness and helps to build a sense of anticipation and excitement as you touch each other's bodies intimately, but not sexually. The _Kama Sutra_ 's readers would have visited professional barbers for a massage and shave, but shaving your man's face, or washing your woman's hair are things easily done at home. Shaving doesn't only have to be for men of course, many women shave their legs and underarms and you can offer to do this for them. Some men and women also shave or wax their genital area, and this can be a particularly sensual experience to share. Carry the sense of ceremony into the bathroom by placing scented candles around the room, make sure the room is clean and fresh and, if you have the space, put in fresh cut flowers to enhance the specialness of the moment. Little ritual for washing your lover's feet **Foot washing can have a particular significance as it introduces a sense of tenderness and service. You can make a ritual out of washing feet, simply by preparing a bowl of warm, scented water, with flower petals floating in it.** • Massage each toe gently as you wash, moving up the foot to the ankles. • When the washing is finished, gently towel dry each foot, then hold a foot in each of your own hands and kiss them saying aloud: **'These feet embrace the earth. These feet carry you through the world. These feet are beautiful. I honour them'**. What to wear **A glimpse of Indian erotic temple sculptures shows us men and women making love looking their very best. Even the much later Mughal erotic paintings of the Islamic period, show men clean-shaven or with moustaches neatly combed and oiled, their bodies smooth.** Both women and men look almost weighed down with ropes of pearls and rubies and often the men are shown still wearing their jewelled turbans! Precious stones sparkle from all parts of their gracefully depicted bodies and in this way an Indian couple of more modern times was shown as directly related to the much earlier erotic art of Vatsyayana's time. We all like to dress up when we go out, and to be seen at our best. Most of us consider sex as something you take your clothes off for, or we buy underwear designed to arouse. Uncover new aspects of your sensuality by deciding what you'll wear before and even during your lovemaking; try bringing a new excitement and variety into your sexual life by dressing to focus on your sensuality, rather than directly on sex. Instead of a tiny black thong, women can try wrapping themselves in some diaphanous fabric that completely covers them from the hips down, yet at the same time is revealingly see-through and beautiful to the touch. Instead of loose boxer shorts, men can try out a silky sarong that will encourage their partner to feel and see the outline of their body in a different way. Massage **'On the second and third nights... he should feel the whole of her body with his hands, and kiss her all over; he should also place his hands upon her thighs and champu them, and if he succeeds in this he should then champu the joints of her thighs.'** NEED TO KNOW **You can buy ready-made massage oils very easily, or you can make your own with just a few drops of pure essential oils – traditional favourites since before Vatsyayana's time, are sandalwood, jasmine, lemon and frankincense. A good base oil like avocado or grape seed is easy to find.** Today in many parts of the Indian subcontinent and Burma, massage is referred to as 'champu' and it is from this word that the modern English word 'shampoo' comes, the kneading, rubbing motions of massage and washing being the same. There are many different kinds of massage available today and many of these come from Asia, which has an ancient tradition of massage for healing, well being and beauty. Like washing and grooming, massage is something that can be learnt quite easily and practised at home. Simply touching your partner in a loving way will be relaxing for both of you. If you are a naturally gifted masseur/masseuse great, but even those of us who are hesitant, or unconfident can give pleasure simply by being willing to try. As with all aspects of ritual, preparation and thought are key to success – there's nothing less relaxing than being in your beautifully prepared space and realising you forgot the massage oil! Decide with your partner in advance what kind of scents you both enjoy, something too strong or too sweet may actually be off putting. If you feel less than confident about giving your partner a massage, you'll be glad to know that tantric massage can involve using things other than the hands, for example: strips of sheer fabric or fur, large soft feathers (try a peacock feather for real exotic indulgence), soft leaves or grass; if you have long hair, trail it along your partner's body. You can try these things before applying oil for a massage, or as something to be enjoyed on their own. If you don't want to attempt the whole body, why not just concentrate on the hands. Many people, particularly those of us who use a computer, carry a great deal of stress and tension in the hands and forearms and a simple massage of the palms and wrists can be great for easing stress and relaxing. There are many ways to begin the massage, depending on how skilled you are or how long you want to spend: • your partner can lie on his/her back or front, whichever is most comfortable • pour a few drops of oil into the palms of your hands and rub them together to warm and energise • if you aren't a confident masseur, try gentle upward and circular sweeps of your hands starting at the soles of the feet, moving to the ankles, knees, thighs and upwards to the face and top of the head, not forgetting the arms and hands • for a simple back and shoulder massage, start by gently placing the flat of your hands on the lower back and between the shoulder blades and gently rocking your partner's whole body – this relaxes the muscles around the spine and can feel very sensual • use your thumbs in small circular motions up each side of the spine from the buttocks to the top of the neck • use the palms of your hands and flat of your fingers in sweeping motions away from the spine and over the shoulder blades and shoulders and down the top of the arms • use your knuckles gently to loosen the muscular tension along the top of the shoulders • massaging the buttocks and tops of the thighs is a particularly sensual and erotic movement, try taking your hands very close to your partner's genitals without actually touching them • avoid direct, hard pressure on your female partner's breasts, instead massage around the breast and ribcage area quite firmly moving in towards the nipple with more and more gentle movements. MUST KNOW **There are some simple rules to remember when you are massaging someone:** • **always ask for feedback – check that you are not pressing too hard or even too softly** • **avoid direct pressure on the spine; take care if you have long or sharp fingernails that you don't scratch your partner accidentally** • **have the massage oil ready prepared in an attractive container; make sure it's not cold and avoid dropping it directly on to your partner's skin** • **remember to have comfortable towels for your partner to lie on and to cover them with if the parts of their body you aren't massaging begin to feel chilly** • **be together in your ceremonial space, remember to make it beautiful, comfortable, softly lit and warm – there's nothing less relaxing than being massaged while shivering** Scratching, biting and marking **'The places that are to be pressed with the nails are as follows: the armpit, the throat, the breasts, the lips, the jaghana (genitals) and thighs. But Suvarnanabha is of the opinion that when the impetuosity of passion is excessive, then the places need not be considered.'** WATCH OUT **Only attempt to mark your partner if he/she has previously agreed to be marked.** The _Kama Sutra_ discusses at length the importance of the nails and teeth in lovemaking, and describes the eight different kinds of marks that can be left by fingernails in a lover's flesh. It even gives detailed descriptions of different kinds of fingernails and how they should look in both men and women. They should be 'bright, well set, clean, entire, convex, soft, and glossy in appearance.' Hindu men clearly wore their fingernails long and the kinds of marks left on the lover's body had names like 'tiger's claw', 'peacocks foot', and 'leaf of a blue lotus'. Marking is a way of remembering your lover when you are not together. Marks, particularly on the private parts, are 'for the remembrance and increase of love'. Gentle scratching movements during massage can be very stimulating without being startling. Try running your fingernails softly all the way down your lover's back and thighs between massage strokes. All the places that can be kissed, are also the places that can be bitten, except the upper lip, the interior of the mouth, and the eyes. The _Kama Sutra_ describes in detail eight different kinds of bite used on different parts of the body. Biting is encouraged as an expression of passion and women in particular are advised to express their enjoyment through biting their lover. These days, most people are pretty circumspect about marking and being marked, particularly in places where it will be visible, such as the neck. Decide with your partner how you feel about this kind of expression and whether it suits you both. Kissing **'The following are the places for kissing: the forehead, the eyes, the cheeks, the throat, the bosom, the breasts, the lips, and the interior of the mouth.'** The kiss has great significance in our culture, and many meanings. We kiss our grandparents, our children, our pets and our friends; we even kiss strangers on the cheek in restaurants. Kissing between lovers is one of the most intimate things two people can do and the _Kama Sutra_ recognises its importance by describing in detail how the lips and tongue can be used, not only to show desire, but also to express a range of thoughts and emotions. Any part of the body can be kissed or licked either as a prelude to lovemaking, or during intercourse itself. The _Kama Sutra_ defines these different types of kissing: • Kissing with the mouth and tongue • Kissing the face and body • Kissing the genitals Kissing with the mouth and tongue **One of the things you may remember from growing up is listening to friends commenting about kissing. 'He/she is a great/rubbish kisser.' To be able to kiss well is undoubtedly an art and one that can easily be learnt with a little practice and imagination. The mouth is one of the most sensitive parts of the human body.** Vatsyayana recognised that a direct, straight on kiss is quite limited, and that to have full mouth and tongue contact the partners need to angle their head to the side. He also describes variations in pressure, and using the fingers during kissing. • The Passive Kiss: It can be very erotic to be kissed, without returning the kiss. Try running your tongue over your lovers parted lips, slowly inserting your tongue between their lips and teeth, massaging the gums. It can be quite hard for them not to respond, but this can be good experience for the tantric practices described later in this book. • The Sucking Kiss: Circle your tongue gently on your partner's lower lip then run your tongue over it and hold it between your teeth. Switch to the upper lip and do the same thing before circling both lips inside and out. Like the Passive Kiss, this is something you can't do simultaneously, but simply receiving an erotic kiss can be quite a novelty. • The Bent Kiss: when the heads of two lovers are bent at an angle to each other, and when so bent, kissing takes place, it is called a 'bent kiss'. This is the best position for mutual kissing and deep tongue penetration. Kissing in this position can be soft and gentle, or aggressive and even violently passionate. Try to feel your partner's likes and dislikes as you kiss; everyone is different and enjoys different things; it is a lover's duty to learn and respond to their partner's desires, not merely explore their own. MUST KNOW **There is a direct link between the lips and the genitals and for some women it's possible to have an orgasm simply from kissing.** Kissing the face and body **'Kissing is of four kinds: moderate, contracted, pressed and soft, according to the different parts of the body which are kissed. For different kinds of kisses are appropriate for different parts of the body.'** MUST KNOW **The backs of the knees, inside of the elbow, back of the neck, the throat, the feet, the hands, the spine, the breasts and abdomen are all highly charged places.** The skin is the largest organ in the body and most of it is an erogenous zone. Who can resist being kissed from the soles of the feet to the top of the head? Kissing and licking your partner's body is not only pleasurable in itself, but also stimulates the senses of touch, taste, smell and sight, which in turn heighten desire. Your partner's natural body scent, mixed with whatever oils or perfumes you've used for bathing or massage, can be highly erotic. Don't overdo it. A few drops of essential oil are enough – you want a mouthful of your partner, not a mouthful of sandalwood flavour. Kissing and licking can readily be combined with scratching and biting if that's something you both enjoy. Find out if your partner is ticklish and if they actually enjoy or are turned off by that sensation. Kissing the skin lightly can often be more stimulating and exciting than hard, heavy kisses. Try a mixture of light brushes with your lips and light scratching with the nails; if you have the co-ordination lick in one area and scratch in another – for example kiss your partner's breasts while drawing your nails down her back, or lick your partner's buttocks while drawing your nails down his flanks. Your tongue can be used hard and pointed, or soft and relaxed – try both ways in different parts of the body for different effects. Imagine you are massaging your partner with your tongue; move in circles, in broad sweeping motions, tickle and stab. In the same way as kisses on the mouth can be mutual or not, kissing of the body can be simultaneous – the pleasure of giving and receiving all at once. Kissing the genitals **Genital kissing, or oral sex, is one of the few areas in which the** _**Kama Sutra**_ **isn't particularly helpful to the modern, heterosexual lover. In the** _**Kama Sutra**_ **and in tantric texts, the female genitals are known as the yoni and the male as the lingam, but we'll be referring to them as the vagina and the penis throughout this book (except when quoting the** _**Kama Sutra**_ **).** In Vatsyayana's time, Auparishtaka, or fellatio, as we call it today, was performed mostly by eunuchs – castrated men – disguised either as women or posing as masseurs. It was also performed by male servants with their masters, by lower caste men between themselves or by women of the very lowest caste. Cunnilingus gets only a short paragraph! Vatsyayana makes it plain in his writing, that kissing of the vagina is not something he thinks much of, but for the sake of being methodical he informs his reader that women of the harem indulge in 'the acts of the mouth on the vaginas of one another and that 'some men do this with women'. In a single sentence he informs his reader that cunnilingus should be performed in the same way as kissing the lips of the mouth. Making the most of genital kissing One of the most arousing ways to begin oral sex for both women and men is to start licking, kissing or playful biting away from the genital area. Massage your partner's thighs or buttocks lightly, drawing your fingernails down their sides or abdomen, moving towards the genitals only slowly. MUST KNOW **Our culture has turned the genitals of men and women into words of abuse and jokes, but beneath that we all retain a sense of the power and awe of our own reproduction.** In tantric sex the vagina and penis are regarded as sacred representations of the goddess Shakti and the god Shiva. Honouring your partner's sex is an important part of tantric loving and for modern men and women it can help us to move away from the Western ideas of our bodies, and our genitals in particular, as unclean or 'private'. A simple ritual to honour your partner's sex Kneel in front of your partner as they recline in a large, comfortable seat – it's important that they can relax comfortably with their legs wide but still be able to look at you directly. In the Hindu tradition, representations of the penis and the vagina were offered gifts of flowers, or incense. Think of a simple gift you can offer your partner's sex, perhaps a strip of soft silk to wrap around his penis, or small flowers to weave into the hair around the vulva. Choose something that reminds you of your partner's sex, their shape, or smell or feel. Bow to your partner as you offer your gift. Try doing this ritual when your partner is not aroused, it is not the erect penis or the aroused vagina that you are honouring, but the genitals themselves – the organs of creation which represent female and male, the beginning of all life, the earth and heavens, Shiva and Shakti. As you kneel remember that this is where you came from, where your ancestors came from and where your descendants will come from. When you gently touch your partner, you are looking not to arouse them but to examine them closely. • look from their genitals up into their eyes – acknowledge them as your partner, as masculine/feminine, the opposite half of yourself • if your partner is female, open her outer lips gently with your fingers, look closely at how she is constructed, at how the labia are formed, and the clitoris in its folds of flesh, the opening of the vagina and the urethra • if your partner is male, hold his testicles in your hand very gently. Perhaps you will feel them move and contract as you do so. Feel the softness of the skin of his penis • describe to your partner what you like best about what you see • to finish the ritual, touch first your forehead, then your lips to your partner's sex and say aloud: **'I honour this part of you, I honour the pleasure it gives me.'** Kissing the vagina **'For the sake of such things courtesans abandon men possessed of good qualities, liberal and clever, and become attached to low persons, such as slaves and elephant drivers.'** Was Vatsyayana himself one of those liberal and clever men who lost his mistress to a mahout (elephant driver)? We shall never know. Recent advances in anatomy show the female genitals to be larger and far more complex than was previously thought. A woman's sex organs are not only the visible vagina and clitoris, or even the internal G-spot, but an extensive, wishbone-shaped network of nerves linking everything from the pubic mound to the perineum and anus. Kissing and licking anywhere in the genital area will be arousing for most women, but few women will be able to orgasm simply through general touching or kissing. As the _Kama Sutra_ advises, always be lead by your partner's inclinations; you can ask as you touch, or you can simply judge by the reactions you're getting. The area between the vagina and the anus, the perineum, is also very sensitive with many nerve-endings and licking and blowing air on this area can be very arousing. Some women enjoy rimming – having the area around the anus licked and stimulated – and if this is something you both enjoy it can be pleasurable for both partners. Inserting one or more fingers into the vagina or the anus as you are licking and sucking your partner can really add to their pleasure and help to stimulate orgasm. MUST KNOW **Direct stimulation of the clitoris with the tongue and lips is very pleasurable for many women and will lead easily to orgasm. For other women this stimulation can be too intense.** Kissing the penis **'When [the eunuch] after kissing it, he touches it with his tongue everywhere, and passes the tongue over the end of it, it is called 'rubbing'. When in the same way, he puts the half of it into his mouth and forcibly kisses and sucks it, this is called sucking a mango fruit.'** MUST KNOW **If you and your partner are comfortable with licking or touching the anal area, try gently inserting a finger into his anus and reach up one and a half inches toward the base of the penis. This stimulates the prostate internally, which can give your partner a mind-blowing orgasm.** Vatsyayana advises using the fingers, the lips, the tongue and even the teeth to stimulate the penis. Some men enjoy vigorous sucking and even biting of their penis and testicles, while others are extremely sensitive and prefer gentle movements of the mouth on their penis. Drawing your tongue up from the base of the penis to circle its head before softly licking and sucking the urethral 'mouth' can be very exciting. If you are able to take most of your partner's penis into your mouth, try rubbing the smooth head against the roof of your mouth and alternately sucking and licking. Encircling the base with your thumb and first finger not only promotes and maintains erection, but allows you to control how far and hard your partner moves in your mouth. Many men enjoy their testicles being kissed, sucked and licked; remember that everyone is different and ask if you are unsure whether what you are doing is pleasurable for your partner. The perineum and anal area is particularly sensitive in men, as this is the location of the prostate gland – the male G-spot. The congress of a crow **'When a man and woman lie down in an inverted order, that is, the head of one toward the feet of the other and carry on this congress it is called the Congress of a Crow.'** WATCH OUT **It is possible to achieve very deep throat penetration if the woman is the reclining partner, but remember that not all women find this comfortable.** Why mutual oral sex has this title is hard to guess. This is what we usually call the '69' position, which can be done lying on the side, or with one partner lying on their back and the other kneeling above them. Some couples find this form of oral sex very exciting and it can be an interesting mutual alternative to intercourse. Lying side by side, is the most relaxing position for this congress, particularly if the man rests his head on the woman's thigh as he licks and caresses her vulva, and the woman does the same with the man's penis and testicles. Both partners can try raising their top knee and putting their foot flat on the ground until you find a position that suits you both. The alternative – one partner lying on their back and the other kneeling above them – is a more dynamic position, with the kneeling partner having more freedom of movement to thrust and wriggle. want to know more? Take it to the next level... * * * Go to... Food as aphrodisiac Safe oral sex * * * Have a go... Have a day at a spa get yourself in shape for your lovelife * * * Other sources Publications The Devil Drives: A Life of Sir Richard Burton, Fawn Brodie, Eland Books, 2003 Erotic Passions: A Guide to Orgasmic Massage, Sensual Bathing, Oral Pleasuring and Female Ejaculation and the G-Spot, Deborah Sundahl, Hunter House (CA), 2003 Kama Sutra Positions An ingenious person should multiply the kinds of congress after the fashion of the different kinds of beasts and of birds. For these different kinds of congress, performed according to the usage of each country, and the liking of each individual, generates love, friendship and respect in the hearts of women. Mallanaga Vatsyayana _Kama Sutra_ positions **Much of the** _**Kama Sutra**_ **is detailed advice on how to behave in what was considered a civilised and courtly manner in ancient India. To the modern reader much of the book can seem irrelevant or even offensive; there are chapters on visiting prostitutes and courtesans, advice on how to seduce very young girls and other men's wives and how to use go-betweens to gain illicit access to a harem.** Mallanaga Vatsyayana was an elderly religious devotee when he wrote the _Kama Sutra_ and his writing style suggests a man very experienced in the ways of the world, but 1600 years or more later, how Vatsyayana really thought, and how much of what he wrote was designed to please as well as instruct his audience we shall never know. In fact there's quite a lot of contradiction in the _Kama Sutra_ : women are clearly socially subservient, and yet, at the same time, they are vastly important and objects of reverence. Using the _Kama Sutra_ positions The focus throughout the _Kama Sutra_ is on heterosexual relationships and heterosexual penetration, but the book also discusses sexual relations between men and men and between women and women, and also refers to men and women who practice anal sex. These positions can be applicable to all relationships and whatever kind of intercourse you as a couple prefer to have. NEED TO KNOW **Remember to use the variety of postures the** _**Kama Sutra**_ **suggests to create a loving flow of movement, energy and affection between yourself and your partner. If you're tired or uncomfortable in one position, use your knowledge of alternatives to simply flow into another, more relaxed one.** The sixty-four The _Kama Sutra_ and other erotic texts often refer to 'the 64'. Many people think this must refer to the number of positions described, but this is not true. There are far fewer than 64 positions in the _Kama Sutra_ , and ancient writers seem to disagree on what 'the 64' really is. Vatsyayana lists the 64 'arts' which men and women should possess to be attractive to others. These include: tattooing, dyeing the teeth, singing, adorning idols with flowers, chemistry and mineralogy, fixing stained glass into the floor (!) and knowledge of languages and dialects. Nothing very sexy there! Just like modern authors, Vatsyayana relied very heavily on earlier writers and acknowledges them frequently in his text, often to disagree with their ideas. The positions described in this section also draw on texts other than the _Kama Sutra_ , including the _Ananga Ranga_ , which was written about one thousand years after the _Kama Sutra_. Using this chapter Because not all of us have the contortionist skills of an ancient Hindu dancing girl the various postures have been 'graded' for ease or difficulty. Level 1 is very relaxed and requires little strain or effort by either partner. Level 2 involves some effort but should not be a strain. Level 3 is pretty acrobatic, particularly for the female partner and probably only advisable for people who are very flexible or who study yoga. By the same token, sometimes the illustration varies slightly from what is described in the text. The models did their very best to follow the instructions to the letter, but because some of the positions require an extreme level of flexibility, they, very rarely, had to do a close approximation. Finally, you'll find that each position is usually given two names, one English and one Indian. The Indian name is the original name given to the position in the _Kama Sutra_. The Hare vs the Elephant **In the** _**Kama Sutra**_ **, Vatsyayana describes the different physical attributes of men and women, categorizing them by size and sexual temperament: for example men are Hares, Bulls or Horses, women are Deer, Mares or Elephants and the level of desire in both men and women is Small, Middling or Intense. He does not say that any particular size or shape is desirable or unfortunate, but suggests practical ways in which couples can come together with the greatest comfort and pleasure.** Many of the positions are designed to accommodate the different needs of his readers by enhancing sensation, pleasure and loving communication between partners who may be of different shapes and sizes. but it does point out that intercourse between people of equal size, sexual appetite and physical strength may be more pleasurable or at least more straightforward for both partners, than sex between people of widely differing qualities. A union between a Deer woman and a Horse man, he refers to as the 'highest union', whereas congress between a Hare man and an Elephant woman would be considered the 'lowest union' – not an aesthetic opinion, but a practical reference to the couple's chances of pleasure. So the reason that these positions, or asanas, came into being is, partly at least, to address these issues of physical difference and improve everyone's chance of maximum pleasure. Many of the quite acrobatic positions were designed to either widen or tighten the woman's vagina, which in turn related to the size of her partner's penis. Remembering that the _Kama Sutra_ was a book intended for male readers this is hardly surprising. However, Vatsyayana makes it plain throughout his work that pleasing women should be the man's highest goal and he seems to have a very clear-sighted grasp of the nature of male/female relationships. Working the positions **'Of all the lovers of a girl he only is her true husband who possesses the qualities that are liked by her, and such a husband only enjoys real superiority over her, because he is the husband of love.'** Sex is one of the very few human activities that crosses all boundaries, all eras, and all social norms. It's easy to imagine, looking at the illustrations in this book, or indeed in any illustrated book about sex, that the postures themselves are what matter. This is not so. Simply getting into a position and having intercourse in that position is not likely to add very much to your overall pleasure in lovemaking, beyond a little novelty. Vatsyayana was well aware of this and so also wrote about how to engage feeling in one's partner, and how to stimulate sexual excitement. Without affection, lovemaking is simply sex, which is the antithesis not only of the _Kama Sutra_ , but also of all the tantric practices that informed much of Vatsyayana's own writings. Like a conversation, a fine meal, or a wonderful piece of music, lovemaking should flow from one mood and one position to another, smoothly and effortlessly. For some of us this comes naturally, for most of us it does not and to achieve this harmonious physical and emotional merging takes effort and practice. This is where we need to remember that the brain is the most important sex organ we possess. In these days of fast-paced, goal-orientated living, sex, like many other aspects of our lives, has become something designed for quick, often superficial, self-gratification. When we do think of pleasing our partner(s) it's easy to let this become fast-paced and goal-orientated too: how many orgasms can a woman have? how long can a man maintain an erection? These kinds of questions are often what concerns a couple more than how they can best express tenderness, affection and respect for each other in lovemaking. Ready for love **Now you've both read** **Getting Into The Mood** **! You've eaten and drunk moderately, you have bathed yourself and your lover in scented water, scattered rose petals across your bed, or the rug in front of the fire.** You know that lovemaking does not have to take place in the bedroom, that everywhere is love's playground, even, on occasion, the most public of places. But creating a special place is all-important, and one of the great pleasures and benefits of making love, as the _Kama Sutra_ suggests, is creating the ritual – a ceremony of worship of your partner, their body and their sex. Now you are ready for the most intimate sharing with your partner, let the _Kama Sutra_ be your guide... The postures Missionary position DIFFICULTY LEVEL 1 Shiva position Probably the best known of all sex positions, Vatsyayana refers to this as 'the natural position'. For many people it is just that, allowing deep and shallow penetration and comfortable contact of the upper body, arms and hands. Men can support their weight with their hands, on their elbows or, if tired, can rest on their partner's breasts. This is usually a very comfortable posture for women, relaxed but still allowing free movement of the arms and legs. It's possible to touch and kiss most of your lover's body in this position, stimulating nipples, clitoris or testicles, if your aim is orgasm. If you are using this position for tantric purposes avoid over-stimulation of erogenous zones, which could lead to an uncontrollable urge to orgasm. Woman on top DIFFICULTY LEVEL 1 Shakti position This is a very relaxing posture for men and is perhaps the best position if you wish to control ejaculation. You can hold hands and look into each other's eyes. Many women enjoy this position because it gives them greater control of movement, speed and depth of penetration. Women can try angling their partner's penis so that the G-spot is stimulated. In this position it is possible to rub the clitoris against the man's pubic bone, depending on how you fit together. You can stimulate your clitoris yourself or your partner can use his fingers to caress and stroke you there. MUST KNOW **This posture makes it easier for the man to concentrate on contracting his pubic muscles to prevent orgasm and to raise the energy from the genitals up the spine. It's also an excellent position for men who are older or less fit.** Milk and water DIFFICULTY LEVEL 1 **'When a man and a woman are very much in love with each other and ... embrace each other as if they were entering into each other's bodies... then it is called an embrace like the 'mixture of milk and water.'** MUST KNOW **Some women find it more comfortable to place a small cushion under their buttocks in this posture – this also puts less pressure on the man's thighs.** The only possible movements here are gentle rocking back and forth or contractions of the pubic muscle. Contracting the pubic muscle is a very subtle form of motion physically but a very powerful one energetically; as you contract your genital/anal area you are stimulating the lowest chakra where kundalini energy is stored. This is considered the very best posture for tantric lovemaking because it gives maximum physical contact with very limited opportunity for movement. As well as being physically very close, this position allows optimum emotional contact – your eyes and lips are very near and the arms naturally entwine with each other and with the neck and shoulders. Tantric masters suggest that this position should be used only after a long session of mouth and genital kissing and intercourse to stimulate the chakras, so that the energy is already moving. Half reclining position DIFFICULTY LEVEL 1 Also known as the Kneeling Missionary position, this is both a relaxing and stimulating position for both partners. The man doesn't have to support his weight with his arms and has a much more controlled and precise use of thrust. From this position the woman can move smoothly into a series of varied postures in which she can exert different pressures on her partner's penis by opening her legs widely, wrapping them round her partners waist, or drawing her knees to her own chest and placing her feet on her partners shoulders. As a tantric position it is less completely intimate than the 'Milk and Water' posture, but it does allow for thrusting and stimulation to happen between you before you move into the specific breathing/connecting phase of lovemaking and is a great position for admiring each other's beauty and decoration. Remember to make yourselves very comfortable before you start so that the energy between you can flow freely. Side-by-side position – spoons DIFFICULTY LEVEL 1 This is a very comfortable posture and one which you can try either facing each other or facing in the same direction. The advantage of this 'spoon' position is that there is fuller and more comfortable penetration, particularly for women whose vagina is closer to their anus than to their clitoris. Eye contact and kissing is awkward if not impossible in this position but it does allow full body contact, twining legs and feet and stroking and caressing, particularly of the woman's breasts, abdomen, genitals, throat and face. From this position it's easy to turn into a rear-entry position. Side-by-side position – facing DIFFICULTY LEVEL 1 Face-to-face this can be a relaxing chill out posture, one that you can try when winding down from something more energetic. For many couples this position offers only quite shallow penetration, which can be helpful if you're using the posture for tantric sex. Eye and mouth contact are easy and comfortable, you are meeting your partner's skin along the whole front length of your bodies and can caress everywhere from hair to hips. If you want deeper or more mobile penetration, women can lift the top leg and drop it over their partner's top thigh and use this bent leg to draw their partner closer. Men, if you want greater thrusting power, hook your top elbow under your partners bent knee. Beloved of love DIFFICULTY LEVEL 1 manmathpriya **'As your partner lies on her back, kneel between her parted legs, raise them, and hook her feet over your thighs, catch hold of her breasts, and enjoy her.'** In this position kneel comfortably between your partner's raised knees while she lifts her legs and drops them over your thighs. During penetration, she can use her feet, ankles and calves to grip you as you move. Women can try gently beating their partner's buttocks with their heels; this is quite stimulating for the man so use cautiously if you are practising avoidance of ejaculation. This is a comfortable position for both partners as it allows the man to be relaxed in his movements and the woman to touch and caress herself and her partner. The monkey DIFFICULTY LEVEL 2 markata From the 'beloved of love' position it's possible to move smoothly into this new position. In the monkey position women hold their own ankles or heels opening the legs as widely as possible; the legs can be straight or bent. This gives her complete control over how and where she moves her legs and with a little practice it should be possible to open very widely indeed. If you find penetration uncomfortable or difficult, this might be a useful position to try as it opens the vagina. Your partner can gently scratch your legs and feet, caress your breasts, the back and front of your thighs, your buttocks, perineum and entire genital area and can gently slap your abdomen or hips. The love god's flag DIFFICULTY LEVEL 2 madandhvaja Here the reclining partner relinquishes hold of her ankles and allows the man to control the position of her legs. Holding your partner's ankles in both hands, raise her legs and hold them as widely as is comfortable for both of you. Try moving from 'the monkey' into this position without interruption. The love god's flag 2 DIFFICULTY LEVEL 2 madandhvaja 2 If you want to vary sensation, the kneeling partner can bring the woman's legs together in front of him, wrapping his arms around her knees so that her vagina holds his penis extra tightly. In this posture the man can kiss and lick his partner's toes and feet, caress and stroke her legs and thighs. Keep eye contact and express your tenderness for each other in looks and words. From this position you can easily move into the next. Raised leg variations **'When the female raises both of her thighs straight up, it is called the rising position.'** From the 'rising position' or the 'love god's flag' where the man holds the woman's ankles wide, try moving into the 'yawning' position. WATCH OUT **In the 'yawning' position as you rest your ankles on his shoulders your vagina will be quite tightly pressed together and in this posture your partner may need to thrust carefully.** Yawning position DIFFICULTY LEVEL 2 When she raises both of her legs and places them on her lover's shoulders, it is called the 'yawning' position. The 'yawning', the 'rising' and 'the love god's flag' positions are all very closely linked, so by moving smoothly from one to another both partners will gain different sensations as the positions of the vagina and penis change. If a woman holds her legs straight up, knees together, this will close the vagina. As the man holds his partner's ankles and opens her legs, her vagina will also open, providing changing sensations for both. Altering pressure on the penis may be exciting for the male partner, and for the woman the 'yawning' position offers a sense of exposure and vulnerability, which some woman may find very exciting. Pressed position, half-pressed, splitting the bamboo, the fixing of the nail DIFFICULTY LEVEL 2 These variations on the raised leg postures require the reclining partner to be quite strong and flexible. In each case, the man controls his partner's feet and legs and thus the sensations around his penis. The 'pressed position' is illustrated below. **'When only one of her legs is stretched out, it is called the "half-pressed position". ...When the woman places one of her legs on her lover's shoulder and stretches out the other and continues to do so alternately, it is called "the splitting of bamboo". ...When one of her legs is placed on his head and the other stretched out, it is called "the fixing of a nail". This is learnt by practice only.'** The goddess of love's delight DIFFICULTY LEVEL 3 ratisundara From any of the raised leg positions the woman can bring the soles of her feet together and drop them towards her chest so that the legs form an 'O' shape. Her partner can then hold her feet together leaving her hands free to caress and stimulate breasts or clitoris. Sky foot DIFFICULTY LEVEL 3 vyomapada From the rising position, if you're very flexible, or practise yoga, the reclining partner may be able to drop her legs backward towards her head. This offers their partner a uniquely exposed view of the vagina and anus. There's the possibility of varying your lovemaking from intercourse to oral sex in this position and back to penetration again if that's something that suits you both. Sky foot 2 DIFFICULTY LEVEL 3 + vyomapada 2 Women who can place their knees beside their ears with comfort can try this novel position which will allow your partner to enter you in reverse. The man kneels or stands beside his partner's shoulders facing her raised buttocks, which are the highest point of her body, and penetrates her; he can hold her buttocks to steady the position if necessary. For both partners this is a very novel position; the woman looking directly up between her partners legs is able to see his penis entering her in a way that is rarely possible without a mirror. For the man this unique posture allows him a close view of his partners vagina and he can gently slap and scratch her buttocks and the backs of her thighs or stimulate her perineum and anus as he moves inside her. This position doesn't offer much direct stimulation for the clitoris or G-spot but is an exciting change! Throat high DIFFICULTY LEVEL 3 uthkanta From 'Sky Foot 2' this may feel like an easy relaxed posture as the woman places her feet beside her throat! All of these 'rising' positions are made easier by adding a cushion or two in the small of the back or under the buttocks. While the woman is in this position, the kneeling partner can caress her buttocks, the backs of her thighs, the anal and perineum area and her abdomen. This is a very exposed position and one which some women may enjoy very much for that reason. MUST KNOW **If you have any lower back or hip problems, try Difficulty Level 3 positions only with great caution.** The tiger's blow DIFFICULTY LEVEL 2 varahagata In this position the woman lies on her left side with one leg stretched out; the right leg is raised straight up into the air until the ankle rests on the man's shoulder. The kneeling partner should position himself either side of the woman's lower leg and hold her raised leg against his chest, grasping the ankle or knee. In this posture he can stimulate his partner's clitoris and pubic mound, which is an extremely sensitive area, full of nerve endings that link directly to the clitoris and G-spot. Men can massage and stroke the raised thigh and calf and kiss and suck the raised foot. The jewel case samputa Later medieval texts on lovemaking refer to 'the jewel case' postures. They were specifically intended to help men and women of different physical sizes achieve more successful and enjoyable lovemaking. Any positions in which the legs are held together and the vagina thereby shortened and tightened will be a 'jewel case' position and these are also possible standing and with rear entry. WATCH OUT **In this position the woman should move with care so as not to cause discomfort to her partner.** The jewel case 1 DIFFICULTY LEVEL 1 samputa 1 Starting from the basic missionary position, the woman closes her legs tightly and cross her ankles while her partner opens his legs widely. In this position the vagina is tightly closed on the penis, gripping it shallowly but firmly hence the name 'Jewel Case'. In any 'jewel case' position the woman will be able to hold her partner in what Vatsyayana refers to as 'the mare's grip'. The jewel case 2 DIFFICULTY LEVEL 1 samputa 2 In a variation on 'jewel case 1', the woman lies on her side facing her partner. Again her legs are tightly closed, her thighs gripping the man's penis. Using her pubic and thigh muscles the woman can squeeze and massage the man's penis. With practice a couple can both experience orgasm simply from this movement as the muscular contractions which 'milk' the penis will also arouse the woman, particularly if the base of her partner's penis/public bone is pressed against her clitoris. Varying lovemaking **Just because you start having intercourse doesn't mean that you have to continue without a break until the end. Just as positions can be varied, so can what you are doing together. Some of the positions mentioned above don't offer much direct clitoral stimulation for a woman, so why not change from intercourse to oral sex?** This has the advantage of relaxing and changing the pace for both partners, slowing things down for the man, which may be particularly useful if you are intending to end your lovemaking with a tantric session and don't wish to ejaculate, and it can greatly enhance pleasure for the woman. You may find your partner tastes and smells differently after intercourse; savour the difference, tell them how good they taste as you worship their sex. Different strokes Just as varying the width and depth of the vagina can give pleasure to both partners, Vatsyayana also notes that a man can please his partner by different motions of his penis. **'When the lingam is held in the hand and turned all around in the yoni it is called "churning".** **When the yoni is lowered and the upper part of it is struck with the lingam it is called "piercing".** **When the yoni is pressed by the lingam for a long time it is called "pressing".** **When the lingam is removed to some distance from the yoni and then forcibly strikes, it is called "giving a blow".** **When only one part of the yoni is rubbed with the lingam it is called the "blow of a boar".** **When the lingam is in the yoni and is moved up and down frequently and without being taken out it is called "the sporting of a sparrow". This takes place at the end of congress.'** Mutual seated positions **At the beginning of this chapter, we looked at the basic seated position, milk and water, which is appropriate to tantric practice. Below are a series of alternative positions offering a variety of movement for both male and female partners.** The swastika (good luck symbol) DIFFICULTY LEVEL 1 svastika In this position you sit facing each other on the floor or bed, and wrap one leg around your partner's waist in a mirror image of each other. The other leg can be either stretched out or bent at the knee as is most comfortable. In Indian culture, a swastika is a holy symbol of good fortune, which was reversed and used in a negative way in the 20th century. The tortoise DIFFICULTY LEVEL 3 In the Tortoise position both partners sit upright and the woman places her feet on her partner's chest while both hold hands or wrists and lean backwards. The ancient text describes the man also placing his feet on his partner's chest! Tension in your arms is what should keep you in an upright position, though movement will be restricted to rocking. This is for the seriously athletic only, or you can try it leaning against a wall, or headboard for support. It should be fun if nothing else! The lotus DIFFICULTY LEVEL 3 In this position one or both partners may find it helpful to have some support at their back as the woman sits in her partner's lap and wraps both her feet and hands behind the man's neck. According to Vatsyayana, many of the women being made love to would have been quite young, fit and very flexible, which may explain the complex nature of some of the erotic postures. The Lotus is a position for the seriously athletic, but you should get pleasure from trying it out! Turned away DIFFICULTY LEVEL 1 paravartita In this position the man sits on a chair or stool while his partner sits in his lap, facing away. There are a number of possible ways of enjoying this versatile posture: the man can try sitting with his knees together or open while his partner closes hers or opens her legs wide, or both the man's and woman's legs can be closed In this position you have a full access to and can caress her entire body and her clitoris. This is a good position if you only want quick sex. This variation of the seated position can also be done on a stool or on a chair face-to-face. If you find sitting cross-legged or holding yourself upright for very long to be less than comfortable, there is no reason why you shouldn't use whatever furniture seems comfortable and appropriate to you. Rear-entry positions **'When a woman stands on her hands and feet like a quadruped, and her lover mounts her from behind, it is called the "Congress of a Cow". At this time everything that is ordinarily done on the bosom should be done on the back. In the same way can be carried on the Congress of a Dog, the Congress of a Goat, the Congress of a Deer, the forcible Mounting of an Ass, the Congress of a Cat, the Jump of a Tiger, the Pressing of an Elephant, the Rubbing of a Boar, and the Mounting of a Horse, and in all these cases the characteristics of the different animals should be manifested by acting like them.'** Two millennia ago in ancient India human beings were surrounded by a wide variety of wild and domestic animals, all of which had a much closer role in their day-to-day lives than animals do in our 21st century lives. Vatsyayana recommend to his readers that they copulate like animals, that they let go of their human nature and indulge, for a short time, and in moderation, that side of themselves that is not entirely human. Vatsyayana clearly knew that there are things humans can learn from animals. What do you have to lose? Take the _Kama Sutra_ 's advice and be an animal occasionally! MUST KNOW **Our nearest animal relatives, the bonobos ape has almost 100 per cent of human genes. These lively primates enjoy sex – oral, manual and penetrative, heterosexual, homosexual and lesbian, in couples and in groups, several times a day, and for no obvious reason and in every conceivable position, including hanging upside down in combinations humans could only fantasise about! They also look deeply into each other's eyes as they do it. These cheerful animals have been shown to resolve all social conflict through sex and consequently murder and serious violence are unknown in their society.** The deer DIFFICULTY LEVEL 1 hirana In this classic rear entry position eye contact is missing but the man has an excellent view of the sweep of his partner's back and parted buttocks and can watch as he enters her vagina. Men can try describing what they see, what their partner looks like in this position. This is often considered the most 'animal' of all positions and it's precisely this very animal quality that makes the posture so appealing to many men and women. It can be very gentle and quiet, as the man strokes and caresses his partner's clitoris, or leans forward and strokes her breasts. It can also be quite forceful and tempestuous as he grips her tightly or slaps her buttocks in time with his thrusts. In this position the woman can stimulate her clitoris or reach back and caress her partner's testicles. For deeper penetration, women can drop their upper body and support themselves on elbows and forearms instead of hands. MUST KNOW **This is a popular position for anal penetration, but remember that it can be very deep, so go carefully.** The deer 2 DIFFICULTY LEVEL 1 hirana samputa This is a useful position if the penis is not fully erect or the man needs extra stimulation. After penetration, the woman closes her legs tightly together while the man spreads his thighs widely. Try moving from standing to kneeling or vice versa without releasing the penis from the vagina. The milk cow DIFFICULTY LEVEL 1 dhenuka This position (not the most romantically named) is a slightly more strenuous variation on 'the deer'. In 'the milk cow' the woman has to support herself, either by putting her hands directly on the floor in front of her or alternatively resting them on her thighs, a stool or the edge of the bed. This makes deep penetration easy and as the man is standing, it gives him easy and forceful thrusting if that is what both partners desire. In this position the man can caress the woman's buttocks and thighs or reach round to stimulate her clitoris or breasts. The milk cow 2 DIFFICULTY LEVEL 1 dhenuka samputa This posture is identical to 'the milk cow' except that the woman crosses her ankles tightly together after penetration and the man has his legs apart. In this position the vagina is particularly tightly closed and penetration and pressure will be very full for the man. Women can use their vaginal and buttock muscles, rhythmically squeezing and relaxing as the man stands still and relaxes. You'll be amazed! The hanging serpent DIFFICULTY LEVEL 3 When snakes mate they twist and entwine together for long periods of time. In this more acrobatic standing position the woman needs to be able to bend over fully. The woman can drop her head between her open knees and reaching back, grasp her partner's ankles. Try making hissing sounds as you make love in this posture. Men can caress their partner's back with undulations suggestive of a snake. WATCH OUT **Men will need to help their partner stay balanced while they move by holding her hips or waist firmly.** Piercing tiger DIFFICULTY LEVEL 1 Wild cats mate lying down with the males biting the neck of the female so she can't get away and can't turn and attack him! In this position the backs of both partners are arched and you are both half-upright on your elbows. Women can use this as either an open or a 'jewel case' position. Unable to see their partner easily, women will be able to let their imagination run free. Try growling and biting like mating tigers, entwine your legs together for extra sensation and closeness. Cobra lock DIFFICULTY LEVEL 1 nagabandha You can move easily from 'Piercing Tiger' into Cobra Lock or vice versa. Here you are both lying on your side facing in the same direction. The woman lifts her topmost leg and drops its back over the man's raised thigh or waist. Although in this position you will be unable to look at each other this is still a very warm and loving embrace with close contact of the entire body. The man is able to hold the woman very firmly and holding breasts or abdomen the legs to can be twisted together as in the 'Piercing Tiger'. Thunderbolt DIFFICULTY LEVEL 3+ kulisha In this position the woman lies face down on a bed or soft cover, while the kneeling or standing man holds her legs high backwards by the knees or thighs. This is an exceptionally acrobatic position that can be moved into from other rear entry positions. For the woman the most comfortable way is probably to lie on the elbows and forearms, but the position requires the woman to have a very flexible lower back and the man to possess strong arms. The cat DIFFICULTY LEVEL 3+ mallaka In an even more gymnastic combination, the woman lies on her abdomen and grasps and lifts her own ankles backwards while opening her knees widely. Your partner will half-lie, half-kneel between your open legs, supporting his weight on his hands. This is actually a well-known yoga position which experts use to strengthen the lower back and internal organs. If you are very flexible in the pelvic area you may feel able to raise your thighs and hips off the ground balancing the weight towards your navel. This is also a very acrobatic position and one which should only be attempted for fun. Standing positions Many of the magnificent and beautiful carvings that can be found in the temples across India are of lovers standing, arms and legs entwined, as they kiss and caress each other's voluptuous bodies. Below are a series of postures that move from the relatively simple and straightforward to the strenuous and acrobatic. Standing positions can be more of a novelty than a truly intimate experience as men, unless they are very strong indeed, usually experience physical stress if they're supporting their partner's body weight; and for women it is unlikely that these positions will provide deep stimulation for either the clitoris or the G-spot. However, standing postures can be great if you want a quickie, if you are in the great outdoors, or if you want to try something different from the usual lying or seated positions. Even if you have no intention of attempting the more complex positions described here, you can practise moving gracefully between the easier ones until you are able to achieve a smooth, highly erotic, dance. The twining of a creeper DIFFICULTY LEVEL 1 jataveshtikata **'When a woman, clinging to a man as a creeper twines round a tree, bends his head down to hers with the desire of kissing him and slightly makes the sound sut sut, embraces him, and looks lovingly towards him, it is called an embrace like the "Twining of a Creeper".'** Try this position with your back to the wall, you can alternate who is leaning and who is standing and find what works best for you. The usual height difference between male and female partners makes a difference in standing postures. Women try twining one leg around your partner, wrap your arms around his neck, or hold hands outstretched, level with your shoulders. Climbing a tree DIFFICULTY LEVEL 2 vrikshadhirudhaka It's quite straightforward for the woman to stand on one of her partner's feet while placing her other foot on his opposite thigh, as high as is comfortable for both. The woman should try passing one arm behind her partner's back and holding his shoulders with the other. The man should lean against the wall and hold his partner quite firmly around the waist as the woman has neither foot on the ground. 'Suspended' positions The knee elbow DIFFICULTY LEVEL 3 janukurpara Here we move to the most difficult of the standing postures, which require considerable strength in the man and confidence in the woman. From the climbing tree position, the man needs to hook one elbow under his partner's raised knee and bracing himself against the wall, does the same with the other knee and lifts, clasping her around the waist. If this posture is too strenuous, simply swing around until the woman's back is against the wall taking some of her weight. Alternatively you can start in this position. MUST KNOW **This is not a good position for a Hare man and Elephant woman, but could work well between theDeer and the Horse.** Suspended DIFFICULTY LEVEL 3+ avalambitaka **'When a man supports himself against the wall, and the woman, sitting on his hands joined together and held underneath her throws her arms around his neck and putting her ankles alongside his waist, moves herself by her feet, which were touching the wall against which the man is leaning, it is called the "Suspended Congress".'** In this final standing position, the man is simply holding his partner while she moves on his penis, using her feet to push against the wall behind him. As an alternative to this strenuous posture, try and find something overhead, a bar or tree branch, which the suspended partner can hold on to. This can be a very unique position for a man as the woman holds her own weight and controls the movement of intercourse. Man lying down positions **'When a woman sees that her lover is fatigued by constant congress, without having his desire satisfied, she should, with his permission, lay him down upon his back, and give him assistance by acting his part.'** The tongs DIFFICULTY LEVEL – DEPENDS ON EFFORT samdamsha This position offers whatever penetration the woman best enjoys. By positioning herself, she can move on her partner's penis in a way that deeply stimulates her G-spot. The woman has control of her own movements and much of her partner's mobility too. You can stimulate your clitoris by rubbing against your partner's pubic bone, which will also move his penis very deeply inside you, giving him pleasure at the same time. You can move gently and slowly or hard and fast. Keep eye contact and hold hands, kiss and stroke each other. Combination positions **Here are some positions of differing levels of difficulty that you can combine, offering new sensations for both you and your partner. Use any combination that pleases you both and leave out any that seem too strenuous.** The top DIFFICULTY LEVEL 2 **'When, while engaged in Congress, she turns round like a wheel, it is called the 'top'. This is learnt by practice only.'** Starting from the Tongs position, the woman (the man may also attempt this manoeuvre) rotates herself on her partner's penis without releasing it from her vagina, therefore performing 'the top', 'the swan', 'the seat of sport' and 'the bee' in one exercise. This might require a bit of practice. The reclining man can assist his partner by raising his knees as appropriate and holding both her hands for support. Now move into the next position... The swan DIFFICULTY LEVEL 1 hansa-lila Swing your left leg across your partner's body, taking time to rub and tickle his chest or face with your toes. Lowering your left leg so that you are sitting 'side-saddle', you move into the Swan. Try moving in this position before continuing with the Top motion. You won't have much mobility, but your partner will be able to thrust upward in a limited way. The seat of sport DIFFICULTY LEVEL 1 lilasana Now twist your body so that you can swing your right leg right round until you are kneeling astride your partner facing his feet. This is the Seat of Sport and it offers new and exciting possibilities for both of you. Lean forward and grasp your partner's ankles, offering him an exciting view of your hips and buttocks. Caress and scratch his inner thighs and gently stroke and stimulate his testicles. Your partner can caress and gently slap your buttocks. By raising his knees and placing his feet flat on the ground, the man develops the position further and, still facing his feet, you can lean forward, supporting yourself on his raised thighs, ready to move into the bee position. The bee DIFFICULTY LEVEL 3 bhramara The Bee takes a bit of strength as well as practice: place your feet flat beside your partner's hips and, holding his knees for support, raise your body until you can swing left and right and circle in a figure of eight on his penis. From the Bee posture you can return to the final stages of the Top. As your partner lowers his knees you continue to move around his body until you return to the original 'Tongs' position. The foot yoke DIFFICULTY LEVEL 3 yugmapada **'If your lover, seated above you with her feet lotus-crossed and her body held erect and still, makes love to you, it is known as Yugmapada.'** Although there is very little movement in this position it is actually a complex and sophisticated pose that in one way represents the pinnacle of the _Kama Sutra_ and later teachings. To sit completely upright with feet crossed on your thighs is not easy even on a floor mat; to do it perched across your lover's hips requires a delicate sense of balance. The ancient texts describe the man as lying completely flat, legs together, arms outstretched at shoulder level in a position of vulnerability and abandon. All movement takes place within the woman's vagina, as she squeezes and stimulates her partner's penis. It is a position without caresses, which focuses almost entirely on what is happening between the partners' sex organs. If you are experienced at yogic positions, this might be a position you and your partner could enjoy for tantric lovemaking. want to know more? Take it to the next level... * * * Go to... Kissing the genitals – Sharing partners * * * Other sources Internet www.kamasutrafree.com Publications Ancient Sexual Positions, Kenneth Ray Stubbs,Jeremy P Tarcher, 2000 The Complete Illustrated Kama Sutra, Vaatsyaayana, Lance Dane (Ed) Inner Traditions International, 2003 Tantra and You According to Hindu mythology, the sexual and spiritual union of the god Shiva and the goddess Shakti gave birth to the universe. Shiva is the embodiment of pure consciousness and his partner, Shakti, pure energy. Together they represent all existence in an erotic act of love that is a creative and unifying force. What is tantra **Tantra is not just about sex, it is a complete way of life, a spiritual path which includes sex as part of what it is to be human. Tantra has been explored and practised by women and men for many thousands of years.** Tantric experts realised that lovemaking has a highly significant role in tantric practice because conscious lovemaking allows a couple to experience themselves and each other in a way that is both satisfyingly physical and also sacred. Conscious sex can harmonise the senses and allow both the male and female nature of each partner to be fully expressed in a loving way. Tantra teaches that lovemaking between a man and woman when experienced with awareness is the path to both sexual and spiritual ecstasy. MUST KNOW **In tantric lovemaking, which is intended to last considerably longer than ordinary lovemaking, comfort and relaxation are particularly important.** Learning tantra then In ancient India a student of tantra would have spent many years studying with a spiritual master learning how to experience and control the energy forces within their body, in much the same way that a serious practitioner of martial arts would study with a teacher today. This learning took great concentration and included yogic exercises such as breath control, and elaborate rituals to purify and control mind and body. These exercises were intended to awaken powerful psychic energies through which the skilled practitioner could enter into higher states of consciousness. When the student was considered ready, he or she was permitted to engage in tantric sex with a partner. Practitioners believed that through the sacred act of intercourse, they were merging the dual nature of their own sexuality – their internal masculine and feminine natures in an erotic union like that of Shakti and Shiva – and forming and realising the true ecstatic nature of the self. Learning tantra now It's possible to study tantra in the intense way described above today, though few of us would have the time, means or focus to do so. However, through quite simple exercises we can still achieve something of what the ancient masters experienced. It is also possible to study a different aspect of tantra quite easily, through studying kundalini yoga. Kundalini and the chakras Kundalini means 'awareness' and this particular form of yoga, also called tantric yoga, practises raising awareness through the seven energy centres, or chakras, of the body in order to experience the higher self and the divine, the same object as tantric sex. Kundalini – also called 'universal Shakti energy' – is believed to rest at the base of the spine in the first chakra, from where, through various exercises, it can be raised up the spine, through all the energy centres, to the crown chakra at the top of the head. The first chakra is linked to the sexual organs, so any sexual activity naturally stimulates the first chakra and its energy. In western thinking, the chakras correspond to various glands and systems of the body, for example the brow or sixth chakra represents the pituitary gland and the fifth, the throat chakra, the thyroid. What can tantra do for you and your lovelife **Tantric lovemaking happens when you learn to control and increase kundalini energy. Regulating the flow of energy is what enables women to experience whole-body orgasms and men to experience repeated ecstatic orgasm without ejaculation. However, the effects of tantra can be far more wide ranging than this, so if you'd like to increase your mental alertness, balance your hormones, reduce stress, improve your self-esteem and general well-being, then tantric sex and/or kundalini yoga could well be for you. Lovemaking that aims to raise energy from the genitals throughout the body will naturally stimulate the entire glandular system, promoting health and well being.** Many of us have glimpsed moments of transcendence in our lovemaking – moments when we felt 'united' with our partner more than just physically. Unfortunately very few of us have the skills or experience to enjoy or reproduce these moments at will, but through tantra we can learn to prolong the magical connection between partners of any sex or sexual preference. Tantra also has the additional benefit of allowing single people to experience ecstatic sex. Because the ultimate goal of tantra is union with the divine, it isn't always necessary to have a partner and the next chapter will look at techniques and experiences for enjoying ecstatic solo sex. Starting to learn tantra Feeling relaxed and good about ourselves is an intrinsic part of happy sexual relationships and especially of successful tantric practice. So take time to really 'be' with yourself, free of the worries of everyday life, even if that time is only fifteen or twenty minutes a day. It could be on the bus, or the train to work, in the bath or sitting in an armchair. Relax and think positive thoughts about yourself and your life. Even if things aren't easy for you, try to focus on the good. Write a list of all the non-sexual things you really enjoy about life and about yourself. It doesn't matter how silly the list may seem. Now make a list of all the sexual things that you enjoy and make you feel good – your partner's hair, your own penis, the scent of your clitoris, the warmth of your lover's skin. Using tantric ritual to enhance awareness of each other **Earlier in this book we looked at the importance of ritual and ceremony in bringing you and your partner closer together. Becoming comfortable with ritual can increase your sense of the sacred in your life. Having an awareness of this sacredness is what will allow you to step beyond your usual, everyday boundaries and experience your sexuality in a more intense way.** In chapter two we looked at some of the ways you can start to do that: creating a beautiful space, making a ritual of bathing, enjoying sensual massage, being aware of what you put into your body and its effects on your energy and libido. Now we can look at how you and your partner can begin to experience each other directly. A simple ritual to bring closeness • Remember to make yourself and your special space beautiful. Sit cross-legged opposite your partner on the floor, close enough that your knees are almost touching. (If sitting in this way is uncomfortable sit in upright chairs.) Just sit and look at each other without touching for several minutes. Look at each other's face, hair and body, clothing, jewellery and cosmetics (if you're wearing any). Think how like a god or goddess your partner looks, how beautiful she/he is to you • After a few minutes bring your gaze up to your partner's eyes but rather than trying to focus on both eyes, look directly into the left. Deliberately and consciously focus on your partner; feel their body heat merging with yours, their breath mingling with yours; notice how they breathe and slowly bring your breathing into harmony with theirs. When you are both breathing together, continue to look into each other's left eye and deepen your breath; feel the air going into the deepest part of your lungs, push your abdomen out slightly as you breathe in and pull it in slightly as you exhale. Make your in and out breath of equal length – this will prevent giddiness • After doing this for several minutes, bring your hands up level with your shoulders and put out both your palms to touch your partner's. There are minor chakras in the palms of your hands, and as you touch, imagine that this is the place where the current begins to flow through you, where the circuit is formed. You will probably feel an unusual amount of heat between your hands and your partner's; this is a tangible expression of your energy. It is possible to feel sexually aroused simply by doing these things; if you find this happening try, without pushing your arousal away, to continue focusing on your breathing and on the other person • After a few minutes in this position, bring your foreheads together in such a way that you can still look into each other's left eye, still breathing in harmony. (If this is physically uncomfortable find a more comfortable seating position before you start.) • To end the ritual, move gently away from each other and, still looking into each other's left eye, bring your own hands together in prayer position, thumbs touching your breastbone. Still in this posture, bow to your partner (without hitting your heads together!) while saying aloud: **Women – 'You are my Shiva'** Men – 'You are my Shakti' • In this way you bring the ten-minute ritual to a close by honouring the god and goddess in each other. MUST KNOW **Some people find this simple exercise surprisingly difficult. Remember that what you're trying to achieve is true intimacy, and that giggling or avoiding the other person's gaze is simply a way of avoiding that intimacy. Your energy is in tune with your thinking; if you allow yourself to be distracted, or if you're uncertain about what you're doing or why, your energies will be unable to flow freely through you and towards your partner.** Tantra exercises **It might take time to learn the exercises that follow, but if you want to love and please yourself and your partner more fully than you ever imagined possible, take the time and enjoy!** Breath control exercise Breath keeps us alive; it also connects us to our sexual self. It affects when and how we orgasm and how powerful that orgasm will be. The deeper and more fully we breathe, the more alive we are. Being aware of our breathing during lovemaking also stops us being distracted by trivial worries like how we look, or smell or feel to the touch. • Lie down in a warm and comfortable place, preferably not your bed, where you won't be disturbed • Close your eyes and become aware of every part of your body by 'feeling' your breath as it sends oxygen to every cell • Deepen your breathing, allowing your abdomen to rise as you breathe in and to hollow as you breathe fully out • Imagine that you hear the breathing of another person very near you, that your breath and that of the other person are exactly in sync • Continue to breathe deeply and visualize the other person blowing warm/cool air very gently over your entire body • Be aware of the least movement of the air, of the breath in your lungs. Notice how alive your skin and your hair feel. Remember how this felt the next time you are with a partner – the relaxation and the feel of your own breath entering and leaving your body. This will help you with the next exercise. Tantric lovemaking **Unlike the many wonderfully exotic positions of the** _**Kama Sutra**_ **, tantra uses just a few simple positions because the aim is to channel energy away from the genitals, rather than to simply enjoy the pleasurable feelings that sex gives.** Tantric lovemaking is something very special and, although hugely rewarding, can be quite demanding. Not everyone will want or need to experience sex in this intense way and certainly not on every occasion. Vatsyayana was almost certainly well-read in the tantric texts of his day, but the sexual positions and techniques he describes in the _Kama Sutra_ are not designed to raise spiritual consciousness; his writings focus on physical pleasure and social harmony. You could try out the many exotic positions of the _Kama Sutra_ without engaging with tantra at all, or you could use all or just a few of Vatsyayana's positions for tantric purposes. Tantra is about being aware of life, yourself and your partner in a new way. So, it's not what you do but how you do it that will bring about the shift from ordinary to super sex. One of the main differences between tantric sex and ordinary sex is that both partners aim to experience multiple, whole body orgasms without tipping over into ejaculation or completion. The reason for men to achieve multiple orgasms without ejaculation is not just to increase a partner's pleasure, or simply to allow you to make love for much longer. The purpose is to learn to experience the effect of orgasm as wave on wave of energy rising up the body rather than a single genital 'rush'. Women can naturally experience multiple orgasms, but the same holds true for men – avoiding the 'letting go' of orgasm can lead to much more holistic and powerful sensations throughout the body. Tantric breathing can help to activate and balance the energy points of the chakras; as these points open, the energy generated by sexual activity is allowed to rise up the spine to the seventh – crown – chakra at the top of the head. This is of course, not as easy as it sounds! Most importantly, men will need to rethink their current attitude to sex and their goals in lovemaking. Be particularly aware of the energy circuit you and your partner make. Rub your own hands together then hold one palm a few inches away from your partner's second chakra – two fingers width below the navel – and feel the movement of energy. You may experience this as heat, as vibration, or as a gentle spiralling motion. You can try this simple exercise on each of your partner's chakras and also on your own. This is a sample of the energy that you are going to increase between you during intercourse. Tantric positions Tantric positions have a fundamentally different purpose and are only important in as much as they allow energy to flow and control to be achieved. For this reason, tantric sex postures are basic and simple: • Shiva position ('missionary' position) • Shakti position (woman on top) • Milk and Water position (man and woman seated and facing) • Half-Reclining position (woman reclines, feet on the ground, man kneels between her thighs) • Side-by-Side position (couple facing and spoons) You are aiming to create a circuit, so touching palms, or feet and looking into each other's eyes as described in the Ritual to Bring Closeness, will help to do that. Find out what suits you best and try to perfect it. Look at these positions (described in detail at the beginning of the Positions chapter) and choose one or two that suit you and that you can remain in, perhaps for a long period of time, without effort or discomfort. Tantric practitioners suggest that even with experience it can take at least 30 to 60 minutes for the energies to balance and the waves of sensation to start flowing through you both. This is a practice that takes skill and effort, but once learnt can revolutionize your life. MUST KNOW **Because the key to tantric sex is sharing, the exercises and rituals described here need to be approached in an honest, whole-hearted and open-minded manner.** Improving your chances of controlling orgasm **Tightening and toning the muscles of the lower abdomen and genital area are important for men and women.** MUST KNOW **Because sexual satisfaction comes from inside us, not from having the 'right' mate, tantric practices begin with ourselves and our own, unique sexual being, the god or goddess within each of us.** The basic Kegel exercise – stopping the flow of urine in mid-stream until you can feel the muscles contract – is a good way to begin strengthening and controlling the muscles, which also play a part in orgasm. Men should also practise contracting their groin and anal muscles while erect. These exercises should be done until women can stop urine mid flow with ease and keep a slim, smooth object, held tightly in the vagina, and men can raise a small towel hanging on the end of their erect penis, simply by contracting the muscles. During lovemaking both partners should float on the edge of orgasm which will, with practice, be less and less centred on the genital area and felt more throughout the entire body as you learn to regulate your breathing and harness the energy from your lower chakras. For men, if you feel that orgasm is close, breathe more slowly and deeply and contract the muscle at the base of the penis – this is where the Kegel exercises come in useful! (For the karezza technique of pressing the perineum to prevent ejaculation). Consciously think of drawing the energy away from your genitals and up your spine. Your partner can help you by remaining still at this time, maintaining eye contact and breathing with you. If either of you feel the onrush of orgasm, breathe deeply in a measured and rhythmical way, allowing the abdomen to rise and sink. Relax all the muscles in your body from your feet to your head; you want to be able to experience the waves of pleasure without being drowned in them, or running away from them. With experience, it may become possible to tap into the energies of where you are – the Earth beneath you, or even the wider universe – which in turn feeds even more energy back into the circuit between you and your partner. Once you start thinking in these terms, it's hardly surprising that some people describe their experiences of tantric lovemaking as 'cosmic' or transcendental! Tantric lovemaking happens when you begin to learn to control and increase kundalini energy. Regulating the flow of energy is what enables women to experience whole-body orgasms and men to experience repeated ecstatic orgasm without ejaculation. However, the effects of tantra can be far more wide ranging than this, so if you'd like to increase your mental alertness, balance your hormones, reduce stress, improve your self-esteem and general well-being, then tantric sex and/or kundalini yoga could well be for you. Lovemaking that aims to raise energy from the genitals throughout the body will naturally stimulate the entire glandular system, promoting health and well being. Through tantra we can learn to prolong the magical connection between partners of any sex or sexual preference. Because the ultimate goal of tantra is union with the divine, it isn't always necessary to have a partner and the next chapter will look at techniques and experiences for enjoying ecstatic solo sex. want to know more? Take it to the next level... * * * Go to... Missionary position Woman on top Half reclining position Side-by-side positions * * * **Other sources** Internet www.tantra.com Courses See Need to know more Publications Tantra: The Art of Conscious Loving, Charles Muir, et al, Mercury House, 1989 * * * Tantra and the Single Person We live in a time when it's becoming increasingly acceptable for people to lead single lives. From a purely physical perspective, no one is barred from sex these days because they don't have a partner, and many individuals find a great release in being able to explore and enjoy their sexual responses alone, without self-consciousness or anxiety. The benefits of singledom **Anyone who has tried to go on holiday alone and come up against the single supplement may very well feel that society still discriminates against men and women who are not part of a couple. Our society remains geared around couples and ultimately, the family, which has an overwhelming social importance single people still cannot hope to match.** Throughout recorded history, literature and art have focused on the couple, particularly on romantic love. It's difficult to think of any major novel, play or film in which a person has a completely solo experience. It's hardly surprising then that people who choose to be, or find themselves alone, feel that they are somehow outside of, or separate to, the rest of society. They may even feel socially or emotionally inadequate in some way. However, there are less attractive aspects to being in relationship including the negative power of coupledom. MUST KNOW **Importantly, being single does not mean being without an active sexual life. In the past, masturbation, particularly by women, was seen as a sad, lonely alternative to sex with a partner. This is increasingly less so, as talking openly about sex and our needs and desires becomes easier right across society, from the young to the elderly.** Romantic love tells us that to be whole we must be in a relationship; we must be in love with someone and have someone love us in return. For many people, particularly young people in the throes of biological change, this is an irresistible lure and we frequently end up handing our personal power, sometimes our lives, over to others who are equally lost or unaware of themselves in the hope that coming together will somehow make us stronger. Sadly this is rarely the case, and as more than 40 per cent of marriages in the western world now end in divorce, and more and more women bring up children alone, singleness as a positive state is both more acceptable and more appreciated. Being single doesn't mean no sex! It's easy to make the mistake of thinking sexual pleasure is something given to us by another person. Anxiety about masturbation and awkwardness about our own bodies as we grow up leads to inhibition, self-consciousness and general discomfort with sex and the body. For many of us it is easier to hand over responsibility for our sexual lives to a partner or partners. There are numerous alternatives to sexual relations with a partner, from celibacy and platonic (non-sexual) partnership, to vigorous sexual activity using fantasy and sex toys. There is an extremely wide, and ever-growing, range of sex toys now available which everyone can enjoy – single or not. Many single men and women have lively sexual fantasies – as do many happy couples – and this is by no means a modern or Western phenomenon. Tibetan tantric teachers suggest that a single person create a fantasy lover, an imaginary partner called a tulpa. When imagining a tulpa, if he or she is based on a real person, you should acknowledge and respect the person on whom the fantasy is based, thereby making your fantasy more real and more loving. Tantra and the single person **The** _**Kama Sutra**_ **has very little to say on single pleasure. Because Vatsyayana's main object was the social responsibilities of the upper-class male, his advice on sex and love was very firmly set in a treatise on society at large.** Tantra, however, has a completely different attitude to the individual and sexual relationships than the _Kama Sutra_. The ideas and practices of Tantra had been around for millennia before Vatsyayana's time; he was well aware of the writings of his tantric predecessors and drew on them in his own work, though he chose not to address the deeper spiritual aspects of the tantric texts. As we saw in **Tantra and you** , tantric practice centres on each individual's uniqueness. In order to be complete and perfect as beings we simply need to acknowledge that that is how we are – complete and perfect. Tantric practitioners teach that we have absolutely no need for another person to make us complete, because true happiness – mental, emotional, spiritual and physical, come from within ourselves, specifically from our relation to, and awareness of, the divine, the All, of which each living thing is a part. Tantra also, of course, relates to relationship and as we saw earlier, tantric sex between individuals is seen as a mirroring of the divine sexual relation between Shakti and Shiva, which in turn represents the cosmic forces of creation. When we come together with another person we merge with the intention of temporarily losing our individual identity; we merge not only with each other, but also with the universal energy and consciousness. Just as this can be achieved in tantric sex with another person, it is also possible through meditation, yogic practice or by arousing our sexual energy alone. Tantric sex as a solo person is not inferior to sex with a partner, it is merely a different way of uniting with the universal energy. Tantra urges us to recognize that there's a great difference between giving yourself an orgasm and having a relationship of love with yourself. Great solo sex **Sexual energy is life energy and being able to move our sexual energy around the body enhances our entire being and our everyday life. When we have tantric sex alone we unite with the universal energy which in turn feeds back energy to us.** The best way to start learning to have ecstatic sex alone is to tone and strengthen your genital muscles, particularly the PC or pubococcygeus muscle, which stretches between your legs from your genitals to your anus. It is part of the pelvic floor musculature in both women and men and the standard way to get in touch with your PC muscle is to stop and start as you urinate. Another way is to imagine you're holding back a bowel movement, tightening and pulling up on your anal muscles, or you can try inserting a well-lubricated finger into the anus and squeezing until you feel the anal muscles and the PC muscle contract. Women can also put a finger or fingers in their vagina and squeeze. Depending on the strength of your muscle the vagina will grip the finger gently or hard. The PC muscle is the ribbed area about one and a half inches up on the back wall of the vagina. In the man the PC muscle runs from the pubic bone to the tailbone in a figure eight around the genitals. Strengthening your PC muscle Many women who have given birth are familiar with Kegel exercises to strengthen their PC muscles, but for many of us, particularly men, this is a new idea. You can do PC squeezes at any time, writing, reading, in the car, on the train, working, watching TV, or listening to music. The idea is to isolate the PC muscle and work on that, though you may find that a tightening of the muscles in the stomach and thighs also happens at first. This is quite normal, but after the first few days or weeks, when you've really located the muscle, these peripheral sensations should start to disappear. Once you have definitely found the PC muscle, start with quick or short squeezes. Contract the muscle 30 times at a rate of about one per second or faster. Do two sessions on your first day. Gradually build up to 100 twice a day. When you can comfortably do 100 short contractions twice a day, add longer movements. Long squeezes are simple. Instead of holding the muscle contraction for a count of one, hold it for a count of three. Start with 30 of these, twice a day. Build up to 100 twice a day. Take your time and avoid straining. The PC muscle is like any other muscle in your body – if you over-exercise it, it can become uncomfortable. Make the contractions as focused as you can and concentrate on the physical sensations. Some people find that they involuntarily raise their eyebrows! Learn to relax between contractions. Relaxation is just as important to your control as the contraction itself. It's this ability to both control and relax that allows you to prolong lovemaking as long as you want without ejaculation. Use your Imagination Because mind, energy and body are intimately connected, use the power of your mind to strengthen your PC area. Women can try imagining their vagina as a structure stretching deep into the earth made up of many powerful bands that can contract or expand at will. Imagine these circular bands of muscle growing in size and strength with each exercise. Men can imagine their PC muscle is a powerful chain or rope tensed between their legs, which they can tighten or loosen at will. Imagine the links of the chain getting thicker and stronger with each repetition. Don't be surprised if the exercises are sexually arousing. The contractions of these muscles are what start to move sexual energy, that's the whole point of working this area – to learn your own responses so you can relax and control at will. In order to help you focus away from growing sexual tension, try thinking 'I honour my vagina' or 'I honour my penis' with each muscle contraction. These exercises will not only help you with orgasm control, but will help you be more in touch with your genitals and sexual feelings in general. It will also improve genital health by improving the blood flow to the area. Orgasm for women **One of the many reasons why women do not have orgasms is because they haven't learnt the importance of muscle contraction.** Tantric sex is about the opposite of tension but if you are anorgasmic and would like to change that, tension in the genitals, buttocks and upper thighs may be exactly what you need to achieve orgasm. One of the great joys of being single is the ability to find out what you really enjoy sexually without worrying about a partner. If you are a woman who finds reaching orgasm difficult or impossible, try this simple exercise when you are comfortable and relaxed. Exercise to help women with orgasm • Remember to prepare your body and create your ritual space; it's important to do this just for yourself and no-one else • Put on music with a good strong rhythm and start by stamping your feet on the ground to move the energy around your whole body. Shake your arms and let yourself move freely. When you are looser and feel the energy of your movement and the music moving around your body, stand for a few moments and feel your heart beating. Be aware of your breath and imagine you are breathing into your pelvis. Imagine your vagina opening and closing with each breath • Sit with your legs stretched out in front of you; raise your body a few inches using your hands then drop your buttocks quite firmly down on the ground. Think of the kundalini energy stored at the base of your spine in your lower chakra. Imagine that each time you bounce your pelvis that you are waking up the energy, that it's starting to move up your spine • When you are aroused and energised, relax back and start caressing yourself in a gentle and loving way. Honour your body, don't touch yourself in a way you wouldn't like someone else to touch you. Stroke your vulva, open its lips. Place a finger in your vagina and contract your PC muscle, feel the power of the muscle as it holds your finger. Imagine that your vagina is the vagina of Shakti and that it can hold the entire world without effort • As you become more aroused, remember to regulate your breathing. Notice how your breath affects what is happening between your legs. Now, try contracting the muscles around your vulva, pull up on your PC muscle, then tense the muscles in the front of your groin, thighs and buttocks and slightly rotate your hips as if you were trying to point your big toes at opposite walls rather than at the ceiling. Some women find it easier to do this if there is something to push against • Experiment with how the different movements of your muscles, combined with your breathing, affect your level of arousal and find what feels best to you. Remember that the entire genital area has nerve endings that can help you orgasm. Orgasm for men **While women may need to connect more fully to their orgasmic power, men frequently need to be able to control their urge to orgasm.** In earlier sections we looked at the 'spiritual' reasons for controlling orgasm in tantric sex; but there are many reasons why a man might want greater control of his ejaculation and here we'll look more closely at how to do that. Whether you want to learn how to control your ejaculation in order to practise tantra and develop a spiritual sexuality, either alone or with a partner, or simply in order to be able to make love or masturbate for much longer periods of time, learning the method known as 'karezza' is an invaluable asset to any man wishing to improve the quality of his sexual life. To spend or save? From a spiritual perspective, it's equally important for women to control their orgasms. Tantric texts were often written by men who lived at a time when female spirituality was ignored or misunderstood and it was urged that women have as many orgasms as possible while men had few or none. Some Taoist sexual practices taught men not only how to avoid ejaculation themselves, but how to draw the spiritual energy from their partner during orgasm to add to their own supply. A kind of sexual vampirism! Few people would suggest that today. Women can of course be multi-orgasmic and continue to make love when men often wish to stop or rest after orgasm. From a purely sexual-spiritual perspective however, it's as important for women to retain and recycle their sexual energy as it is for men because lovemaking is not simply about being able to 'go on longer', but about increasing emotional and spiritual health and physical vitality. Karezza It's very much easier to learn how your body responds to sexual stimuli when you're alone than it is with a partner; so take advantage of your singledom and give yourself the time and space to notice what actually kicks you over the edge. Is it always the same thing? Can you feel that edge approaching and pull back from it? Strengthening your PC muscles will help you greatly as you begin to learn how to actively judge and control your reactions rather than trying to distract yourself by thinking of mowing the lawn or the soccer scores. Try to pinpoint that moment at which you know orgasm is approaching but is not yet beyond your control. Men (and women) usually experience between seven and twenty muscular contractions when they do actually orgasm. Remember to count if you can, so that you know how many contractions you usually experience. Does the number change; is it fewer when you are more tired for example? Exercise to control orgasm • Remember to prepare your body and create your ritual space; it's important to acknowledge your own value to yourself • Put on some gentle, relaxing music and make sure the room is warm. Start by stroking yourself all over your body while you are still standing. Caress your abdomen, thighs and neck, the backs of your arms and your buttocks. Feel your skin and hair, how good it feels. Stand quietly for a few moments and feel your heart beating, be aware of your breath and imagine you are breathing into your pelvis, imagine your lower chakra slowly awakening with each breath • Lie down and make yourself comfortable. Continue to massage your abdomen, moving down towards your genital area until you are touching and caressing your penis and can stroke your testicles and perineum area. If you have some gentle, unscented massage oil try using this to make your movements more smooth and arousing • Avoid your usual style of masturbation; rather than going straight for what you know will turn you on and give you a quick orgasm, continue to massage and squeeze your whole genital area. Try, if you haven't done so before, to explore the area around your anus. Is it pleasurable? • Carefully massage the perineum, the area between the scrotum and anus, and locate, if you can, the external position of the male G-spot, your prostate gland. Ancient Far Eastern texts referred to this point as the 'Gate of Life and Death' because it is not only the gland which produces semen, but the physical position of the base chakra through which vital energy enters and leaves the body. If pressed correctly this spot will prevent ejaculation • As you become more turned on, remember the deep breathing exercises which can help you control your arousal. If you are practising ejaculation control for tantric purposes, imagine that you are breathing into your genital area, imagine the energy circulating there at the base of your spine, waiting to be drawn up towards your brain • As you feel orgasm approaching, stop what you are doing and relax all the muscles in your abdomen and pelvic area. As you become more aware of what your body does, try to let one or two contractions happen before relaxing. Concentrate on your responses and be aware of exactly what your body is doing. As you become more confident with this you can repeat it until it's easy under any circumstances • If you don't immediately experience the waves of pleasure tantra offers, remember that this may be because you are not yet fully relaxed. The more confident you are with your body and its reactions, the more likely you are to experience the undulating waves of pleasure that mean you are now a full-body orgasmic man! • If you find yourself unable to control the ejaculation, don't be irritated or disappointed with yourself. This is the opposite of what you may have expected all your sexual life and can take time, so be patient. If the relaxation and breathing techniques are not enough to keep orgasm at bay, remember that pulling hard on your PC muscle will help, and finally you have the option of pressing very firmly on the Gate of Life and Death (your perineum) with two or three fingers, which will physically prevent ejaculate leaving the prostate and entering the penis. You do need to time this carefully; if you squeeze and press just before ejaculation begins you will experience the pleasurable contractions of orgasm without ejaculating. Too late is just that... too late! In time the pressing technique should become unnecessary as you become more familiar with the edge where orgasm occurs and learn to ride it in a relaxed way. MUST KNOW **There is no medical evidence that practising karezza can damage your organs. Physiologically, the semen is re-absorbed by the body. Tantric practitioners believe that the semen you retain actually increases your spiritual energy.** Spiritual vs physical? **If you visualise your base chakra as simply a place between your legs you may not be able to imagine its energy rising and twining around your spine to the top of your head. Just because you can't imagine it, doesn't mean it won't happen.** The techniques of tantra are firmly based in the human physiological response, not just ancient notions that have no relevance for us today. Though much has changed over the millennia, human physical responses most definitely have not. In **Tantra and You** , we looked at how women and men can choose whether to adopt the sexual exercises described above as part of a spiritual path or simply as a physical technique that will help you become a better and more sensitive lover of yourself or of a partner. Paradoxically, technique is rarely the answer to sexual relationship difficulties and even mastery of your own body cannot guarantee a profound spiritual experience. Technique is often the enemy of feeling, and even if you are not inclined to practise tantra in an intense way, remember that heartfelt respect and love for your partner and the act of lovemaking itself are what lead to ecstasy. want to know more? Take it to the next level... * * * Go to... What is tantra? Kundalini and the chakras * * * Other sources Internet www.tantra.com Publications Balancing Your Chakras: How to Balance Your Seven Energy Centres for Health and Wellbeing, Sonia Choquette, Piatkus Books, 2000 * * * Pleasure Enhancers Many of the sex toys and stimulators to be found in modern sex shops look remarkably like the items described in the _Kama Sutra_ and, while gay men have enjoyed toys like these for years, more and more heterosexual men and women are now discovering the pleasure of sex toys. Sex toys **Reading the original** _**Kama Sutra**_ **can be a fascinating experience, not just for advice on sexual technique and positions, but because of the wonderful insight into the times and the people who inhabited that world. Surprisingly, the men and women portrayed seem very little different to us living in the 21st century.** People with leisure in ancient India were extremely interested in sex, social life and fun. This is particularly evident in the chapter in which Vatsyayana discusses what, today, would be called sex toys, aphrodisiacs and sex magic: **'Or, he may make use of certain Apadravyas, or things which are put on or around the lingam to supplement its length or its thickness, so as to fit it to the yoni.'** Apadravaya is a word for anything which can be fixed on or around the penis in order to keep it erect, or to increase its size. It has come to mean a particular type of genital piercing, but Vatsyayana had a more general understanding of the word. He also describes various bracelets, which can be fitted or tied around the penis, again to maintain erection or to give a woman increased pleasure. The 'Kantuka' (a strap on dildo – 'outwardly rough and studded with soft globules') is something to be used in connection with or in the place of the penis, and although contemporary Indians lacked the variety of fabrics that we have today – modern dildos can be made from plastic, rubber, silicone and even steel – they evidently made up for this with inventiveness. MUST KNOW **Using a dildo for penetration can really enhance orgasm as you can control the speed and depth of penetration and still have one hand free for stimulating your clitoris, penis or nipples.** These days the quantity of sex toys available seems endless and a wide range of sex toys are readily available for anyone who wants to experiment, diversify their sex life and have fun alone or with a partner. The modern name, 'sex toys', covers a very wide range of items, from dildos and vibrators through to restraints like handcuffs and collars and S&M equipment, such as whips or paddles. Dildos are the oldest and best known of all sex toys and today there's an extensive range of shapes and sizes, from realistic penis types that 'ejaculate', to fun shapes like dolphins or birds. Phallic symbols from ancient India often have a man's/god's face carved into the side. Art, but not comfortable! Dildos can be short and thick, or long and slender. For comfort and sensitivity they are best used with one of the many water-based lubricants available from the chemist's. Dildos can enhance women's and men's sexual pleasure, either during masturbation or with a partner, or both. Dildos can be fitted with suction cups and stuck pretty much anywhere for hands-free pleasure. Some men enjoy seeing their partner penetrated in different ways and a growing number of heterosexual men are discovering the male G-spot and the pleasures of anal penetration, which can produce very intense, long-lasting orgasms, similar to those experienced by women during intercourse that stimulates the female G-spot. For some women, penetrating their partner can be a very liberating experience that promotes intimacy and trust. Many women also enjoy being penetrated anally and find it both excitingly different and relaxing. If you are both comfortable with these practices and enjoy toys, there are many different kinds of strap-on and double-ended varieties of dildos to choose from which are worn by women using a pelvic harness. The single strap-on dildo is worn outside the body but is usually designed to fit over the clitoris giving powerful stimulation as the woman thrusts. The double-ended type fits inside the woman's vagina so as she penetrates her partner she is also stimulating herself. This can be a particularly exciting and unusual experience for women as they are able to watch their partner's reactions in a new way while being penetrated themselves. WATCH OUT **Go gently and use lots of lubrication!** Sex furniture, a relatively new addition to Western pleasure shops, was also available in Vatsyayana's time. A much later erotic text describes how the women of Orissa use a seat that can be raised up and down on their partner by means of a pulley. This activity seems as much a testament to the strength and physical fitness of Indian women, as to the inventiveness of the seat's designer! Today it is possible to find exactly the sort of seat described above, as well as harnesses to hang from the ceiling and 'love-seats' that support the body during sex! Piercing **Piercing of the genitals is not exactly common in the Western world today but over the last few decades it has become increasingly fashionable among younger people and gay men and women. Again this is a practice which has existed around the world for millennia.** In these days of Viagra and surgical penis enhancement, it's good to realise that we human beings have always been fascinated by our own bodies and sexual behaviour and have always sought to change and adapt what nature has given us. Some people imagine tattooing, piercing and other forms of body art (or mutilation, depending on your viewpoint!) are new and modern, but even a brief reading of the _Kama Sutra_ explains that such things are very ancient indeed. **'Now, when a young man perforates his lingam he should pierce it with a sharp instrument, and then stand in water so long as the blood continues to flow. At night, he should engage in sexual intercourse, even with vigour, so as to clean the hole. After this he should continue to wash the hole with decoctions, and increase the size by putting into it small pieces of cane, thus gradually enlarging the orifice... In the hole made in the lingam a man may put Apadravyas of various forms... . All these Apadravyas should be rough on the outside according to their requirements.'** Today of course, it is not only men who are pierced genitally; the labia, clitoral hood and perineum are all sites for piercing. Nipple piercing became popular in the 1980's and navel piercing is very common among young women today. If you are interested in being tattooed or pierced as part of your sexual life, make sure you go to professionals who are registered practitioners and have a good reputation. Aphrodisiacs **'The means of producing love and sexual vigour should be learnt from the science of medicine, from the Vedas, from those who are learned in the arts of magic and from confidential friends. No means should be tried which are doubtful in their effects, which are likely to cause injury to the body, which involve the deaths of animals and which would bring us into contact with impure things.'** Like many people who have studied and written about the erotic arts, Vatsyayana was fascinated by the possibilities of aphrodisiacs. What we today consider to be aphrodisiacs – pills or potions that increase libido – are actually only a very small part of what our ancestors would have considered interesting or useful. There was a very thin line between what were considered 'tonics and medicines', and aphrodisiacs, and Vatsyayana often refers to the use of 'medicines' to speed up orgasm in women, or keep a man erect for longer. The aphrodisiacs described in the _Kama Sutra_ cover a range of possible requirements: • substances to make oneself more desirable • potions to increase passion • ointments to make one's lover more desirous or oneself less so • massage oils and 'unguents' to make the penis larger, or the vagina tighter or wider. Some of the recipes sound downright dangerous. The most bizarre of these includes monkey excrement, red arsenic, leaves that have been strewn on a human corpse before burning, insect bristles, the sweat of the testicle of a white horse, and the bones of vultures and peacocks. Some, such as drinking a milk and sugar mixture, which has had the testicle of a ram or a goat boiled in it to increase vigour, just sound rather unpleasant to modern tastes. Interestingly Vatsyayana's recipes were not only for making oneself attractive and for increasing one's own libido, but there are also suggestions on how to avoid desire and how to overcome one's attraction to a partner, in other words anaphrodisiacs: 'If a man... applies this composition of the yoni of a woman, and then has sexual intercourse with her, his love for her will be destroyed.' Many of the _Kama Sutra_ 's recipes are about increasing sexual attractiveness rather than specifically about increasing desire. There is information on how to redden the lips, or bleach the hair and how to make the black cosmetic collyrium to encircle the eye. Modern aphrodisiacs **'The sages say that wheat flour cake baked with honey and sugar and sprinkled with the powdered seeds of pumpkin and sage can give one strength for a thousand women.'** These days the use of aphrodisiacs tends to be more controlled and medicinal, with information on how to increase one's sexual potency through the use of vitamins, minerals or drugs, such as Viagra. In Eastern and Western cultures, herbs, such as damiana and ginseng are believed to both increase sexual vigour and to increase longevity, and have been used for many thousands of years in foods and as medicines. However, it's not only the obscure plants that are known for their aphrodisiac properties; some of our most common herbs have powerful sexual associations. Sexy basil • Magic – Basil has ancient links to love and sex in cultures across the world. In Haiti it has associations with the goddess of love, and legend says that wives who wish to 'cure' their husband of infidelity should perform a ritual in which they powder the herb and sprinkle it across their body. In European folk tradition basil is an important ingredient in erotic rituals, and Arab writers have written about it as an important aphrodisiac capable of enhancing erotic passion, especially in women • Food – Basil is commonly used in many sauces, such as pesto. It has a powerful taste and, fresh or dried, enhances many recipes • Massage – Basil is also an essential oil; try adding it to your regular massage carrier oil to give it an aphrodisiac dimension. It also has a range of medicinal properties for helping problems like headache, flu symptoms, vomiting and nervous tension • Herbalists advise that if you wish to use basil specifically as an aphrodisiac you need to between .5 and 1.5g of the dried powdered herb. You should then place the powder under your tongue for fifteen to twenty minutes before swallowing it with some water and honey. This particular recipe is believed to work with both sweet basil, available in shops, and wild basil, which is also known as 'selfheal'. Selfheal can also be used by mashing up the plant and adding 30 to 50g of it to one litre of mineral water. Drinking two or three cups of this per day is believed to stimulate the sexual function. Food as an aphrodisiac **One of the simplest ways to enhance sexual performance is to keep your blood sugar level high before you make love; this does not mean eating large quantities of sugar! It means eating simple and refined carbohydrates such as baked potato, pasta and brown rice. Cutting down on complex sugars, sweets and biscuits, which cause quick elevation and then depletion of blood sugar, would also be helpful in preventing loss of energy halfway through lovemaking.** Aphrodisiac plants and fruits include walnut, winter savory, cowslip, goats rue, blackcurrant, yarrow and giant horsetail. Simple foods like celery, garlic, ginger and nutmeg are all believed to have mild aphrodisiac effects as does honey, which some cultures consider the queen of aphrodisiacs. Several ancient erotic texts, including the _Kama Sutra_ , recommend the use of honey topically. MUST KNOW **Given that our diets have now been proved to cause everything from allergies to cancer and diabetes, it's not surprising that it can have a profound effect on our sexual life as well.** Chocolate is another substance long considered to be aphrodisiac. The 16th-century Mexicans treasured its bitter flavour and thought of it as a kind of ambrosia, or food of the gods. They drank it mixed with chilli peppers, which must have made it a pretty heady brew. Research has shown that chocolate contains a chemical which causes the brain to react in much the same way as it does during lovemaking. So perhaps chocolate is an alternative or substitute for sex after all. WATCH OUT **The causes of low libido or even impotency can be many and varied and if you feel you have an ongoing problem with which your doctor has not been able to help you, you should always visit a herbalist or naturopath and take professional advice rather than treating yourself. Care should be taken with any over-the-counter preparations such as Saw Palmetto or Wild Yam as these may conflict with existing medications. Always follow the instructions on the packet very carefully or better still visit a professionally qualified herbalist.** Sex supplements **From the most basic perspective, vitamins and minerals that boost your everyday functions such as Vitamins C and the mineral zinc will also help to improve your sexual performance. There are also specific herbal preparations widely reputed to enhance libido because of their direct hormonal function.** • Saw Palmetto, long known to be a sexual stimulant for men, apparently works directly on male sex hormones. It's is believed to have healthful effect on the male bladder and prostate • Wild Yam, which is thought to have aphrodisiac and health giving properties for women is a natural progesterone which affects female hormones • Horny Goat Weed is widely used in Chinese medicine and is believed to be one of the strongest herbs in the Chinese pharmacopoeia for increasing libido, as it dilates the capillaries, improves blood flow and increases the sperm count • Guarana, widely available in almost any street corner shop as soft drinks or even chewing gum, is thought to increase general energy, thereby boosting libido – though you'll probably need more than a packet of gum for that! • Ginseng and the Siberian ginseng root have been used by oriental men for more than 5000 years though it has lost popularity recently and its role has been taken over by the Arctic root • Rhodiola Rosea, which is believed to increase serotonin levels – creating calm, elevating mood and preventing stress – works on low libido in a quite different way. NEED TO KNOW **Some types of medication, particularly antidepressant, can powerfully affect the libido in a negative way. This is also true of medicines for high blood pressure. Some diuretics and oral contraceptives affect women's moods in many different ways.** Making sex magic **'When a person fails to obtain the object of his desires by any of the ways previously related, he should then have recourse to other ways of attracting others to himself. ...Now, good looks, qualities, youth, and liberality are the chief and most natural means of making a person agreeable in the eyes of others. But in the absence of these a man or woman must have resort to artificial means, or to art, and the following are some recipes that may be found useful'.** Most of us would probably agree with Vatsyayana here – in fact our modern cosmetic industry is based on these principles! The _Kama Sutra_ chapter about the means of attracting others to yourself is a peculiar mixture of hard-nosed social advice on such things as how to avoid giving yourself or your relatives away for free; good luck charms and incantations; cosmetics and unguents; and aphrodisiacs, which if applied to the body or directly to the penis, will subject women to one's will. Not all the advice is very attractive or useful to the modern reader. Few men these days would bother tying a gold-covered hyena bone to their right hand in order to make them 'lovely'. And probably not many young women would agree to be secluded and locked up as a means of making them more attractive and desirable. But these 'tricks' were seen as having the power to significantly increase desirability by casting a 'glamour' over a person through quite simple magic. The magic of intention. Using intention **In** **Getting In The Mood** **we saw how creating a ritual of lovemaking can enhance your sexual relationship with your partner. Magic ritual is easily as old as tantra and much older than the** _**Kama Sutra**_ **and has many traditions designed to attract partners, improve one's sex life and make one more attractive to others.** Today we would say that most of these charms, or spells, are about 'intention', the power of our wish, of our focus, to have the thing we desire, whether that is to find a sexual partner, or have a better relationship with the one we already have. NEED TO KNOW **Remember that magic is the power of your intention working with the power of the universe.** A little ritual to attract a sexual partner You're heading out for the evening. You have made yourself ready, showered, shaved – or applied makeup. Before you leave home do one last thing: • Darken the room and light a candle on the table • Sit or stand in front of the candle and look directly into the flame • As you stare at the flame focus all your intention on the kind of person that you would like to meet between leaving the house and returning. Try to think of the attributes that would most attract to you • What does she/he look like? How do they sound? Are they serious? Fun? • When you have a picture in your mind of the person you would like to meet, think of making yourself attractive and desirable to that person. You've already done everything you can to make yourself look your best, now you need an additional something! • Rub the palms of your hands briskly together and place them three or four inches away from each side of the candle flame • Feel the flame warming your palms and fingers; keep staring at the candle flame experiencing its warmth entering your hands • Imagine the warmth travelling up your arms into your shoulders and your chest • Imagine the warmth bringing light to the area around your heart and see the person you have imagined in the centre of that light • As you feel this happening say aloud: **'This flame was yours, this flame is mine, bring me now my love so fine.'** When you finish speaking, pinch out the candle saying, **'So will it be'**. The more intensely you believe that you will have what you want, the more likely it is that it will happen. But, remember, if it doesn't happen you may not have wished for the right thing. The more clear and honest you are with yourself and any potential partner, the more likely you are to succeed. Having a clear intention that could bring harm to you or others is less likely to succeed and it certainly won't bring you real happiness. want to know more? Take it to the next level... * * * Go to... Food and drink * * * Other sources Websites www.nicesextoys.com www.annsummers.com Publications Essence of Love: Fragrance, Aphrodisiacs, and Aromatherapy for Lovers, Maggie Tisserand, HarperSanFrancisco, 1994 * * * Sharing Kama Sutra Sex In many ways the culture revealed in the _Kama Sutra_ is very little different to our own modern society. What to the Victorians of Sir Richard Burton's era would have seemed unbelievably shocking – such as having sexual relations with more than one partner at a time – doesn't seem so very strange to us in the 21st century. Sharing partners then **Because ancient Hindu society did not have the same constraints around sex and the body that Western societies later developed, the restrictions on sexual behaviour were quite different to the ones we acknowledge today.** Vatsyayana makes it plain that he is writing as part of a religious duty, but he does not consider it inappropriate to describe the spell which can render a man invisible in order that he may enter the harem unseen in order to cuckold the King! He also offers his readers advice on where and at what times royal harem women are least protected and most available. (Male fantasies have clearly changed little in millennia!) **'The women of the Royal harem know each other's secrets, and having but one object to attain, they give assistance to each other. A young man who enjoys all of them, and who is common to them all, can continue enjoying his union with them so long as it is kept quiet, and is not known abroad.'** In guiding his reader to success in the harem, Vatsayayana also takes the opportunity to offer advice about having sex with more than one person at a time. Ancient upper-class Hindu society seems very hedonistic – easily as pleasure orientated as our own world today – and the idea of a man or woman having sex with more than one person at a time does not concern Vatsyayana as long as the ground rules concerning class and marriage are observed. So, the respectable wife of a respectable citizen would never be encouraged to do such things ... only the wives of other men in other countries do these things. **'In Gramaneri, many young men enjoy a woman that may be married to one of them, either one after the other or at the same time. Thus one of them holds her, another enjoys her, the third uses her mouth, a fourth holds her middle part, and in this way they go on, enjoying her several parts alternately.'** Sharing partners today Although having more than one sexual partner is no longer a matter of social censure as it would have been in Burton's day, it's far from being an accepted norm in western culture. Most major religions forbid more than one partner and monogamy is still considered the social ideal. Even religions that do allow a man to have more than one wife strictly limit and control the way in which these relationships are conducted. Despite this, for many men and women the idea of openly sharing partners including one's husband or wife is becoming increasingly acceptable if not exactly fashionable. 'Swinging', wife/husband 'swapping' and 'key parties' have been a source of fun and excitement, as well as jokes and urban mythology, since the 1950's. Gay men have led the way in western culture in conducting and maintaining long-lasting open, relationships. Gay men have claimed for many years that sexual adventure and exploration is acceptable as long as honesty prevails; these attitudes and behaviours are now moving into the mainstream. What used to happen only in the home, at private parties or during intimate weekends among friends, is increasingly turning into a club event, where members actually go and meet other people purely for the purposes of sex. People who enjoy and take part in these events say that honesty and openness are the best way to enjoy life and that, if it is only physical affection that is being shared, nothing of value is being taken away from their long-term partnership. Couples who have _love_ relationships with more than one person argue that love is not a commodity like water or clothes that can only be given to one person by taking it away from another. The argument for both loving and having sex with more than one person is that love and desire are not lessened by division. MUST KNOW **The opposing perspective, which may be held by those who have tried such relationships and found they have not worked for them, is that to maintain a truly loving relationship with even one person takes time, energy and commitment, which few of us are able to fulfil to its potential. Spreading one's effort even more thinly, it is argued, by necessity means that no one can be getting the best from the situation.** Group sex **Only you and your partner, if you have one, can decide what kind of relationship you want for yourselves. The argument for having multiple partners is that sex is fun and that with trust and commitment to openness between you, only pleasure will result. This can be true for a great many people; it may well be true for you. Also be aware that many couples who do explore sex with others find that one or both partners are unable to cope with the after effects.** Before deciding on whether this lifestyle is for you, think carefully about what actually is going to happen. For most of us, sex is a very private thing, and intimate act between one other person and ourselves. While we may have fantasies about orgies, group sex or even rape – and very many of us do – few of us would wish to translate these into actuality. On the other hand, if you feel this is something that you would enjoy, either alone or with a partner, then turning it into reality is probably easier today than it has ever been. Things to consider The following might be things to think about with your partner: • Will the action be purely heterosexual, or will there be any bisexual activity? • Do you want to see your boyfriend/girlfriend/wife/husband being kissed by another woman, or another man? • How do you think you will react? WATCH OUT **You will need to think about the health aspects of this kind of sex – statistically speaking, the more people you have sex with the more likely it is that you will expose yourself to the possibility of sexually transmitted infections. If you currently have unprotected sex with your long-term partner, how will that be affected by having sex with others, even with people you think you know very well? (SeeSafer Sex)** • If you have never done this before, how do you feel about being sexually intimate with someone of your own gender? • How will you and your partner feel about each other after the fun is over? • Will it add to your relationship and give a fillip to your own sex lives? • Alternatively, will it create a barrier of anxiety and jealousy? • What will you do if you find one of your 'playmates' more attractive, stimulating or interesting than your partner? • How will you feel if you're partner is having a great time but you aren't and vice versa? NEED TO KNOW **You will need to have frank discussions about your feelings for each other and your relationship before you consider extending your sexual relationship beyond its current boundaries.** Getting involved **So what is 'group sex', 'swinging' or 'partner-swapping'? Group sex means sex between more than two people at a time in the same place. Swinging or swapping includes activities between a couple and another couple(s); or a couple and a single man or men, or a couple and a single woman or women, either in the same space or in different rooms/venues.** The 'lifestyle' as some people refer to it, includes a wide range of sexual activities conducted between three or more people. This can include: • watching other people having sex • having sex with your partner while being watched • swapping partners – male or female, and • having sex with other people either in front of your partner, or when your partner is absent or in another room Hosting a party If you are inviting friends or a friend to your house to enjoy sex with you and/or your partner, or if you are a single person inviting a couple or couples to enjoy sex with you, prepare the space as you would for yourself or for a lover. Here are a few things you can do that will help your guests enjoy themselves: • Maybe bed is not the best place if there isn't room for everyone to be comfortable. Many people like making love on a floor space where there can be different levels. Try covering your sitting-room floor with quilts or rugs, but you can also make use of chairs, sofas or the tops of tables • Remember that scent is important and light incense and candles or have perfumed flowers • Make sure your fridge is well-stocked with snacks, drinks and other refreshments • The bathroom should have plenty of clean towels. Soaps and shampoos should be available for your guests to use • Cleanliness and hygiene are essential in any sexual situation – in a group situation this becomes even more important • Make sure you have plenty of condoms around the 'play room' with tissues and hand towels easily accessible • Some people enjoy watching pornography as a prelude to or during sex. If your guests are into that and you know their taste in entertainment, adult videos can be fun and stimulating for all concerned. NEED TO KNOW **If you are going to be using recreational drugs, remember that these will most probably be illegal and while they may enhance sexual activity, they also affect your judgement and your health sense. Take a moment to ask yourself how much fun you would have without the drugs and if the answer is 'not that much', perhaps you need to look at why you're in the situation at all.** Group positions **Group sex is a common sexual fantasy: the idea of being touched, tasted, kissed or penetrated by more than one person at time can be extraordinarily exciting.** Remember that your brain and imagination are the keys to sexual pleasure and allow yourself to create new combinations. Any action that happens between two people can be done by a group, regardless of sexual orientation: homosexual, heterosexual, bisexual or metrosexual (a person who just enjoys sex per se, regardless of the gender/age/number of their partner(s)). Remember that anything done by a man can also be done by a woman wearing a dildo, so let your imagination go wild! Both ends now In this combination, a man penetrates a partner in the vagina or anus, while another man penetrates her (or him) orally. You can try this on all fours, reclining, or standing up bent over. If you are the penetrating partners, you can caress and stimulate each other, as well. Double penetration Two men, or a man and a woman, simultaneously penetrate a woman vaginally and anally. This can be a very intense experience for the woman being penetrated, and, depending on the number of partners available, she may enjoy oral penetration as well. Daisy chain A daisy chain is any group of people making genital/genital, genital/anal or oral/genital contact, or any combination of these things. Many of the erotic sculptures in the temples of Orissa in central India show a variety of sexual activities taking place at once among many people of both sexes. So a daisy chain can be a group of men penetrating each other anally, or a group of lesbians penetrating each other vaginally using strap-on dildos, or any bisexual combination of these actions. Mouth chain Again, this can be any combination of men and women linked together by oral sex. This is a good option if you don't want to include genital penetration in your activities. Dealing with feelings **'A man should therefore pay regard to the place, to the time, and to the practice which is to be carried out, also as to whether it is agreeable to his nature and to himself, and then he may or may not practise these things according to circumstances. But after all, these things being done secretly, and the mind of man being fickle, how can it be known what any person will do at any particular time and for any particular purpose.'** MUST KNOW **Your health and personal safety are prerequisites for sexual pleasure and if you decide that having more than one partner is something you would enjoy then remember that no one is simply a body, not you, your partner or your prospective lovers.** Everyone has feelings and this is something to be very conscious of at all times. The _Kama Sutra_ recommends affectionate graciousness as a key to smooth social interaction while being aware of and taking responsibility for one's own feelings and actions. Being a man of the world however, Vatsayayana adds that ultimately we are all a mystery even to ourselves. want to know more? Take it to the next level... * * * Go to... Safer sex * * * Have a go... Organize your own party once you've found willing participants * * * Other sources Internet www.bibliomania.com Publications Swinging for Beginners, Kaye Bellemeade, New Tradition Books, Digital Download – available from Amazon Safer Sex One of the best ways to enjoy a healthy, disease-free sex life is to be aware of what could go wrong well in advance and to understand and use some basic hygiene precautions. Unwanted pregnancy, simple infections such as candida (thrush), sexually transmitted disease (STDs), such as gonhorrea, herpes and HIV/AIDS can be prevented if you practise safer sex. Safer sex **Safer sex means not exchanging body fluids like semen or blood, which means that to be safer, sex is non-penetrative or done only while using a condom. However, because condoms can and do break, no penetrative (penis/vagina, penis/anus) sex can be guaranteed as completely 'safe'.** If you are in a long-term, monogamous relationship where neither you nor your partner have anything you could transmit to each other and when birth control is not an issue, it is most unlikely that you will need to practise safer sex, although hygiene practices will still apply. In all other cases your peace of mind can be enhanced by making decisions about safer sex beforehand and keeping to them. Risk-free activities • Kissing • Caressing • Massage • Mutual masturbation • Frottage (mutual genital/body rubbing) Low-risk activities • Anal or vaginal sex with a condom • Fellatio • Fisting • Cunnilingus • Inserting fingers into the vagina or anus • Sharing sex toys High-risk activities • Anal or vaginal sex without a condom • Swallowing cum if you have sore gums or mouth ulcers • Drawing blood. Any sex during menstruation. There are also basic rules of hygiene which should be followed by everyone regardless of risk or whether you need to practise safer sex with your partner or not. It's very easy to pass minor infections like 'thrush' from one person to another so: Some people keep anti-bacterial wipes handy, but bear in mind that not all bugs will be killed. Remember that oral-anal contact (rimming) can transmit intestinal infections and parasites that no anti-bacterial wipe can eliminate. If you've had your fingers in someone's vagina, or someone has ejaculated on your hands it's a good idea to wash your hands with hot water and anti-bacterial soap before touching your eyes or anyone else's genitals. Always avoid getting semen in your own or your partner's eyes as: • it can transmit disease through the delicate membrane and, • it can hurt like hell. MUST KNOW • **Never put fingers/toys in a woman's anus and then into her vagina** • **Never insert your fingers into your partners anus/vagina and then into your own** • **Never share dildos, vibrators or any toy without cleaning or changing condoms. Ideally have your own toys that you use just for you** • **Don't engage in oral/genital or oral/anal sex, without bathing/douching first** Condoms **These are available for both men and women and if used properly are very effective in preventing the exchange of semen or vaginal fluid.** MUST KNOW **Practise rolling a condom on and off before you get too carried away – practise unrolling a condom onto a banana or a dildo; try squeezing and inserting the Femidom in a sensual, erotic way.** Condoms have been around since at least the 17th century and are considerably more comfortable and effective than the sheep's intestines King Charles II reputedly used to prevent syphilis! It's important to use condoms carefully to prevent splitting or tearing. Some men find them difficult to put on, or feel that they reduce enjoyment; condoms can, however, become part of foreplay if both partners learn how to use them quickly and safely. WATCH OUT **Never use a condom with oil or an oil-based lubricant as it will destroy the latex in minutes!** There are many varieties of condom available in all shapes, sizes and flavours; however many of these are not effective in preventing an exchange of fluids. Only use approved, kite-marked condoms, within their sell-by date. Put some water-based lubricant on the outside of the condom for comfort, mutual pleasure and to keep the condom from tearing during sex. Some men find they have more sensation if they also put a small amount of lubricant inside the tip of their condom. After opening the packet carefully, squeeze the tip of the condom to prevent an air bubble, which could burst the condom during sex. Placing the unrolled condom on the top of the fully erect penis, begin to roll it down until it reaches the base of the penis. A condom that is too loose or too tight is ineffectual and can cause discomfort to both partners, so get the size that's right for you and remember to hold the base of the penis and the base of the condom tightly when withdrawing to avoid spilling the contents. Then wrap them in toilet paper and put them in the bin for waste disposal. MUST KNOW **Condoms cannot be re-used – ever! A new condom needs to be used for each new partner, and if you're switching from anal to vaginal intercourse you should put on a new condom to avoid causing vaginal infections.** It's possible to put a condom on by "blowing" it onto the penis with the mouth and rolling it down with the lips and fingers. This takes some effort to perfect. The Femidom, the female condom, is placed inside the vagina and held there by a flexible ring that fits around the cervix; it's held in place outside the body by a larger ring. It comes ready-lubricated inside and is particularly effective in preventing infections of the external sex organs, the vulva and labia. To insert the Femidom, gently squeeze the smaller, insertable ring until it forms a narrow slit, then slide it as high as possible into the vagina while pushing down gently with the pubic muscles. The small ring expands inside the vagina and holds the condom in place over the cervix preventing it sliding out during intercourse. As you draw it out after sex, remember not to spill any semen and dispose of it safely. Safe oral sex **Advice on safer oral sex varies. Herpes can be transmitted from genitals to mouth or mouth to genitals during oral sex. It is also possible to contract a bacterial infection of the mouth or throat by having cunnilingus or fellatio with a partner who has a bacterial STD (sexually transmitted disease), such as the increasingly common infection chlamydia (which can cause infertility in women), gonorrhea, and, much more rarely, syphillis. Bacterial infections are almost always curable these days with antibiotics once they're identified.** WATCH OUT **Remember that most transmissible infections can't be seen with the naked eye so someone looking OK doesn't mean that they really are OK.** The risk of transmitting HIV is very much lower for unprotected oral sex than for unprotected anal or vaginal intercourse. There is almost no risk to the person being sucked or licked, but it's considered that there is some risk to the person doing the sucking or licking. Some health professionals recommend NOT flossing or brushing your teeth for an hour before giving unprotected oral sex (use an anti-bacterial mouthwash if you want to freshen your mouth and teeth). Always (subtly!) check out the genitals you're about to take into your mouth for any obvious signs of STDs (including genital warts). Analingus (rimming), where partners lick and suck each other's anus, requires particular hygiene awareness and should be avoided with non-regular partners, particularly if the person doing the licking isn't immunised against hepatitis A or if the person being licked may have a bacterial or parasitic infection. Douching/enemas are an essential part of clean and comfortable anal sex, either penetrative (fingers, penis or dildo) or oral. Don't consider any anal contact with a partner who hasn't douched thoroughly beforehand. MUST KNOW **You can reduce this small risk even further by taking simple precautions: make sure your gums and lips/mouth/throat are healthy, i.e. without cuts, sores or abrasions; if you are uncertain of your partner's health status – don't let him ejaculate in your mouth – don't have cunnilingus while she is menstruating. Some people use condoms for oral sex as it is now thought that fellatio can, rarely, transmit HIV/AIDS. Some lesbians use latex dental dams as a barrier for safer cunnilingus.** Birth control NEED TO KNOW **For further advice on preventing infection and safer sex, see** **Want To Know More** **.** If birth control as well as health protection is an issue for you then condoms can be equally effective at preventing unwanted pregnancy. For additional protection consider natural birth control, the Pill, or another barrier method such as the cervical cap. want to know more? Take it to the next level... * * * Go to... Kissing the genitals * * * Other sources Internet www.netdoctor.co.uk Publications ABC of Sexually Transmitted Infections (ABC S.), Michael W. Adler, BMJ Books, 2004 * * * Glossary of terms **Anoragasmic** A person who is unable to have an orgasm. **Apadravyas** An ancient Indian sex toy that was fixed on or around the penis in order to keep it erect, or to increase its size. It has come to mean a particular type of genital piercing, but then it referred more to what we would call a cock ring. **Aphrodisiacs** These are passion stimulators: pills, potions or foods that increase libido. **Artha** Artha is the acquisition of arts, land, gold, cattle, wealth, equipages and friends. **Auparishtaka** Fellatio, or oral sex on a male partner. **Burton, Sir Richard** Sir Richard was a 19th century British explorer who spent many years in India. He had the texts of the Kama Sutra translated from Sanskrit into English. **Chakras** The chakras are the seven energy centres of the body, starting with the first chakra, which is linked to the sexual organs. In western thinking, the chakras correspond to various glands and systems of the body. **Champu** In many parts of the Indian subcontinent and Burma massage is referred to as 'champu'; origin of the English word 'shampoo'. **Clitoris** A small erectile part of the female genitals at the upper end of the vulva. **Cunnilingus** Oral sex on a female partner. **Dharma** Dharma is obedience to the command of the Shastras or Holy Writ of the Hindus. **Dildo** A sex toy to be used in place of a penis. **Erogenous zones** Parts of the body sensitive to sexual stimulation. **Ganika** A high-class courtesan in the ancient Indian court. **G-spot (female)** This is a spot on the inside of the front wall of the vagina, which, when firmly stimulated produces intense orgasms. **G-spot (male)** The prostate gland: a spot one and a half inches inside and above the anus toward the base of the penis, which when stimulated internally can give your partner a mind-blowing orgasm. **HIV** The Human Immuno-deficiency virus, either of two retroviruses causing AIDS (Acquired Immune Deficiency Syndrome). **Jaghana** The genitals. **Kama** The enjoyment of appropriate objects by the five senses of hearing, feeling, seeing, tasting and smelling, assisted by the mind together with the soul. **KS Physical attributes** The different physical attributes of men and women, categorized by size and sexual temperament: men are Hares, Bulls or Horses, women are Deer, Mares or Elephants. Many of the positions in the _Kama Sutra_ are designed to accommodate the needs of differently shaped and sized sexual partners. **Kantuka** The ancient Indian version of our strap on dildo. **Karezza** A tantric exercise in which men try to delay orgasm by pinpointing the moment at which orgasm is approaching but not yet beyond their control. **Kegel exercises** To tone and strengthen your genital muscles, particularly the PC muscle. The basic Kegel exercise – stopping the flow of urine in mid-stream until you can feel the muscles contract – is a good way to begin strengthening and controlling the PC muscles. **Key parties** A party, popular in the 1970s, in which each couple at a party drops their car keys into a bowl. Each woman has sex with the man whose keys she picks out of the bowl. **Kundalini Yoga** Kundalini means 'awareness' and this particular form of yoga, also called tantric yoga, practises raising awareness through the seven energy centres, or chakras. **Lingham** This is the name given to the male genitalia in the _Kama Sutra_. **Mahout** An elephant driver. **Mare's grip** Any 'jewel case' position (where the woman closes her legs after penetration). The woman will be able to hold her partner's penis tightly, increasing the pleasure of both partners. **Oral sex** A sexual practice in which the genitals of one person are stimulated by the mouth of another. **PC muscle** The PC, or pubococcygeus muscle, stretches between the legs from the genitals to the anus. It is part of the pelvic floor musculature in both women and men. It is a ribbed area about one and a half inches up on the back wall of the vagina in women and in a man the PC muscle runs from the pubic bone to the tailbone in a figure eight around the genitals. **Perineum** The area between the anus and the penis/vagina. The perineum and anal area is particularly sensitive in men, as this is the location of the prostate gland – the male G-spot. **Safer sex** Avoiding catching STDs - means not exchanging body fluids like semen or blood, which means that to be safer, sex is non-penetrative or done only while using a condom. However, because condoms can and do break, no penetrative (penis/vagina, penis/anus) sex can be guaranteed as completely 'safe'. **Shakti** In tantric practices Shakti is pure energy. Combined with his partner Shiva, they represent all existence in an erotic act of love that is a creative and unifying force. **Shiva** In tantric practices Shiva is the embodiment of pure consciousness. See Shakti. **STDs** Sexually Transmitted Diseases, such as gonhorrea, herpes and HIV/AIDS can be prevented if you practise safer sex. **Swinging** Swinging or husband/wife swapping includes sexual activities between a couple and (an)other couple(s)/ single(s) either in the same space or in different rooms/venues. **The 'lifestyle'** A way of life for a couple, which includes unexclusive sexual relationships, such as swinging, wife/husband swapping, key parties. **Vatsyayana, Mallanaga** Vatsyayana was an elderly religious devotee and Hindu sage who wrote the _Kama Sutra_ between the second and fourth centuries AD. **Viagra** A pill which helps men with erectile dysfunction to maintain an erection. **Yoni** This is the name given to female genitalia in the _Kama Sutra_. Need to Know More? **There is a wealth of further information available, particularly if you have access to the internet. Listed below are just a few of the organizations or resources that you might find useful.** **Useful websites** www.tantra.com General info on tantra and the _Kama Sutra_. www.kamasutrafree.com Information on positions and more. www.bibliomania.com The full text of the original _Kama Sutra_. www.annsummers.com Website of the sexy underwear people www.nicesextoys.com Pretty self-explanatory **Courses** **Diamond Light Tantra** PO Box 38204, London NW3 6YZ; tel: 08700 780 584 email: [email protected] **Sky Dancing Tantra** For information on dates and other details, please contact: tel: +44 (0) 1736 759519 email: [email protected] **Burren Yoga & Meditation Centre** Lig do Scith, Cappaghmore, Kinvara, County Galway, Ireland; tel: +353 (0)91 637680 email: [email protected] **Further reading** **Kama Sutra then and now:** _The Complete Illustrated Kama Sutra,_ Vatsyayana _,_ Lance Dane (Ed) (Inner Traditions International, 2003) _The Gay Man's Kama Sutra,_ Terry Sanderson (Carlton Books Limited, 2003) _Kama Sutra_ (Oxford World's Classics) Mallanaga Vatsyayana, et al, (Oxford University Press, June 2002) _Kama Sutra: the Arts of Love,_ Indra Sinha, Zek Halu and Misha Halu (Thorsons,1992) _The Kama Sutra of Vatsyayana in Pop-up,_ Sir Richard Burton (F.F. Arbuthnot, 2004) _The Lesbian Kama Sutra,_ Kat Harding (Carlton Books Limited, 2004) **Tantra:** _The Art of Sexual Magic: An Inspirational Guide to Tantric Sex That Will Transform Your Life,_ Margo Anand (Piatkus Books, 1995) _Healing with Form, Energy and Light: The Five Elements in Tibetan Shamanism, Tantra and Dzogchen,_ Tenzin Wangyal Rinpoche (Snow Lion Publications, 2002) _Secrets of Western Tantra: The Sexuality of the Middle Path,_ Christopher S. Hyatt (New Falcon Publications, 2004) _Tantra: The Art of Mind-blowing Sex,_ Val Sampson (Vermilion, 2004) _Tantric Orgasm for Women,_ Diana Richardson (Inner Traditions International, 2004) **Kundalini and Yoga:** _Chakras for Starters,_ Savitri Simpson, (Crystal Clarity Publications, 2002) _Kundalini and the Chakras: A Practical Manual - Evolution in This Lifetime,_ Genevieve Lewis Paulson (Llewellyn, 1991) _Kundalini Yoga for the West: A Foundation for Character Building, Courage and Awareness,_ Swami Sivananda Radha (Shambala Publications, 1994) _Open Your Heart with Kundalini Yoga,_ Sir i Datta (Thorsons, 2003) **General:** _Good Vibrations: The New Complete Guide to Vibrators,_ Joani Blank (Down There Press, 1999) _The Multi-orgasmic Man: All the Sexual Secrets That Every Man Should Know,_ Mantak Chia, et al (HarperCollins, 2001) _Perfect Love: Romance, Ecstasy and Higher Consciousness,_ D.J. Conway (Llewellyn, 1998) _Secrets of Western Sex Magic: Magical Energy and Gnostic Trance,_ Frater U.D. (Llewellyn, 2001) _Swinging for Beginners,_ Kaye Bellemeade (New Tradition Books, digital download available from Amazon) Aphrodisiacs and Fragrance: _Botanica Erotica: Arousing Body, Mind and Spirit,_ Diana De Luca (Inner Traditions International, 1998) _Herbal Love Potions: Aphrodisiac Array of Libido-lifting Potent Plants,_ William H. Lee and Lynn Lee (Keats Pub Inc., 1991) _Indian Aphrodisiacs,_ Dash B (Roli Books, 2001) _Natural Aphrodisiacs,_ Fiona Marshall (Vega, 2002) **Sexual Health:** _ABC of Sexually Transmitted Infections (ABC S.),_ Michael W. Adler (BMJ Books, 2004) **General reading:** _Ancient Cities of the Indus Valley Civilization,_ Jonathan Mark Kenoyer (OUP Pakistan, 1998) _Gem in the Lotus: The Seeding of Indian Civilisation,_ Abraham Eraly (Weidenfeld & Nicolson, 2004) _Indian Erotic Art (Pocket Art S.),_ Alka Pande (Roli Books, 2002) _Khajuraho (Monumental Legacy S.),_ Devangana Desai (OUP India, 2003) _India Discovered: The Recovery of a Lost Civilization,_ John Keay (HarperCollins, 2001) Searchable Terms **A** analingus anus and anal sex rimming safety sex toys aphrodisiacs attraction **B** bacterial infections basil, aphrodisiacs bathing beds birth control biting body, kissing bonobos breath control exercise Burton, Sir Richard **C** candles ceremony, lovemaking as chakras chlamydia chocolate clitoris clothes condoms Congress of a Crow contraception cunnilingus _see oral sex_ **D** daisy chain, group sex dildos double penetration, group sex douching drugs **E** ejaculation, controlling energy **F** face, kissing fantasies feelings, dealing with feet, washing fellatio _see oral sex_ Femidom fingernails food and drink furniture **G** G-spot genital warts genitals: exercising muscles kissing piercing ginseng gonorrhea group sex guarana **H** hands: fingernails massage health hepatitis A herbs, aphrodisiac herpes Hinduism HIV honouring your partner's sex horny goat weed hygiene **I** imagination, strengthening PC muscle impotence infections intention **K** Kama Sutra karezza Kegel exercises kissing kundalini energy **L** libido, low lighting love relationships 'love-seats' lubricants **M** magic ritual marking skin massage masturbation mouth, kissing mouth chain, group sex multiple orgasms music **N** nipples, piercing **O** oils, massage oral sex orgasm: controlling whole-body orgasms women **P** parties, group sex pelvic floor muscles penis: condoms oral sex piercing sex toys varying motions of perineum piercing positions 'the bee' 'beloved of love' 'cat' 'climbing a tree' 'cobra lock' 'deer' combination 'fixing of the nail' 'foot yoke' 'goddess of love's delight' group sex half reclining 'half-pressed' 'hanging serpent' 'jewel case' 'knee elbow' kneeling missionary 'lotus' 'love god's flag' man lying down 'milk and water' 'milk cow' missionary 'monkey' mutual seated 'piercing tiger' 'pressed' raised leg rear-entry standing 'suspended' tantric 'the seat of sport' seated Shakti '64' '69' 'sky foot' 'splitting the bamboo' 'spoons' standing 'suspended' 'the swan' 'swastika' 'throat high' 'thunderbolt' 'tiger's blow' 'the tongs' 'the top' 'tortoise' 'turned away' 'twining of a creeper' 'yawning' prostate gland pubococcygeus (PC) muscle **R** relaxation rhodiola rosea rimming ritual: lovemaking as magic to bring closeness **S** safer sex saw palmetto scratching semen, safer sex sex furniture sex toys sexually-transmitted infections Shakti sharing partners Shiva Shiva position Siberian ginseng side-by-side positions single people, tantra solo sex, tantra spirituality supplements syphilis **T** tantra enhancing awareness exercises kundalini energy learning lovemaking orgasm positions solo sex testicles, kissing thrush tongue, kissing **V** vagina: female condom oral sex Vatsyayana, Mallanaga vibrators **W** warts, genital washing wild yam woman on top position **Y** yoga, kundalini Copyright 10 09 08 07 06 05 8 7 6 5 4 3 2 1 Text © Dr J Rogiere 2005 Photography © John Freeman 2005 All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without the prior written permission of the publishers. A catalogue record for this book is available from the British Library Photographer: John Freeman, assisted by Irene Scioti and Alice Hiscoke Hair and make-up: Bettina Graham Style and art direction: John Freeman and Bettina Graham Editor: Terry Moore Designer: Grade Design Consultants All rights reserved under International and Pan-American Copyright Conventions. By payment of the required fees, you have been granted the nonexclusive, nontransferable right to access and read the text of this e-book on-screen. No part of this text may be reproduced, transmitted, downloaded, decompiled, reverse-engineered, or stored in or introduced into any information storage and retrieval system, in any form or by any means, whether electronic or mechanical, now known or hereinafter invented, without the express written permission of HarperCollins e-books. ISBN 9780007195824 EPub Edition © December 2011 ISBN: 9780007448289 About the Publisher Australia HarperCollins Publishers (Australia) Pty. Ltd. 25 Ryde Road (P.O. Box 321) Pymble, NSW 2073, Australia www.harpercollins.com.au/ebooks Canada HarperCollins Canada 2 Bloor Street East - 20th Floor Toronto, ON, M4W, 1A8, Canada <http://www.harpercollins.ca> New Zealand HarperCollins Publishers (New Zealand) Limited P.O. Box 1 Auckland, New Zealand <http://www.harpercollins.co.nz> United Kingdom HarperCollins Publishers Ltd. 77-85 Fulham Palace Road London, W6 8JB, UK <http://www.harpercollins.co.uk> United States HarperCollins Publishers Inc. 10 East 53rd Street New York, NY 10022 <http://www.harpercollins.com>
/** * Subscription on guava BUS. * * @param youTubeVideoAdded * new video added */ @Subscribe public void onYouTubeVideoCreation(Video youTubeVideoAdded) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("[NewVideoEvent] Processing for video {} ", youTubeVideoAdded.getVideoid()); } suggestedVideoDao.updateGraphNewVideo(youTubeVideoAdded); }
<gh_stars>1-10 import { TestData } from '../pages/testdata'; import { Panel } from '../pages/panel'; import { Graph } from '../pages/graph'; import { componentFactory } from '../support'; import { Dashboard } from '../pages/dashboard'; export const Components = { DataSource: { TestData, }, Panels: { Panel, Visualization: { Graph, }, }, Drawer: { General: componentFactory({ selectors: { title: (title: string) => `Drawer title ${title}`, expand: 'Drawer expand', contract: 'Drawer contract', close: 'Drawer close', rcContentWrapper: () => '.drawer-content-wrapper', }, }), }, PanelEditor: { General: componentFactory({ selectors: { content: 'Panel editor content', }, }), OptionsPane: componentFactory({ selectors: { content: 'Panel editor option pane content', close: Dashboard.selectors.toolbarItems('Close options pane'), open: Dashboard.selectors.toolbarItems('Open options pane'), select: 'Panel editor option pane select', }, }), // not sure about the naming *DataPane* DataPane: componentFactory({ selectors: { content: 'Panel editor data pane content', }, }), }, PanelInspector: { Data: componentFactory({ selectors: { content: 'Panel inspector Data content', }, }), Stats: componentFactory({ selectors: { content: 'Panel inspector Stats content', }, }), Json: componentFactory({ selectors: { content: 'Panel inspector Json content', }, }), Query: componentFactory({ selectors: { content: 'Panel inspector Query content', }, }), }, Tab: componentFactory({ selectors: { title: (title: string) => `Tab ${title}`, active: () => '[class*="-activeTabStyle"]', }, }), QueryTab: componentFactory({ selectors: { content: 'Query editor tab content', }, }), AlertTab: componentFactory({ selectors: { content: 'Alert editor tab content', }, }), TransformTab: componentFactory({ selectors: { content: 'Transform editor tab content', }, }), QueryEditorToolbarItem: componentFactory({ selectors: { button: (title: string) => `QueryEditor toolbar item button ${title}`, }, }), BackButton: componentFactory({ selectors: { backArrow: 'Go Back button', }, }), OptionsGroup: componentFactory({ selectors: { toggle: (title: string) => `Options group ${title}`, }, }), PluginVisualization: componentFactory({ selectors: { item: (title: string) => `Plugin visualization item ${title}`, current: () => '[class*="-currentVisualizationItem"]', }, }), Select: componentFactory({ selectors: { option: 'Select option', }, }), FieldConfigEditor: componentFactory({ selectors: { content: 'Field config editor content', }, }), OverridesConfigEditor: componentFactory({ selectors: { content: 'Field overrides editor content', }, }), };
/** * * @author Le Nhut Nam */ public class ServerMainForm extends javax.swing.JFrame { // Properties SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss a"); Thread thread; ServerThread serverThread; /** Chat List **/ public Vector socketList = new Vector(); public Vector clientList = new Vector(); /** File Sharing List **/ public Vector clientFileSharingUsername = new Vector(); public Vector clientFileSharingSocket = new Vector(); /** Server **/ ServerSocket server; /** * Creates new form MainForm */ public ServerMainForm() { initComponents(); } /** * * @param msg */ public void appendMessage(String msg){ Date date = new Date(); jTextAreaChatServerConsole.append(simpleDateFormat.format(date) + ": " + msg + "\n"); jTextAreaChatServerConsole.setCaretPosition(jTextAreaChatServerConsole.getText().length() - 1); } /** * * @param msg */ public void appendMessageVoiceChatConsole(String msg){ Date date = new Date(); jTextAreaVoiceChatConsole.append(simpleDateFormat.format(date) + ": " + msg + "\n"); jTextAreaVoiceChatConsole.setCaretPosition(jTextAreaVoiceChatConsole.getText().length() - 1); } /** * * @param msg */ public void appendMessageVideoChatConsole(String msg){ Date date = new Date(); jTextAreaVideoChatConsole.append(simpleDateFormat.format(date) + ": " + msg + "\n"); jTextAreaVideoChatConsole.setCaretPosition(jTextAreaVideoChatConsole.getText().length() - 1); } /** Setters **/ /** * * @param socket */ public void setSocketList(Socket socket){ try { socketList.add(socket); appendMessage("[setSocketList]: Added"); } catch (Exception exception) { appendMessage("[setSocketList]: " + exception.getMessage()); } } /** * * @param client */ public void setClientList(String client){ try { clientList.add(client); appendMessage("[setClientList]: Added"); } catch (Exception exception) { appendMessage("[setClientList]: " + exception.getMessage()); } } /** * * @param user */ public void setClientFileSharingUsername(String user){ try { clientFileSharingUsername.add(user); } catch (Exception exception) { System.out.println(exception.getMessage()); } } /** * * @param soc */ public void setClientFileSharingSocket(Socket soc){ try { clientFileSharingSocket.add(soc); } catch (Exception exception) { System.out.println(exception.getMessage()); } } /** Getters * * @param client * @return **/ public Socket getClientList(String client){ Socket tsoc = null; for(int i = 0; i < clientList.size(); i++){ if(clientList.get(i).equals(client)){ tsoc = (Socket) socketList.get(i); break; } } return tsoc; } /** * * @param client */ public void removeFromTheList(String client){ try { for(int i = 0; i < clientList.size(); i++){ if(clientList.elementAt(i).equals(client)){ clientList.removeElementAt(i); socketList.removeElementAt(i); appendMessage("[Removed]: " + client); break; } } } catch (Exception exception) { appendMessage("[RemovedException]: " + exception.getMessage()); } } /** * * @param username * @return */ public Socket getClientFileSharingSocket(String username){ Socket tsoc = null; for(int i = 0; i < clientFileSharingUsername.size(); i++){ if(clientFileSharingUsername.elementAt(i).equals(username)){ tsoc = (Socket) clientFileSharingSocket.elementAt(i); break; } } return tsoc; } /* Remove Client File Sharing List */ /** * * @param username */ public void removeClientFileSharing(String username){ for(int i = 0; i < clientFileSharingUsername.size(); i++){ if(clientFileSharingUsername.elementAt(i).equals(username)){ try { Socket rSock = getClientFileSharingSocket(username); if(rSock != null){ rSock.close(); } clientFileSharingUsername.removeElementAt(i); clientFileSharingSocket.removeElementAt(i); appendMessage("[FileSharing]: Removed "+ username); } catch (IOException iOException) { appendMessage("[FileSharing]: " + iOException.getMessage()); appendMessage("[FileSharing]: Unable to Remove "+ username); } break; } } } /** * * @return */ String getIPAddress(){ return jSpinnerFirstByte.getValue().toString() + "." + jSpinnerSecondByte.getValue().toString() + "." +jSpinnerThirdByte.getValue().toString() + "." + jSpinnerFourthByte.getValue().toString(); } /** * * @return */ private Integer getPort(){ return (Integer) jSpinnerPortNumber.getValue(); } /** * * @return */ String getIPAddressVoiceChatServerControl(){ return jSpinnerFirstByteIpVoiceChat.getValue().toString() + "." + jSpinnerSecondByteIpVoiceChat.getValue().toString() + "." +jSpinnerThirdByteIpVoiceChat.getValue().toString() + "." + jSpinnerFourthByteIpVoiceChat.getValue().toString(); } /** * * @return */ private Integer getPortVoiceChatServerControl(){ return (Integer) jSpinnerPortNumberVoiceChat.getValue(); } /** * * @return */ String getIPAddressVideoChatServerControl(){ return jSpinnerFirstByteIpVideoChat.getValue().toString() + "." + jSpinnerSecondByteIpVideoChat.getValue().toString() + "." +jSpinnerThirdByteIpVideoChat.getValue().toString() + "." + jSpinnerFourthByteIpVideoChat.getValue().toString(); } /** * * @return */ private Integer getPortVideoChatServerControl(){ return (Integer) jSpinnerPortNumberVideoChat.getValue(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jButtonStartChatServer = new javax.swing.JButton(); jButtonStopChatServer = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextAreaChatServerConsole = new javax.swing.JTextArea(); jButtonTestChatServer = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jSpinnerFirstByte = new javax.swing.JSpinner(); jSpinnerSecondByte = new javax.swing.JSpinner(); jSpinnerThirdByte = new javax.swing.JSpinner(); jSpinnerFourthByte = new javax.swing.JSpinner(); jSpinnerPortNumber = new javax.swing.JSpinner(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jSpinnerFirstByteIpVoiceChat = new javax.swing.JSpinner(); jSpinnerSecondByteIpVoiceChat = new javax.swing.JSpinner(); jSpinnerThirdByteIpVoiceChat = new javax.swing.JSpinner(); jSpinnerFourthByteIpVoiceChat = new javax.swing.JSpinner(); jLabel6 = new javax.swing.JLabel(); jSpinnerPortNumberVoiceChat = new javax.swing.JSpinner(); jScrollPane2 = new javax.swing.JScrollPane(); jTextAreaVoiceChatConsole = new javax.swing.JTextArea(); jButtonStartVoiceChatServer = new javax.swing.JButton(); jButtonTestVoiceChatServer = new javax.swing.JButton(); jButtonStopVoiceChatServer = new javax.swing.JButton(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jSpinnerFirstByteIpVideoChat = new javax.swing.JSpinner(); jSpinnerSecondByteIpVideoChat = new javax.swing.JSpinner(); jSpinnerThirdByteIpVideoChat = new javax.swing.JSpinner(); jSpinnerFourthByteIpVideoChat = new javax.swing.JSpinner(); jLabel9 = new javax.swing.JLabel(); jSpinnerPortNumberVideoChat = new javax.swing.JSpinner(); jButtonVideoChatStartServer = new javax.swing.JButton(); jButtonTestVideoChatServer = new javax.swing.JButton(); jButtonStopVideoServer = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); jTextAreaVideoChatConsole = new javax.swing.JTextArea(); jLabel10 = new javax.swing.JLabel(); jLabel24 = new javax.swing.JLabel(); jLabel25 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenu2 = new javax.swing.JMenu(); jMenuItem3 = new javax.swing.JMenuItem(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuAboutServer = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Server Control Panel"); setBackground(new java.awt.Color(255, 255, 255)); setResizable(false); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jButtonStartChatServer.setBackground(new java.awt.Color(0, 102, 255)); jButtonStartChatServer.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jButtonStartChatServer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8-start-24.png"))); // NOI18N jButtonStartChatServer.setText("Start Server"); jButtonStartChatServer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonStartChatServerActionPerformed(evt); } }); jButtonStopChatServer.setBackground(new java.awt.Color(255, 51, 51)); jButtonStopChatServer.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jButtonStopChatServer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8-stop-sign-24.png"))); // NOI18N jButtonStopChatServer.setText("Stop Server"); jButtonStopChatServer.setEnabled(false); jButtonStopChatServer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonStopChatServerActionPerformed(evt); } }); jTextAreaChatServerConsole.setEditable(false); jTextAreaChatServerConsole.setBackground(new java.awt.Color(0, 0, 0)); jTextAreaChatServerConsole.setColumns(20); jTextAreaChatServerConsole.setFont(new java.awt.Font("Consolas", 0, 13)); // NOI18N jTextAreaChatServerConsole.setForeground(new java.awt.Color(51, 255, 0)); jTextAreaChatServerConsole.setRows(5); jTextAreaChatServerConsole.setPreferredSize(null); jScrollPane1.setViewportView(jTextAreaChatServerConsole); jButtonTestChatServer.setBackground(new java.awt.Color(204, 204, 0)); jButtonTestChatServer.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jButtonTestChatServer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8-test-program-24.png"))); // NOI18N jButtonTestChatServer.setText("Test Server"); jButtonTestChatServer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonTestChatServerActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jLabel1.setText("IP Address"); jLabel2.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jLabel2.setText("Port Number"); jSpinnerFirstByte.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerFirstByte.setModel(new javax.swing.SpinnerNumberModel(127, 0, 255, 1)); jSpinnerSecondByte.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerSecondByte.setModel(new javax.swing.SpinnerNumberModel(0, 0, 255, 1)); jSpinnerThirdByte.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerThirdByte.setModel(new javax.swing.SpinnerNumberModel(0, 0, 255, 1)); jSpinnerFourthByte.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerFourthByte.setModel(new javax.swing.SpinnerNumberModel(1, 0, 255, 1)); jSpinnerPortNumber.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerPortNumber.setModel(new javax.swing.SpinnerNumberModel(4000, 1, 65536, 1)); jLabel3.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 18)); // NOI18N jLabel3.setText("Voice Chat control area"); jLabel4.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 18)); // NOI18N jLabel4.setText("Chat control area"); jLabel5.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jLabel5.setText("IP Address"); jSpinnerFirstByteIpVoiceChat.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerFirstByteIpVoiceChat.setModel(new javax.swing.SpinnerNumberModel(127, 0, 255, 1)); jSpinnerSecondByteIpVoiceChat.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerSecondByteIpVoiceChat.setModel(new javax.swing.SpinnerNumberModel(0, 0, 255, 1)); jSpinnerThirdByteIpVoiceChat.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerThirdByteIpVoiceChat.setModel(new javax.swing.SpinnerNumberModel(0, 0, 255, 1)); jSpinnerFourthByteIpVoiceChat.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerFourthByteIpVoiceChat.setModel(new javax.swing.SpinnerNumberModel(1, 0, 255, 1)); jLabel6.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jLabel6.setText("Port Number"); jSpinnerPortNumberVoiceChat.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerPortNumberVoiceChat.setModel(new javax.swing.SpinnerNumberModel(4006, 1, 65536, 1)); jTextAreaVoiceChatConsole.setEditable(false); jTextAreaVoiceChatConsole.setBackground(new java.awt.Color(0, 0, 0)); jTextAreaVoiceChatConsole.setColumns(20); jTextAreaVoiceChatConsole.setFont(new java.awt.Font("Consolas", 0, 13)); // NOI18N jTextAreaVoiceChatConsole.setForeground(new java.awt.Color(51, 255, 0)); jTextAreaVoiceChatConsole.setRows(5); jScrollPane2.setViewportView(jTextAreaVoiceChatConsole); jButtonStartVoiceChatServer.setBackground(new java.awt.Color(0, 102, 255)); jButtonStartVoiceChatServer.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jButtonStartVoiceChatServer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8-start-24.png"))); // NOI18N jButtonStartVoiceChatServer.setText("Start Server"); jButtonStartVoiceChatServer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonStartVoiceChatServerActionPerformed(evt); } }); jButtonTestVoiceChatServer.setBackground(new java.awt.Color(204, 204, 0)); jButtonTestVoiceChatServer.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jButtonTestVoiceChatServer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8-test-program-24.png"))); // NOI18N jButtonTestVoiceChatServer.setText("Test Server"); jButtonTestVoiceChatServer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonTestVoiceChatServerActionPerformed(evt); } }); jButtonStopVoiceChatServer.setBackground(new java.awt.Color(255, 51, 51)); jButtonStopVoiceChatServer.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jButtonStopVoiceChatServer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8-stop-sign-24.png"))); // NOI18N jButtonStopVoiceChatServer.setText("Stop Server"); jButtonStopVoiceChatServer.setEnabled(false); jButtonStopVoiceChatServer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonStopVoiceChatServerActionPerformed(evt); } }); jLabel7.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 18)); // NOI18N jLabel7.setText("Video Chat control area"); jLabel8.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jLabel8.setText("IP Address"); jSpinnerFirstByteIpVideoChat.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerFirstByteIpVideoChat.setModel(new javax.swing.SpinnerNumberModel(127, 0, 255, 1)); jSpinnerSecondByteIpVideoChat.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerSecondByteIpVideoChat.setModel(new javax.swing.SpinnerNumberModel(0, 0, 255, 1)); jSpinnerThirdByteIpVideoChat.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerThirdByteIpVideoChat.setModel(new javax.swing.SpinnerNumberModel(0, 0, 255, 1)); jSpinnerFourthByteIpVideoChat.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerFourthByteIpVideoChat.setModel(new javax.swing.SpinnerNumberModel(1, 0, 255, 1)); jLabel9.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jLabel9.setText("Port Number"); jSpinnerPortNumberVideoChat.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 13)); // NOI18N jSpinnerPortNumberVideoChat.setModel(new javax.swing.SpinnerNumberModel(4007, 1, 65536, 1)); jButtonVideoChatStartServer.setBackground(new java.awt.Color(0, 102, 255)); jButtonVideoChatStartServer.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jButtonVideoChatStartServer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8-start-24.png"))); // NOI18N jButtonVideoChatStartServer.setText("Start Server"); jButtonVideoChatStartServer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonVideoChatStartServerActionPerformed(evt); } }); jButtonTestVideoChatServer.setBackground(new java.awt.Color(204, 204, 0)); jButtonTestVideoChatServer.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jButtonTestVideoChatServer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8-test-program-24.png"))); // NOI18N jButtonTestVideoChatServer.setText("Test Server"); jButtonTestVideoChatServer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonTestVideoChatServerActionPerformed(evt); } }); jButtonStopVideoServer.setBackground(new java.awt.Color(255, 51, 51)); jButtonStopVideoServer.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jButtonStopVideoServer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8-stop-sign-24.png"))); // NOI18N jButtonStopVideoServer.setText("Stop Server"); jButtonStopVideoServer.setEnabled(false); jButtonStopVideoServer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonStopVideoServerActionPerformed(evt); } }); jTextAreaVideoChatConsole.setEditable(false); jTextAreaVideoChatConsole.setBackground(new java.awt.Color(0, 0, 0)); jTextAreaVideoChatConsole.setColumns(20); jTextAreaVideoChatConsole.setFont(new java.awt.Font("Consolas", 0, 13)); // NOI18N jTextAreaVideoChatConsole.setForeground(new java.awt.Color(51, 255, 0)); jTextAreaVideoChatConsole.setRows(5); jScrollPane3.setViewportView(jTextAreaVideoChatConsole); jLabel10.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 18)); // NOI18N jLabel10.setText("Development Information"); jLabel24.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jLabel24.setText("Java 8 - Apache Netbeans 12 LTS"); jLabel25.setFont(new java.awt.Font("DejaVu Sans Condensed", 0, 14)); // NOI18N jLabel25.setText("2020 (c) Open Source"); jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/fit-hcmus-150.png"))); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel6) .addGap(20, 20, 20) .addComponent(jSpinnerPortNumberVoiceChat, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButtonStartVoiceChatServer) .addGap(18, 18, 18) .addComponent(jButtonTestVoiceChatServer) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonStopVoiceChatServer)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addComponent(jSpinnerFirstByteIpVoiceChat, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jSpinnerSecondByteIpVoiceChat, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addComponent(jSpinnerThirdByteIpVoiceChat, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addComponent(jSpinnerFourthByteIpVoiceChat, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)))))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(10, 10, 10) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addGap(20, 20, 20) .addComponent(jSpinnerPortNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButtonStartChatServer) .addGap(18, 18, 18) .addComponent(jButtonTestChatServer) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonStopChatServer)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addComponent(jSpinnerFirstByte, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addComponent(jSpinnerSecondByte, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addComponent(jSpinnerThirdByte, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(20, 20, 20) .addComponent(jSpinnerFourthByte, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)))) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel9) .addGap(18, 18, 18) .addComponent(jSpinnerPortNumberVideoChat, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addComponent(jButtonVideoChatStartServer) .addGap(18, 18, 18) .addComponent(jButtonTestVideoChatServer) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButtonStopVideoServer, javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel7) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addComponent(jSpinnerFirstByteIpVideoChat, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addComponent(jSpinnerSecondByteIpVideoChat, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addComponent(jSpinnerThirdByteIpVideoChat, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addComponent(jSpinnerFourthByteIpVideoChat, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE))) .addGap(10, 10, 10)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 631, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel10) .addComponent(jLabel24) .addComponent(jLabel25)) .addGap(18, 18, 18) .addComponent(jLabel11) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(29, 29, 29) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSpinnerFirstByte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSpinnerSecondByte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSpinnerThirdByte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSpinnerFourthByte, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(8, 8, 8) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jSpinnerPortNumber) .addComponent(jButtonStartChatServer) .addComponent(jButtonTestChatServer) .addComponent(jButtonStopChatServer) .addComponent(jButtonVideoChatStartServer)) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(33, 33, 33) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSpinnerFirstByteIpVideoChat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSpinnerSecondByteIpVideoChat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSpinnerThirdByteIpVideoChat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSpinnerFourthByteIpVideoChat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonTestVideoChatServer) .addComponent(jButtonStopVideoServer))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSpinnerPortNumberVideoChat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSpinnerFirstByteIpVoiceChat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSpinnerSecondByteIpVoiceChat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSpinnerThirdByteIpVoiceChat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSpinnerFourthByteIpVoiceChat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(8, 8, 8) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jSpinnerPortNumberVoiceChat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonStartVoiceChatServer) .addComponent(jButtonTestVoiceChatServer) .addComponent(jButtonStopVoiceChatServer) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 264, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel11) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel24, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel25, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jMenu1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8-administrative-tools-24.png"))); // NOI18N jMenu1.setText("Tools"); jMenuBar1.add(jMenu1); jMenu2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8-contact-us-24.png"))); // NOI18N jMenu2.setText("Contacts"); jMenuItem3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8-documents-24.png"))); // NOI18N jMenuItem3.setText("Online docs"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu2.add(jMenuItem3); jMenuItem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8-help-24.png"))); // NOI18N jMenuItem1.setText("Help & Support"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu2.add(jMenuItem1); jMenuAboutServer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/icons8-about-24.png"))); // NOI18N jMenuAboutServer.setText("About"); jMenuAboutServer.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuAboutServerActionPerformed(evt); } }); jMenu2.add(jMenuAboutServer); jMenuBar1.add(jMenu2); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jButtonStartChatServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStartChatServerActionPerformed // TODO add your handling code here: int port = this.getPort(); serverThread = new ServerThread(port, this); thread = new Thread(serverThread); thread.start(); new Thread(new OnlineListThread(this)).start(); jButtonStartChatServer.setEnabled(false); jButtonTestChatServer.setEnabled(false); jButtonStopChatServer.setEnabled(true); }//GEN-LAST:event_jButtonStartChatServerActionPerformed private void jButtonStopChatServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStopChatServerActionPerformed // TODO add your handling code here: int confirm = JOptionPane.showConfirmDialog(null, "Close Server.?"); if(confirm == 0){ serverThread.stop(); } jButtonStartChatServer.setEnabled(true); jButtonTestChatServer.setEnabled(true); jButtonStopChatServer.setEnabled(false); }//GEN-LAST:event_jButtonStopChatServerActionPerformed private void jButtonTestChatServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTestChatServerActionPerformed // TODO add your handling code here: int port = this.getPort(); String ip = this.getIPAddress(); appendMessage("[Server]: Prepare running at " + ip + " in port " + port); }//GEN-LAST:event_jButtonTestChatServerActionPerformed private void jButtonStartVoiceChatServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStartVoiceChatServerActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButtonStartVoiceChatServerActionPerformed private void jButtonTestVoiceChatServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTestVoiceChatServerActionPerformed // TODO add your handling code here: int port = this.getPortVoiceChatServerControl(); String ip = this.getIPAddressVoiceChatServerControl(); appendMessageVoiceChatConsole("[Voice Server]: Prepare running at " + ip + " in port " + port); }//GEN-LAST:event_jButtonTestVoiceChatServerActionPerformed private void jButtonStopVoiceChatServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStopVoiceChatServerActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButtonStopVoiceChatServerActionPerformed private void jButtonVideoChatStartServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonVideoChatStartServerActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButtonVideoChatStartServerActionPerformed private void jButtonTestVideoChatServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTestVideoChatServerActionPerformed // TODO add your handling code here: int port = this.getPortVideoChatServerControl(); String ip = this.getIPAddressVideoChatServerControl(); appendMessageVideoChatConsole("[Video Server]: Prepare running at " + ip + " in port " + port); }//GEN-LAST:event_jButtonTestVideoChatServerActionPerformed private void jButtonStopVideoServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStopVideoServerActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButtonStopVideoServerActionPerformed private void jMenuAboutServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuAboutServerActionPerformed // TODO add your handling code here: String information = "Coder: Le Nhut Nam\nChat App Project (c) July 2020\nMIT License\nOpen Source"; JOptionPane.showMessageDialog(this, information, "About", JOptionPane.DEFAULT_OPTION); }//GEN-LAST:event_jMenuAboutServerActionPerformed private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed // TODO add your handling code here: if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { try { try { Desktop.getDesktop().browse(new URI("https://lenhutnam298.github.io/chat-app/index.html")); } catch (IOException ex) { Logger.getLogger(ServerMainForm.class.getName()).log(Level.SEVERE, null, ex); } } catch (URISyntaxException ex) { Logger.getLogger(ServerMainForm.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_jMenuItem3ActionPerformed private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jMenuItem1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException classNotFoundException) { java.util.logging.Logger.getLogger(ServerMainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, classNotFoundException); } catch (InstantiationException instantiationException) { java.util.logging.Logger.getLogger(ServerMainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, instantiationException); } catch (IllegalAccessException illegalAccessException) { java.util.logging.Logger.getLogger(ServerMainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, illegalAccessException); } catch (javax.swing.UnsupportedLookAndFeelException unsupportedLookAndFeelException) { java.util.logging.Logger.getLogger(ServerMainForm.class.getName()).log(java.util.logging.Level.SEVERE, null, unsupportedLookAndFeelException); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { ServerMainForm serverMainForm = new ServerMainForm(); ImageIcon img = new ImageIcon("src/icons/icons8-server-96.png"); serverMainForm.setIconImage(img.getImage()); serverMainForm.setLocationRelativeTo(null);; serverMainForm.setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonStartChatServer; private javax.swing.JButton jButtonStartVoiceChatServer; private javax.swing.JButton jButtonStopChatServer; private javax.swing.JButton jButtonStopVideoServer; private javax.swing.JButton jButtonStopVoiceChatServer; private javax.swing.JButton jButtonTestChatServer; private javax.swing.JButton jButtonTestVideoChatServer; private javax.swing.JButton jButtonTestVoiceChatServer; private javax.swing.JButton jButtonVideoChatStartServer; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JMenu jMenu1; private javax.swing.JMenu jMenu2; private javax.swing.JMenuItem jMenuAboutServer; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JSpinner jSpinnerFirstByte; private javax.swing.JSpinner jSpinnerFirstByteIpVideoChat; private javax.swing.JSpinner jSpinnerFirstByteIpVoiceChat; private javax.swing.JSpinner jSpinnerFourthByte; private javax.swing.JSpinner jSpinnerFourthByteIpVideoChat; private javax.swing.JSpinner jSpinnerFourthByteIpVoiceChat; private javax.swing.JSpinner jSpinnerPortNumber; private javax.swing.JSpinner jSpinnerPortNumberVideoChat; private javax.swing.JSpinner jSpinnerPortNumberVoiceChat; private javax.swing.JSpinner jSpinnerSecondByte; private javax.swing.JSpinner jSpinnerSecondByteIpVideoChat; private javax.swing.JSpinner jSpinnerSecondByteIpVoiceChat; private javax.swing.JSpinner jSpinnerThirdByte; private javax.swing.JSpinner jSpinnerThirdByteIpVideoChat; private javax.swing.JSpinner jSpinnerThirdByteIpVoiceChat; private javax.swing.JTextArea jTextAreaChatServerConsole; private javax.swing.JTextArea jTextAreaVideoChatConsole; private javax.swing.JTextArea jTextAreaVoiceChatConsole; // End of variables declaration//GEN-END:variables }
//! ## Memory Layout //! //! ```ignore //! +-------+-------------+------------+--------------+---------------+----------+ //! | ... | Dynamic (1) | Static (2) | FP (3) (i32) | Constant Pool | Heap ... | //! o-------o-------------o------------+--------------o---------------o----------+ //! | | | | | //! index 0 SP FP Stack Base Heap Base //! ``` //! Since WebAssembly's Memory Instruction cannot take negative values for offsets, the address //! calculation should be designed so that it can be calculated by adding positive values. //! //! - (1) Dynamically allocated memory on the stack. //! - (2) Statically allocated memory on the stack. The size of this area is known at compile time. //! - (3) Caller's FP = Load(FP + sizeof(Static)) //! Caller's SP = FP + sizeof(Static) + sizeof(FP) //! //! ### Global Context Registers //! //! Global variables that are shared by multiple execution contexts. //! //! - **Stack Pointer (SP)** - Stack pointer. End of stack. //! - **Stack Base** - Start index of the virtual stack segment. The virtual stack extends in //! the negative direction. If the access is out of range, it will be trapped in the host environment. //! - **Heap Base** - Start index of the heap segment. The heap extends in the positive direction. //! If the access is out of range, it will be trapped in the host environment. //! //! ### Execution Context Registers //! //! Run-time context allocated in global variables. We should be able to switch between multiple //! execution contexts by saving them somewhere. //! //! - **Frame Pointer (FP)** - The frame pointer of the current function. //! //! ### Virtual Stack Segment //! //! Unlike WebAssembly's value stack, it is placed in a contiguous memory area and a frame is //! allocated for each function call. //! //! - When the closure is introduced, we will secure not only the FP of the caller, //! but also the FP of the function where a closure is defined. //! - Can it be laid out well so that variables that are not referenced by the closure can be discarded? //! //! ### Constant Pool //! //! This is the area of the object whose size is determined at compile time and survives throughout //! the execution of the program, starting at Stack Base and extending in the positive direction to Heap Base. //! //! ### Heap //! //! A memory area for dynamically allocated objects. How to manage the memory is still under consideration. pub mod allocator; pub mod emitter; pub mod wasm; use crate::sem::Type; use crate::util::naming::PrefixNaming; pub use allocator::Allocator; pub use emitter::AsmBuilder; use std::cell::RefCell; use std::convert::TryFrom; use std::rc::Rc; /// Memory alignment const ALIGNMENT: wasm::Size = wasm::SIZE_BYTES; #[inline] fn align(n: wasm::Size) -> wasm::Size { let m = n / ALIGNMENT; let a = ALIGNMENT * m; if a < n { ALIGNMENT * (m + 1) } else { a } } fn wasm_type(ty: &Rc<RefCell<Type>>) -> Option<wasm::Type> { match *ty.borrow() { Type::Int32 => Some(wasm::Type::I32), Type::Boolean => Some(wasm::Type::I32), Type::String => Some(wasm::Type::I32), Type::Void => None, Type::Array(_) => Some(wasm::Type::I32), Type::Struct { .. } => Some(wasm::Type::I32), _ => panic!("Type `{}` can't be resolved to WASM type.", ty.borrow()), } } #[derive(Debug, Default)] pub struct StackFrame { sizes: Vec<wasm::Size>, } impl StackFrame { /// Reserve memory in "Static" on the stack. pub fn reserve(&mut self, size: wasm::Size) { self.sizes.push(size); } /// Returns the total size of "Static" on the stack. pub fn static_size(&self) -> wasm::Size { align(self.sizes.iter().sum()) } } /// The struct *LocalStorage* represents name and type for local variables and /// function parameters. /// This struct can be cloned because the name of storage will be unchanged. #[derive(Debug, PartialEq)] pub enum Storage { LocalVariable(LocalVariable), Function(Function), } #[derive(Debug, PartialEq, Clone)] pub struct LocalVariable { name: String, r#type: wasm::Type, } #[derive(Debug, PartialEq)] pub struct Function { name: String, function_type: Rc<RefCell<Type>>, } impl Storage { pub fn function<S: Into<String>>(name: S, r#type: &Rc<RefCell<Type>>) -> Self { if let Type::Function { .. } = *r#type.borrow() { Self::Function(Function { name: name.into(), function_type: Rc::clone(r#type), }) } else { panic!("Can't create Storage::Function with {}", r#type.borrow()); } } pub fn local_variable<S: Into<String>>(name: S, r#type: &Rc<RefCell<Type>>) -> Self { Self::LocalVariable(LocalVariable { name: name.into(), r#type: wasm_type(r#type).unwrap(), }) } pub fn unwrap_function(&self) -> &Function { match self { Storage::Function(fun) => fun, _ => panic!("storage must be a function"), } } pub fn unwrap_local_variable(&self) -> &LocalVariable { match self { Storage::LocalVariable(var) => var, _ => panic!("storage must be a local variable"), } } } /// This structure allocates required local/temporary variables within a WASM function frame. /// It manages the scope and allocates the minimum number of local variables required in /// a function frame. #[derive(Debug)] pub struct LocalVariables { i32_naming: PrefixNaming, // Free - temporary variables not used in active scopes, but reserved for a function. free: Vec<Rc<Storage>>, // Used - used temporary variables stack. The top of stack is the current scope. They will be // reclaimed when a scope terminated, and moved to free list. used: Vec<Vec<Rc<Storage>>>, } impl LocalVariables { // To avoid collision with other variables, specify special prefix (e.g. ".") // $.i32.0, $.i32.1, ... pub fn new(prefix: &str) -> Self { Self { i32_naming: PrefixNaming::new(&format!("{}i32.", prefix)), free: vec![], used: vec![], } } pub fn variables(&self) -> &Vec<Rc<Storage>> { &self.free } pub fn push_scope(&mut self) { self.used.push(vec![]); } pub fn pop_scope(&mut self) { if let Some(used) = self.used.pop() { for var in used { self.free.push(var); } } } pub fn reserve(&mut self, ty: &Rc<RefCell<Type>>) -> Rc<Storage> { let wasm_type = wasm_type(ty); if let Some(wasm::Type::I32) = wasm_type { self.reserve_i32() } else { panic!("unsupported type {}", ty.borrow()); } } pub fn reserve_i32(&mut self) -> Rc<Storage> { let used_scope = self.used.last_mut().expect("empty scope stack"); let index = self .free .iter() .map(|x| x.unwrap_local_variable()) .position(|x| x.r#type == wasm::Type::I32); let var = if let Some(index) = index { self.free.swap_remove(index) } else { let name = self.i32_naming.next(); Rc::new(Storage::LocalVariable(LocalVariable { name, r#type: wasm::Type::I32, })) }; used_scope.push(Rc::clone(&var)); var } pub fn reserve_name_i32(&mut self) -> String { let var = self.reserve_i32(); var.unwrap_local_variable().name.clone() } } /// String literal allocation in constant pool that is allocated at compile time. /// /// ```ignore /// +----------------------------+----------------------------+---------------------+ /// | Reference | Object | /// +----------------------------+----------------------------+---------------------+ /// | index (u32 little endian) | length (u32 little endian) | UTF-8 byte sequence | /// +----------------------------+----------------------------+---------------------+ /// ``` /// - `index` is **absolute index in the memory**. It points to the beginning of UTF-8 bytes. /// - `length` is the number of UTF-8 bytes only. /// #[derive(Debug, PartialEq)] pub struct ConstantString { content: String, // the largest amount of memory possible with 32-bit pointers, // which is what WebAssembly currently supports offset: wasm::Size, } #[allow(clippy::len_without_is_empty)] impl ConstantString { pub fn from_str(content: &str, offset: wasm::Size) -> Self { Self { content: content.to_string(), offset, } } /// Returns memory offset. /// /// ## Examples /// /// ``` /// # use nico::asm::ConstantString; /// let s = ConstantString::from_str("", 0); /// assert_eq!(s.offset(), 0) /// ``` pub fn offset(&self) -> u32 { self.offset } /// Returns the number of bytes of reference and UTF-8 bytes /// including memory alignment. pub fn memory_size(&self) -> wasm::Size { let len = self.content.as_bytes().len(); align( wasm::SIZE_BYTES + // offset wasm::SIZE_BYTES + // length wasm::Size::try_from(len).unwrap(), // UTF-8 bytes ) } pub fn bytes(&self, base: wasm::Size) -> Vec<u8> { let bytes = self.content.as_bytes(); let offset = (base + self.offset + wasm::SIZE_BYTES + wasm::SIZE_BYTES).to_le_bytes(); let length = (wasm::Size::try_from(bytes.len()).unwrap()).to_le_bytes(); offset .iter() .chain(length.iter()) .chain(bytes.iter()) .copied() .collect::<Vec<_>>() } } #[cfg(test)] mod tests { use super::*; use std::collections::HashSet; #[test] fn empty_string() { let s = ConstantString::from_str("", 0); assert_eq!(s.offset(), 0); assert_eq!(s.memory_size(), 8); assert_eq!(s.bytes(0), [0x8, 0, 0, 0, 0, 0, 0, 0]); } #[test] fn some_string() { let s = ConstantString::from_str("123", 0); assert_eq!(s.offset(), 0); assert_eq!(s.memory_size(), 12); assert_eq!( s.bytes(1), [0x9, 0, 0, 0, 0x3, 0, 0, 0, '1' as u8, '2' as u8, '3' as u8] ); } #[test] fn local_variables_empty() { let mut locals = LocalVariables::new("."); locals.push_scope(); locals.pop_scope(); assert!(locals.variables().is_empty()); } #[test] fn local_variables() { let mut locals = LocalVariables::new("."); { locals.push_scope(); let var1 = locals.reserve_i32(); let var2 = locals.reserve_i32(); assert_ne!( var1.unwrap_local_variable().name, var2.unwrap_local_variable().name ); locals.pop_scope(); } { locals.push_scope(); let var3 = locals.reserve_i32(); let var4 = locals.reserve_i32(); assert_ne!( var3.unwrap_local_variable().name, var4.unwrap_local_variable().name ); { locals.push_scope(); locals.reserve_i32(); locals.pop_scope(); } locals.pop_scope(); } let vars = locals.variables(); let mut names = HashSet::new(); for var in vars { let name = var.unwrap_local_variable().name.clone(); assert!(!names.contains(&name)); names.insert(name); } assert_eq!(vars.len(), 3); } }
// handler for the main page func homeHandler(response http.ResponseWriter, request *http.Request) { response.Header().Set("Content-type", "text/html") webpage, err := ioutil.ReadFile("home.html") if err != nil { http.Error(response, fmt.Sprintf("home.html file error %v", err), 500) } fmt.Fprint(response, string(webpage)) }
/** * Pushes the queued client ops into the unacked ops, clearing the queued ops. * @return see {@link #unackedClientOps()} */ public List<M> pushQueuedOpsToUnacked() { Preconditions.checkState(unackedClientOps.isEmpty(), "Queue contains unacknowledged operations: %s", unackedClientOps); unackedClientOps = new LinkedList<M>(transformer.compact(queuedClientOps)); queuedClientOps = new LinkedList<M>(); return unackedClientOps(); }
<reponame>Eric-Arellano/rust<filename>src/test/ui/issues/issue-8709.rs // run-pass macro_rules! sty { ($t:ty) => (stringify!($t)) } macro_rules! spath { ($t:path) => (stringify!($t)) } fn main() { assert_eq!(sty!(isize), "isize"); assert_eq!(spath!(std::option), "std::option"); }
Autologous chondrocyte implantation versus matrix-induced autologous chondrocyte implantation for osteochondral defects of the knee: a prospective, randomised study. Autologous chondrocyte implantation (ACI) is used widely as a treatment for symptomatic chondral and osteochondral defects of the knee. Variations of the original periosteum-cover technique include the use of porcine-derived type I/type III collagen as a cover (ACI-C) and matrix-induced autologous chondrocyte implantation (MACI) using a collagen bilayer seeded with chondrocytes. We have performed a prospective, randomised comparison of ACI-C and MACI for the treatment of symptomatic chondral defects of the knee in 91 patients, of whom 44 received ACI-C and 47 MACI grafts. Both treatments resulted in improvement of the clinical score after one year. The mean modified Cincinnati knee score increased by 17.6 in the ACI-C group and 19.6 in the MACI group (p = 0.32). Arthroscopic assessments performed after one year showed a good to excellent International Cartilage Repair Society score in 79.2% of ACI-C and 66.6% of MACI grafts. Hyaline-like cartilage or hyaline-like cartilage with fibrocartilage was found in the biopsies of 43.9% of the ACI-C and 36.4% of the MACI grafts after one year. The rate of hypertrophy of the graft was 9% (4 of 44) in the ACI-C group and 6% (3 of 47) in the MACI group. The frequency of re-operation was 9% in each group. We conclude that the clinical, arthroscopic and histological outcomes are comparable for both ACI-C and MACI. While MACI is technically attractive, further long-term studies are required before the technique is widely adopted.
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=1e5+100; struct node{ ll s,x; node(ll xx,ll yy){ s=xx;x=yy; } }; ll n,S; vector<node> a,b; ll sum1=0,sum2=0,sum=0; bool cmp(node p,node q){ return p.x<q.x; } bool check(){ ll x1=sum1/S,x2=sum2/S,x3=(sum1+sum2)/S; if(sum1%S) x1++; if(sum2%S) x2++; if((sum1+sum2)%S) x3++; if(x1+x2==x3) return true ; else return false; } int main(){ cin>>n>>S; ll x,y,z; for(int i=1;i<=n;i++){ scanf("%lld%lld%lld",&x,&y,&z); if(y>=z){ a.push_back({x,y-z}); sum1+=x*1LL; sum+=(x*y)*1LL; } else { b.push_back({x,z-y}); sum2+=x*1LL; sum+=(1LL)*x*z; } } if(check()){ cout<<sum<<endl;return 0; } sort(a.begin(),a.end(),cmp); sort(b.begin(),b.end(),cmp); // cout<<sum<<" "<<sum1<<" "<<sum2<<endl; ll ans1=sum,ans2=sum; ll xx=sum1%S; for(int i=0;i<a.size();i++){ ll Min=min(xx,a[i].s); ans1-=Min*a[i].x; xx-=Min; if(xx==0) break; } ll yy=sum2%S; for(int i=0;i<b.size();i++){ ll Min=min(yy,b[i].s); ans2-=Min*b[i].x; yy-=Min; if(yy==0) break; } cout<<max(ans1,ans2)<<endl; }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.oastem.frc.pid; import org.oastem.frc.pid.PIDGainOutput; import edu.wpi.first.wpilibj.PIDOutput; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.Victor; import org.oastem.frc.ascent.RobotMain; import org.oastem.frc.control.DriveSystem; /** * * @author KTOmega */ public class TargetOutput { private DriveSystem drive; // Connect this to angle output public PIDGainOutput angleRobotToGoal = new PIDGainOutput() { private double zone = 0.05; public void pidWrite(double output) { // angle is negative when goal is to the left. // angle is positive when goal is to the right. System.out.println("Angler PID Output: " + output); if (output < -zone) { drive.tankDrive(-output, output); } else if (output > zone) { drive.tankDrive(output, -output); } else { drive.tankDrive(0, 0); } } public double getKp() { return 0.5; } public double getKi() { return 0.2; } public double getKd() { return 0.1; } }; // Connect this to width output public PIDGainOutput driveRobotToGoal = new PIDGainOutput() { private double zone = 0.5; private double forward = 1.0; private double speed = 0.33; public void pidWrite(double output) { double goalDist = 100; System.out.println("Driver PID Output: " + output); if (output > goalDist) { // too close, back up drive.tankDrive(-speed, speed); } else if (output < goalDist) { // too far, go forward drive.tankDrive(speed, speed); } else { // yeeee drive.tankDrive(0, 0); } } public double getKp() { return 0.5; } public double getKi() { return 0.2; } public double getKd() { return 0.1; } }; // Connect this to height output public PIDGainOutput angleTraamToGoal = new PIDGainOutput() { private double zone = 0.05; private double targetHeight = 120; // in pixels public void pidWrite(double output) { double delta = output - targetHeight; double outPower = 0.0; if (delta > zone) { // goal above target outPower = -1.0; } else if (delta < -zone) { // goal below target outPower = 1.0; } else { // on target outPower = 0.0; } //drive.set(RobotMain.TRAAM, outPower); } public double getKp() { return 0.0; } public double getKi() { return 0.0; } public double getKd() { return 0.0; } }; // Connect this to height output public PIDGainOutput powerWheelForGoal = new PIDGainOutput() { private double zone = 0.05; private double targetHeight = 120; // in pixels public void pidWrite(double output) { double delta = output - targetHeight; double outPower = 0.0; if (delta > zone) { // goal above target outPower = Math.min(Math.abs(delta) * 2, 1.0); } else { // on target outPower = 0.0; } //drive.set(RobotMain.SHOOTER_WHEEL, outPower); } public double getKp() { return 0.0; } public double getKi() { return 0.0; } public double getKd() { return 0.0; } }; public TargetOutput() { drive = DriveSystem.getInstance(); } }
Story highlights Joe Biden met with black clergy in South Carolina on Tuesday Biden to ministers: "This is not your father's Republican Party" South Carolina is an early presidential primary state Washington (CNN) Vice President Joe Biden, in a closed-door meeting with black clergy in South Carolina on Tuesday, referred to himself as "the only white boy on the east side of Wilmington" as he recalled his days as a Delaware public defender and pressed faith leaders to elect Democrats this year. He offered a candid critique of Republicans, calling the tea party "crazy," according to a detailed readout of Biden's remarks provided to CNN by a person in the room. "This is not your father's Republican Party," he said, according to the source. "This is a different breed of cat, man. I am not making a moral judgment, but I will tell you that they have no judgment." Biden was in South Carolina for the day to support local Democrats in competitive races. But South Carolina's role as an early presidential primary state added another layer of political intrigue to his trip, one of several to the state this year. His office declined to comment on his remarks at the private meeting. Read More
<reponame>tusharchoudhary0003/Custom-Football-Game package com.mopub.nativeads; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.mopub.common.Preconditions; import com.mopub.common.VisibleForTesting; import java.util.WeakHashMap; public class MoPubStaticNativeAdRenderer implements MoPubAdRenderer<StaticNativeAd> { /* renamed from: a */ private final ViewBinder f35890a; @VisibleForTesting /* renamed from: b */ final WeakHashMap<View, C11512Ab> f35891b = new WeakHashMap<>(); public MoPubStaticNativeAdRenderer(ViewBinder viewBinder) { this.f35890a = viewBinder; } public View createAdView(Context context, ViewGroup parent) { return LayoutInflater.from(context).inflate(this.f35890a.f36081a, parent, false); } public void renderAdView(View view, StaticNativeAd staticNativeAd) { C11512Ab staticNativeViewHolder = (C11512Ab) this.f35891b.get(view); if (staticNativeViewHolder == null) { staticNativeViewHolder = C11512Ab.m38088a(view, this.f35890a); this.f35891b.put(view, staticNativeViewHolder); } m38291a(staticNativeViewHolder, staticNativeAd); NativeRendererHelper.updateExtras(staticNativeViewHolder.f35590b, this.f35890a.f36088h, staticNativeAd.getExtras()); m38290a(staticNativeViewHolder, 0); } public boolean supports(BaseNativeAd nativeAd) { Preconditions.checkNotNull(nativeAd); return nativeAd instanceof StaticNativeAd; } /* renamed from: a */ private void m38291a(C11512Ab staticNativeViewHolder, StaticNativeAd staticNativeAd) { NativeRendererHelper.addTextView(staticNativeViewHolder.f35591c, staticNativeAd.getTitle()); NativeRendererHelper.addTextView(staticNativeViewHolder.f35592d, staticNativeAd.getText()); NativeRendererHelper.addTextView(staticNativeViewHolder.f35593e, staticNativeAd.getCallToAction()); NativeImageHelper.loadImageView(staticNativeAd.getMainImageUrl(), staticNativeViewHolder.f35594f); NativeImageHelper.loadImageView(staticNativeAd.getIconImageUrl(), staticNativeViewHolder.f35595g); NativeRendererHelper.addPrivacyInformationIcon(staticNativeViewHolder.f35596h, staticNativeAd.getPrivacyInformationIconImageUrl(), staticNativeAd.getPrivacyInformationIconClickThroughUrl()); } /* renamed from: a */ private void m38290a(C11512Ab staticNativeViewHolder, int visibility) { View view = staticNativeViewHolder.f35590b; if (view != null) { view.setVisibility(visibility); } } }
/** * TestNodeDispatcherService is ... * * @author Greg Schueler <a href="mailto:[email protected]">[email protected]</a> */ public class TestNodeDispatcherService extends AbstractBaseTest { private static final String PROJ_NAME = "TestNodeDispatcherService"; private File resourcesfile; private File extResourcesfile; public TestNodeDispatcherService(String name) { super(name); } public void setUp() { super.setUp(); final Framework frameworkInstance = getFrameworkInstance(); final FrameworkProject frameworkProject = frameworkInstance.getFrameworkProjectMgr().createFrameworkProject( PROJ_NAME); resourcesfile = new File(frameworkProject.getNodesResourceFilePath()); //copy test nodes to resources file try { FileUtils.copyFileStreams(new File("src/test/resources/com/dtolabs/rundeck/core/common/test-nodes1.xml"), resourcesfile); } catch (IOException e) { throw new RuntimeException("Caught Setup exception: " + e.getMessage(), e); } extResourcesfile = new File("src/test/resources/com/dtolabs/rundeck/core/common/test-nodes2.xml"); } public void tearDown() throws Exception { super.tearDown(); File projectdir = new File(getFrameworkProjectsBase(), PROJ_NAME); FileUtils.deleteDir(projectdir); } public void testGetNodeDispatcher() throws Exception { final Framework frameworkInstance = getFrameworkInstance(); final NodeDispatcherService service = NodeDispatcherService.getInstanceForFramework( frameworkInstance); { final NodeSet nodeSet = new NodeSet(); nodeSet.createInclude().setName(".*"); nodeSet.setThreadCount(2); //get node dispatcher for a context. nodeset>1 and threadcount>1 returns parallel provider final ExecutionContext context = ExecutionContextImpl.builder() .frameworkProject(PROJ_NAME) .framework(frameworkInstance) .user("blah") .nodeSelector(nodeSet) .nodes(frameworkInstance.filterNodeSet(nodeSet,PROJ_NAME,null)) .threadCount(nodeSet.getThreadCount()) .keepgoing(nodeSet.isKeepgoing()) .build(); final NodeDispatcher nodeDispatcher = service.getNodeDispatcher(context); assertNotNull(nodeDispatcher); assertTrue(nodeDispatcher instanceof ParallelNodeDispatcher); } { //get node dispatcher for a context. nodeset>1 and threadcount<2 returns sequential provider final NodeSet nodeSet = new NodeSet(); nodeSet.createInclude().setName(".*"); nodeSet.setThreadCount(1); final ExecutionContext context = ExecutionContextImpl.builder() .frameworkProject(PROJ_NAME) .framework(frameworkInstance) .user("blah") .nodeSelector(nodeSet) .threadCount(nodeSet.getThreadCount()) .keepgoing(nodeSet.isKeepgoing()) .build(); final NodeDispatcher nodeDispatcher = service.getNodeDispatcher(context); assertNotNull(nodeDispatcher); assertTrue(nodeDispatcher instanceof SequentialNodeDispatcher); } { //get node dispatcher for a context. nodeset<2 and threadcount<2 returns sequential provider final NodeSet nodeSet = new NodeSet(); nodeSet.setSingleNodeName("test1"); nodeSet.setThreadCount(1); final ExecutionContext context = ExecutionContextImpl.builder() .frameworkProject(PROJ_NAME) .framework(frameworkInstance) .user("blah") .nodeSelector(nodeSet) .threadCount(nodeSet.getThreadCount()) .keepgoing(nodeSet.isKeepgoing()) .build(); final NodeDispatcher nodeDispatcher = service.getNodeDispatcher(context); assertNotNull(nodeDispatcher); assertTrue(nodeDispatcher instanceof SequentialNodeDispatcher); } { //get node dispatcher for a context. nodeset<2 and threadcount>1 returns sequential provider final NodeSet nodeSet = new NodeSet(); nodeSet.setSingleNodeName("test1"); nodeSet.setThreadCount(2); final ExecutionContext context = ExecutionContextImpl.builder() .frameworkProject(PROJ_NAME) .framework(frameworkInstance) .user("blah") .nodeSelector(nodeSet) .nodes(frameworkInstance.filterNodeSet(nodeSet,PROJ_NAME,null)) .threadCount(nodeSet.getThreadCount()) .keepgoing(nodeSet.isKeepgoing()) .build(); final NodeDispatcher nodeDispatcher = service.getNodeDispatcher(context); assertNotNull(nodeDispatcher); assertTrue(nodeDispatcher instanceof SequentialNodeDispatcher); } } /** * Test specifying an external nodes file */ public void testExtResources() throws Exception { final Framework frameworkInstance = getFrameworkInstance(); final NodeDispatcherService service = NodeDispatcherService.getInstanceForFramework( frameworkInstance); { //use test-1 file final NodeSet nodeSet = new NodeSet(); nodeSet.createInclude().setTags("priority1"); //matches single nodes in test1 file nodeSet.setThreadCount(2); //get node dispatcher for a context. nodeset<2 and threadcount>1 returns sequential provider final ExecutionContext context = ExecutionContextImpl.builder() .frameworkProject(PROJ_NAME) .framework(frameworkInstance) .user("blah") .nodeSelector(nodeSet) .threadCount(nodeSet.getThreadCount()) .keepgoing(nodeSet.isKeepgoing()) .nodesFile(resourcesfile) .nodes(frameworkInstance.filterNodeSet(nodeSet, PROJ_NAME, resourcesfile)) .build(); final NodeDispatcher nodeDispatcher = service.getNodeDispatcher(context); assertNotNull(nodeDispatcher); assertTrue(nodeDispatcher instanceof SequentialNodeDispatcher); } { final NodeSet nodeSet = new NodeSet(); nodeSet.createInclude().setTags("priority1"); //matches two nodes in external file nodeSet.setThreadCount(2); //get node dispatcher for a context. nodeset>1 and threadcount>1 returns parallel provider final ExecutionContext context = ExecutionContextImpl.builder() .frameworkProject(PROJ_NAME) .framework(frameworkInstance) .user("blah") .nodeSelector(nodeSet) .threadCount(nodeSet.getThreadCount()) .keepgoing(nodeSet.isKeepgoing()) .nodesFile(extResourcesfile) .nodes(frameworkInstance.filterNodeSet(nodeSet, PROJ_NAME, extResourcesfile)) .build(); assertEquals(2,context.getNodes().getNodeNames().size()); final NodeDispatcher nodeDispatcher = service.getNodeDispatcher(context); assertNotNull(nodeDispatcher); assertTrue(nodeDispatcher instanceof ParallelNodeDispatcher); } } }
"""Testes para as rotas de users""" def test_get_users(client_users_with_one_user): """Testando a rota get_users""" url = "/api/users/" response = client_users_with_one_user.get(url=url) assert response.status_code == 200 assert isinstance(response.json(), dict) assert isinstance(response.json()["data"], list) assert "id" in response.json()["data"][0] assert "name" in response.json()["data"][0] def test_get_user(client_users_with_one_user, fake_user): """Testando a rota get_user""" url = f"/api/users/{fake_user.id}" response = client_users_with_one_user.get(url=url) assert response.status_code == 200 assert isinstance(response.json(), dict) assert isinstance(response.json()["data"], dict) assert "id" in response.json()["data"] assert "name" in response.json()["data"] def test_register_user(client_users, fake_user): """Testando a rota register_user""" url = "/api/users/" json = { "name": fake_user.name, "email": fake_user.email, "username": fake_user.username, "password": <PASSWORD>, } response = client_users.post(url=url, json=json) assert response.status_code == 201 assert isinstance(response.json(), dict) assert isinstance(response.json()["data"], dict) assert "id" in response.json()["data"] assert "name" in response.json()["data"] def test_update_user(client_users_with_one_user, fake_user): """Testando a rota update_user""" url = f"/api/users/{fake_user.id}/" json = { "name": "margarida", "email": "<EMAIL>", "username": "meu_nome_nao_e_jhony", } response = client_users_with_one_user.put(url=url, json=json) assert response.status_code == 200 assert isinstance(response.json(), dict) assert isinstance(response.json()["data"], dict) assert "id" in response.json()["data"] assert "name" in response.json()["data"] def test_delete_user(client_users_with_one_user, fake_user): """Testando a rota update_user""" url = f"/api/users/{fake_user.id}/" response = client_users_with_one_user.delete(url=url) assert response.status_code == 204 assert isinstance(response.json(), dict) assert isinstance(response.json()["data"], dict) assert "id" in response.json()["data"] assert "name" in response.json()["data"]
def media_images_height_max(self): return self._media_images_height_max
<reponame>superxuzj/eqimManeger package com.boliangshenghe.eqim.common.datasource; import com.alibaba.cobar.client.transaction.MultipleDataSourcesTransactionManager; public class MultiDataSourceTransactionManager extends MultipleDataSourcesTransactionManager { /** * */ private static final long serialVersionUID = 2280154135234778335L; @Override public void afterPropertiesSet() throws Exception { super.afterPropertiesSet(); // 不同步,不然报错,spring2.5没有此问题 this.setTransactionSynchronization(SYNCHRONIZATION_NEVER); } }
def ensure_security_groups(req_context, brickconfig): g_id = [] exists = False sec_groups = opencrack.api_request( 'compute', req_context.auth_token, req_context.tenant_id, '/os-security-groups', method='GET' ).json() for group in sec_groups['security_groups']: if group['name'] == u"%s" % brickconfig.name: exists = True g_id.append(group['id']) break if not exists: sec_group_data = { 'security_group': { 'name': brickconfig.name, 'description': 'Auto-generated security group for %s' % brickconfig.name } } sec_group = opencrack.api_request( 'compute', req_context.auth_token, req_context.tenant_id, '/os-security-groups', data=sec_group_data ).json().get('security_group') g_id.append(sec_group['id']) for port in brickconfig.ports: port_data = { 'security_group_rule': { 'ip_protocol': 'tcp', 'from_port': port, 'to_port': port, 'cidr': '0.0.0.0/0', 'parent_group_id': sec_group['id'], 'group_id': None } } opencrack.api_request( 'compute', req_context.auth_token, req_context.tenant_id, '/os-security-group-rules', data=port_data) return g_id
/** * Agency recruitment service. * * @author swindle */ public class AgencyRecruitmentServiceImpl implements RecruitmentService { /* (non-Javadoc) * @see net.swindle.springdemo.service.RecruitmentService#recruitEmployees(java.lang.String, * java.lang.String, int) */ @Override public String recruitEmployees( String companyName, String departmentName, int numberOfRecruitments) { final Random random = new Random(); return "\n" + companyName + "'s " + departmentName + " hired " + random.nextInt(numberOfRecruitments) + " employees " + "using various hiring agencies."; } }
package parser import ( "errors" "github.com/graphql-go/graphql" "github.com/graphql-go/graphql/language/ast" ) type namedDefintion interface { ast.Definition GetName() *ast.Name } func customDefinition(p *Parser, d ast.Definition) (gt graphql.Type, err error) { t, ok := d.(namedDefintion) if !ok { return nil, errors.New("not a type definition") } if gt, ok := p.gqlTypeMap[t.GetName().Value]; ok { return gt, nil } // Prevent recursion switch t := d.(type) { case *ast.ScalarDefinition: serialize := func(v interface{}) interface{} { return v } parseValue := func(v interface{}) interface{} { return v } if fn, ok := p.Scalars[t.Name.Value]; ok { if fn.Serialize != nil { serialize = fn.Serialize } if fn.Parse != nil { parseValue = fn.Parse } } sc := graphql.ScalarConfig{ Name: t.Name.Value, ParseValue: parseValue, ParseLiteral: func(v ast.Value) interface{} { return parseValue(v.GetValue()) }, Serialize: serialize, } setDescription(&sc.Description, t) st := graphql.NewScalar(sc) p.gqlTypeMap[st.Name()] = st gt = st case *ast.EnumDefinition: gt, err = enumDefinition(p, t) case *ast.InputObjectDefinition: gt, err = inputObjectDefinition(p, t) case *ast.InterfaceDefinition: gt, err = interfaceDefinition(p, t) case *ast.ObjectDefinition: gt, err = objectDefintion(p, t) case *ast.UnionDefinition: gt, err = unionDefinition(p, t) default: err = errors.New("unsupported type defintion") } return }
<gh_stars>0 /** * Copyright (C) 2019, <NAME>. * All right reserved. * @author xiongfa.li * @version V1.0 * Description: */ package generator import ( "fmt" "github.com/xfali/gobatis-cmd/pkg/common" "github.com/xfali/gobatis-cmd/pkg/config" "github.com/xfali/gobatis-cmd/pkg/io" "strings" ) func GenProxy(config config.Config, tableName string, models []common.ModelInfo) { mapperDir := config.Path if !io.IsPathExists(mapperDir) { io.Mkdir(mapperDir) } mapperFile, err := io.OpenAppend(mapperDir + strings.ToLower(tableName) + "_proxy.go") if err == nil { defer mapperFile.Close() modelName := common.TableName2ModelName(tableName) builder := strings.Builder{} builder.WriteString("package ") builder.WriteString(config.PackageName) builder.WriteString(common.Newline()) builder.WriteString(common.Newline()) builder.WriteString("import (") builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(`"context"`) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(`"github.com/xfali/gobatis"`) builder.WriteString(common.Newline()) //builder.WriteString(common.ColumnSpace()) //builder.WriteString(`"github.com/xfali/gobatis/factory"`) //builder.WriteString(common.Newline()) //builder.WriteString(common.ColumnSpace()) //builder.WriteString(`"github.com/xfali/gobatis/session/runner"`) //builder.WriteString(common.Newline()) builder.WriteString(")") builder.WriteString(common.Newline()) builder.WriteString(common.Newline()) proxyName := fmt.Sprintf("%sCallProxy", modelName) builder.WriteString(fmt.Sprintf("type %s gobatis.Session", proxyName)) builder.WriteString(common.Newline()) builder.WriteString(common.Newline()) builder.WriteString("func init() {") builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(fmt.Sprintf("modelV := %s{}", modelName)) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString("gobatis.RegisterModel(&modelV)") builder.WriteString(common.Newline()) if config.MapperFile == "xml" { builder.WriteString(common.ColumnSpace()) builder.WriteString(fmt.Sprintf("gobatis.RegisterMapperFile(\"%sxml/%s.xml\")", config.Path, tableName)) builder.WriteString(common.Newline()) } else if config.MapperFile == "go" { builder.WriteString(common.ColumnSpace()) builder.WriteString(fmt.Sprintf("gobatis.RegisterMapperData([]byte(%sMapper))", modelName)) builder.WriteString(common.Newline()) } builder.WriteString("}") builder.WriteString(common.Newline()) builder.WriteString(common.Newline()) builder.WriteString(fmt.Sprintf("func New%s(proxyMrg *gobatis.SessionManager) *%s {", proxyName, proxyName)) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(fmt.Sprintf("return (*%s)(proxyMrg.NewSession())", proxyName)) builder.WriteString(common.Newline()) builder.WriteString("}") builder.WriteString(common.Newline()) builder.WriteString(common.Newline()) //Tx builder.WriteString(fmt.Sprintf("func (proxy *%s) Tx(txFunc func(s *%s) error) {", proxyName, proxyName)) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(`sess := (*gobatis.Session)(proxy)`) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(`sess.Tx(func(session *gobatis.Session) error {`) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(common.ColumnSpace()) builder.WriteString("return txFunc(proxy)") builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(`})`) builder.WriteString(common.Newline()) builder.WriteString("}") builder.WriteString(common.Newline()) builder.WriteString(common.Newline()) //Tx end //select builder.WriteString(fmt.Sprintf("func (proxy *%s)Select%s(model %s) ([]%s, error) {", proxyName, modelName, modelName, modelName)) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(fmt.Sprintf("var dataList []%s", modelName)) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(fmt.Sprintf(`err := (*gobatis.Session)(proxy).Select("select%s").Context(context.Background()).Param(model).Result(&dataList)`, modelName)) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString("return dataList, err") builder.WriteString(common.Newline()) builder.WriteString("}") builder.WriteString(common.Newline()) builder.WriteString(common.Newline()) //select end //select count builder.WriteString(fmt.Sprintf("func (proxy *%s)Select%sCount(model %s) (int64, error) {", proxyName, modelName, modelName)) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString("var ret int64") builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(fmt.Sprintf(`err := (*gobatis.Session)(proxy).Select("select%sCount").Context(context.Background()).Param(model).Result(&ret)`, modelName)) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString("return ret, err") builder.WriteString(common.Newline()) builder.WriteString("}") builder.WriteString(common.Newline()) builder.WriteString(common.Newline()) //select count end //insert builder.WriteString(fmt.Sprintf("func (proxy *%s)Insert%s(model %s) (int64, int64, error) {", proxyName, modelName, modelName)) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString("var ret int64") builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(fmt.Sprintf(`runner := (*gobatis.Session)(proxy).Insert("insert%s").Context(context.Background()).Param(model)`, modelName)) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(`err := runner.Result(&ret)`) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(`id := runner.LastInsertId()`) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString("return ret, id, err") builder.WriteString(common.Newline()) builder.WriteString("}") builder.WriteString(common.Newline()) builder.WriteString(common.Newline()) //insert end //update builder.WriteString(fmt.Sprintf("func (proxy *%s)Update%s(model %s) (int64, error) {", proxyName, modelName, modelName)) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString("var ret int64") builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(fmt.Sprintf(`err := (*gobatis.Session)(proxy).Update("update%s").Context(context.Background()).Param(model).Result(&ret)`, modelName)) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString("return ret, err") builder.WriteString(common.Newline()) builder.WriteString("}") builder.WriteString(common.Newline()) builder.WriteString(common.Newline()) //update end //delete builder.WriteString(fmt.Sprintf("func (proxy *%s)Delete%s(model %s) (int64, error) {", proxyName, modelName, modelName)) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString("var ret int64") builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString(fmt.Sprintf(`err := (*gobatis.Session)(proxy).Delete("delete%s").Context(context.Background()).Param(model).Result(&ret)`, modelName)) builder.WriteString(common.Newline()) builder.WriteString(common.ColumnSpace()) builder.WriteString("return ret, err") builder.WriteString(common.Newline()) builder.WriteString("}") builder.WriteString(common.Newline()) builder.WriteString(common.Newline()) //delete end io.Write(mapperFile, []byte(builder.String())) } }
<filename>config.go package jccclient import ( "io/ioutil" "os" "gopkg.in/yaml.v2" ) // ClientConfig - type ClientConfig struct { ServAddr string Token string Tags []string } // Config - config type Config struct { //------------------------------------------------------------------ // clients Clients []ClientConfig //------------------------------------------------------------------ // configuration // MaxMultiFailTimes - If the client fail {{MaxMultiFailTimes}} times in succession, it need to ignore some task MaxMultiFailTimes int // EffectiveFailTime - If the interval between 2 failures is less than {{EffectiveFailTime}} seconds, it should be counted as a multiple failure. EffectiveFailTime int // IgnoreTaskTime - The client will ignore the task for {{IgnoreTaskTime}} seconds. IgnoreTaskTime int // SleepTime - The client will ignore the task for {{SleepTime}} seconds. SleepTime int // DefaultMobileDevice - default mobile device DefaultMobileDevice string //------------------------------------------------------------------ // databse configuration DBPath string DBEngine string } func checkClientConfig(cfg *ClientConfig) error { if cfg.ServAddr == "" { return ErrNoServAddr } if cfg.Token == "" { return ErrNoToken } return nil } func checkConfig(cfg *Config) error { mapServAddr := make(map[string]bool) for _, v := range cfg.Clients { _, isok := mapServAddr[v.ServAddr] if isok { return ErrDuplicateServAddr } err := checkClientConfig(&v) if err != nil { return err } mapServAddr[v.ServAddr] = true } if cfg.MaxMultiFailTimes <= 0 { cfg.MaxMultiFailTimes = MaxMultiFailTimes } if cfg.EffectiveFailTime <= 0 { cfg.EffectiveFailTime = EffectiveFailTime } if cfg.IgnoreTaskTime <= 0 { cfg.IgnoreTaskTime = IgnoreTaskTime } if cfg.SleepTime <= 0 { cfg.SleepTime = DefaultSleepTime } if cfg.DBPath == "" { return ErrNoDBPath } if cfg.DBEngine == "" { return ErrNoDBEngine } return nil } // LoadConfig - load config func LoadConfig(filename string) (*Config, error) { fi, err := os.Open(filename) if err != nil { return nil, err } defer fi.Close() fd, err := ioutil.ReadAll(fi) if err != nil { return nil, err } cfg := &Config{} err = yaml.Unmarshal(fd, cfg) if err != nil { return nil, err } err = checkConfig(cfg) if err != nil { return nil, err } return cfg, nil }
dic={} for i in range(100002): dic[i]=0 input() for n in map(int,input().split()): dic[n]+=1 m=0 for i in range(0,100000): m=max(m,dic[i]+dic[i+1]+dic[i+2]) print(m)
<reponame>Pandaaaa906/product_spider<filename>product_spider/spiders/bdg_spider.py import re from string import ascii_lowercase from more_itertools import first from scrapy import Request from product_spider.items import RawData from product_spider.utils.spider_mixin import BaseSpider p_cas = re.compile(r'\d+-\d{2}-\d\b') class BDGSpider(BaseSpider): name = "bdg" base_url = "https://bdg.co.nz/" start_urls = [f"https://bdg.co.nz/product-category/{a}/" for a in ascii_lowercase] def parse(self, response): urls = response.xpath('//h4/a/@href').extract() for url in urls: yield Request(url, callback=self.parse_detail) next_page = response.xpath('//div[@class="pages"]/span/following-sibling::a[1]/@href').get() if next_page: yield Request(next_page, callback=self.parse) def parse_detail(self, response): r_cas = response.xpath('//strong[contains(text(),"CAS Number: ")]/text()').get() l_cas = p_cas.findall(r_cas) cas = None if not l_cas else first(l_cas) d = { "brand": "bdg", "parent": ';'.join(response.xpath('//span[@class="posted_in"]/a/text()').getall()) or None, "cat_no": response.xpath('//span[@class="sku"]/text()').get(), "en_name": response.xpath('//h1[@itemprop="name"]/text()').get(), "cas": cas, "mf": ''.join(response.xpath('//strong[text()="Molecular Formula"]/../following-sibling::td//text()').getall()), "mw": ''.join(response.xpath('//strong[text()="Molecular Weight"]/../following-sibling::td//text()').getall()), "img_url": response.xpath('//img[@class="wp-post-image"]/@src').get(), "prd_url": response.request.url, } yield RawData(**d)
def run_ice(number, env, ref=False): name = "IceXI" description = "Ice XI 8 molecules DZP diagonalisation" grid_cutoff = 80.0 xc = "PBE" kpts = [9,9,9] basis = {'H' : {'file' : 'H_DZP_v323_PBE.ion'}, 'O' : {'file' : 'O_DZP_v323_PBE.ion'}} env.set_nprocs(4) cell = [4.137266, 7.298682, 6.740787] positions = [(0.00004235166920939, 0.52132867339661904, 0.01312804623422056), (0.00002422597654387, 0.66197026160406081, 0.21915381211889559), (0.00002811635854249, 0.47868217543515051, 0.51312960244626338), (0.00005632421000542, 0.33803483627959369, 0.71915539992719857), (0.50006428950131876, 0.16197109165777751, 0.21915594041982714), (0.50005083190497801, 0.02132700140357800, 0.01312812071049466), (0.50002880918180725, 0.83803779015457791, 0.71915331922284009), (0.50002715936536779, 0.97867748875666416, 0.51312809969130790), (0.29280958502426158, 0.75746687855426764, 0.98904730686645670), (0.70726827228582734, 0.75745492928010660, 0.98904450053802062), (0.29280268188327385, 0.24255842762989188, 0.48904040599159815), (0.70726690993963393, 0.24255384186864903, 0.48905272571304059), (0.20730246202883651, 0.25745862648053025, 0.98905082501075958), (0.79283945672356571, 0.25745578333197661, 0.98905090188310130), (0.20724870545567675, 0.74255081462513184, 0.48904100890172741), (0.79278388107700459, 0.74255422496356938, 0.48904173022674335), (0.00001782623484499, 0.65894809106556096, 0.06181159443008376), (0.00003361021850561, 0.34106276127523438, 0.56181309250277522), (0.50005855789217557, 0.15894559382014778, 0.06181332063013109), (0.50001707071609058, 0.84105732900959684, 0.56181020612117150), (0.50003416709071735, 0.82863413453639312, 0.93818224732333610), (0.50003324583385567, 0.17137873439506193, 0.43818522549074967), (0.00005961164496471, 0.32862823724067103, 0.93818694298206462), (0.00001192955904678, 0.67137526341019071, 0.43818338648467903)] ice = Atoms("H16O8", positions=positions) ice.set_cell(cell, scale_atoms=True) tester = StaticTest(number, name, description, ice, verbose=True) handler = TestIOHandler(tester, ref) handler.set_ion_path(env.ion_path, basis) handler.run_test(grid_cutoff, xc, kpts, basis)
class WizardBreakableContext: """ Context that can be broken by a 'Break' expression. """ @abstractmethod def break_(self) -> WizardInterpreterContext: """ Called when a 'Break' instruction is encountered, should usually return the parent. Returns: The next context to use after this break. """ pass
/** * Process notification of character data received from the body of * an XML element. * * @param buffer The characters from the XML document * @param start Starting offset into the buffer * @param length Number of characters from the buffer * * @throws SAXException if a parsing error is to be reported */ @Override public void characters( final char buffer[], final int start, final int length ) throws SAXException { super.characters( buffer, start, length ); currTextSegment.append( buffer, start, length ); }
def artist(self, artist_id: str) -> dict: artist_id = _get_id("artist", artist_id) return self._get("artists/" + artist_id)
/** * Adds a <modules><module name=deployment.${moduleName}/></modules> to the cacheManager in the server configFile * in case it does not exist. */ public static void addCacheManagerModuleDep(File configFile, String moduleName) throws Exception { Document doc = buildDoc(configFile); Node cacheManager = doc.getElementsByTagName("cache-container").item(0); NodeList childNodes = cacheManager.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { if (childNodes.item(i).getNodeName().equals("modules")) { return; } } Element module = doc.createElement("module"); module.setAttribute("name", "deployment." + moduleName); Element modules = doc.createElement("modules"); modules.appendChild(module); cacheManager.appendChild(modules); saveDocToFile(doc, configFile); }
#include <stdio.h> #define ROUND 4 /* 小数点以下第ROUND位を四捨五入 */ /*--- 四捨五入 ---*/ double round(double num) { int i, cmp; for (i = 0; i < ROUND; i++) /* 四捨五入する値を1の位にもってくる */ num *= 10; cmp = (int)num; /* int型にキャストしたものをcmpに代入 */ while (cmp > 10) /* 一桁の数にして */ cmp %= 10; if (cmp >= 5) /* その値が5より大きければ*/ num += 1; /* numに1を加えて */ for(i = 0; i < ROUND; i++) /* 元の数に戻す */ num /= 10; return num; } int main(void) { double a, b, c, d, e, f; /* ax + by = c, dx + ey = fの連立方程式 */ double ans_x, ans_y; /* xとyの答え */ while (scanf("%lf %lf %lf %lf %lf %lf", &a, &b, &c, &d, &e, &f) != EOF) { ans_y = (d*c - a*f) / (d*b - a*e); ans_x = (c - b*ans_y) / a; ans_y = round(ans_y); ans_x = round(ans_x); printf("%.3f %.3f\n", ans_x, ans_y); } return 0; }
/** * Configures the stateTimer's actionPerformed event and delay. * The stateTimer is set to not repeat and have 500ms delay. * When the timer triggers it will find all matches on the board, * then update and start the timer again. Once there are no more matches, * the game state is swapped back to choosing pos1. * * The timer is ready to begin after this method by calling stateTimer.start(); */ private void configureTimer() { stateTimer = new Timer(500, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { List<Position> matches = matchBoard.findAllMatches(); updateScore(matches.size()); if(!matches.isEmpty()) { List<Position> cellsToReplace = matchBoard.shuffledDownToFill(matches); matchBoard.fillPositions(cellsToReplace); recentMatches = matches; recentNewCells = cellsToReplace; repaint(); stateTimer.start(); System.out.println("Made changes, waiting again!"); } else { System.out.println("All done :)"); gameState = GameState.ChoosePos1; } } }); stateTimer.setRepeats(false); }
#pragma once #include <string> #include "clock.h" #include "channel.h" class TimeSlave { private: Clock _clock; Channel *_channel; std::string _name; public: TimeSlave(std::string name, int hours, int minutes, int seconds, bool monotone); void set_clock_speed(int speed) { _clock.set_clock_speed_offset(speed); } Channel *get_channel() { return _channel; } void operator()(); };
/** * A collection of task groups, where a task group is a collection of tasks that are known to be * equal in the way they schedule. This is expected to be tasks associated with the same job key, * who also have {@code equal()} {@link ITaskConfig} values. * <p> * This is used to prevent redundant work in trying to schedule tasks as well as to provide * nearly-equal responsiveness when scheduling across jobs. In other words, a 1000 instance job * cannot starve a 1 instance job. */ public class TaskGroups implements EventSubscriber { private static final Logger LOG = Logger.getLogger(TaskGroups.class.getName()); private final LoadingCache<GroupKey, TaskGroup> groups; private final Clock clock; private final RescheduleCalculator rescheduleCalculator; static class TaskGroupsSettings { private final BackoffStrategy taskGroupBackoff; private final RateLimiter rateLimiter; TaskGroupsSettings(BackoffStrategy taskGroupBackoff, RateLimiter rateLimiter) { this.taskGroupBackoff = checkNotNull(taskGroupBackoff); this.rateLimiter = checkNotNull(rateLimiter); } } @Inject TaskGroups( ShutdownRegistry shutdownRegistry, TaskGroupsSettings settings, TaskScheduler taskScheduler, Clock clock, RescheduleCalculator rescheduleCalculator) { this( createThreadPool(shutdownRegistry), settings.taskGroupBackoff, settings.rateLimiter, taskScheduler, clock, rescheduleCalculator); } @VisibleForTesting TaskGroups( final ScheduledExecutorService executor, final BackoffStrategy taskGroupBackoffStrategy, final RateLimiter rateLimiter, final TaskScheduler taskScheduler, final Clock clock, final RescheduleCalculator rescheduleCalculator) { checkNotNull(executor); checkNotNull(taskGroupBackoffStrategy); checkNotNull(rateLimiter); checkNotNull(taskScheduler); this.clock = checkNotNull(clock); this.rescheduleCalculator = checkNotNull(rescheduleCalculator); final TaskScheduler ratelLimitedScheduler = new TaskScheduler() { @Override public TaskSchedulerResult schedule(String taskId) { rateLimiter.acquire(); return taskScheduler.schedule(taskId); } }; groups = CacheBuilder.newBuilder().build(new CacheLoader<GroupKey, TaskGroup>() { @Override public TaskGroup load(GroupKey key) { TaskGroup group = new TaskGroup(key, taskGroupBackoffStrategy); LOG.info("Evaluating group " + key + " in " + group.getPenaltyMs() + " ms"); startGroup(group, executor, ratelLimitedScheduler); return group; } }); } private synchronized boolean maybeInvalidate(TaskGroup group) { if (group.getTaskIds().isEmpty()) { groups.invalidate(group.getKey()); return true; } return false; } private void startGroup( final TaskGroup group, final ScheduledExecutorService executor, final TaskScheduler taskScheduler) { Runnable monitor = new Runnable() { @Override public void run() { GroupState state = group.isReady(clock.nowMillis()); switch (state) { case EMPTY: maybeInvalidate(group); break; case READY: String id = group.pop(); TaskScheduler.TaskSchedulerResult result = taskScheduler.schedule(id); switch (result) { case SUCCESS: if (!maybeInvalidate(group)) { executor.schedule(this, group.resetPenaltyAndGet(), TimeUnit.MILLISECONDS); } break; case TRY_AGAIN: group.push(id, clock.nowMillis()); executor.schedule(this, group.penalizeAndGet(), TimeUnit.MILLISECONDS); break; default: throw new IllegalStateException("Unknown TaskSchedulerResult " + result); } break; case NOT_READY: executor.schedule(this, group.getPenaltyMs(), TimeUnit.MILLISECONDS); break; default: throw new IllegalStateException("Unknown GroupState " + state); } } }; executor.schedule(monitor, group.getPenaltyMs(), TimeUnit.MILLISECONDS); } private static ScheduledExecutorService createThreadPool(ShutdownRegistry shutdownRegistry) { // TODO(William Farner): Leverage ExceptionHandlingScheduledExecutorService: // com.twitter.common.util.concurrent.ExceptionHandlingScheduledExecutorService final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor( 1, new ThreadFactoryBuilder().setDaemon(true).setNameFormat("TaskScheduler-%d").build()); Stats.exportSize("schedule_queue_size", executor.getQueue()); shutdownRegistry.addAction(new Command() { @Override public void execute() { new ExecutorServiceShutdown(executor, Amount.of(1L, Time.SECONDS)).execute(); } }); return executor; } private synchronized void add(IAssignedTask task, long scheduleDelayMs) { groups.getUnchecked(new GroupKey(task.getTask())) .push(task.getTaskId(), clock.nowMillis() + scheduleDelayMs); } /** * Informs the task groups of a task state change. * <p> * This is used to observe {@link org.apache.aurora.gen.ScheduleStatus#PENDING} tasks and begin * attempting to schedule them. * * @param stateChange State change notification. */ @Subscribe public synchronized void taskChangedState(TaskStateChange stateChange) { if (stateChange.getNewState() == PENDING) { IScheduledTask task = stateChange.getTask(); long readyAtMs = stateChange.isTransition() ? rescheduleCalculator.getFlappingPenaltyMs(task) : rescheduleCalculator.getStartupScheduleDelayMs(task); add(task.getAssignedTask(), readyAtMs); } } /** * Signals the scheduler that tasks have been deleted. * * @param deleted Tasks deleted event. */ @Subscribe public synchronized void tasksDeleted(TasksDeleted deleted) { for (IAssignedTask task : Iterables.transform(deleted.getTasks(), Tasks.SCHEDULED_TO_ASSIGNED)) { TaskGroup group = groups.getIfPresent(new GroupKey(task.getTask())); if (group != null) { group.remove(task.getTaskId()); } } } public Iterable<TaskGroup> getGroups() { return ImmutableSet.copyOf(groups.asMap().values()); } static class GroupKey { private final ITaskConfig canonicalTask; GroupKey(ITaskConfig task) { this.canonicalTask = task; } @Override public int hashCode() { return Objects.hashCode(canonicalTask); } @Override public boolean equals(Object o) { if (!(o instanceof GroupKey)) { return false; } GroupKey other = (GroupKey) o; return Objects.equal(canonicalTask, other.canonicalTask); } @Override public String toString() { return JobKeys.toPath(Tasks.INFO_TO_JOB_KEY.apply(canonicalTask)); } } }
/* * ArrayReference.cpp * * Created on: 2020/02/15 * Author: iizuka */ #include "instance/instance_array/ArrayReference.h" #include "instance/instance_array/VmArrayInstance.h" #include "instance/AbstractVmInstance.h" #include "instance/VmInstanceTypesConst.h" #include "instance/instance_gc/GcManager.h" #include "ext_binary/ExtNullPtrObject.h" namespace alinous { ArrayReference::ArrayReference(IAbstractVmInstanceSubstance* owner, VirtualMachine* vm) : AbstractReference(owner, VmInstanceTypesConst::REF_ARRAY) { this->instArray = nullptr; } ArrayReference::ArrayReference(IAbstractVmInstanceSubstance* owner, VirtualMachine* vm, VmArrayInstance* instArray) : AbstractReference(owner, VmInstanceTypesConst::REF_ARRAY){ this->instArray = instArray; } ArrayReference::~ArrayReference() { this->instArray = nullptr; } IAbstractVmInstanceSubstance* ArrayReference::getInstance() noexcept { return this->instArray; } void ArrayReference::substitute(IAbstractVmInstanceSubstance* rightValue, VirtualMachine* vm) { GcManager* gc = vm->getGc(); if(this->instArray != nullptr){ gc->removeObject(this); this->instArray = nullptr; } if(rightValue != nullptr && !rightValue->instIsNull()){ VmArrayInstance* inst = dynamic_cast<VmArrayInstance*>(rightValue); this->instArray = inst; gc->registerObject(this); } } bool ArrayReference::isNull() const noexcept { return this->instArray == nullptr; } int ArrayReference::valueCompare(const IAbstractVmInstanceSubstance* right) const noexcept { if(isNull()){ return right == nullptr ? 0 : -1; } else if(right == nullptr){ return isNull() ? 0 : 1; } const VmArrayInstance* objRight = dynamic_cast<const VmArrayInstance*>(right); if(objRight == nullptr){ return -1; } return this->instArray->valueCompare(objRight); } AbstractExtObject* ArrayReference::toClassExtObject(const UnicodeString* name, VTableRegistory* table) { return this->instArray != nullptr ? this->instArray->instToClassExtObject(name, table) : new ExtNullPtrObject(name, VmInstanceTypesConst::INST_ARRAY); } void ArrayReference::resetOnGc() noexcept { this->instArray = nullptr; } const UnicodeString* ArrayReference::toString() const noexcept { return isNull() ? AbstractReference::toString() : this->instArray->toString(); } } /* namespace alinous */
Engineers at Nasa’s Jet Propulsion Laboratory (JPL) in Pasadena, California, have the ultimate iPhone app. But it’s not something you will find in the App Store. With a few taps on the screen, I can send a replica of Nasa’s Curiosity rover trundling - at a slow walking pace - across the rocky terrain of JPL’s outdoor test area, known as Mars Yard. I find myself treating the experience like a video game: starting out cautiously with a few gentle turns, before commanding the car-sized rover to cross some sizable boulders. Mobility test engineer Daniel Fuller calls ‘game over’ when I manage to ground one of the vehicle’s six wheels on a particularly large lump of stone. Thankfully the real rover, some 200 million kilometers (125 million miles) away on the Red Planet, is in safer hands. And the way it’s driven is rather different. “It’s a common misconception that we’re just ‘joysticking’ it or we’re driving and sending these commands and we’re suffering a 15 minute delay,” says Fuller, who divides his time between the rover control room and Mars yard. “We actually plan an entire day – or a sol as it’s called on Mars.” Each of these daily missions is overseen by people like Sanjeev Gupta from Imperial College London. When I meet him, the geologist and senior member of the JPL science team is living on Mars time. “During the Mars night we prepare the sequences the rover has to do,” he explains. “Then we uplink those commands and, when the rover wakes up, it carries out those tasks. But a Mars day is 40 minutes longer than an Earth day so you get progressively out of synch, so the time I arrive at work changes by an hour every day.” And that’s not all. “We don’t get a signal direct from the rover to Earth,” says Gupta. “It has to go through communications satellites - Mars Reconnaissance Orbiter (MRO) and Odyssey - and these obviously have different times [when they’re overhead].” “Generally you’re moving an hour forward each day but suddenly, like tomorrow, I’m going to step back two hours. I’m progressively getting used to it but the first three weeks were awful,” he groans, “I was permanently exhausted.” Unexpected plans During the Martian night, dozens of scientists, including Gupta, anaylse the images and data coming back from the Red Planet and discuss what they want to do next. They hold a series of meetings to prioritise time on the instruments, choose which images to capture and where the rover’s going to move. “It’s quite complicated because you have to work out how much power each instrument is going to use and how much heating time they require,” Gupta says. “Because they’re so many instruments, everybody wants to have a go – so one instrument might get five minutes, another ten minutes.” Once the arguments are had and decisions reached, the drivers get to work, coding the next day’s instructions. And this is way more complicated than programming one of those ‘80s-era Big Trak robot toys. Curiosity is the fourth rover (since the 1996 Pathfinder mission) Nasa has run on Mars in recent years, and the procedures have got better with every mission. Armed with 3D images from its navigation cameras, the drivers work through the Martian night to map out the best, smoothest, route to the next destination. They factor in any stops along the way, to take pictures or operate an instrument, and run a simulation of the journey to double-check they have got it right. The aim is that when a new day dawns on Mars, the drivers are ready to go. Once either the Odyssey or MRO satellite is in the right place, they send a command to wake up the rover and upload its commands for the day. A bit like emailing a ‘to do’ list. Gupta admits that the whole process is more time consuming than he first imagined. “Things that I can do in an hour on Earth, take days on Mars. Usually on Earth I work by myself, here we’ve got a team of 200 scientists so we have to work out these interactions and protocols.” Once it’s started moving, Curiosity also has the ability to think for itself using data from its hazard avoidance cameras and built-in safely protocols. This autonomy should prevent it grounding on a rock or falling over an unexpected cliff but also adds to the pressure on the drivers and scientists planning each sol’s activities. This is where the rovers in Mars Yard come in handy. This dusty outdoor arena at the back of the lab is around the size of a couple of tennis courts. Strewn with boulders, mounds of sand and even a cliff face, it’s home to two full-scale mock-ups of Curiosity. Although the real thing was tested extensively before launch, these rovers are still in use everyday by drivers trying to choreograph movement on Mars. “We do have a pretty good idea how it’s going to perform,” Fuller confirms. “But these give us a chance, in flight, to modify and fine tune and to get as much bang for our buck as possible.” Specially, they allow engineers to test movements, software and work on any glitches that develop on the real thing. The first rover is an identical copy of Curiosity; it’s even loaded with the exact same software. The second – and the one (for obvious reasons) they let me control – is not fitted with the same onboard computers, earning it the nickname Scarecrow, because it doesn’t have a “brain”. Although it’s the same size as Curiosity, Scarecrow is lighter, to simulate the effects of moving around in the lower gravity of Mars. Scarecrow is little more than an impressively large remote controlled car. Scroll the tumblers to set distance and angle of movement on the iPhone app, hit go and it reacts instantly, there’s even a stop button if things start going awry. Thanks to the efforts of its drivers and the engineering team behind them, Curiosity has covered (at the time of writing) more than 300m (1,000ft), including a single push of 42m (138ft), its biggest roll to date since landing on Mars two months ago. Despite being millions of miles away, it’s considerably further than I achieve before grounding Scarecrow. “That’s the most fun a reporter has ever had with our rover,” says Fuller. I’m not sure he is paying me a compliment. If you would like to comment on this article or anything else you have seen on Future, head over to our Facebook page or message us on Twitter.
/** * This is the milk-standard extension to <code>EventObject</code>. It adds * type and argument fields, a <code>sendTo()</code> method, and a couple * other goodies. * * @author Dan Bornstein, [email protected] * @author Copyright 1999 Dan Bornstein, all rights reserved. */ abstract public class BaseEvent extends EventObject { /** the type tag */ protected final int myType; /** the argument */ protected final Object myArgument; /** the timestamp */ private final long myTimeStamp; /** * Construct a <code>BaseEvent</code>. * * @param source the source of the event * @param type the type of the event * @param argument the argument of the event */ public BaseEvent (Object source, int type, Object argument) { super (source); myType = type; myArgument = argument; myTimeStamp = System.currentTimeMillis (); } /** * Get the type of the event. * * @return the type */ public final int getType () { return myType; } /** * Get the type of the event as a string. * * @return the type string */ public final String getTypeString () { return typeToString (myType); } /** * Get the argment of the event. * * @return the argument */ public final Object getArgument () { return myArgument; } /** * Get the time stamp of the event. The time stamp is the moment * that the event was created, and is returned as a standard Java * time (milliseconds since whatever the hell that base date is... * 1-Jan-1970 midnight GMT or something like that). * * @return the time stamp of the event (msec since the base date) */ public final long getTimeStamp () { return myTimeStamp; } /** * Get the string form of this event. * * @return the string form */ public final String toString () { String result = "{" + getClass ().getName () + " " + source + " " + typeToString (myType); if (myArgument != null) { result += " " + myArgument; } result += "}"; return result; } /** * Turn the given type code into a string. Subclasses need to override * this method. It <i>really</i> wants to be an abstract <i>class</i> * (not <i>instance</i>) method, but Java doesn't do that. It just * sucks that way sometimes. * * @param type the type code to translate * @return the type as a string */ protected abstract String typeToString (int type); /** * Send this event to the given listener. Subclasses need to override * this method, implementing it to cast the listener to an appropriate * class and calling the appropriate method on it. * * @param listener the listener to send to */ public abstract void sendTo (EventListener listener); /** * Return true if this event is appropiate for the given listener. * Subclasses need to override this method, implementing it to do the * appropriate <code>instanceof</code> check, or whatever else it needs * to do to determine if the listener and event match. * * @param listener the listener to check * @return true if the listener listens to this kind of event */ public abstract boolean canSendTo (EventListener listener); }
// // TCP*Sockets. // Note that these will TCP*Socket::open() will *use* its existing file descriptor, // on the theory that the caller may have prepared it specially (e.g. to make it nonblocking). // void TCPClientSocket::open(const IPSockAddress &peer, int fdFlags) { prepare(fdFlags, AF_INET, SOCK_STREAM); connect(peer); }
/** * Measure the distance between two comments. * @param mutComment * @param testTargetComment * @return double * @date 2020/4/22 1:36 PM * @author sunweisong */ public static double measureDistanceBetweenTwoComments(String mutComment , String testTargetComment) { String commentDescription = mutComment; if (commentDescription == null) { return -1; } List<TokenModel> tokenModelList1 = NLPUtil.commentNLPProcessing(commentDescription); String[] keywordArray = testTargetComment.split(";"); List<TokenModel> tokenModelList2 = new ArrayList<>(keywordArray.length); for (String keyword : keywordArray) { int left = keyword.indexOf("{"); int right = keyword.lastIndexOf("}"); keyword = keyword.substring(left + 1, right); String[] elementArray = keyword.split(","); String token = elementArray[0]; left = token.indexOf("'"); right = token.lastIndexOf("'"); token = token.substring(left + 1, right); String pos = elementArray[1]; left = pos.indexOf("'"); right = pos.lastIndexOf("'"); pos = pos.substring(left + 1, right); String lemma = elementArray[2]; left = lemma.indexOf("'"); right = lemma.lastIndexOf("'"); lemma = lemma.substring(left + 1, right); tokenModelList2.add(new TokenModel(token, pos, lemma)); } Map<String, String> keywordMap1 = NLPUtil.getNormalizedToken(tokenModelList1); Map<String, String> keywordMap2 = NLPUtil.getNormalizedToken(tokenModelList2); double distance = NLPUtil.calculateJDTwoKeyWordMaps(keywordMap1, keywordMap2); return distance; }
Collision identification between convex polyhedra using neural networks Collision identification between convex polyhedra is a major research focus in computer-aided manufacturing and path planning for robots. This paper presents a collision-identification neural network (CINN) to identify possible collisions between two convex polyhedra. It consists of a modified Hamming net and a constraint subnet. The modified Hamming net is designed for point-to-polyhedron collision identification, and the constraint subnet is designed to move a point within a polyhedron and detect possible collisions with another polyhedron. A CINN has a simple canonical structure. It is very easy to program and can be implemented by a modest number of nonlinear amplifiers and three analog integrators. The working principle of the CINN is very similar to the well-known Hopfield net model. Its simple collective computing power accomplishes the relatively complicated task of collision identification between convex polyhedra, rendering a suitable device for online path planning of robots. An example is presented to demonstrate the application of CINN's to collision-free motion planning.
import * as statistics from '../util/statistics'; import { RowData } from '../helper'; export interface AggregateParams { as: string[]; fields?: string[]; groupBy?: string | string[]; op: Array<keyof typeof statistics>; } export declare function aggregate(rows: RowData[], options: AggregateParams): RowData[];
<reponame>crccheck/atx-bandc # Generated by Django 3.0.2 on 2020-01-19 03:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("agenda", "0003_auto_20160124_1941"), ] operations = [ migrations.AlterField( model_name="document", name="thumbnail", field=models.ImageField( blank=True, help_text="A jpeg of the first page", null=True, upload_to="thumbs/%Y/%m", ), ), ]
/** * Configure a new tape loading it from console user input. * * @throws IOException Signals that an I/O exception has occurred. */ public void configureTape(String white) throws IOException { if (tape == null) throw new NullPointerException("tape is null"); tape.clear(); System.out.print("Add a new tape: "); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String input = reader.readLine(); for (int i = 1; i <= input.length(); i++) { tape.add(input.substring(i - 1, i)); } tape.add(0, white); tape.add(0, white); tape.add(tape.size(), white); tape.add(tape.size(), white); if (!input.isEmpty()) System.out.println("Loaded tape: " + toString()); else System.out.println(toString()); }
package jei.collections2; public interface Bag<T> { void add(T value); }
<filename>src/shims/panic.rs<gh_stars>0 //! Panic runtime for Miri. //! //! The core pieces of the runtime are: //! - An implementation of `__rust_maybe_catch_panic` that pushes the invoked stack frame with //! some extra metadata derived from the panic-catching arguments of `__rust_maybe_catch_panic`. //! - A hack in `libpanic_unwind` that calls the `miri_start_panic` intrinsic instead of the //! target-native panic runtime. (This lives in the rustc repo.) //! - An implementation of `miri_start_panic` that stores its argument (the panic payload), and then //! immediately returns, but on the *unwind* edge (not the normal return edge), thus initiating unwinding. //! - A hook executed each time a frame is popped, such that if the frame pushed by `__rust_maybe_catch_panic` //! gets popped *during unwinding*, we take the panic payload and store it according to the extra //! metadata we remembered when pushing said frame. use syntax::source_map::Span; use rustc::mir; use rustc::ty::{self, layout::LayoutOf}; use rustc_target::spec::PanicStrategy; use crate::*; /// Holds all of the relevant data for a call to /// `__rust_maybe_catch_panic`. /// /// If a panic occurs, we update this data with /// the information from the panic site. #[derive(Debug)] pub struct CatchUnwindData<'tcx> { /// The dereferenced `data_ptr` argument passed to `__rust_maybe_catch_panic`. pub data_place: MPlaceTy<'tcx, Tag>, /// The dereferenced `vtable_ptr` argument passed to `__rust_maybe_catch_panic`. pub vtable_place: MPlaceTy<'tcx, Tag>, /// The `dest` from the original call to `__rust_maybe_catch_panic`. pub dest: PlaceTy<'tcx, Tag>, } impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {} pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> { /// Handles the special "miri_start_panic" intrinsic, which is called /// by libpanic_unwind to delegate the actual unwinding process to Miri. fn handle_miri_start_panic( &mut self, args: &[OpTy<'tcx, Tag>], unwind: Option<mir::BasicBlock> ) -> InterpResult<'tcx> { let this = self.eval_context_mut(); trace!("miri_start_panic: {:?}", this.frame().span); // Get the raw pointer stored in arg[0] (the panic payload). let scalar = this.read_immediate(args[0])?; assert!(this.machine.panic_payload.is_none(), "the panic runtime should avoid double-panics"); this.machine.panic_payload = Some(scalar); // Jump to the unwind block to begin unwinding. this.unwind_to_block(unwind); return Ok(()) } fn handle_catch_panic( &mut self, args: &[OpTy<'tcx, Tag>], dest: PlaceTy<'tcx, Tag>, ret: mir::BasicBlock, ) -> InterpResult<'tcx> { let this = self.eval_context_mut(); let tcx = &{this.tcx.tcx}; // fn __rust_maybe_catch_panic( // f: fn(*mut u8), // data: *mut u8, // data_ptr: *mut usize, // vtable_ptr: *mut usize, // ) -> u32 // Get all the arguments. let f = this.read_scalar(args[0])?.not_undef()?; let f_arg = this.read_scalar(args[1])?.not_undef()?; let data_place = this.deref_operand(args[2])?; let vtable_place = this.deref_operand(args[3])?; // Now we make a function call, and pass `f_arg` as first and only argument. let f_instance = this.memory.get_fn(f)?.as_instance()?; trace!("__rust_maybe_catch_panic: {:?}", f_instance); let ret_place = MPlaceTy::dangling(this.layout_of(tcx.mk_unit())?, this).into(); this.call_function( f_instance, &[f_arg.into()], Some(ret_place), // Directly return to caller. StackPopCleanup::Goto { ret: Some(ret), unwind: None }, )?; // We ourselves will return `0`, eventually (will be overwritten if we catch a panic). this.write_null(dest)?; // In unwind mode, we tag this frame with some extra data. // This lets `handle_stack_pop` (below) know that we should stop unwinding // when we pop this frame. if this.tcx.tcx.sess.panic_strategy() == PanicStrategy::Unwind { this.frame_mut().extra.catch_panic = Some(CatchUnwindData { data_place, vtable_place, dest, }) } return Ok(()); } fn handle_stack_pop( &mut self, mut extra: FrameData<'tcx>, unwinding: bool ) -> InterpResult<'tcx, StackPopInfo> { let this = self.eval_context_mut(); trace!("handle_stack_pop(extra = {:?}, unwinding = {})", extra, unwinding); // We only care about `catch_panic` if we're unwinding - if we're doing a normal // return, then we don't need to do anything special. let res = if let (true, Some(unwind_data)) = (unwinding, extra.catch_panic.take()) { // We've just popped a frame that was pushed by `__rust_maybe_catch_panic`, // and we are unwinding, so we should catch that. trace!("unwinding: found catch_panic frame during unwinding: {:?}", this.frame().span); // `panic_payload` now holds a `*mut (dyn Any + Send)`, // provided by the `miri_start_panic` intrinsic. // We want to split this into its consituient parts - // the data and vtable pointers - and store them according to // `unwind_data`, i.e., we store them where `__rust_maybe_catch_panic` // was told to put them. let payload = this.machine.panic_payload.take().unwrap(); let payload = this.ref_to_mplace(payload)?; let payload_data_place = payload.ptr; let payload_vtable_place = payload.meta.expect("Expected fat pointer"); this.write_scalar(payload_data_place, unwind_data.data_place.into())?; this.write_scalar(payload_vtable_place, unwind_data.vtable_place.into())?; // We set the return value of `__rust_maybe_catch_panic` to 1, // since there was a panic. let dest = unwind_data.dest; this.write_scalar(Scalar::from_int(1, dest.layout.size), dest)?; StackPopInfo::StopUnwinding } else { StackPopInfo::Normal }; this.memory.extra.stacked_borrows.borrow_mut().end_call(extra.call_id); Ok(res) } fn assert_panic( &mut self, span: Span, msg: &AssertMessage<'tcx>, unwind: Option<mir::BasicBlock>, ) -> InterpResult<'tcx> { use rustc::mir::interpret::PanicInfo::*; let this = self.eval_context_mut(); match msg { BoundsCheck { ref index, ref len } => { // Forward to `panic_bounds_check` lang item. // First arg: Caller location. let location = this.alloc_caller_location_for_span(span); // Second arg: index. let index = this.read_scalar(this.eval_operand(index, None)?)?; // Third arg: len. let len = this.read_scalar(this.eval_operand(len, None)?)?; // Call the lang item. let panic_bounds_check = this.tcx.lang_items().panic_bounds_check_fn().unwrap(); let panic_bounds_check = ty::Instance::mono(this.tcx.tcx, panic_bounds_check); this.call_function( panic_bounds_check, &[location.ptr.into(), index.into(), len.into()], None, StackPopCleanup::Goto { ret: None, unwind }, )?; } _ => { // Forward everything else to `panic` lang item. // First arg: Message. let msg = msg.description(); let msg = this.allocate_str(msg, MiriMemoryKind::Env.into()); // Second arg: Caller location. let location = this.alloc_caller_location_for_span(span); // Call the lang item. let panic = this.tcx.lang_items().panic_fn().unwrap(); let panic = ty::Instance::mono(this.tcx.tcx, panic); this.call_function( panic, &[msg.to_ref(), location.ptr.into()], None, StackPopCleanup::Goto { ret: None, unwind }, )?; } } Ok(()) } }
/// this method is called in one pass over all drawables after finish frame void antialias::after_finish(cgv::render::context& ctx) { if (multi_pass_ignore_finish(ctx)) return; glReadBuffer(GL_BACK); glAccum(GL_ACCUM, 1.0f/nr_samples); if (multi_pass_terminate(ctx)) { glAccum(GL_RETURN, 1.0f); restore_view(ctx, 0); } }
package fi.kapsi.kosmik.javamididecoder; import fi.kapsi.kosmik.javamididecoder.MidiMetaM.MidiChannelPrefixM; import fi.kapsi.kosmik.javamididecoder.MidiMetaM.MidiEndOfTrackM; import fi.kapsi.kosmik.javamididecoder.MidiMetaM.MidiKeySignatureM; import fi.kapsi.kosmik.javamididecoder.MidiMetaM.MidiMetaMVisitor; import fi.kapsi.kosmik.javamididecoder.MidiMetaM.MidiMetaTextM; import fi.kapsi.kosmik.javamididecoder.MidiMetaM.MidiSMTPEOffsetM; import fi.kapsi.kosmik.javamididecoder.MidiMetaM.MidiSequenceNumberM; import fi.kapsi.kosmik.javamididecoder.MidiMetaM.MidiSequencerSpecificMetaM; import fi.kapsi.kosmik.javamididecoder.MidiMetaM.MidiTempoM; import fi.kapsi.kosmik.javamididecoder.MidiMetaM.MidiTimeSignatureM; import fi.kapsi.kosmik.javamididecoder.MidiMetaM.MidiUnsupportedMetaM; import static fi.kapsi.kosmik.javamididecoder.Util.getHexString; import static java.lang.String.format; public class DescribingMidiMetaMVisitor implements MidiMetaMVisitor<String> { @Override public String visit(MidiSequenceNumberM m) { return format("sequence number %d", m.getNumber()); } @Override public String visit(MidiMetaTextM m) { return format("%s: %s", m.getType().label.toLowerCase(), m.getText()); } @Override public String visit(MidiChannelPrefixM m) { return format("channel prefix %d", m.getPrefix()); } @Override public String visit(MidiEndOfTrackM m) { return "end of track"; } @Override public String visit(MidiTempoM m) { return format("tempo %.2f bpm, %s microseconds per beat", m.getBpm(), m.getMicrosecondsPerBeat()); } @Override public String visit(MidiSMTPEOffsetM m) { return format("%d:%d:%d.%d.%d", m.getPart1(), m.getPart2(), m.getPart3(), m.getPart4(), m.getPart5()); } @Override public String visit(MidiTimeSignatureM m) { return format("time signature %d/%d", m.getTimeSignature().getBeats(), m.getTimeSignature().getUnit()); } @Override public String visit(MidiKeySignatureM m) { return format("key signature %s", m.getDescription()); } @Override public String visit(MidiSequencerSpecificMetaM m) { return format("sequencer specific meta: %s", getHexString(m.getData())); } @Override public String visit(MidiUnsupportedMetaM m) { return format("unsupported meta message: [%s]", getHexString(m.getData())); } }
/** * This is a subclas of PGgeometry that uses hex encoded EWKB to communicate * with the backend, which is much more efficient, but only works with Lwgeom * enabled PostGIS (1.0.0 and up). */ public class PGgeometryLW extends PGgeometry { /* JDK 1.5 Serialization */ private static final long serialVersionUID = 0x100; BinaryWriter bw = new BinaryWriter(); public PGgeometryLW() { super(); } public PGgeometryLW(Geometry geom) { super(geom); } public PGgeometryLW(String value) throws SQLException { super(value); } public String toString() { return geom.toString(); } public String getValue() { return bw.writeHexed(geom); } public Object clone() { return new PGgeometryLW(geom); } }
'The more things change…': Barriers to community services utilisation in Queensland Community services are central to the lives of many elderly Australians or Australians with disabilities if they are to remain in the community. Over the past two decades, significant advances have been made in policy and associated programs, significantly improving the standards of service delivery. This research reports on the perceptions of service providers in community services for people with disabilities in six communities in Queensland. It illustrates that significant barriers to service utilisation remain, despite reform. It suggests that continuous efforts to promote service access need to be built in at the program level.
The Impact of Level of Education, Teaching Experience and Gender on Professionalism and Performance: The Case Study of Universitas Muhammadiyah Palembang’s Academic Teaching Staffs This study investigates the impact of education level, teaching experience and gender on professionalism and performance of academic teaching staffs at the University of Muhammadiyah Palembang. In 2017, there are 431 academic teaching staffs across seven faculties and one graduate study program as the population study and the sample size is 355 respondents. This study uses survey research method to collect the data using closed-ended questionnairre. Professionalism is measured using the sertification status and the performance is measured using the number of publication during the last three years. Education level is measured using the degree qualification such as master degree, doctoral degree and professorship. Teaching experience is measured using the length of teaching experience and the gender is measured as sex status such as male and female academic teaching staffs. The data is analysed using ordinary least square (OLS). The result shows that there is a significant impact of education level, teaching experience and gender on professionalism and performance of academic teaching staffs.
// -*- C++ -*- // // Package: SimMuon/MCTruth // Class: MuonToTrackingParticleAssociatorEDProducer // /**\class MuonToTrackingParticleAssociatorEDProducer MuonToTrackingParticleAssociatorEDProducer.cc SimMuon/MCTruth/plugins/MuonToTrackingParticleAssociatorEDProducer.cc Description: [one line class summary] Implementation: [Notes on implementation] */ // // Original Author: <NAME> // Created: Wed, 07 Jan 2015 21:30:14 GMT // // // system include files #include <memory> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/stream/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "Geometry/Records/interface/TrackerTopologyRcd.h" #include "Geometry/TrackerGeometryBuilder/interface/TrackerGeometry.h" #include "MuonToTrackingParticleAssociatorByHitsImpl.h" #include "SimDataFormats/Associations/interface/MuonToTrackingParticleAssociator.h" #include "SimMuon/MCTruth/interface/TrackerMuonHitExtractor.h" // // class declaration // namespace { using TrackHitsCollection = MuonAssociatorByHitsHelper::TrackHitsCollection; class InputDumper { public: InputDumper(const edm::ParameterSet &conf, edm::ConsumesCollector &&iC) : simtracksTag(conf.getParameter<edm::InputTag>("simtracksTag")), simtracksXFTag(conf.getParameter<edm::InputTag>("simtracksXFTag")), crossingframe(conf.getParameter<bool>("crossingframe")) { if (crossingframe) { simtracksXFToken_ = iC.consumes<CrossingFrame<SimTrack>>(simtracksXFTag); simvertsXFToken_ = iC.consumes<CrossingFrame<SimVertex>>(simtracksXFTag); } else { simtracksToken_ = iC.consumes<edm::SimTrackContainer>(simtracksTag); simvertsToken_ = iC.consumes<edm::SimVertexContainer>(simtracksTag); } } void read(const edm::Event &); void dump(const TrackHitsCollection &, const TrackingParticleCollection &) const; private: edm::InputTag simtracksTag; edm::InputTag simtracksXFTag; edm::EDGetTokenT<CrossingFrame<SimTrack>> simtracksXFToken_; edm::EDGetTokenT<CrossingFrame<SimVertex>> simvertsXFToken_; edm::EDGetTokenT<edm::SimTrackContainer> simtracksToken_; edm::EDGetTokenT<edm::SimVertexContainer> simvertsToken_; edm::Handle<CrossingFrame<SimTrack>> simtracksXF_; edm::Handle<CrossingFrame<SimVertex>> simvertsXF_; edm::Handle<edm::SimTrackContainer> simtracks_; edm::Handle<edm::SimVertexContainer> simverts_; bool const crossingframe; }; void InputDumper::read(const edm::Event &iEvent) { if (crossingframe) { iEvent.getByToken(simtracksXFToken_, simtracksXF_); iEvent.getByToken(simvertsXFToken_, simvertsXF_); } else { iEvent.getByToken(simtracksToken_, simtracks_); iEvent.getByToken(simvertsToken_, simverts_); } } void InputDumper::dump(const TrackHitsCollection &tC, const TrackingParticleCollection &tPC) const { using namespace std; // reco::Track collection edm::LogVerbatim("MuonToTrackingParticleAssociatorEDProducer") << "\n" << "reco::Track collection --- size = " << tC.size(); // TrackingParticle collection edm::LogVerbatim("MuonToTrackingParticleAssociatorEDProducer") << "\n" << "TrackingParticle collection --- size = " << tPC.size(); int j = 0; for (TrackingParticleCollection::const_iterator ITER = tPC.begin(); ITER != tPC.end(); ITER++, j++) { edm::LogVerbatim("MuonToTrackingParticleAssociatorEDProducer") << "TrackingParticle " << j << ", q = " << ITER->charge() << ", p = " << ITER->p() << ", pT = " << ITER->pt() << ", eta = " << ITER->eta() << ", phi = " << ITER->phi(); edm::LogVerbatim("MuonToTrackingParticleAssociatorEDProducer") << "\t pdg code = " << ITER->pdgId() << ", made of " << ITER->numberOfHits() << " PSimHit" << " (in " << ITER->numberOfTrackerLayers() << " layers)" << " from " << ITER->g4Tracks().size() << " SimTrack:"; for (TrackingParticle::g4t_iterator g4T = ITER->g4Track_begin(); g4T != ITER->g4Track_end(); g4T++) { edm::LogVerbatim("MuonToTrackingParticleAssociatorEDProducer") << "\t\t Id:" << g4T->trackId() << "/Evt:(" << g4T->eventId().event() << "," << g4T->eventId().bunchCrossing() << ")"; } } if (crossingframe) { std::unique_ptr<MixCollection<SimTrack>> SimTk(new MixCollection<SimTrack>(simtracksXF_.product())); edm::LogVerbatim("MuonToTrackingParticleAssociatorEDProducer") << "\n" << "CrossingFrame<SimTrack> collection with InputTag = " << simtracksXFTag << " has size = " << SimTk->size(); int k = 0; for (MixCollection<SimTrack>::MixItr ITER = SimTk->begin(); ITER != SimTk->end(); ITER++, k++) { edm::LogVerbatim("MuonToTrackingParticleAssociatorEDProducer") << "SimTrack " << k << " - Id:" << ITER->trackId() << "/Evt:(" << ITER->eventId().event() << "," << ITER->eventId().bunchCrossing() << ")" << ", q = " << ITER->charge() << ", p = " << ITER->momentum().P() << ", pT = " << ITER->momentum().Pt() << ", eta = " << ITER->momentum().Eta() << ", phi = " << ITER->momentum().Phi() << "\n\t pdgId = " << ITER->type() << ", Vertex index = " << ITER->vertIndex() << ", Gen Particle index = " << (ITER->genpartIndex() > 0 ? ITER->genpartIndex() - 1 : ITER->genpartIndex()) << endl; } std::unique_ptr<MixCollection<SimVertex>> SimVtx(new MixCollection<SimVertex>(simvertsXF_.product())); edm::LogVerbatim("MuonToTrackingParticleAssociatorEDProducer") << "\n" << "CrossingFrame<SimVertex> collection with InputTag = " << simtracksXFTag << " has size = " << SimVtx->size(); int kv = 0; for (MixCollection<SimVertex>::MixItr VITER = SimVtx->begin(); VITER != SimVtx->end(); VITER++, kv++) { edm::LogVerbatim("MuonToTrackingParticleAssociatorEDProducer") << "SimVertex " << kv << " - Id:" << VITER->vertexId() << ", position = " << VITER->position() << ", parent SimTrack Id = " << VITER->parentIndex() << ", processType = " << VITER->processType(); } } else { const edm::SimTrackContainer simTC = *(simtracks_.product()); edm::LogVerbatim("MuonToTrackingParticleAssociatorEDProducer") << "\n" << "SimTrack collection with InputTag = " << simtracksTag << " has size = " << simTC.size() << endl; int k = 0; for (edm::SimTrackContainer::const_iterator ITER = simTC.begin(); ITER != simTC.end(); ITER++, k++) { edm::LogVerbatim("MuonToTrackingParticleAssociatorEDProducer") << "SimTrack " << k << " - Id:" << ITER->trackId() << "/Evt:(" << ITER->eventId().event() << "," << ITER->eventId().bunchCrossing() << ")" << ", q = " << ITER->charge() << ", p = " << ITER->momentum().P() << ", pT = " << ITER->momentum().Pt() << ", eta = " << ITER->momentum().Eta() << ", phi = " << ITER->momentum().Phi() << "\n\t pdgId = " << ITER->type() << ", Vertex index = " << ITER->vertIndex() << ", Gen Particle index = " << (ITER->genpartIndex() > 0 ? ITER->genpartIndex() - 1 : ITER->genpartIndex()) << endl; } const edm::SimVertexContainer simVC = *(simverts_.product()); edm::LogVerbatim("MuonToTrackingParticleAssociatorEDProducer") << "\n" << "SimVertex collection with InputTag = " << "g4SimHits" << " has size = " << simVC.size() << endl; int kv = 0; for (edm::SimVertexContainer::const_iterator VITER = simVC.begin(); VITER != simVC.end(); VITER++, kv++) { edm::LogVerbatim("MuonToTrackingParticleAssociatorEDProducer") << "SimVertex " << kv << " - Id:" << VITER->vertexId() << ", position = " << VITER->position() << ", parent SimTrack Id = " << VITER->parentIndex() << ", processType = " << VITER->processType(); } } } } // namespace class MuonToTrackingParticleAssociatorEDProducer : public edm::stream::EDProducer<> { public: explicit MuonToTrackingParticleAssociatorEDProducer(const edm::ParameterSet &); ~MuonToTrackingParticleAssociatorEDProducer() override; static void fillDescriptions(edm::ConfigurationDescriptions &descriptions); private: void produce(edm::Event &, const edm::EventSetup &) override; // ----------member data --------------------------- edm::ParameterSet const config_; MuonAssociatorByHitsHelper helper_; TrackerHitAssociator::Config trackerHitAssociatorConfig_; TrackerMuonHitExtractor hitExtractor_; std::unique_ptr<RPCHitAssociator> rpctruth_; std::unique_ptr<GEMHitAssociator> gemtruth_; std::unique_ptr<DTHitAssociator> dttruth_; std::unique_ptr<CSCHitAssociator> csctruth_; std::unique_ptr<TrackerHitAssociator> trackertruth_; std::unique_ptr<InputDumper> diagnostics_; }; // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // MuonToTrackingParticleAssociatorEDProducer::MuonToTrackingParticleAssociatorEDProducer(const edm::ParameterSet &iConfig) : config_(iConfig), helper_(iConfig), trackerHitAssociatorConfig_(iConfig, consumesCollector()), hitExtractor_(iConfig, consumesCollector()) { // register your products produces<reco::MuonToTrackingParticleAssociator>(); // hack for consumes RPCHitAssociator rpctruth(iConfig, consumesCollector()); GEMHitAssociator gemtruth(iConfig, consumesCollector()); DTHitAssociator dttruth(iConfig, consumesCollector()); CSCHitAssociator cscruth(iConfig, consumesCollector()); edm::LogVerbatim("MuonToTrackingParticleAssociatorEDProducer") << "\n constructing MuonToTrackingParticleAssociatorEDProducer" << "\n"; if (iConfig.getUntrackedParameter<bool>("dumpInputCollections")) { diagnostics_ = std::make_unique<InputDumper>(iConfig, consumesCollector()); } } MuonToTrackingParticleAssociatorEDProducer::~MuonToTrackingParticleAssociatorEDProducer() { // do anything here that needs to be done at desctruction time // (e.g. close files, deallocate resources etc.) } // // member functions // // ------------ method called to produce the data ------------ void MuonToTrackingParticleAssociatorEDProducer::produce(edm::Event &iEvent, const edm::EventSetup &iSetup) { using namespace edm; hitExtractor_.init(iEvent, iSetup); // Retrieve tracker topology from geometry edm::ESHandle<TrackerTopology> tTopoHand; iSetup.get<TrackerTopologyRcd>().get(tTopoHand); const TrackerTopology *tTopo = tTopoHand.product(); bool printRtS = true; // NOTE: This assumes that produce will not be called until the edm::Event // used in the previous call // has been deleted. This is true for now. In the future, we may have to have // the resources own the memory. // Tracker hit association trackertruth_ = std::make_unique<TrackerHitAssociator>(iEvent, trackerHitAssociatorConfig_); // CSC hit association csctruth_ = std::make_unique<CSCHitAssociator>(iEvent, iSetup, config_); // DT hit association printRtS = false; dttruth_ = std::make_unique<DTHitAssociator>(iEvent, iSetup, config_, printRtS); // RPC hit association rpctruth_ = std::make_unique<RPCHitAssociator>(iEvent, iSetup, config_); // GEM hit association gemtruth_ = std::make_unique<GEMHitAssociator>(iEvent, iSetup, config_); MuonAssociatorByHitsHelper::Resources resources = { tTopo, trackertruth_.get(), csctruth_.get(), dttruth_.get(), rpctruth_.get(), gemtruth_.get(), {}}; if (diagnostics_) { diagnostics_->read(iEvent); resources.diagnostics_ = [this](const TrackHitsCollection &hC, const TrackingParticleCollection &pC) { diagnostics_->dump(hC, pC); }; } std::unique_ptr<reco::MuonToTrackingParticleAssociatorBaseImpl> impl{ new MuonToTrackingParticleAssociatorByHitsImpl(hitExtractor_, resources, &helper_)}; std::unique_ptr<reco::MuonToTrackingParticleAssociator> toPut( new reco::MuonToTrackingParticleAssociator(std::move(impl))); iEvent.put(std::move(toPut)); } // ------------ method fills 'descriptions' with the allowed parameters for the // module ------------ void MuonToTrackingParticleAssociatorEDProducer::fillDescriptions(edm::ConfigurationDescriptions &descriptions) { // The following says we do not know what parameters are allowed so do no // validation // Please change this to state exactly what you do use, even if it is no // parameters edm::ParameterSetDescription desc; desc.setUnknown(); descriptions.addDefault(desc); } // define this as a plug-in DEFINE_FWK_MODULE(MuonToTrackingParticleAssociatorEDProducer);
Orf in Britain. law courts. By the time that stage is reached the recollection of the caller may have been blurred (as may that of the doctor) so that the service committee or judge has to decide which of two conflicting accounts to believe as to the precise questions asked by the doctor, the information given to him, and the advice finally given. Both parties may be endeavouring to tell the truth and both may be mistaken. One knows that before certain tribunals the following argument is often used: (1) The doctor may deal with 60 patients per day. (2) A night telephone caller to a doctor is usually doing something unusual and is therefore unlikely to be confused in his recollection about what happened. (3) Accordingly the account of the caller is to be preferred to that of the doctor. These are some of the dangers which surround a doctor who upon receipt of a night telephone call decides not to visit the patient unless he is called a second time.
/** * Implementation of a class Random to generate random int, double, pair * or vector * * The methode "getInstance" is used to initialize the instance of * class Random, the methode "getDouble" is used to generate a double * randomly,the methode "getInt" is used to generate an int between * ]"a", "b"[randomly, "getPair" is used to generate a pair of type * pair<pair<int, int>, pair<int, int>> randomly, "getVector" is used * to generate a normalised vector with length "n". * * */ class Random{ private: static Random* instance; Random(){ srand (time(NULL)); } public: static Random *getInstance() { if (!instance) instance = new Random(); return instance; } double getDouble(){ double rnd = ((double) rand() / (RAND_MAX)) ; return rnd; } bool getBool(){ return rand() % 2 ; } int getInt(int a , int b){ assert( a < b ); int val = a + rand() % (( b + 1 ) - a); assert( val >= a && val <= b ); return val; } ii getPair( int a, int b){ return make_pair( getInt(a, b), getInt(a,b )); } vector< float > getVector( int n ){ long double sum = 0; vector< float > res; for( int i = 0; i < n ; i++){ res.push_back( this->getInt(1, 101)); sum += res.back(); } assert( sum >= 1.); for( int i =0; i < n; i++) res[i] /= sum; return res; } unsigned char * getDarkColor(){ unsigned char *color = new unsigned char[ 3 ]; color[ 0 ] = static_cast<int>( Random::getInstance()->getInt(0, 128) ); color[ 1 ] = static_cast<int>( Random::getInstance()->getInt(0, 128) ); color[ 2 ] = static_cast<int>( Random::getInstance()->getInt(0, 128) ); return color; } }
def is_defun(fn): return isinstance( fn, ( function._DefinedFunction, function._OverloadedFunction ))
use std::env; use std::process::Command; use std::fs::File; use std::path::Path; #[cfg(target_os = "windows")] const PYTHON: &'static str = "python"; #[cfg(not(target_os = "windows"))] const PYTHON: &'static str = "python3"; fn main() { let decoders = [ "src/cpu/arm.decoder", "src/cpu/thumb.decoder", "src/io/dmac.decoder" ]; for decoder in decoders.iter() { let out_dir = env::var("OUT_DIR").unwrap(); let filename = Path::new(decoder).file_name().unwrap(); let out = format!("{}/{}.rs", out_dir, filename.to_os_string().to_str().unwrap()); let decoder_stat = Command::new(PYTHON) .arg("tools/decoder-gen/decoder-gen.py") .arg(decoder) .stdout(File::create(&out).unwrap()) .output() .expect("failed to execute child"); if !decoder_stat.status.success() { use std::io::{stderr, Write}; eprintln!("ERROR: decoder generation failed on {}!", out); eprintln!("Script stderr:"); stderr().write_all(&decoder_stat.stderr).unwrap(); } println!("cargo:rerun-if-changed={}", decoder); } }
# -*- coding:utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement from networkapi.infrastructure.xml_utils import loads, XMLError, dumps_networkapi from networkapi.rest import RestResource from networkapi.admin_permission import AdminPermission from networkapi.auth import has_perm from networkapi.grupo.models import * import logging from networkapi.distributedlock import distributedlock, LOCK_GROUP_USER, LOCK_GROUP_EQUIPMENT, LOCK_PERM, LOCK_GROUP_RIGHTS from networkapi.util import is_valid_string_maxsize, is_valid_int_greater_zero_param,\ destroy_cache_function from networkapi.exception import InvalidValueError class GrupoEquipamentoResource(RestResource): log = logging.getLogger('GrupoEquipamentoResource') def handle_get(self, request, user, *args, **kwargs): '''Trata as requisições de GET para listar todos os grupos de equipamento. URL: egrupo/$ ''' try: if not has_perm(user, AdminPermission.EQUIPMENT_GROUP_MANAGEMENT, AdminPermission.READ_OPERATION): return self.not_authorized() egroups = EGrupo.search() map_list = [] for egroup in egroups: egroup_map = dict() egroup_map['id'] = egroup.id egroup_map['nome'] = egroup.nome map_list.append(egroup_map) return self.response(dumps_networkapi({'grupo': map_list})) except (GrupoError): return self.response_error(1) def handle_post(self, request, user, *args, **kwargs): """Trata as requisições de POST para inserir um grupo de equipamento. URL: egrupo/ """ try: if not has_perm(user, AdminPermission.EQUIPMENT_GROUP_MANAGEMENT, AdminPermission.WRITE_OPERATION): return self.not_authorized() xml_map, attrs_map = loads(request.raw_post_data) self.log.debug('XML_MAP: %s', xml_map) networkapi_map = xml_map.get('networkapi') if networkapi_map is None: return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.') egroup_map = networkapi_map.get('grupo') if egroup_map is None: return self.response_error(3, u'Não existe valor para a tag grupo do XML de requisição.') name = egroup_map.get('nome') if not is_valid_string_maxsize(name, 100): self.log.error(u'Parameter name is invalid. Value: %s', name) raise InvalidValueError(None, 'name', name) egroup = EGrupo() egroup.nome = name egroup.create(user) return self.response(dumps_networkapi({'grupo': {'id': egroup.id}})) except InvalidValueError, e: return self.response_error(269, e.param, e.value) except EGrupoNameDuplicatedError: return self.response_error(254, name) except XMLError, x: self.log.error(u'Erro ao ler o XML da requisicao.') return self.response_error(3, x) except GrupoError: return self.response_error(1) def handle_put(self, request, user, *args, **kwargs): """Trata as requisições de PUT para alterar um grupo de equipamento. URL: egrupo/<id_grupo>/ """ try: egroup_id = kwargs.get('id_grupo') if not is_valid_int_greater_zero_param(egroup_id): self.log.error( u'The egroup_id parameter is not a valid value: %s.', egroup_id) raise InvalidValueError(None, 'egroup_id', egroup_id) egrp = EGrupo.get_by_pk(egroup_id) if not has_perm(user, AdminPermission.EQUIPMENT_GROUP_MANAGEMENT, AdminPermission.WRITE_OPERATION): return self.not_authorized() xml_map, attrs_map = loads(request.raw_post_data) self.log.debug('XML_MAP: %s', xml_map) networkapi_map = xml_map.get('networkapi') if networkapi_map is None: return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.') egroup_map = networkapi_map.get('grupo') if egroup_map is None: return self.response_error(3, u'Não existe valor para a tag grupo do XML de requisição.') name = egroup_map.get('nome') if not is_valid_string_maxsize(name, 100): self.log.error(u'Parameter name is invalid. Value: %s', name) raise InvalidValueError(None, 'name', name) with distributedlock(LOCK_GROUP_EQUIPMENT % egroup_id): # Destroy equipment's cache equip_id_list = [] for equipament in egrp.equipamento_set.all(): equip_id_list.append(equipament.id) destroy_cache_function(equip_id_list, True) EGrupo.update(user, egroup_id, nome=name) return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value) except EGrupoNotFoundError: return self.response_error(102) except EGrupoNameDuplicatedError: return self.response_error(254, name) except XMLError, x: self.log.error(u'Erro ao ler o XML da requisicao.') return self.response_error(3, x) except GrupoError: return self.response_error(1) def handle_delete(self, request, user, *args, **kwargs): """Trata as requisições de DELETE para remover um grupo de equipamento. URL: egrupo/<id_grupo>/ """ try: egroup_id = kwargs.get('id_grupo') if not is_valid_int_greater_zero_param(egroup_id): self.log.error( u'The egroup_id parameter is not a valid value: %s.', egroup_id) raise InvalidValueError(None, 'egroup_id', egroup_id) egrp = EGrupo.get_by_pk(egroup_id) if not has_perm(user, AdminPermission.EQUIPMENT_GROUP_MANAGEMENT, AdminPermission.WRITE_OPERATION): return self.not_authorized() with distributedlock(LOCK_GROUP_EQUIPMENT % egroup_id): EGrupo.remove(user, egroup_id) return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value) except GroupDontRemoveError, e: return self.response_error(310, e.cause, e.message) except EGrupoNotFoundError: return self.response_error(102) except GrupoError: return self.response_error(1) class DireitoGrupoEquipamentoResource(RestResource): log = logging.getLogger('DireitoGrupoEquipamentoResource') def __get_direito_map(self, direito): direito_map = dict() direito_map['id'] = direito.id direito_map['id_grupo_usuario'] = direito.ugrupo_id direito_map['nome_grupo_usuario'] = direito.ugrupo.nome direito_map['id_grupo_equipamento'] = direito.egrupo_id direito_map['nome_grupo_equipamento'] = direito.egrupo.nome direito_map['leitura'] = direito.leitura direito_map['escrita'] = direito.escrita direito_map['alterar_config'] = direito.alterar_config direito_map['exclusao'] = direito.exclusao return direito_map def handle_get(self, request, user, *args, **kwargs): '''Trata as requisições de GET para listar os direitos de grupo de usuários em grupo de equipamentos. URLs: direitosgrupoequipamento/$ direitosgrupoequipamento/ugrupo/<id_grupo_usuario>/$ direitosgrupoequipamento/egrupo/<id_grupo_equipamento>/$ direitosgrupoequipamento/<id_direito>/$ ''' try: if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.READ_OPERATION): return self.not_authorized() map_list = [] right_id = kwargs.get('id_direito') if not is_valid_int_greater_zero_param(right_id, False): self.log.error( u'The right_id parameter is not a valid value: %s.', right_id) raise InvalidValueError(None, 'right_id', right_id) if right_id is not None: map_list.append( self.__get_direito_map(DireitosGrupoEquipamento.get_by_pk(right_id))) else: ugroup = kwargs.get('id_grupo_usuario') egroup = kwargs.get('id_grupo_equipamento') if not is_valid_int_greater_zero_param(ugroup, False): self.log.error( u'The ugroup_id parameter is not a valid value: %s.', ugroup) raise InvalidValueError(None, 'ugroup_id', ugroup) if not is_valid_int_greater_zero_param(egroup, False): self.log.error( u'The egroup_id parameter is not a valid value: %s.', egroup) raise InvalidValueError(None, 'egroup_id', egroup) if ugroup is not None: UGrupo.get_by_pk(ugroup) if egroup is not None: EGrupo.get_by_pk(egroup) rights = DireitosGrupoEquipamento.search(ugroup, None, egroup) for right in rights: map_list.append(self.__get_direito_map(right)) return self.response(dumps_networkapi({'direito_grupo_equipamento': map_list})) except InvalidValueError, e: return self.response_error(269, e.param, e.value) except DireitosGrupoEquipamento.DoesNotExist: return self.response_error(258, right_id) except EGrupoNotFoundError: return self.response_error(102) except UGrupoNotFoundError: return self.response_error(180, ugroup) except (GrupoError): return self.response_error(1) def __valida_id_ugrupo(self, id_grupo): if id_grupo is None: return self.response_error(235) try: id_grupo = int(id_grupo) except (TypeError, ValueError): self.log.error( u'Valor do id_grupo_usuario inválido: %s.', id_grupo) return self.response_error(180, id_grupo) return None def __valida_id_egrupo(self, id_grupo): if id_grupo is None: return self.response_error(106) try: id_grupo = int(id_grupo) except (TypeError, ValueError): self.log.error( u'Valor do id_grupo_equipamento inválido: %s.', id_grupo) return self.response_error(102) return None def __valida_request(self, direito_map, handle_post=True): if handle_post: id_ugrupo = direito_map.get('id_grupo_usuario') response = self.__valida_id_ugrupo(id_ugrupo) if response is not None: return response id_egrupo = direito_map.get('id_grupo_equipamento') response = self.__valida_id_egrupo(id_egrupo) if response is not None: return response read = direito_map.get('leitura') if read is None: raise InvalidValueError(None, 'leitura', read) elif (read == "0"): direito_map['leitura'] = False elif (read == "1"): direito_map['leitura'] = True else: raise InvalidValueError(None, 'leitura', read) write = direito_map.get('escrita') if write is None: raise InvalidValueError(None, 'escrita', write) elif (write == "0"): direito_map['escrita'] = False elif (write == "1"): direito_map['escrita'] = True else: raise InvalidValueError(None, 'escrita', write) update_config = direito_map.get('alterar_config') if update_config is None: raise InvalidValueError(None, 'alterar_config', update_config) elif (update_config == "0"): direito_map['alterar_config'] = False elif (update_config == "1"): direito_map['alterar_config'] = True else: raise InvalidValueError(None, 'alterar_config', update_config) delete = direito_map.get('exclusao') if delete is None: raise InvalidValueError(None, 'exclusao', delete) elif (delete == "0"): direito_map['exclusao'] = False elif (delete == "1"): direito_map['exclusao'] = True else: raise InvalidValueError(None, 'exclusao', delete) return None def handle_post(self, request, user, *args, **kwargs): """Trata as requisições de POST para inserir direitos de um grupo de usuário em um grupo de equipamento. URL: direitosgrupoequipamento/ """ try: if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.WRITE_OPERATION): return self.not_authorized() try: xml_map, attrs_map = loads(request.raw_post_data) self.log.debug('XML_MAP: %s', xml_map) except XMLError, x: self.log.error(u'Erro ao ler o XML da requisicao.') return self.response_error(3, x) networkapi_map = xml_map.get('networkapi') if networkapi_map is None: return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.') direito_map = networkapi_map.get('direito_grupo_equipamento') if direito_map is None: return self.response_error(3, u'Não existe valor para a tag direito_grupo_equipamento do XML de requisição.') response = self.__valida_request(direito_map) if response is not None: return response direito = DireitosGrupoEquipamento() direito.egrupo = EGrupo(id=direito_map.get('id_grupo_equipamento')) direito.ugrupo = UGrupo(id=direito_map.get('id_grupo_usuario')) direito.leitura = direito_map.get('leitura') direito.escrita = direito_map.get('escrita') direito.alterar_config = direito_map.get('alterar_config') direito.exclusao = direito_map.get('exclusao') direito.create(user) return self.response(dumps_networkapi({'direito_grupo_equipamento': {'id': direito.id}})) except InvalidValueError, e: return self.response_error(269, e.param, e.value) except UGrupo.DoesNotExist: return self.response_error(180, direito_map.get('id_grupo_usuario')) except EGrupoNotFoundError: return self.response_error(102) except DireitoGrupoEquipamentoDuplicatedError: return self.response_error(267, direito_map.get('id_grupo_usuario'), direito_map.get('id_grupo_equipamento')) except (GrupoError): return self.response_error(1) def handle_put(self, request, user, *args, **kwargs): """Trata as requisições de PUT para alterar direitos de um grupo de usuário em um grupo de equipamento. URL: direitosgrupoequipamento/<id_direito>/ """ try: if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.WRITE_OPERATION): return self.not_authorized() right_id = kwargs.get('id_direito') if not is_valid_int_greater_zero_param(right_id): self.log.error( u'The right_id parameter is not a valid value: %s.', right_id) raise InvalidValueError(None, 'right_id', right_id) try: xml_map, attrs_map = loads(request.raw_post_data) self.log.debug('XML_MAP: %s', xml_map) except XMLError, x: self.log.error(u'Erro ao ler o XML da requisicao.') return self.response_error(3, x) networkapi_map = xml_map.get('networkapi') if networkapi_map is None: return self.response_error(3, u'Não existe valor para a tag networkapi do XML de requisição.') direito_map = networkapi_map.get('direito_grupo_equipamento') if direito_map is None: return self.response_error(3, u'Não existe valor para a tag direito_grupo_equipamento do XML de requisição.') response = self.__valida_request(direito_map, False) if response is not None: return response with distributedlock(LOCK_GROUP_RIGHTS % right_id): DireitosGrupoEquipamento.update(user, right_id, leitura=direito_map.get( 'leitura'), escrita=direito_map.get( 'escrita'), alterar_config=direito_map.get( 'alterar_config'), exclusao=direito_map.get('exclusao')) return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value) except DireitosGrupoEquipamento.DoesNotExist: return self.response_error(258, right_id) except (GrupoError): return self.response_error(1) def handle_delete(self, request, user, *args, **kwargs): """Trata as requisições de DELETE para remover direitos de um grupo de usuário em um grupo de equipamento. URL: direitosgrupoequipamento/<id_direito>/ """ try: if not has_perm(user, AdminPermission.USER_ADMINISTRATION, AdminPermission.WRITE_OPERATION): return self.not_authorized() right_id = kwargs.get('id_direito') if not is_valid_int_greater_zero_param(right_id, False): self.log.error( u'The right_id parameter is not a valid value: %s.', right_id) raise InvalidValueError(None, 'right_id', right_id) DireitosGrupoEquipamento.get_by_pk(right_id) with distributedlock(LOCK_GROUP_RIGHTS % right_id): DireitosGrupoEquipamento.remove(user, right_id) return self.response(dumps_networkapi({})) except InvalidValueError, e: return self.response_error(269, e.param, e.value) except DireitosGrupoEquipamento.DoesNotExist: return self.response_error(258, right_id) except (GrupoError): return self.response_error(1)
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <algorithm> #include <iostream> #include <utility> #include <vector> #include "paddle/fluid/framework/eigen.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/transpose_op.h" namespace paddle { namespace operators { template <typename T, typename Type> static void getKthvalue(Type input_height, Type input_width, int input_dim, const framework::Tensor* input, T* t_out, Type* t_indices, const int& k) { bool partial_sort_flag = (k * 64) < input_width; #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (Type i = 0; i < input_height; ++i) { std::vector<std::pair<T, Type>> col_vec; col_vec.reserve(input_width); if (input_dim == 1) { auto e_input = framework::EigenVector<T>::Flatten(*input); for (Type j = 0; j < input_width; ++j) { col_vec.emplace_back(std::pair<T, Type>(e_input(j), j)); } } else { auto e_input = framework::EigenMatrix<T>::Reshape(*input, input_dim - 1); for (Type j = 0; j < input_width; ++j) { col_vec.emplace_back(std::pair<T, Type>(e_input(i, j), j)); } } if (partial_sort_flag) { std::partial_sort( col_vec.begin(), col_vec.begin() + k, col_vec.end(), [](const std::pair<T, Type>& l, const std::pair<T, Type>& r) { return (!std::isnan(static_cast<double>(l.first)) && std::isnan(static_cast<double>(r.first))) || (l.first < r.first); }); } else { std::nth_element( col_vec.begin(), col_vec.begin() + k - 1, col_vec.end(), [](const std::pair<T, Type>& l, const std::pair<T, Type>& r) { return (!std::isnan(static_cast<double>(l.first)) && std::isnan(static_cast<double>(r.first))) || (l.first < r.first); }); } t_out[i] = col_vec[k - 1].first; t_indices[i] = col_vec[k - 1].second; } } template <typename T, typename Type> static void kthvalueAssign(const Type& input_height, const Type& input_width, const int& input_dim, const framework::Tensor* input, const framework::Tensor* indices, T* output_data) { #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (Type i = 0; i < input_height; ++i) { if (input_dim == 1) { auto e_input = framework::EigenVector<T>::Flatten(*input); auto e_indices = framework::EigenVector<Type>::Flatten(*indices); output_data[i * input_width + e_indices(0)] = e_input(0); } else { auto e_input = framework::EigenMatrix<T>::Reshape(*input, input_dim - 1); auto e_indices = framework::EigenMatrix<Type>::Reshape(*indices, input_dim - 1); output_data[i * input_width + e_indices(i, 0)] = e_input(i, 0); } } } template <typename DeviceContext, typename T> class KthvalueCPUKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { auto* input = context.Input<framework::Tensor>("X"); auto* output = context.Output<framework::Tensor>("Out"); auto* indices = context.Output<framework::Tensor>("Indices"); const auto& in_dims = input->dims(); int k = static_cast<int>(context.Attr<int>("k")); bool keepdim = static_cast<bool>(context.Attr<bool>("keepdim")); int axis = static_cast<int>(context.Attr<int>("axis")); if (axis < 0) axis += in_dims.size(); T* output_data = output->mutable_data<T>(context.GetPlace()); int64_t* indices_data = indices->mutable_data<int64_t>(context.GetPlace()); auto out_dims = output->dims(); if (axis == in_dims.size() - 1) { const int64_t& input_height = phi::product(phi::slice_ddim(in_dims, 0, in_dims.size() - 1)); const int64_t& input_width = in_dims[in_dims.size() - 1]; getKthvalue<T, int64_t>(input_height, input_width, in_dims.size(), input, output_data, indices_data, k); } else { std::vector<int> trans; for (int i = 0; i < axis; i++) { trans.emplace_back(i); } trans.emplace_back(in_dims.size() - 1); for (int i = axis + 1; i < in_dims.size() - 1; i++) { trans.emplace_back(i); } trans.emplace_back(axis); if (!keepdim) { std::vector<int> tmp_out_shape; for (int i = 0; i < axis; i++) { tmp_out_shape.emplace_back(in_dims[i]); } tmp_out_shape.emplace_back(1); for (int i = axis + 1; i < in_dims.size(); i++) { tmp_out_shape.emplace_back(in_dims[i]); } framework::DDim tmp_out_dims = phi::make_ddim(tmp_out_shape); output->Resize(tmp_out_dims); indices->Resize(tmp_out_dims); } framework::DDim trans_dims(in_dims); framework::DDim trans_out_dims(in_dims); for (size_t i = 0; i < trans.size(); i++) { trans_dims[i] = in_dims[trans[i]]; trans_out_dims[i] = in_dims[trans[i]]; } trans_out_dims[in_dims.size() - 1] = 1; framework::Tensor trans_inp; trans_inp.mutable_data<T>(trans_dims, context.GetPlace()); int ndims = trans.size(); auto& dev_context = context.template device_context<platform::CPUDeviceContext>(); TransCompute<platform::CPUDeviceContext, T>(ndims, dev_context, *input, &trans_inp, trans); const int64_t input_height = phi::product(phi::slice_ddim(trans_dims, 0, trans_dims.size() - 1)); const int64_t input_width = trans_dims[trans_dims.size() - 1]; framework::Tensor tmp_out, tmp_indices; T* t_out = tmp_out.mutable_data<T>(trans_out_dims, context.GetPlace()); auto* t_ind = tmp_indices.mutable_data<int64_t>(trans_out_dims, context.GetPlace()); getKthvalue<T, int64_t>(input_height, input_width, in_dims.size(), &trans_inp, t_out, t_ind, k); TransCompute<platform::CPUDeviceContext, int64_t>( ndims, dev_context, tmp_indices, indices, trans); TransCompute<platform::CPUDeviceContext, T>(ndims, dev_context, tmp_out, output, trans); if (!keepdim) { output->Resize(out_dims); indices->Resize(out_dims); } } } }; template <typename DeviceContext, typename T> class KthvalueGradCPUKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { auto* x = context.Input<framework::Tensor>("X"); auto* out_grad = context.Input<framework::Tensor>(framework::GradVarName("Out")); auto* indices = context.Input<framework::Tensor>("Indices"); auto* x_grad = context.Output<framework::Tensor>(framework::GradVarName("X")); int axis = static_cast<int>(context.Attr<int>("axis")); bool keepdim = static_cast<bool>(context.Attr<bool>("keepdim")); auto in_dims = x->dims(); auto out_dims = indices->dims(); axis = (axis < 0) ? (in_dims.size() + axis) : axis; if (!keepdim) { std::vector<int> tmp_out_shape; for (int i = 0; i < axis; i++) { tmp_out_shape.emplace_back(out_dims[i]); } tmp_out_shape.emplace_back(1); for (int i = axis + 1; i < in_dims.size(); i++) { tmp_out_shape.emplace_back(out_dims[i - 1]); } out_dims = phi::make_ddim(tmp_out_shape); } T* x_grad_data = x_grad->mutable_data<T>(context.GetPlace()); if (axis == in_dims.size() - 1) { const int64_t input_height = phi::product(phi::slice_ddim(in_dims, 0, in_dims.size() - 1)); const int64_t input_width = in_dims[in_dims.size() - 1]; memset(x_grad_data, 0, x_grad->numel() * sizeof(T)); if (keepdim) { kthvalueAssign(input_height, input_width, in_dims.size(), out_grad, indices, x_grad_data); } else { auto& dev_context = context.template device_context<platform::CPUDeviceContext>(); framework::Tensor out_grad_tmp, indices_tmp; out_grad_tmp.mutable_data<T>(out_grad->dims(), dev_context.GetPlace()); indices_tmp.mutable_data<int64_t>(indices->dims(), dev_context.GetPlace()); framework::TensorCopy(*out_grad, dev_context.GetPlace(), dev_context, &out_grad_tmp); framework::TensorCopy(*indices, dev_context.GetPlace(), dev_context, &indices_tmp); out_grad_tmp.Resize(out_dims); indices_tmp.Resize(out_dims); kthvalueAssign(input_height, input_width, in_dims.size(), &out_grad_tmp, &indices_tmp, x_grad_data); } } else { std::vector<int> trans; for (int i = 0; i < axis; i++) { trans.emplace_back(i); } trans.emplace_back(out_dims.size() - 1); for (int i = axis + 1; i < out_dims.size() - 1; i++) { trans.emplace_back(i); } trans.emplace_back(axis); framework::DDim trans_dims(out_dims); framework::DDim trans_in_dims(in_dims); for (size_t i = 0; i < trans.size(); i++) { trans_dims[i] = out_dims[trans[i]]; trans_in_dims[i] = in_dims[trans[i]]; } framework::Tensor trans_dO, trans_ind; trans_dO.mutable_data<T>(trans_dims, context.GetPlace()); trans_ind.mutable_data<int64_t>(trans_dims, context.GetPlace()); int ndims = trans.size(); auto& dev_context = context.template device_context<platform::CPUDeviceContext>(); if (keepdim) { TransCompute<platform::CPUDeviceContext, T>( ndims, dev_context, *out_grad, &trans_dO, trans); TransCompute<platform::CPUDeviceContext, int64_t>( ndims, dev_context, *indices, &trans_ind, trans); } else { framework::Tensor out_grad_tmp, indices_tmp; out_grad_tmp.mutable_data<T>(out_grad->dims(), dev_context.GetPlace()); indices_tmp.mutable_data<int64_t>(indices->dims(), dev_context.GetPlace()); framework::TensorCopy(*out_grad, dev_context.GetPlace(), dev_context, &out_grad_tmp); framework::TensorCopy(*indices, dev_context.GetPlace(), dev_context, &indices_tmp); out_grad_tmp.Resize(out_dims); indices_tmp.Resize(out_dims); TransCompute<platform::CPUDeviceContext, T>( ndims, dev_context, out_grad_tmp, &trans_dO, trans); TransCompute<platform::CPUDeviceContext, int64_t>( ndims, dev_context, indices_tmp, &trans_ind, trans); } const int64_t input_height = phi::product( phi::slice_ddim(trans_in_dims, 0, trans_in_dims.size() - 1)); const int64_t input_width = trans_in_dims[trans_in_dims.size() - 1]; framework::Tensor tmp_out; T* t_out = tmp_out.mutable_data<T>(trans_in_dims, context.GetPlace()); memset(t_out, 0, x_grad->numel() * sizeof(T)); kthvalueAssign<T, int64_t>(input_height, input_width, in_dims.size(), &trans_dO, &trans_ind, t_out); TransCompute<platform::CPUDeviceContext, T>(ndims, dev_context, tmp_out, x_grad, trans); } } }; } // namespace operators } // namespace paddle
<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import subprocess import sys def exe(*args): if os.name == 'posix': cmd = 'gpsbabel' flags = 0 else: assert(os.name == 'nt') cmd = 'C:\Program Files (x86)\GPSBabel\gpsbabel.exe' flags = subprocess.CREATE_NO_WINDOW try: subprocess.run([cmd, *args], check=True, creationflags=flags) except subprocess.CalledProcessError: print('外部プログラム ' + cmd + ' の実行に失敗しました', file=sys.stderr) sys.exit(1) def main(): """for debug only.""" exe('-V') if __name__ == '__main__': main() # __END__
<reponame>parthw/funCoding<filename>react/burger-builder/src/components/Burger/BuildControls/BuildControl/BuildControl.tsx<gh_stars>1-10 import React from "react"; import styles from "./BuildControl.module.css"; type BuildControlType = { label: string; addIngredient: React.MouseEventHandler; removeIngredient: React.MouseEventHandler; disableButton: boolean; }; export default function BuildControl(props: BuildControlType) { return ( <div className={styles.BuildControl}> <div className={styles.Label}>{props.label}</div> <button className={styles.Less} onClick={props.removeIngredient} disabled={props.disableButton} > Less </button> <button className={styles.More} onClick={props.addIngredient}> More </button> </div> ); }
def run_connector(self, in_opts=None): opts = in_opts or self.get_connector_opts() conn = connector.Connector(opts) container = proton.reactor.Container(conn) container.run() return conn.get_messages()
/** * Randomly pick an object from an array of objects. * @param <T> generic type of the array elements. * @param objects an array of objects, one of whom is to be picked. * @param probabilities the probabilities of selecting each of the objects. * @return a random element from objects. */ public final <T> T selectOneOf(final T[] objects, final double[] probabilities) { final double r = getDouble(); double cdf = 0.0; for (int i = 0; i < objects.length; i++) { cdf += probabilities[i]; if (r <= cdf) { return objects[i]; } } return objects[objects.length]; }
/** * @author Spencer Gibb */ @RunWith(SpringRunner.class) @SpringBootTest(properties = { "spring.application.name=testConsulLoadBalancer", "spring.cloud.consul.discovery.prefer-ip-address=true", "spring.cloud.consul.discovery.tags=foo=bar", }, webEnvironment = RANDOM_PORT) public class ConsulLoadbalancerClientTests { @Autowired private LoadBalancerClient client; @Test public void chooseWorks() { ServiceInstance instance = client.choose("testConsulLoadBalancer"); assertThat(instance).isNotNull(); assertThat(instance.isSecure()).isFalse(); assertIpAddress(instance); assertThat(instance.getMetadata()) .containsEntry("foo", "bar"); } private void assertIpAddress(ServiceInstance instance) { assertTrue("host isn't an ip address", Character.isDigit(instance.getHost().charAt(0))); } @SpringBootConfiguration @EnableAutoConfiguration @EnableDiscoveryClient @RibbonClient(name = "testConsulLoadBalancer", configuration = MyRibbonConfig.class) public static class MyTestConfig { } public static class MyRibbonConfig { public MyRibbonConfig() { System.err.println("here"); } @Bean public ServerListFilter<Server> ribbonServerListFilter() { return servers -> servers; } } }