text:
from __future__ import generators, nested_scopes

import sys

from twisted.internet import reactor

from twisted.trial import unittest, util

from twisted.internet.defer import waitForDeferred, deferredGenerator, Deferred
from twisted.internet import defer

def getThing():
    d = Deferred()
    reactor.callLater(0, d.callback, "hi")
    return d

def getOwie():
    d = Deferred()
    def CRAP():
        d.errback(ZeroDivisionError('OMG'))
    reactor.callLater(0, CRAP)
    return d

# NOTE: most of the tests in DeferredGeneratorTests are duplicated
# with slightly different syntax for the InlineCallbacksTests below.

class TerminalException(Exception):
    pass

class BaseDefgenTests:
    """
    This class sets up a bunch of test cases which will test both
    deferredGenerator and inlineCallbacks based generators. The subclasses
    DeferredGeneratorTests and InlineCallbacksTests each provide the actual
    generator implementations tested.
    """

    def testBasics(self):
        """
        Test that a normal deferredGenerator works.  Tests yielding a
        deferred which callbacks, as well as a deferred errbacks. Also
        ensures returning a final value works.
        """

        return self._genBasics().addCallback(self.assertEqual, 'WOOSH')

    def testBuggy(self):
        """
        Ensure that a buggy generator properly signals a Failure
        condition on result deferred.
        """
        return self.assertFailure(self._genBuggy(), ZeroDivisionError)

    def testNothing(self):
        """Test that a generator which never yields results in None."""

        return self._genNothing().addCallback(self.assertEqual, None)

    def testHandledTerminalFailure(self):
        """
        Create a Deferred Generator which yields a Deferred which fails and
        handles the exception which results.  Assert that the Deferred
        Generator does not errback its Deferred.
        """
        return self._genHandledTerminalFailure().addCallback(self.assertEqual, None)

    def testHandledTerminalAsyncFailure(self):
        """
        Just like testHandledTerminalFailure, only with a Deferred which fires
        asynchronously with an error.
        """
        d = defer.Deferred()
        deferredGeneratorResultDeferred = self._genHandledTerminalAsyncFailure(d)
        d.errback(TerminalException("Handled Terminal Failure"))
        return deferredGeneratorResultDeferred.addCallback(
            self.assertEqual, None)

    def testStackUsage(self):
        """
        Make sure we don't blow the stack when yielding immediately
        available deferreds.
        """
        return self._genStackUsage().addCallback(self.assertEqual, 0)

    def testStackUsage2(self):
        """
        Make sure we don't blow the stack when yielding immediately
        available values.
        """
        return self._genStackUsage2().addCallback(self.assertEqual, 0)

class DeferredGeneratorTests(BaseDefgenTests, unittest.TestCase):

    # First provide all the generator impls necessary for BaseDefgenTests
    def _genBasics(self):

        x = waitForDeferred(getThing())
        yield x
        x = x.getResult()

        self.assertEquals(x, "hi")

        ow = waitForDeferred(getOwie())
        yield ow
        try:
            ow.getResult()
        except ZeroDivisionError, e:
            self.assertEquals(str(e), 'OMG')
        yield "WOOSH"
        return
    _genBasics = deferredGenerator(_genBasics)

    def _genBuggy(self):
        yield waitForDeferred(getThing())
        1/0
    _genBuggy = deferredGenerator(_genBuggy)

    def _genNothing(self):
        if 0: yield 1
    _genNothing = deferredGenerator(_genNothing)

    def _genHandledTerminalFailure(self):
        x = waitForDeferred(defer.fail(TerminalException("Handled Terminal Failure")))
        yield x
        try:
            x.getResult()
        except TerminalException:
            pass
    _genHandledTerminalFailure = deferredGenerator(_genHandledTerminalFailure)

    def _genHandledTerminalAsyncFailure(self, d):
        x = waitForDeferred(d)
        yield x
        try:
            x.getResult()
        except TerminalException:
            pass
    _genHandledTerminalAsyncFailure = deferredGenerator(_genHandledTerminalAsyncFailure)

    def _genStackUsage(self):
        for x in range(5000):
            # Test with yielding a deferred
            x = waitForDeferred(defer.succeed(1))
            yield x
            x = x.getResult()
        yield 0
    _genStackUsage = deferredGenerator(_genStackUsage)

    def _genStackUsage2(self):
        for x in range(5000):
            # Test with yielding a random value
            yield 1
        yield 0
    _genStackUsage2 = deferredGenerator(_genStackUsage2)

    # Tests unique to deferredGenerator

    def testDeferredYielding(self):
        """
        Ensure that yielding a Deferred directly is trapped as an
        error.
        """
        # See the comment _deferGenerator about d.callback(Deferred).
        def _genDeferred():
            yield getThing()
        _genDeferred = deferredGenerator(_genDeferred)

        return self.assertFailure(_genDeferred(), TypeError)

## This has to be in a string so the new yield syntax doesn't cause a
## syntax error in Python 2.4 and before.
inlineCallbacksTestsSource = '''
from twisted.internet.defer import inlineCallbacks, returnValue

class InlineCallbacksTests(BaseDefgenTests, unittest.TestCase):
    # First provide all the generator impls necessary for BaseDefgenTests

    def _genBasics(self):

        x = yield getThing()

        self.assertEquals(x, "hi")

        try:
            ow = yield getOwie()
        except ZeroDivisionError, e:
            self.assertEquals(str(e), 'OMG')
        returnValue("WOOSH")
    _genBasics = inlineCallbacks(_genBasics)

    def _genBuggy(self):
        yield getThing()
        1/0
    _genBuggy = inlineCallbacks(_genBuggy)

    def _genNothing(self):
        if 0: yield 1
    _genNothing = inlineCallbacks(_genNothing)

    def _genHandledTerminalFailure(self):
        try:
            x = yield defer.fail(TerminalException("Handled Terminal Failure"))
        except TerminalException:
            pass
    _genHandledTerminalFailure = inlineCallbacks(_genHandledTerminalFailure)

    def _genHandledTerminalAsyncFailure(self, d):
        try:
            x = yield d
        except TerminalException:
            pass
    _genHandledTerminalAsyncFailure = inlineCallbacks(
        _genHandledTerminalAsyncFailure)

    def _genStackUsage(self):
        for x in range(5000):
            # Test with yielding a deferred
            x = yield defer.succeed(1)
        returnValue(0)
    _genStackUsage = inlineCallbacks(_genStackUsage)

    def _genStackUsage2(self):
        for x in range(5000):
            # Test with yielding a random value
            yield 1
        returnValue(0)
    _genStackUsage2 = inlineCallbacks(_genStackUsage2)

    # Tests unique to inlineCallbacks

    def testYieldNonDeferrred(self):
        """
        Ensure that yielding a non-deferred passes it back as the
        result of the yield expression.
        """
        def _test():
            x = yield 5
            returnValue(5)
        _test = inlineCallbacks(_test)

        return _test().addCallback(self.assertEqual, 5)

    def testReturnNoValue(self):
        """Ensure a standard python return results in a None result."""
        def _noReturn():
            yield 5
            return
        _noReturn = inlineCallbacks(_noReturn)

        return _noReturn().addCallback(self.assertEqual, None)

    def testReturnValue(self):
        """Ensure that returnValue works."""
        def _return():
            yield 5
            returnValue(6)
        _return = inlineCallbacks(_return)

        return _return().addCallback(self.assertEqual, 6)

'''

if sys.version_info > (2, 5):
    # Load tests
    exec inlineCallbacksTestsSource
else:
    # Make a placeholder test case
    class InlineCallbacksTests(unittest.TestCase):
        skip = "defer.defgen doesn't run on python < 2.5."
        def test_everything(self):
            pass


text:
@implementation STVSection
+ (instancetype)sectionWithTitle:(nullable NSString *)title
               sectionIndexTitle:(nullable NSString *)sectionIndexTitle
                            rows:(nullable NSArray<STVRow *> *)rows
{
  STVSection *section = [STVSection new];
  section->_title = [title copy];
  section->_sectionIndexTitle = [sectionIndexTitle copy];
  section->_rows = [rows copy];
  return section;
}
@end

@implementation STVRow
+ (instancetype)rowWithCellReuseIdentifier:(NSString *)cellReuseIdentifier
                                     title:(NSString *)title
                                  subtitle:(NSString *)subtitle
                        configureCellBlock:(SimpleTableViewRowBlock)configureCellBlock
                            didSelectBlock:(SimpleTableViewRowBlock)didSelectBlock
{
  STVRow *row = [STVRow new];
  row->_cellReuseIdentifier = [cellReuseIdentifier copy];
  row->_title = [title copy];
  row->_subtitle = [subtitle copy];
  row->_configureCellBlock = [configureCellBlock copy];
  row->_didSelectBlock = [didSelectBlock copy];
  return row;
}
@end

@interface SimpleTableView () <UITableViewDelegate, UITableViewDataSource>
@end

@implementation SimpleTableView {
  NSArray<NSString *> *_sortedSectionTitles;
  NSDictionary<NSString *, NSNumber *> *_sectionTitleToIndexMap;
}

- (instancetype)initWithTableViewStyle:(UITableViewStyle)tableViewStyle
{
  self = [super initWithFrame:CGRectMake(0, 0, 320, 480)];
  if (self) {
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.bounds style:tableViewStyle];
    tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    tableView.dataSource = self;
    tableView.delegate = self;
    _tableView = tableView;
    _shouldDeselectRowsAutomatically = YES;
    [self addSubview:_tableView];
  }
  return self;
}

- (void)setSectionModels:(NSArray<STVSection *> *)sectionModels
{
  _sectionModels = sectionModels;

  // setup index map
  NSMutableArray<NSString *> *sortedSectionTitles = [NSMutableArray array];
  NSMutableDictionary<NSString *, NSNumber *> *sectionTitleToIndexMap = [NSMutableDictionary dictionary];
  [sectionModels enumerateObjectsUsingBlock:^(STVSection *section, NSUInteger idx, BOOL *stop) {
    if (section.sectionIndexTitle.length > 0) {
      [sortedSectionTitles addObject:section.sectionIndexTitle];
      sectionTitleToIndexMap[section.sectionIndexTitle] = @(idx);
    }
  }];
  _sortedSectionTitles = sortedSectionTitles;
  _sectionTitleToIndexMap = [sectionTitleToIndexMap copy];

  [_tableView reloadData];
}

#pragma mark UITableViewDelegate / UITableViewDatasource

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
  return tableView.rowHeight;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
  return _sectionModels.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return _sectionModels[section].rows.count;
}

- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
  return _sectionModels[section].title;
}

#pragma mark - Cell configuration

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  STVRow *const row = _sectionModels[indexPath.section].rows[indexPath.row];
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:row.cellReuseIdentifier];
  cell.textLabel.text = row.title;
  cell.detailTextLabel.text = row.subtitle;
  if (row.configureCellBlock) {
    row.configureCellBlock(row, cell, tableView, indexPath);
  }
  return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
  if (_rowHeightProvider) {
    return _rowHeightProvider(_sectionModels[indexPath.section].rows[indexPath.row], tableView, indexPath);
  } else {
    return tableView.rowHeight;
  }
}

#pragma mark - Selection

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  STVRow *const row = _sectionModels[indexPath.section].rows[indexPath.row];
  if (row.didSelectBlock) {
    row.didSelectBlock(row, [tableView cellForRowAtIndexPath:indexPath], tableView, indexPath);
  }
  if (_shouldDeselectRowsAutomatically) {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
  }
}

#pragma mark - Section Indexes

- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
  return _sortedSectionTitles;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
  return _sectionTitleToIndexMap[title].integerValue;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
  [_scrollDelegate scrollViewDidScroll:scrollView];
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
  [_scrollDelegate scrollViewWillEndDragging:scrollView withVelocity:velocity targetContentOffset:targetContentOffset];
}

@end

redpajama_set_name: RedPajamaGithub


text:
package android.gril.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import android.gril.bean.PhotoUpImageBucket;
import android.gril.bean.PhotoUpImageItem;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.MediaStore.Audio.Albums;
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.Images.Thumbnails;
import android.util.Log;

public class PhotoUpAlbumHelper extends AsyncTask<Object, Object, Object>{

	final String TAG = getClass().getSimpleName();
	Context context;
	ContentResolver cr;
	// 缩略图列表
	HashMap<String, String> thumbnailList = new HashMap<String, String>();
	// 专辑列表
	List<HashMap<String, String>> albumList = new ArrayList<HashMap<String, String>>();
	HashMap<String, PhotoUpImageBucket> bucketList = new HashMap<String, PhotoUpImageBucket>();
	private GetAlbumList getAlbumList;

	private PhotoUpAlbumHelper() {}
	public static PhotoUpAlbumHelper getHelper() {
		PhotoUpAlbumHelper instance = new PhotoUpAlbumHelper();
		return instance;
	}

	/**
	 * 初始化
	 * @param context
	 */
	public void init(Context context) {
		if (this.context == null) {
			this.context = context;
			cr = context.getContentResolver();
		}
	}

	/**
	 * 得到缩略图
	 */
	private void getThumbnail() {
		String[] projection = { Thumbnails._ID, Thumbnails.IMAGE_ID,
				Thumbnails.DATA};
		Cursor cursor1 = Thumbnails.queryMiniThumbnails(cr, Thumbnails.EXTERNAL_CONTENT_URI,
				Thumbnails.MINI_KIND, projection);
		getThumbnailColumnData(cursor1);
		cursor1.close();
	}

	/**
	 * 从数据库中得到缩略图
	 * @param cur
	 */
	private void getThumbnailColumnData(Cursor cur) {
		if (cur.moveToFirst()) {
			int image_id;
			String image_path;
			int image_idColumn = cur.getColumnIndex(Thumbnails.IMAGE_ID);
			int dataColumn = cur.getColumnIndex(Thumbnails.DATA);
			do {
				image_id = cur.getInt(image_idColumn);
				image_path = cur.getString(dataColumn);
				thumbnailList.put("" + image_id, image_path);
			} while (cur.moveToNext());
		}
	}

	/**
	 * 得到原图-n
	 */
	void getAlbum() {
		String[] projection = { Albums._ID, Albums.ALBUM, Albums.ALBUM_ART,
				Albums.ALBUM_KEY, Albums.ARTIST, Albums.NUMBER_OF_SONGS };
		Cursor cursor1 = cr.query(Albums.EXTERNAL_CONTENT_URI, projection, null,
				null, Albums.ALBUM_ID+" desc");
		getAlbumColumnData(cursor1);
		cursor1.close();
	}

	/**
	 * 从本地数据库中得到原图
	 * @param cur
	 */
	private void getAlbumColumnData(Cursor cur) {
		if (cur.moveToFirst()) {
			int _id;
			String album;
			String albumArt;
			String albumKey;
			String artist;
			int numOfSongs;
			int _idColumn = cur.getColumnIndex(Albums._ID);
			int albumColumn = cur.getColumnIndex(Albums.ALBUM);
			int albumArtColumn = cur.getColumnIndex(Albums.ALBUM_ART);
			int albumKeyColumn = cur.getColumnIndex(Albums.ALBUM_KEY);
			int artistColumn = cur.getColumnIndex(Albums.ARTIST);
			int numOfSongsColumn = cur.getColumnIndex(Albums.NUMBER_OF_SONGS);
			do {
				_id = cur.getInt(_idColumn);
				album = cur.getString(albumColumn);
				albumArt = cur.getString(albumArtColumn);
				albumKey = cur.getString(albumKeyColumn);
				artist = cur.getString(artistColumn);
				numOfSongs = cur.getInt(numOfSongsColumn);
				HashMap<String, String> hash = new HashMap<String, String>();
				hash.put("_id", _id + "");
				hash.put("album", album);
				hash.put("albumArt", albumArt);
				hash.put("albumKey", albumKey);
				hash.put("artist", artist);
				hash.put("numOfSongs", numOfSongs + "");
				albumList.add(hash);
			} while (cur.moveToNext());
		}
	}

	/**
	 * 是否创建了图片集
	 */
	boolean hasBuildImagesBucketList = false;
	/**
	 * 得到图片集
	 */
	void buildImagesBucketList() {
		// 构造缩略图索引
		getThumbnail();
		// 构造相册索引
		String columns[] = new String[] { Media._ID, Media.BUCKET_ID,
				Media.PICASA_ID, Media.DATA, Media.DISPLAY_NAME, Media.TITLE,
				Media.SIZE, Media.BUCKET_DISPLAY_NAME };
		// 得到一个游标
		Cursor cur = cr.query(Media.EXTERNAL_CONTENT_URI, columns, null, null,
				Media.DATE_MODIFIED+" desc");
		if (cur.moveToFirst()) {
			// 获取指定列的索引
			int photoIDIndex = cur.getColumnIndexOrThrow(Media._ID);
			int photoPathIndex = cur.getColumnIndexOrThrow(Media.DATA);
			int bucketDisplayNameIndex = cur.getColumnIndexOrThrow(Media.BUCKET_DISPLAY_NAME);
			int bucketIdIndex = cur.getColumnIndexOrThrow(Media.BUCKET_ID);
			/**
			 * Description:这里增加了一个判断:判断照片的名字是否合法,例如.jpg .png    图片名字是不合法的,直接过滤掉
			 */
			do {
				int start = cur.getString(photoPathIndex).lastIndexOf("/")+1;
				int end = cur.getString(photoPathIndex).contains(".") ?
						cur.getString(photoPathIndex).lastIndexOf(".") : cur.getString(photoPathIndex).length();
				if (end <= start || cur.getString(photoPathIndex).substring(start,end).replaceAll(" ", "").length()<=0)
				{
					Log.d(TAG, "出现了异常图片的地址:cur.getString(photoPathIndex)="+cur.getString(photoPathIndex));
//					Log.d(TAG, "出现了异常图片的地址:cur.getString(photoPathIndex).substring="+cur.getString(photoPathIndex)
//							.substring(cur.getString(photoPathIndex).lastIndexOf("/")+1,cur.getString(photoPathIndex).lastIndexOf(".")));
				}else {
					String _id = cur.getString(photoIDIndex);
					String path = cur.getString(photoPathIndex);
					String bucketName = cur.getString(bucketDisplayNameIndex);
					String bucketId = cur.getString(bucketIdIndex);
					PhotoUpImageBucket bucket = bucketList.get(bucketId);
					if (bucket == null) {
						bucket = new PhotoUpImageBucket();
						bucketList.put(bucketId, bucket);
						bucket.imageList = new ArrayList<PhotoUpImageItem>();
						bucket.bucketName = bucketName;
					}
					bucket.count++;
					PhotoUpImageItem imageItem = new PhotoUpImageItem();
					imageItem.setImageId(_id);
					imageItem.setImagePath(path);
//					imageItem.setThumbnailPath(thumbnailList.get(_id));
					bucket.imageList.add(imageItem);
					Log.i(TAG, "PhotoUpAlbumHelper类中 的——》path="+thumbnailList.get(_id));
				}
			} while (cur.moveToNext());
		}
		cur.close();
		hasBuildImagesBucketList = true;
	}

	/**
	 * 得到图片集
	 * @param refresh
	 * @return
	 */
	public List<PhotoUpImageBucket> getImagesBucketList(boolean refresh) {
		if (refresh || (!refresh && !hasBuildImagesBucketList)) {
			buildImagesBucketList();
		}
		List<PhotoUpImageBucket> tmpList = new ArrayList<PhotoUpImageBucket>();
		Iterator<Entry<String, PhotoUpImageBucket>> itr = bucketList.entrySet().iterator();
		while (itr.hasNext()) {
			Map.Entry<String, PhotoUpImageBucket> entry = (Map.Entry<String, PhotoUpImageBucket>) itr
					.next();
			tmpList.add(entry.getValue());
		}
		return tmpList;
	}

	/**
	 * 得到原始图像路径
	 * @param image_id
	 * @return
	 */
	String getOriginalImagePath(String image_id) {
		String path = null;
		Log.i(TAG, "---(^o^)----" + image_id);
		String[] projection = { Media._ID, Media.DATA };
		Cursor cursor = cr.query(Media.EXTERNAL_CONTENT_URI, projection,
				Media._ID + "=" + image_id, null, Media.DATE_MODIFIED+" desc");
		if (cursor != null) {
			cursor.moveToFirst();
			path = cursor.getString(cursor.getColumnIndex(Media.DATA));
		}
		return path;
	}
	public void destoryList()
	{
		thumbnailList.clear();
		thumbnailList = null;
		albumList.clear();
		albumList = null;
		bucketList.clear();
		bucketList = null;
	}

	public void setGetAlbumList(GetAlbumList getAlbumList) {
		this.getAlbumList = getAlbumList;
	}

	public interface GetAlbumList{
		public void getAlbumList(List<PhotoUpImageBucket> list);
	}

	@Override
	protected Object doInBackground(Object... params) {
		return getImagesBucketList((Boolean)(params[0]));
	}
	@SuppressWarnings("unchecked")
	@Override
	protected void onPostExecute(Object result) {
		super.onPostExecute(result);
		getAlbumList.getAlbumList((List<PhotoUpImageBucket>)result);
	}

}


text:
window.ASC = window.ASC || {};

window.ASC.TMTalk = window.ASC.TMTalk || {};

window.ASC.TMTalk.contactsManager = (function () {
  var
    isInit = false,
    groups = [],
    contacts = [],
    onlineContacts = {},
    customEvents = {
      // update contactlist
      updateContacts : 'onupdategroups',
      // adding new contact
      addContact : 'onaddcontact',
      // remove contact
      removeContact : 'onremovecontact',
      // contact is come
      comeContact : 'oncomecontact',
      // contact is leave
      leftContact : 'onleftcontact',
      // update vCard
      updateCard : 'oncardupdate'
    },
    eventManager = new CustomEvent(customEvents);

  var sortByName = function (a, b) {
    if (!a.name) {
      return 1;
    }
    if (!b.name) {
      return -1;
    }
    return a.name === b.name ? 0 : a.name > b.name ? 1 : -1;
  };

  var translateSymbols = function (str, toText) {

    var
      symbols = [
        ['<',  '<'],
        ['>',  '>'],
        ['∧', '\\^'],
        ['∼', '~'],
        ['&', '&']
      ];

    if (typeof str !== 'string' || str.length === 0) {
      return '';
    }

    // replace html to symbols
    if (typeof toText === 'undefined' || toText === true) {
      var symInd = symbols.length;
      while (symInd--) {
        str = str.replace(new RegExp(symbols[symInd][0], 'g'), symbols[symInd][1]);
      }
    // replace symbols to html
    } else {
      var symInd = symbols.length;
      while (symInd--) {
        str = str.replace(new RegExp(symbols[symInd][1], 'g'), symbols[symInd][0]);
      }
    }
    return str;
  };

  var init = function () {
    if (isInit = true) {
      return undefined;
    }
    isInit = true;
    // TODO
  };

  var bind = function (eventName, handler, params) {
    return eventManager.bind(eventName, handler, params);
  };

  var unbind = function (handlerId) {
    return eventManager.unbind(handlerId);
  };

  var fillContacts = function (items) {
    groups = [];
    contacts = [];
    onlineContacts = {};

    var
      item = null,
      itemsInd = 0,
      groupsInd = 0,
      contact = null,
      groupname = '',
      contactname = '',
      contactShow = '',
      groupNode = null,
      statuses = ASC.TMTalk.connectionManager.statuses;

    itemsInd = items.length;
    while (itemsInd--) {
      item = items[itemsInd];
      groupNode = item.getElementsByTagName('group');
      if (groupNode.length === 0) {
        groupNode = Strophe.getElementsByTagName(item, 'group');
      }
      groupname = groupNode.length > 0 ? ASC.TMTalk.dom.getContent(groupNode[0]) : '';
      contactname = item.getAttribute('name') || '';

      // groupname = translateSymbols(groupname, false);
      // contactname = translateSymbols(contactname, false);

      contact = {
        jid     : item.getAttribute('jid'),
        group   : groupname,
        name    : contactname,
        state   : ASC.TMTalk.connectionManager.offlineStatusId,
        show    : statuses[ASC.TMTalk.connectionManager.offlineStatusId].title,
        status  : ''
      };
      contacts.push(contact);

      groupsInd = groups.length;
      while (groupsInd--) {
        if (groups[groupsInd].name === groupname) {
          groups[groupsInd].contacts.push(contact);
          break;
        }
      }
      if (groupsInd === -1) {
        groups.push({
          name      : groupname,
          contacts  : [contact]
        });
      }
    }

    groupsInd = groups.length;
    while (groupsInd--) {
      groups[groupsInd].contacts.sort(sortByName);
    }
    groups.sort(sortByName);
    contacts.sort(sortByName);

    eventManager.call(customEvents.updateContacts, window, [groups, contacts]);
  };

  var clearOnlineContacts = function () {
    var
      jid = '',
      contactsInd = 0,
      currentStatus = ASC.TMTalk.connectionManager.statuses[ASC.TMTalk.connectionManager.offlineStatusId];
    for (jid in onlineContacts) {
      if (onlineContacts.hasOwnProperty(jid)) {
        delete onlineContacts[jid];

        contactsInd = contacts.length;
        while (contactsInd--) {
          if (contacts[contactsInd].jid === jid) {
            contacts[contactsInd].show = currentStatus.title;
            contacts[contactsInd].state = currentStatus.id;
            contacts[contactsInd].status = '';
            break;
          }
        }

        eventManager.call(customEvents.leftContact, window, [jid, currentStatus]);
      }
    }
  };

  var comeContact = function (presence) {
    var
      nodes = null,
      newResource = null,
      resources = null,
      statuses = ASC.TMTalk.connectionManager.statuses,
      currentStatus = statuses[ASC.TMTalk.connectionManager.onlineStatusId],
      show = currentStatus.show,
      message = '',
      from = presence.getAttribute('from'),
      jid = '',
      resource = from ? from.substring(from.indexOf('/') + 1) : '',
      priority = 0;

    if (typeof from !== 'string') {
      return undefined;
    }

    jid = from.substring(0, from.indexOf('/')).toLowerCase();
    jid = jid === '' ? from : jid;

    nodes = presence.getElementsByTagName('priority');
    priority = nodes.length > 0 ? ASC.TMTalk.dom.getContent(nodes[0]) : priority;

    nodes = presence.getElementsByTagName('show');
    show = nodes.length > 0 ? ASC.TMTalk.dom.getContent(nodes[0]) : show;

    nodes = presence.getElementsByTagName('status');
    message = nodes.length > 0 ? ASC.TMTalk.dom.getContent(nodes[0]) : message;

    message = translateSymbols(message, false);

    priority = isFinite(+priority) ? +priority : priority;
    var statusesInd = statuses.length;
    while (statusesInd--) {
      if (statuses[statusesInd].show === show) {
        currentStatus = statuses[statusesInd];
        break;
      }
    }
    newResource = {
      name      : resource,
      priority  : priority,
      show      : show,
      message   : message
    };

    if (onlineContacts.hasOwnProperty(jid)) {
      resources = onlineContacts[jid];
      var
        resourceExist = false,
        newResourcePos = -1,
        resourceInd = resources.length;
      while (resourceInd--) {
        if (resources[resourceInd].name === resource) {
          newResourcePos = resourceInd;
          resourceExist = true;
          break;
        }
        if (resources[resourceInd].priority > priority) {
          newResourcePos = resourceInd + 1;
        }
      }
      // if check all and not found resource with larger priority, add to front
      if (newResourcePos === -1 && resourceInd === -1) {
        newResourcePos = 0;
      }
      if (resourceExist === true) {
        // if resource exist
        resources[newResourcePos].show = show;
      } else {
        // if not found, add in place
        resources.splice(newResourcePos, 0, newResource);
      }

      if (newResourcePos === 0) {
        var contactsInd = contacts.length;
        while (contactsInd--) {
          if (contacts[contactsInd].jid === jid) {
            contacts[contactsInd].show = currentStatus.title;
            contacts[contactsInd].state = currentStatus.id;
            contacts[contactsInd].status = newResource.message;
            break;
          }
        }
        eventManager.call(customEvents.comeContact, window, [jid, currentStatus, newResource]);
      }
    } else {
      var contactsInd = contacts.length;
      while (contactsInd--) {
        if (contacts[contactsInd].jid === jid) {
          contacts[contactsInd].show = currentStatus.title;
          contacts[contactsInd].state = currentStatus.id;
          contacts[contactsInd].status = newResource.message;
          break;
        }
      }
      onlineContacts[jid] = [newResource];
      eventManager.call(customEvents.comeContact, window, [jid, currentStatus, newResource]);
    }
  };

  var leftContact = function (presence) {
    var
      statusesInd = 0,
      resources = null,
      newResource = null,
      statuses = ASC.TMTalk.connectionManager.statuses,
      currentStatus = statuses[ASC.TMTalk.connectionManager.onlineStatusId],
      show = currentStatus.show,
      message = '',
      jid = presence.getAttribute('from'),
      resource = jid ? jid.substring(jid.indexOf('/') + 1) : '';

    jid = jid.substring(0, jid.indexOf('/')).toLowerCase();
    if (!onlineContacts.hasOwnProperty(jid)) {
      return undefined;
    }

    if (onlineContacts[jid].length === 1) {
        currentStatus = statuses[ASC.TMTalk.connectionManager.offlineStatusId];
        var contactsInd = contacts.length;
        while (contactsInd--) {
            if (contacts[contactsInd].jid === jid) {
                contacts[contactsInd].show = currentStatus.title;
                contacts[contactsInd].state = currentStatus.id;
                contacts[contactsInd].status = '';
                break;
            }
        }
        delete onlineContacts[jid];
        eventManager.call(customEvents.leftContact, window, [jid, currentStatus]);
        return undefined;
    }
    resources = onlineContacts[jid];
    var resourceInd = resources.length;
    while (resourceInd--) {
      if (resources[resourceInd].name === resource) {
        resources.splice(resourceInd, 1);
        break;
      }
    }
   // commented for signalr
   // if (resourceInd === 0) {
        newResource = resources[0];
        show = newResource.show;
        message = newResource.message;
        var statusesInd = statuses.length;
        while (statusesInd--) {
            if (statuses[statusesInd].show === show) {
                currentStatus = statuses[statusesInd];
                break;
            }
        }
        var contactsInd = contacts.length;
        while (contactsInd--) {
            if (contacts[contactsInd].jid === jid) {
                contacts[contactsInd].show = currentStatus.title;
                contacts[contactsInd].state = currentStatus.id;
                contacts[contactsInd].status = newResource.message;
                break;
            }
        }
        eventManager.call(customEvents.comeContact, window, [jid, currentStatus, newResource]);
   // }
  };

  var addContact = function () {

  };

  var removeContact = function () {

  };

  var updateCard = function (iq) {
    var
      nodes = null,
      nodesInd = 0,
      child = null,
      childs = null,
      childsInd = 0,
      from = iq.getAttribute('from'),
      groupname = '',
      contactname = '',
      jid = from.substring(0, from.indexOf('/')).toLowerCase();

    nodes = iq.getElementsByTagName('vCard');
    if (nodes.length === 0) {
      nodes = Strophe.getElementsByTagName(iq, 'vCard');
    }

    if (nodes.length === 0) {
      return undefined;
    }

    childs = nodes[0].childNodes;
    childsInd = childs.length;
    while (childsInd--) {
      child = childs[childsInd];
      switch (child.tagName.toLowerCase()) {
        case 'fn' :
          contactname = ASC.TMTalk.dom.getContent(child);
          break;
        case 'org' :
          nodes = child.getElementsByTagName('ORGUNIT');
          if (nodes.length === 0) {
            nodes = Strophe.getElementsByTagName(child, 'ORGUNIT');
          }
          if (nodes.length > 0) {
            groupname = ASC.TMTalk.dom.getContent(nodes[0]);
          }
          break;
      }
    }

    //groupname = translateSymbols(groupname, false);
    //contactname = translateSymbols(contactname, false);

    var contact = {
      jid     : jid,
      group   : groupname,
      name    : contactname,
      state   : ASC.TMTalk.connectionManager.offlineStatusId,
      show    : ASC.TMTalk.connectionManager.statuses[ASC.TMTalk.connectionManager.offlineStatusId].title,
      status  : ''
    };

    var contactsInd = contacts.length;
    while (contactsInd--) {
      if (contacts[contactsInd].jid === jid) {
        contacts[contactsInd].name = contactname;
        contacts[contactsInd].group = groupname;
        break;
      }
    }
    if (contactsInd === -1) {
      contacts.push(contact);
    }

    var groupsInd = groups.length;
    while (groupsInd--) {
      if (groups[groupsInd].name === groupname) {
        groups[groupsInd].contacts.push(contact);
        break;
      }
    }
    if (groupsInd === -1) {
      groups.push({
        name      : groupname,
        contacts  : [contact]
      });
    }
  };

  var getContact = function (jid) {
    if (typeof jid !== 'string') {
      jid = ASC.TMTalk.connectionManager.getJid();
    }
    var contactsInd = contacts.length;
    while (contactsInd--) {
      if (contacts[contactsInd].jid === jid) {
        return contacts[contactsInd];
      }
    }
    return null;
  };

  var getContactName = function (jid) {
    if (typeof jid !== 'string') {
      jid = ASC.TMTalk.connectionManager.getJid();
    }
    var resource = jid.indexOf('/');
    if (resource !== -1) {
      jid = jid.substring(0, resource);
    }
    var contactsInd = contacts.length;
    while (contactsInd--) {
      if (contacts[contactsInd].jid === jid) {
        return contacts[contactsInd].name;
      }
    }
    return jid;
  };

  var getContactStatus = function (jid) {
    if (typeof jid === 'undefined' || jid === ASC.TMTalk.connectionManager.getJid()) {
      ASC.TMTalk.connectionManager.statuses[ASC.TMTalk.connectionManager.onlineStatusId];
    }

    var
      statusId = -1,
      statuses = ASC.TMTalk.connectionManager.statuses,
      status = statuses[ASC.TMTalk.connectionManager.offlineStatusId],
      contactsInd = contacts.length;
    while (contactsInd--) {
      if (contacts[contactsInd].jid === jid) {
        statusId = contacts[contactsInd].state;
        break;
      }
    }
    if (statusId !== -1) {
      var statusesInd = statuses.length;
      while (statusesInd--) {
        if (statuses[statusesInd].id === statusId) {
          status = statuses[statusesInd];
          break;
        }
      }
    }
    return status;
  };

  var getContactsGroupByName = function (groupname) {
    if (typeof groupname !== 'string') {
      return [];
    }
    var groupsInd = groups.length;
    while (groupsInd--) {
      if (groups[groupsInd].name === groupname) {
        return groups[groupsInd].contacts;
      }
    }
    return [];
  };

  return {
    init  : init,

    bind    : bind,
    unbind  : unbind,

    events  : customEvents,

    fillContacts  : fillContacts,

    clearOnlineContacts : clearOnlineContacts,

    comeContact   : comeContact,
    leftContact   : leftContact,
    addContact    : addContact,
    removeContact : removeContact,
    updateCard    : updateCard,

    getContact        : getContact,
    getContactName    : getContactName,
    getContactStatus  : getContactStatus,

    getContactsGroupByName  : getContactsGroupByName
  };
})();


text:
package org.apache.flex.forks.batik.dom.svg;

import java.awt.geom.AffineTransform;

import org.apache.flex.forks.batik.parser.ParseException;
import org.apache.flex.forks.batik.parser.TransformListHandler;
import org.apache.flex.forks.batik.parser.TransformListParser;

import org.w3c.dom.DOMException;
import org.w3c.dom.svg.SVGException;
import org.w3c.dom.svg.SVGMatrix;
import org.w3c.dom.svg.SVGTransform;
import org.w3c.dom.svg.SVGTransformList;

/**
 * This class is the implementation of
 * SVGTransformList.
 *
 * @author Nicolas Socheleau
 * @version $Id: AbstractSVGTransformList.java 498484 2007-01-21 23:13:31Z cam $
 */
public abstract class AbstractSVGTransformList
    extends AbstractSVGList
    implements SVGTransformList {

    /**
     * Separator for a point list.
     */
    public static final String SVG_TRANSFORMATION_LIST_SEPARATOR
        = "";

    /**
     * Return the separator between transform in the list.
     */
    protected String getItemSeparator() {
        return SVG_TRANSFORMATION_LIST_SEPARATOR;
    }

    /**
     * Create an SVGException when the checkItemType fails.
     * @return SVGException
     */
    protected abstract SVGException createSVGException(short type,
                                                       String key,
                                                       Object[] args);

    /**
     * DOM: Implements {@link SVGTransformList#initialize(SVGTransform)}.
     */
    public SVGTransform initialize(SVGTransform newItem)
            throws DOMException, SVGException {
        return (SVGTransform) initializeImpl(newItem);
    }

    /**
     * DOM: Implements {@link SVGTransformList#getItem(int)}.
     */
    public SVGTransform getItem(int index) throws DOMException {
        return (SVGTransform) getItemImpl(index);
    }

    /**
     * DOM: Implements {@link
     * SVGTransformList#insertItemBefore(SVGTransform,int)}.
     */
    public SVGTransform insertItemBefore(SVGTransform newItem, int index)
            throws DOMException, SVGException {
        return (SVGTransform) insertItemBeforeImpl(newItem, index);
    }

    /**
     * DOM: Implements {@link
     * SVGTransformList#replaceItem(SVGTransform,int)}.
     */
    public SVGTransform replaceItem(SVGTransform newItem, int index)
            throws DOMException, SVGException {
        return (SVGTransform) replaceItemImpl(newItem, index);
    }

    /**
     * DOM: Implements {@link SVGTransformList#removeItem(int)}.
     */
    public SVGTransform removeItem(int index) throws DOMException {
        return (SVGTransform) removeItemImpl(index);
    }

    /**
     * DOM: Implements {@link SVGTransformList#appendItem(SVGTransform)}.
     */
    public SVGTransform appendItem(SVGTransform newItem)
            throws DOMException, SVGException {
        return (SVGTransform) appendItemImpl(newItem);
    }

    /**
     * DOM: Implements {@link
     * SVGTransformList#createSVGTransformFromMatrix(SVGMatrix)}.
     */
    public SVGTransform createSVGTransformFromMatrix(SVGMatrix matrix) {
        SVGOMTransform transform = new SVGOMTransform();
        transform.setMatrix(matrix);
        return transform;
    }

    /**
     * DOM: Implements {@link SVGTransformList#consolidate()}.
     */
    public SVGTransform consolidate() {
        revalidate();

        int size = itemList.size();
        if (size == 0) {
            return null;
        } else if (size == 1) {
            return getItem(0);
        }

        SVGTransformItem t = (SVGTransformItem) getItemImpl(0);
        AffineTransform at = (AffineTransform) t.affineTransform.clone();

        for (int i = 1; i < size; i++) {
            t = (SVGTransformItem) getItemImpl(i);
            at.concatenate(t.affineTransform);
        }
        SVGOMMatrix matrix = new SVGOMMatrix(at);
        return initialize(createSVGTransformFromMatrix(matrix));
    }

    /**
     * Returns an {@link AffineTransform} that represents the same transform
     * as that specified by this transform list.
     */
    public AffineTransform getAffineTransform() {
        AffineTransform at = new AffineTransform();
        for (int i = 0; i < getNumberOfItems(); i++) {
            SVGTransformItem item = (SVGTransformItem) getItem(i);
            at.concatenate(item.affineTransform);
        }
        return at;
    }

    /**
     * Creates a new {@link SVGItem} object from the given {@link SVGTransform}.
     */
    protected SVGItem createSVGItem(Object newItem) {
        return new SVGTransformItem((SVGTransform) newItem);
    }

    /**
     * Parse the attribute associated with this SVGTransformList.
     *
     * @param value the transform list attribute value
     * @param handler transform list handler
     */
    protected void doParse(String value, ListHandler handler)
            throws ParseException {

        TransformListParser transformListParser = new TransformListParser();
        TransformListBuilder builder = new TransformListBuilder(handler);
        transformListParser.setTransformListHandler(builder);
        transformListParser.parse(value);
    }

    /**
     * Asserts that the given item is an {@link SVGTransformList}.
     */
    protected void checkItemType(Object newItem) {
        if (!(newItem instanceof SVGTransform)) {
            createSVGException(SVGException.SVG_WRONG_TYPE_ERR,
                               "expected.transform", null);
        }
    }

    /**
     * An {@link SVGTransform} in the list.
     */
    protected class SVGTransformItem
            extends AbstractSVGTransform
            implements SVGItem {

        /**
         * Whether the transform value specifies only an x value, no y value.
         */
        protected boolean xOnly;

        /**
         * Whether the rotation transform value specifies only an angle.
         */
        protected boolean angleOnly;

        /**
         * List the item belongs to.
         */
        protected AbstractSVGList parent;

        /**
         * String representation of the item.
         *
         * This is a cached representation of the
         * item while it is not changed.
         */
        protected String itemStringValue;

        /**
         * Creates a new, uninitialized SVGTransformItem.
         */
        protected SVGTransformItem() {
        }

        /**
         * Creates a new SVGTransformItem from the given {@link SVGTransform}.
         */
        protected SVGTransformItem(SVGTransform transform) {
            assign(transform);
        }

        /**
         * Notifies the parent list that this item has changed.  This also
         * discards the cached representation of the item.
         */
        protected void resetAttribute() {
            if (parent != null) {
                itemStringValue = null;
                parent.itemChanged();
            }
        }

        /**
         * Assigns a parent list to this item.
         * @param list The list the item belongs.
         */
        public void setParent(AbstractSVGList list) {
            parent = list;
        }

        /**
         * Returns the parent list of this item.
         */
        public AbstractSVGList getParent() {
            return parent;
        }

        /**
         * Returns the cached representation of the item if valid, otherwise
         * recomputes the String representation of the item.
         */
        public String getValueAsString() {
            if (itemStringValue == null) {
                itemStringValue = getStringValue();
            }
            return itemStringValue;
        }

        /**
         * Copies the values from the given {@link SVGTransform} into this
         * {@link SVGTransformItem}.
         */
        public void assign(SVGTransform transform) {
            type = transform.getType();
            SVGMatrix matrix = transform.getMatrix();
            switch (type) {
                case SVGTransform.SVG_TRANSFORM_TRANSLATE:
                    setTranslate(matrix.getE(), matrix.getF());
                    break;
                case SVGTransform.SVG_TRANSFORM_SCALE:
                    setScale(matrix.getA(), matrix.getD());
                    break;
                case SVGTransform.SVG_TRANSFORM_ROTATE:
                    if (matrix.getE() == 0.0f) {
                        rotate(transform.getAngle());
                    } else {
                        angleOnly = false;
                        if (matrix.getA() == 1.0f) {
                            setRotate(transform.getAngle(),
                                      matrix.getE(), matrix.getF());
                        } else if (transform instanceof AbstractSVGTransform) {
                            AbstractSVGTransform internal =
                                (AbstractSVGTransform) transform;
                            setRotate(internal.getAngle(),
                                      internal.getX(), internal.getY());
                        } else {
                            // XXX Should extract the angle, x and y from the
                            //     matrix.
                        }
                    }
                    break;
                case SVGTransform.SVG_TRANSFORM_SKEWX:
                    setSkewX(transform.getAngle());
                    break;
                case SVGTransform.SVG_TRANSFORM_SKEWY:
                    setSkewY(transform.getAngle());
                    break;
                case SVGTransform.SVG_TRANSFORM_MATRIX:
                    setMatrix(matrix);
                    break;
            }
        }

        /**
         * Sets the transform to be an x translation.
         */
        protected void translate(float x) {
            xOnly = true;
            setTranslate(x, 0.0f);
        }

        /**
         * Sets the transform to be rotation.
         */
        protected void rotate(float angle) {
            angleOnly = true;
            setRotate(angle, 0.0f, 0.0f);
        }

        /**
         * Sets the transform to be an x scale.
         */
        protected void scale(float x) {
            xOnly = true;
            setScale(x, x);
        }

        /**
         * Sets the transform to be a matrix transform.
         */
        protected void matrix(float a, float b, float c,
                              float d, float e, float f) {
            setMatrix(new SVGOMMatrix(new AffineTransform(a, b, c, d, e, f)));
        }

        /**
         * DOM: Implements {@link SVGTransform#setMatrix(SVGMatrix)}.
         */
        public void setMatrix(SVGMatrix matrix) {
            super.setMatrix(matrix);
            resetAttribute();
        }

        /**
         * DOM: Implements {@link SVGTransform#setTranslate(float,float)}.
         */
        public void setTranslate(float tx, float ty) {
            super.setTranslate(tx, ty);
            resetAttribute();
        }

        /**
         * DOM: Implements {@link SVGTransform#setScale(float,float)}.
         */
        public void setScale(float sx, float sy) {
            super.setScale(sx, sy);
            resetAttribute();
        }

        /**
         * DOM: Implements {@link
         * SVGTransform#setRotate(float,float,float)}.
         */
        public void setRotate(float angle, float cx, float cy) {
            super.setRotate(angle, cx, cy);
            resetAttribute();
        }

        /**
         * DOM: Implements {@link SVGTransform#setSkewX(float)}.
         */
        public void setSkewX(float angle) {
            super.setSkewX(angle);
            resetAttribute();
        }

        /**
         * DOM: Implements {@link SVGTransform#setSkewY(float)}.
         */
        public void setSkewY(float angle) {
            super.setSkewY(angle);
            resetAttribute();
        }

        /**
         * Creates the {@link SVGMatrix} used to store the transform.
         */
        protected SVGMatrix createMatrix() {
            return new AbstractSVGMatrix() {
                protected AffineTransform getAffineTransform() {
                    return SVGTransformItem.this.affineTransform;
                }
                public void setA(float a) throws DOMException {
                    SVGTransformItem.this.type = SVGTransform.SVG_TRANSFORM_MATRIX;
                    super.setA(a);
                    SVGTransformItem.this.resetAttribute();
                }
                public void setB(float b) throws DOMException {
                    SVGTransformItem.this.type = SVGTransform.SVG_TRANSFORM_MATRIX;
                    super.setB(b);
                    SVGTransformItem.this.resetAttribute();
                }
                public void setC(float c) throws DOMException {
                    SVGTransformItem.this.type = SVGTransform.SVG_TRANSFORM_MATRIX;
                    super.setC(c);
                    SVGTransformItem.this.resetAttribute();
                }
                public void setD(float d) throws DOMException {
                    SVGTransformItem.this.type = SVGTransform.SVG_TRANSFORM_MATRIX;
                    super.setD(d);
                    SVGTransformItem.this.resetAttribute();
                }
                public void setE(float e) throws DOMException {
                    SVGTransformItem.this.type = SVGTransform.SVG_TRANSFORM_MATRIX;
                    super.setE(e);
                    SVGTransformItem.this.resetAttribute();
                }
                public void setF(float f) throws DOMException {
                    SVGTransformItem.this.type = SVGTransform.SVG_TRANSFORM_MATRIX;
                    super.setF(f);
                    SVGTransformItem.this.resetAttribute();
                }
            };
        }

        /**
         * Returns the string representation of this transform.
         */
        protected String getStringValue(){
            StringBuffer buf = new StringBuffer();
            switch(type) {
                case SVGTransform.SVG_TRANSFORM_TRANSLATE:
                    buf.append("translate(");
                    buf.append((float) affineTransform.getTranslateX());
                    if (!xOnly) {
                        buf.append(' ');
                        buf.append((float) affineTransform.getTranslateY());
                    }
                    buf.append(')');
                    break;
                case SVGTransform.SVG_TRANSFORM_ROTATE:
                    buf.append("rotate(");
                    buf.append(angle);
                    if (!angleOnly) {
                        buf.append(' ');
                        buf.append(x);
                        buf.append(' ');
                        buf.append(y);
                    }
                    buf.append(')');
                    break;
                case SVGTransform.SVG_TRANSFORM_SCALE:
                    buf.append("scale(");
                    buf.append((float) affineTransform.getScaleX());
                    if (!xOnly) {
                        buf.append(' ');
                        buf.append((float) affineTransform.getScaleY());
                    }
                    buf.append(')');
                    break;
                case SVGTransform.SVG_TRANSFORM_SKEWX:
                    buf.append("skewX(");
                    buf.append(angle);
                    buf.append(')');
                    break;
                case SVGTransform.SVG_TRANSFORM_SKEWY:
                    buf.append("skewY(");
                    buf.append(angle);
                    buf.append(')');
                    break;
                case SVGTransform.SVG_TRANSFORM_MATRIX:
                    buf.append("matrix(");
                    double[] matrix = new double[6];
                    affineTransform.getMatrix(matrix);
                    for(int i = 0; i < 6; i++) {
                        if (i != 0) {
                            buf.append(' ');
                        }
                        buf.append((float) matrix[i]);
                    }
                    buf.append(')');
                    break;
            }
            return buf.toString();
        }
    }

    /**
     * Helper class to interface the {@link TransformListParser} and the
     * {@link ListHandler}.
     */
    protected class TransformListBuilder implements TransformListHandler {

        /**
         * The {@link ListHandler} to pass newly created
         * {@link SVGTransformItem} objects to.
         */
        protected ListHandler listHandler;

        /**
         * Creates a new TransformListBuilder.
         */
        public TransformListBuilder(ListHandler listHandler) {
            this.listHandler = listHandler;
        }

        /**
         * Implements {@link TransformListHandler#startTransformList()}.
         */
        public void startTransformList() throws ParseException {
            listHandler.startList();
        }

        /**
         * Implements {@link
         * TransformListHandler#matrix(float,float,float,float,float,float)}.
         */
        public void matrix(float a, float b, float c, float d, float e, float f)
                throws ParseException {
            SVGTransformItem item  = new SVGTransformItem();
            item.matrix(a, b, c, d, e, f);
            listHandler.item(item);
        }

        /**
         * Implements {@link TransformListHandler#rotate(float)}.
         */
        public void rotate(float theta) throws ParseException {
            SVGTransformItem item = new SVGTransformItem();
            item.rotate(theta);
            listHandler.item(item);
        }

        /**
         * Implements {@link TransformListHandler#rotate(float,float,float)}.
         */
        public void rotate(float theta, float cx, float cy)
                throws ParseException {
            SVGTransformItem item = new SVGTransformItem();
            item.setRotate(theta, cx, cy);
            listHandler.item(item);
        }

        /**
         * Implements {@link TransformListHandler#translate(float)}.
         */
        public void translate(float tx) throws ParseException {
            SVGTransformItem item = new SVGTransformItem();
            item.translate(tx);
            listHandler.item(item);
        }

        /**
         * Implements {@link TransformListHandler#translate(float,float)}.
         */
        public void translate(float tx, float ty) throws ParseException {
            SVGTransformItem item = new SVGTransformItem();
            item.setTranslate(tx, ty);
            listHandler.item(item);
        }

        /**
         * Implements {@link TransformListHandler#scale(float)}.
         */
        public void scale(float sx) throws ParseException {
            SVGTransformItem item  = new SVGTransformItem();
            item.scale(sx);
            listHandler.item(item);
        }

        /**
         * Implements {@link TransformListHandler#scale(float,float)}.
         */
        public void scale(float sx, float sy) throws ParseException {
            SVGTransformItem item = new SVGTransformItem();
            item.setScale(sx, sy);
            listHandler.item(item);
        }

        /**
         * Implements {@link TransformListHandler#skewX(float)}.
         */
        public void skewX(float skx) throws ParseException {
            SVGTransformItem item = new SVGTransformItem();
            item.setSkewX(skx);
            listHandler.item(item);
        }

        /**
         * Implements {@link TransformListHandler#skewY(float)}.
         */
        public void skewY(float sky) throws ParseException {
            SVGTransformItem item  = new SVGTransformItem();
            item.setSkewY(sky);
            listHandler.item(item);
        }

        /**
         * Implements {@link TransformListHandler#endTransformList()}.
         */
        public void endTransformList() throws ParseException {
            listHandler.endList();
        }
    }
}


text:
module Google
  module Cloud
    module Dataproc
      module V1beta2
        module ClusterController
          # Path helper methods for the ClusterController API.
          module Paths
            ##
            # Create a fully-qualified Cluster resource string.
            #
            # The resource will be in the following format:
            #
            # `projects/{project}/locations/{location}/clusters/{cluster}`
            #
            # @param project [String]
            # @param location [String]
            # @param cluster [String]
            #
            # @return [::String]
            def cluster_path project:, location:, cluster:
              raise ::ArgumentError, "project cannot contain /" if project.to_s.include? "/"
              raise ::ArgumentError, "location cannot contain /" if location.to_s.include? "/"

              "projects/#{project}/locations/#{location}/clusters/#{cluster}"
            end

            extend self
          end
        end
      end
    end
  end
end


text:
class Pakyow::Console::DataType
  attr_reader :id, :name, :icon_class

  def initialize(name, icon_class, &block)
    @id = name
    @name = name
    @icon_class = icon_class
    @relations = {}
    @attributes = {}
    @nice_names = {}
    @extras = {}
    @actions = {}
    @dynamic = []
    instance_exec(self, &block) if block_given?
  end

  def related_to(name, as: nil)
    @relations[name] = as || name
  end

  def reference(&block)
    @reference = block
  end

  def attribute(name, type = nil, nice: nil, **extras)
    if type.nil?
      return {
        extras: @extras[name]
      }
    end

    @attributes[name] = type
    @nice_names[name] = nice unless nice.nil?
    @extras[name] = extras
  end

  def attributes(datum = nil)
    @attributes.map { |attribute|
      {
        name: attribute[0],
        type: attribute[1],
        nice: @nice_names.fetch(attribute[0], Inflecto.humanize(attribute[0])),
        extras: @extras[attribute[0]],
      }
    }.concat(attributes_for_datum(datum))
  end

  def actions
    @actions.values
  end

  def [](var)
    instance_variable_get(:"@#{var}")
  end

  def model_object
    Object.const_get(model)
  end

  def display_name
    return nice_name unless pluralize?
    Inflecto.pluralize(nice_name)
  end

  def action(name, label: nil, notification: nil, display: nil, &block)
    @actions[name] = {
      name: name,
      label: label || Inflecto.humanize(name),
      notification: notification,
      display: display,
      logic: block,
    }
  end

  def nice_name(name = nil)
    if name.nil?
      @nice_name || Inflecto.humanize(Inflecto.underscore(self.name.to_s))
    else
      @nice_name = name
    end
  end

  def model(name = nil)
    return @model if name.nil?
    @model = name
  end

  def pluralize
    @pluralize = true
  end

  def hidden
    @hidden = true
  end

  def display?
    !@hidden
  end

  def dynamic(&block)
    @dynamic << block
  end

  private

  def pluralize?
    @pluralize == true
  end

  def attributes_for_datum(datum = nil)
    return [] if datum.nil?

    @dynamic.inject([]) do |arr, block|
      datatype = Pakyow::Console::DataType.new(name, icon_class)
      datatype.instance_exec(datum, &block)
      arr.concat(datatype.attributes)
    end
  end
end


text:
using System;

namespace Oocx.Pkcs
{
    public class OctetString : Asn1Object<byte[]>
    {
        public OctetString(byte[] data) : base(0x04)
        {
            Data = data ?? throw new ArgumentNullException(nameof(data));
            UnencodedValue = data;
        }
    }
}


text:
import {
  Component,
  ComponentRef,
  ViewChild,
  ViewEncapsulation,
  NgZone,
  ElementRef,
  EventEmitter,
  Inject,
  Optional,
  ChangeDetectorRef,
} from '@angular/core';
import {
  animate,
  trigger,
  state,
  style,
  transition,
  AnimationEvent,
} from '@angular/animations';
import {DOCUMENT} from '@angular/platform-browser';
import {BasePortalHost, ComponentPortal, PortalHostDirective, TemplatePortal} from '../core';
import {MdDialogConfig} from './dialog-config';
import {FocusTrapFactory, FocusTrap} from '../core/a11y/focus-trap';

/**
 * Throws an exception for the case when a ComponentPortal is
 * attached to a DomPortalHost without an origin.
 * @docs-private
 */
export function throwMdDialogContentAlreadyAttachedError() {
  throw Error('Attempting to attach dialog content after content is already attached');
}

/**
 * Internal component that wraps user-provided dialog content.
 * Animation is based on https://material.io/guidelines/motion/choreography.html.
 * @docs-private
 */
@Component({
  moduleId: module.id,
  selector: 'md-dialog-container, mat-dialog-container',
  templateUrl: 'dialog-container.html',
  styleUrls: ['dialog.css'],
  encapsulation: ViewEncapsulation.None,
  animations: [
    trigger('slideDialog', [
      // Note: The `enter` animation doesn't transition to something like `translate3d(0, 0, 0)
      // scale(1)`, because for some reason specifying the transform explicitly, causes IE both
      // to blur the dialog content and decimate the animation performance. Leaving it as `none`
      // solves both issues.
      state('enter', style({ transform: 'none', opacity: 1 })),
      state('void', style({ transform: 'translate3d(0, 25%, 0) scale(0.9)', opacity: 0 })),
      state('exit', style({ transform: 'translate3d(0, 25%, 0)', opacity: 0 })),
      transition('* => *', animate('400ms cubic-bezier(0.25, 0.8, 0.25, 1)')),
    ])
  ],
  host: {
    'class': 'mat-dialog-container',
    '[attr.role]': '_config?.role',
    '[attr.aria-labelledby]': '_ariaLabelledBy',
    '[attr.aria-describedby]': '_config?.ariaDescribedBy || null',
    '[@slideDialog]': '_state',
    '(@slideDialog.start)': '_onAnimationStart($event)',
    '(@slideDialog.done)': '_onAnimationDone($event)',
  },
})
export class MdDialogContainer extends BasePortalHost {
  /** The portal host inside of this container into which the dialog content will be loaded. */
  @ViewChild(PortalHostDirective) _portalHost: PortalHostDirective;

  /** The class that traps and manages focus within the dialog. */
  private _focusTrap: FocusTrap;

  /** Element that was focused before the dialog was opened. Save this to restore upon close. */
  private _elementFocusedBeforeDialogWasOpened: HTMLElement | null = null;

  /** The dialog configuration. */
  _config: MdDialogConfig;

  /** State of the dialog animation. */
  _state: 'void' | 'enter' | 'exit' = 'enter';

  /** Emits when an animation state changes. */
  _animationStateChanged = new EventEmitter<AnimationEvent>();

  /** ID of the element that should be considered as the dialog's label. */
  _ariaLabelledBy: string | null = null;

  /** Whether the container is currently mid-animation. */
  _isAnimating = false;

  constructor(
    private _ngZone: NgZone,
    private _elementRef: ElementRef,
    private _focusTrapFactory: FocusTrapFactory,
    private _changeDetectorRef: ChangeDetectorRef,
    @Optional() @Inject(DOCUMENT) private _document: any) {

    super();
  }

  /**
   * Attach a ComponentPortal as content to this dialog container.
   * @param portal Portal to be attached as the dialog content.
   */
  attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> {
    if (this._portalHost.hasAttached()) {
      throwMdDialogContentAlreadyAttachedError();
    }

    this._savePreviouslyFocusedElement();
    return this._portalHost.attachComponentPortal(portal);
  }

  /**
   * Attach a TemplatePortal as content to this dialog container.
   * @param portal Portal to be attached as the dialog content.
   */
  attachTemplatePortal(portal: TemplatePortal): Map<string, any> {
    if (this._portalHost.hasAttached()) {
      throwMdDialogContentAlreadyAttachedError();
    }

    this._savePreviouslyFocusedElement();
    return this._portalHost.attachTemplatePortal(portal);
  }

  /** Moves the focus inside the focus trap. */
  private _trapFocus() {
    if (!this._focusTrap) {
      this._focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement);
    }

    // If were to attempt to focus immediately, then the content of the dialog would not yet be
    // ready in instances where change detection has to run first. To deal with this, we simply
    // wait for the microtask queue to be empty.
    this._focusTrap.focusInitialElementWhenReady();
  }

  /** Restores focus to the element that was focused before the dialog opened. */
  private _restoreFocus() {
    const toFocus = this._elementFocusedBeforeDialogWasOpened;

    // We need the extra check, because IE can set the `activeElement` to null in some cases.
    if (toFocus && 'focus' in toFocus) {
      toFocus.focus();
    }

    if (this._focusTrap) {
      this._focusTrap.destroy();
    }
  }

  /** Saves a reference to the element that was focused before the dialog was opened. */
  private _savePreviouslyFocusedElement() {
    if (this._document) {
      this._elementFocusedBeforeDialogWasOpened = this._document.activeElement as HTMLElement;
    }
  }

  /** Callback, invoked whenever an animation on the host completes. */
  _onAnimationDone(event: AnimationEvent) {
    if (event.toState === 'enter') {
      this._trapFocus();
    } else if (event.toState === 'exit') {
      this._restoreFocus();
    }

    this._animationStateChanged.emit(event);
    this._isAnimating = false;
  }

  /** Callback, invoked when an animation on the host starts. */
  _onAnimationStart(event: AnimationEvent) {
    this._isAnimating = true;
    this._animationStateChanged.emit(event);
  }

  /** Starts the dialog exit animation. */
  _startExitAnimation(): void {
    this._state = 'exit';

    // Mark the container for check so it can react if the
    // view container is using OnPush change detection.
    this._changeDetectorRef.markForCheck();
  }
}


text:
"""

Custom request from our Director on High to provide a script which generates
a PowerPoint slide set based on a specific input convention in a text file.

INPUT:

- Spaces at the beginning of a line (0-2) are header levels
- Content is composed entirely of bulleted lists
- List elements start with # symbols, and more than one indicates nesting levels

Example:

This would be title 1
#this would be text for first bullet
#this would be text for second bullet
##text for sub-bullet
##second sub-bullet
#text for third bullet

This would be title 2
#blah1a
#blah1b
##blah2

Module documentation:
https://python-pptx.readthedocs.io/en/latest/user/quickstart.html

"""

import argparse
import os
from pptx import Presentation

def main():
    parser = argparse.ArgumentParser( description='Create PowerPoint slides from a plain text file')

    parser.add_argument('-i', '--input_file', type=str, required=True, help='Path to an input text file to be read' )
    parser.add_argument('-o', '--output_file', type=str, required=True, help='Path to an output pptx file to be created' )
    args = parser.parse_args()

    prs = Presentation()
    bullet_layout = prs.slide_layouts[1]

    current_slide = None
    current_body_shape = None
    current_tf = None

    for line in open(args.input_file):
        line = line.rstrip()

        # skip blank lines
        if len(line) == 0:
            continue

        if line.startswith('   '):
            raise Exception("Header levels greater than 3 are not supported")
        elif line.startswith('  '):
            raise Exception('Sub-headers not yet supported')
        elif line.startswith(' '):
            raise Exception('Sub-headers not yet supported')
        elif line.startswith('#'):
            hash_count = get_hash_count(line)

            if hash_count == 1:
                if current_tf is None:
                    current_tf = current_body_shape.text_frame
                    current_tf.text = line.lstrip('#')
                else:
                    p = current_tf.add_paragraph()
                    p.text = line.lstrip('#')
                    p.level = hash_count - 1
            elif hash_count > 1:
                p = current_tf.add_paragraph()
                p.text = line.lstrip('#')
                p.level = hash_count - 1

        else:
            # Must be a title slide line
            current_slide = prs.slides.add_slide(bullet_layout)
            shapes = current_slide.shapes

            title_shape = shapes.title
            title_shape.text = line

            current_body_shape = shapes.placeholders[1]
            current_tf = None

    prs.save(args.output_file)

def get_hash_count(s):
    cnt = 0
    for c in s:
        if c == '#':
            cnt += 1
        else:
            break

    return cnt

if __name__ == '__main__':
    main()


text:
//=========================================================================
// FILENAME	: tagutils-ogg.h
// DESCRIPTION	: Ogg metadata reader
//=========================================================================
// Copyright (c) 2008- NETGEAR, Inc. All Rights Reserved.
//=========================================================================

/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

static int _get_oggfileinfo(char *filename, struct song_metadata *psong);


text:
package rui.coder.design.pattern.behaviour.interpreter;

public interface Expression {
    public boolean interpret(String context);
}


text:
"""
Notes:
- this is the 'core' driver for the ZI HDAWG: it contains the generic parts of
  the driver. Application dependent parts (e.g. codeword handling) reside in ZI_HDAWG8.py

To do:
- replace print() by logging

Changelog:

20190212 WJV
- separated off application independent stuff into this ZI_HDAWG_core class,
  file ZI_HDAWG8.py will keep application dependent stuff. The software
  interface remains unchanged.
- addressed many warnings identified by PyCharm
- started adding more type annotations

20190214 WJV
- added check_timing_error()
- moved out _add_extra_parameters() and _add_codeword_parameters()
- added load_default_settings()
- moved in _set_dio_delay()
- replaced some warnings by Exceptions
- made some instance variables 'private'

20190219 WJV
- removed unused open from _write_csv_waveform()

20190429 WJV
- merged branch 'QCC_testing' into 'feature/cc', changes:
    pulled in changed upload_waveform_realtime from ZI_HDAWG8.py again

20190618 WJV
- merged branch 'develop' into 'feature/cc', changes:
    pulled in changed upload_waveform_realtime from ZI_HDAWG8.py again

20190709 NCH
- Updated to use the improved ZI_base_instrument functionality, which now
    makes a lot of methods common to both the HDAWG and the UHF-QA.
- Removed zishell_NH

"""

import logging
import time
import json
import copy

import pycqed.instrument_drivers.physical_instruments.ZurichInstruments.ZI_base_instrument as zibase

log = logging.getLogger(__name__)

class ZI_HDAWG_core(zibase.ZI_base_instrument):
    """
    This is PycQED/QCoDeS driver driver for the Zurich Instruments HDAWG.

    Parameter files are generated from the python API of the instrument
    using the "create_parameter_file" method in the ZI_base_instrument class.
    These are used to add parameters to the instrument.
    """

    # Define minimum required revisions
    MIN_FWREVISION = 62730
    MIN_FPGAREVISION = 62832
    MIN_SLAVEREVISION = 62659

    ##########################################################################
    # 'public' functions: device control
    ##########################################################################

    def __init__(self,
                 name: str,
                 device: str,
                 interface: str = '1GbE',
                 server: str = 'localhost',
                 port: int = 8004,
                 num_codewords: int = 32,
                 **kw) -> None:
        """
        Input arguments:
            name:           (str) name of the instrument as seen by the user
            device          (str) the name of the device e.g., "dev8008"
            interface       (str) the name of the interface to use ('1GbE' or 'USB')
            server          (str) the host where the ziDataServer is running
            port            (int) the port to connect to for the ziDataServer (don't change)
            num_codewords   (int) the number of codeword-based waveforms to prepare
        """
        t0 = time.time()
        super().__init__(name=name, device=device, interface=interface, server=server, port=port, num_codewords=num_codewords, **kw)
        self._default_waveform_length = 48  # Override default waveform length to 20 ns at 2.4 GSa/s

        # NB: we don't want to load defaults automatically, but leave it up to the user

        # Configure instrument to blink forever
        self.seti('raw/error/blinkseverity', 1)
        self.seti('raw/error/blinkforever', 1)

        t1 = time.time()
        log.info(f"{self.devname}: Initialized ZI_HDAWG_core in {t1 - t0:.3}s")

    def _check_devtype(self):
        if self.devtype != 'HDAWG8' and self.devtype != 'HDAWG4':
            raise zibase.ziDeviceError('Device {} of type {} is not a HDAWG instrument!'.format(self.devname, self.devtype))

    def _check_options(self):
        """
        Checks that the correct options are installed on the instrument.
        """
        options = self.gets('features/options').split('\n')
        if 'PC' not in options:
            raise zibase.ziOptionsError('Device {} is missing the PC option!'.format(self.devname))

    def _check_awg_nr(self, awg_nr):
        """
        Checks that the given AWG index is valid for the device.
        """
        if self.devtype == 'HDAWG8' and (awg_nr < 0 or awg_nr > 3):
            raise zibase.ziValueError('Invalid AWG index of {} detected!'.format(awg_nr))
        elif self.devtype == 'HDAWG4' and (awg_nr < 0 or awg_nr > 1):
            raise zibase.ziValueError('Invalid AWG index of {} detected!'.format(awg_nr))

    def _check_versions(self):
        """
        Checks that sufficient versions of the firmware are available.
        """
        if self.geti('system/fwrevision') < ZI_HDAWG_core.MIN_FWREVISION:
            raise zibase.ziVersionError('Insufficient firmware revision detected! Need {}, got {}!'.format(ZI_HDAWG_core.MIN_FWREVISION, self.geti('system/fwrevision')))

        if self.geti('system/fpgarevision') < ZI_HDAWG_core.MIN_FPGAREVISION:
            raise zibase.ziVersionError('Insufficient FPGA revision detected! Need {}, got {}!'.format(ZI_HDAWG_core.MIN_FPGAREVISION, self.geti('system/fpgarevision')))

        if self.geti('system/slaverevision') < ZI_HDAWG_core.MIN_SLAVEREVISION:
            raise zibase.ziVersionError('Insufficient FPGA Slave revision detected! Need {}, got {}!'.format(ZI_HDAWG_core.MIN_SLAVEREVISION, self.geti('system/slaverevision')))

    def _num_channels(self):
        if self.devtype == 'HDAWG8':
            return 8
        elif self.devtype == 'HDAWG4':
            return 4
        else:
            raise Exception("Unknown device type '{}'".format(self.devtype))

    def load_default_settings(self):
        """
        bring device into known state
        """

        log.warning('{}: loading default settings (FIXME: still incomplete)'
                    .format(self.devname))

        # Setting the clock to external
        self.assure_ext_clock()

        # clear output

        # clear AWGs

        # reset DIO parameters (bits, timing)
        self._set_dio_delay(0)  # set all delays to 0

        # interesting nodes:
        # SYSTEM/AWG/CHANNELGROUPING
        # SYSTEM/CLOCKS/SAMPLECLOCK/FREQ
        #

    def assure_ext_clock(self) -> None:
        """
        Make sure the instrument is using an external reference clock

        Based on: AWG8_V2_DIO_Calibrarion.ipynb
        """

        # get source:
        #   1: external
        #   0: internal (commanded so, or because of failure to sync to external clock)
        source = self.system_clocks_referenceclock_source()
        if source == 1:
            log.info(f'{self.devname}: Already using external clock')
            return

        log.info(f'{self.devname}: Switching to external clock. This could take a while')
        while True:
            self.system_clocks_referenceclock_source(1)
            while True:
                # get status (see docstring):
                #   0: synced
                #   1: sync failed (will force clock source to internal and retry)
                #   2: syncing
                status = self.system_clocks_referenceclock_status()
                if status == 0:             # synced
                    break
                elif status == 2:           # syncing
                    print('.', end='')
                else:                       # sync failed
                    print('X', end='')
                time.sleep(0.1)
            if self.system_clocks_referenceclock_source() != 1:
                log.error(f'{self.devname}: Switching to external clock failed. Trying again')
            else:
                break
        log.info(f'{self.devname}: Successfully switched to external clock')

    # FIXME: add check_virt_mem_use(self)
    # AWGS/0/SEQUENCER/MEMORYUSAGE
    # AWGS/0/WAVEFORM/MEMORYUSAGE

    def get_idn(self) -> dict:
        idn_dict = super().get_idn()
        idn_dict['slave_firmware'] = self.geti('system/slaverevision')
        return idn_dict

    ##########################################################################
    # 'public' functions: generic AWG/waveform support
    ##########################################################################

    def upload_waveform_realtime(self, w0, w1, awg_nr: int, wf_nr: int = 1):
        """
        Warning! This method should be used with care.
        Uploads a waveform to the awg in realtime, note that this get's
        overwritten if a new program is uploaded.

        Arguments:
            w0   (array): waveform for ch0 of the awg pair.
            w1   (array): waveform for ch1 of the awg pair.
            awg_nr (int): awg_nr indicating what awg pair to use.
            wf_nr  (int): waveform in memory to overwrite, default is 1.

        There are a few important notes when using this method
        - w0 and w1 must be of the same length
        - any parts of a waveform longer than w0/w1 will not be overwritten.
        - loading speed depends on the size of w0 and w1 and is ~80ms for 20us.

        """
        raise NotImplementedError('Please use the waveform parameters ("wave_chN_cwM") of the object to change waveforms!')

    ##########################################################################
    # 'public' functions: DIO debug support
    ##########################################################################

    def plot_dio_snapshot(self, bits=range(32)):
        zibase.plot_timing_diagram(self.getv('raw/dios/0/data'), bits, 64)

    def plot_awg_codewords(self, awg_nr=0, range=None):
        ts = []
        cws = []
        for d in self.getv('awgs/{}/dio/data'.format(awg_nr)):
            cws.append(d & 0x3ff)
            ts.append((d >> 10) & 0x3fffff)
        zibase.plot_codeword_diagram(ts, cws, range)

    ##########################################################################
    # 'private' functions, internal to the driver
    ##########################################################################

    # FIXME: no longer used
    def _set_dio_delay(self, delay):
        """
        The function sets the DIO delay for the instrument. The valid delay range is
        0 to 15. The delays are applied to all bits of the DIO bus.
        """
        if delay < 0:
            log.warning('{}: Clamping delay to 0'.format(self.devname))
        if delay > 15:
            log.warning('{}: Clamping delay to 15'.format(self.devname))
            delay = 15

        self.seti('raw/dios/0/delays/*/value', delay)


text:
package org.orekit.files.ccsds.definitions;

import java.util.Locale;
import java.util.function.Function;

import org.orekit.annotation.DefaultDataContext;
import org.orekit.bodies.CelestialBodies;
import org.orekit.bodies.CelestialBody;
import org.orekit.bodies.CelestialBodyFactory;
import org.orekit.data.DataContext;
import org.orekit.frames.FactoryManagedFrame;
import org.orekit.frames.Frame;
import org.orekit.frames.Predefined;

/** Orbit central bodies for which a Celestial body can be created.
 * @author sports
 * @since 6.1
 */
public enum CenterName {
    /** Solar system barycenter aggregated body. */
    SOLAR_SYSTEM_BARYCENTER(celestialBodies -> celestialBodies.getSolarSystemBarycenter()),

    /** Sun body. */
    SUN(celestialBodies -> celestialBodies.getSun()),

    /** Mercury body. */
    MERCURY(celestialBodies -> celestialBodies.getMercury()),

    /** Venus body. */
    VENUS(celestialBodies -> celestialBodies.getVenus()),

    /** Earth-Moon barycenter bodies pair. */
    EARTH_MOON(celestialBodies -> celestialBodies.getEarthMoonBarycenter()),

    /** Earth body. */
    EARTH(celestialBodies -> celestialBodies.getEarth()),

    /** Moon body. */
    MOON(celestialBodies -> celestialBodies.getMoon()),

    /** Mars body. */
    MARS(celestialBodies -> celestialBodies.getMars()),

    /** Jupiter body. */
    JUPITER(celestialBodies -> celestialBodies.getJupiter()),

    /** Saturn body. */
    SATURN(celestialBodies -> celestialBodies.getSaturn()),

    /** Uranus body. */
    URANUS(celestialBodies -> celestialBodies.getUranus()),

    /** Neptune body. */
    NEPTUNE(celestialBodies -> celestialBodies.getNeptune()),

    /** Pluto body. */
    PLUTO(celestialBodies -> celestialBodies.getPluto());

    /** Suffix of the name of the inertial frame attached to a planet. */
    private static final String INERTIAL_FRAME_SUFFIX = "/inertial";

    /** Suffix of the name of the rotating frame attached to a planet. */
    private static final String ROTATING_FRAME_SUFFIX = "/rotating";

    /**
     * Standardized locale to use, to ensure files can be exchanged without
     * internationalization issues.
     */
    private static final Locale STANDARDIZED_LOCALE = Locale.US;

    /** Substring common to all ITRF frames. */
    /** Celestial body getter.
     * @return getter for celestial body
     */
    private final Function<CelestialBodies, CelestialBody> celestialBodyGetter;

    /** Simple constructor.
     * @param celestialBodyGetter getter for celestial body
     */
    CenterName(final Function<CelestialBodies, CelestialBody> celestialBodyGetter) {
        this.celestialBodyGetter = celestialBodyGetter;
    }

    /**
     * Get the celestial body corresponding to the CCSDS constant.
     *
     * <p>This method uses the {@link DataContext#getDefault() default data context}.
     *
     * @return celestial body corresponding to the CCSDS constant
     * @see #getCelestialBody(CelestialBodies)
     */
    @DefaultDataContext
    public CelestialBody getCelestialBody() {
        return getCelestialBody(DataContext.getDefault().getCelestialBodies());
    }

    /**
     * Get the celestial body corresponding to the CCSDS constant.
     *
     * @param celestialBodies the set of celestial bodies to use.
     * @return celestial body corresponding to the CCSDS constant
     * @since 10.1
     */
    public CelestialBody getCelestialBody(final CelestialBodies celestialBodies) {
        return celestialBodyGetter.apply(celestialBodies);
    }

    /**
     * Guess the name of the center of the reference frame.
     *
     * @param frame a reference frame for ephemeris output.
     * @return the string to use in the OEM file to describe the origin of {@code frame}.
     */
    public static String guessCenter(final Frame frame) {
        final String name = frame.getName();
        if (name.endsWith(INERTIAL_FRAME_SUFFIX) || name.endsWith(ROTATING_FRAME_SUFFIX)) {
            return name.substring(0, name.length() - 9).toUpperCase(STANDARDIZED_LOCALE);
        } else if (frame instanceof ModifiedFrame) {
            return ((ModifiedFrame) frame).getCenterName();
        } else if (frame.getName().equals(Predefined.ICRF.getName())) {
            return CelestialBodyFactory.SOLAR_SYSTEM_BARYCENTER.toUpperCase(STANDARDIZED_LOCALE);
        } else if (frame.getDepth() == 0 || frame instanceof FactoryManagedFrame) {
            return "EARTH";
        } else {
            return "UNKNOWN";
        }
    }

    /**
     * Map an Orekit frame to a CCSDS center.
     *
     * @param frame a reference frame.
     * @return the string to use in the OEM file to describe the origin of {@code frame},
     * or null if no such center can be found
     */
    public static CenterName map(final Frame frame) {
        try {
            return CenterName.valueOf(guessCenter(frame));
        } catch (IllegalArgumentException iae) {
            // we were unable to find a match
            return null;
        }
    }

}


text:
cask 'stay' do
  version '1.3'
  sha256 'fc20518adc53aba6856cc5b3149889f046ab640134a9876952c5a0cb61e9b6a2'

  url "https://cordlessdog.com/stay/versions/Stay%20#{version}.dmg"
  appcast 'https://cordlessdog.com/stay/appcast.xml'
  name 'Stay'
  homepage 'https://cordlessdog.com/stay/'

  depends_on macos: '>= :mojave'

  app 'Stay.app'

  zap trash: [
               '~/Library/Application Support/Stay',
               '~/Library/Application Support/com.cordlessdog.Stay',
               '~/Library/Preferences/com.cordlessdog.Stay.plist',
             ]
end


text:
====
Cost
====

Calibrating the economic cost side of EZ-Climate requires specifying a relationship between the marginal cost of emissions reductions or per-ton tax rate, :math:`\tau`, the resulting flow of emissions in gigatonnes of :math:`CO_2`-equivalent emissions per year (Gt :math:`CO_2`), :math:`g(\tau)`, and the fraction of emissions reduced, :math:`x(\tau)`.

We calibrate :math:`\tau`, :math:`g(\tau)`, and :math:`x(\tau)` in EZ-Climate based on McKinsey's global MACC effort (McKinsey_), with one crucial modification; we assume no mitigation (:math:`x(\tau)=0`) at :math:`\tau \le 0` i.e. no net-negative or zero-cost mitigation. Table 1 below shows the resulting calibration.

.. image:: ../_static/cost1.png
   :width: 600 px
   :align: center

Fitting McKinsey's modified point estimates (in $US) from Table 1 to a power function for :math:`x(\tau)` yields:

.. math::

	x(\tau) = 0.0923 \tau^{0.414}.

The corresponding inverse function, solving for the appropriate tax rate to achieve :math:`x` is:

.. math::

	\tau(x) = 314.32 x^{2.413}.

The above equation shows the marginal cost of abatement. Ultimately, we are interested in the total cost to society, :math:`\kappa(x)`, for each particular fractional-mitigation :math:`x`. We calculate using the envelope theorem and get the following equation:

.. math::

	\kappa(x) = \left(\frac{92.08 g_0}{c_0}\right) x^{3.413},

where :math:`g_0=52` Gt :math:`CO_2` represents the current level of global annual emissions, and :math:`c_0=$31` trilling/year in current (2015) global consumption. The equation for :math:`\kappa(x)` expresses the societal cost of a given level of mitigation as a percentage of consumption. We assume that, absent technological change, the function is time invariant.

We also allow for backstop technology and technological changes. For discussion and derivation of these parameters, see paper_. At the end, we have the following cost function:

.. math::

	\kappa_t(x) = \kappa(x) \left( 1-\phi_0 - \phi_1 X_t \right)

where :math:`\phi_0` is a constant component, and :math:`\phi_1 X_t` a component linked to mitigation efforts  to date (where :math:`X_t` is the average mitigation up to time :math:`t`). See :mod:`ezclimate.cost` for more details.

.. _McKinsey: http://www.mckinsey.com/business-functions/sustainability-and-resource-productivity/our-insights/pathways-to-a-low-carbon-economy
.. _paper: http://www.nber.org/papers/w22795


text:
#ifndef SPECTRUMANALYSER_H
#define SPECTRUMANALYSER_H

#include <QByteArray>
#include <QObject>
#include <QVector>

#ifdef DUMP_SPECTRUMANALYSER
#include <QDir>
#include <QFile>
#include <QTextStream>
#endif

#include "frequencyspectrum.h"
#include "spectrum.h"

#ifndef DISABLE_FFT
#include "FFTRealFixLenParam.h"
#endif

QT_FORWARD_DECLARE_CLASS(QAudioFormat)
QT_FORWARD_DECLARE_CLASS(QThread)

class FFTRealWrapper;

class SpectrumAnalyserThreadPrivate;

/**
 * Implementation of the spectrum analysis which can be run in a
 * separate thread.
 */
class SpectrumAnalyserThread : public QObject
{
    Q_OBJECT
public:
    SpectrumAnalyserThread(QObject *parent);
    ~SpectrumAnalyserThread();

public slots:
    void setWindowFunction(WindowFunction type);
    void calculateSpectrum(const QByteArray &buffer,
                           int inputFrequency,
                           int bytesPerSample);

signals:
    void calculationComplete(const FrequencySpectrum &spectrum);

private:
    void calculateWindow();

private:
#ifndef DISABLE_FFT
    FFTRealWrapper*                             m_fft;
#endif

    const int                                   m_numSamples;

    WindowFunction                              m_windowFunction;

#ifdef DISABLE_FFT
    typedef qreal                               DataType;
#else
    typedef FFTRealFixLenParam::DataType        DataType;
#endif
    QVector<DataType>                           m_window;

    QVector<DataType>                           m_input;
    QVector<DataType>                           m_output;

    FrequencySpectrum                           m_spectrum;

#ifdef SPECTRUM_ANALYSER_SEPARATE_THREAD
    QThread*                                    m_thread;
#endif
};

/**
 * Class which performs frequency spectrum analysis on a window of
 * audio samples, provided to it by the Engine.
 */
class SpectrumAnalyser : public QObject
{
    Q_OBJECT
public:
    SpectrumAnalyser(QObject *parent = 0);
    ~SpectrumAnalyser();

#ifdef DUMP_SPECTRUMANALYSER
    void setOutputPath(const QString &outputPath);
#endif

public:
    /*
     * Set the windowing function which is applied before calculating the FFT
     */
    void setWindowFunction(WindowFunction type);

    /*
     * Calculate a frequency spectrum
     *
     * \param buffer       Audio data
     * \param format       Format of audio data
     *
     * Frequency spectrum is calculated asynchronously.  The result is returned
     * via the spectrumChanged signal.
     *
     * An ongoing calculation can be cancelled by calling cancelCalculation().
     *
     */
    void calculate(const QByteArray &buffer, const QAudioFormat &format);

    /*
     * Check whether the object is ready to perform another calculation
     */
    bool isReady() const;

    /*
     * Cancel an ongoing calculation
     *
     * Note that cancelling is asynchronous.
     */
    void cancelCalculation();

signals:
    void spectrumChanged(const FrequencySpectrum &spectrum);

private slots:
    void calculationComplete(const FrequencySpectrum &spectrum);

private:
    void calculateWindow();

private:

    SpectrumAnalyserThread*    m_thread;

    enum State {
        Idle,
        Busy,
        Cancelled
    };

    State              m_state;

#ifdef DUMP_SPECTRUMANALYSER
    QDir                m_outputDir;
    int                 m_count;
    QFile               m_textFile;
    QTextStream         m_textStream;
#endif
};

#endif // SPECTRUMANALYSER_H


text:
/* ----------------------- System includes ----------------------------------*/
#include "stdlib.h"
#include "string.h"

/* ----------------------- Platform includes --------------------------------*/
#include "port.h"

/* ----------------------- Modbus includes ----------------------------------*/
#include "mb.h"
#include "mbconfig.h"
#include "mbtcp.h"
#include "mbframe.h"
#include "mbport.h"

#if MB_TCP_ENABLED > 0

/* ----------------------- Defines ------------------------------------------*/

/* ----------------------- MBAP Header --------------------------------------*/
/*
 *
 * <------------------------ MODBUS TCP/IP ADU(1) ------------------------->
 *              <----------- MODBUS PDU (1') ---------------->
 *  +-----------+---------------+------------------------------------------+
 *  | TID | PID | Length | UID  |Code | Data                               |
 *  +-----------+---------------+------------------------------------------+
 *  |     |     |        |      |
 * (2)   (3)   (4)      (5)    (6)
 *
 * (2)  ... MB_TCP_TID          = 0 (Transaction Identifier - 2 Byte)
 * (3)  ... MB_TCP_PID          = 2 (Protocol Identifier - 2 Byte)
 * (4)  ... MB_TCP_LEN          = 4 (Number of bytes - 2 Byte)
 * (5)  ... MB_TCP_UID          = 6 (Unit Identifier - 1 Byte)
 * (6)  ... MB_TCP_FUNC         = 7 (Modbus Function Code)
 *
 * (1)  ... Modbus TCP/IP Application Data Unit
 * (1') ... Modbus Protocol Data Unit
 */

#define MB_TCP_TID          0
#define MB_TCP_PID          2
#define MB_TCP_LEN          4
#define MB_TCP_UID          6
#define MB_TCP_FUNC         7

#define MB_TCP_PROTOCOL_ID  0   /* 0 = Modbus Protocol */

/* ----------------------- Start implementation -----------------------------*/
eMBErrorCode
eMBTCPDoInit( USHORT ucTCPPort )
{
    eMBErrorCode    eStatus = MB_ENOERR;

    if( xMBTCPPortInit( ucTCPPort ) == FALSE )
    {
        eStatus = MB_EPORTERR;
    }
    return eStatus;
}

void
eMBTCPStart( void )
{
}

void
eMBTCPStop( void )
{
    /* Make sure that no more clients are connected. */
    vMBTCPPortDisable( );
}

eMBErrorCode
eMBTCPReceive( UCHAR * pucRcvAddress, UCHAR ** ppucFrame, USHORT * pusLength )
{
    eMBErrorCode    eStatus = MB_EIO;
    UCHAR          *pucMBTCPFrame;
    USHORT          usLength;
    USHORT          usPID;

    if( xMBTCPPortGetRequest( &pucMBTCPFrame, &usLength ) != FALSE )
    {
        usPID = pucMBTCPFrame[MB_TCP_PID] << 8U;
        usPID |= pucMBTCPFrame[MB_TCP_PID + 1];

        if( usPID == MB_TCP_PROTOCOL_ID )
        {
            *ppucFrame = &pucMBTCPFrame[MB_TCP_FUNC];
            *pusLength = usLength - MB_TCP_FUNC;
            eStatus = MB_ENOERR;

            /* Modbus TCP does not use any addresses. Fake the source address such
             * that the processing part deals with this frame.
             */
            *pucRcvAddress = MB_TCP_PSEUDO_ADDRESS;
        }
    }
    else
    {
        eStatus = MB_EIO;
    }
    return eStatus;
}

eMBErrorCode
eMBTCPSend( UCHAR _unused, const UCHAR * pucFrame, USHORT usLength )
{
    eMBErrorCode    eStatus = MB_ENOERR;
    UCHAR          *pucMBTCPFrame = ( UCHAR * ) pucFrame - MB_TCP_FUNC;
    USHORT          usTCPLength = usLength + MB_TCP_FUNC;

    /* The MBAP header is already initialized because the caller calls this
     * function with the buffer returned by the previous call. Therefore we
     * only have to update the length in the header. Note that the length
     * header includes the size of the Modbus PDU and the UID Byte. Therefore
     * the length is usLength plus one.
     */
    pucMBTCPFrame[MB_TCP_LEN] = ( usLength + 1 ) >> 8U;
    pucMBTCPFrame[MB_TCP_LEN + 1] = ( usLength + 1 ) & 0xFF;
    if( xMBTCPPortSendResponse( pucMBTCPFrame, usTCPLength ) == FALSE )
    {
        eStatus = MB_EIO;
    }
    return eStatus;
}

#endif


text:
namespace com.googlecode.lanterna.gui2.table
{

	/// <summary>
	/// Formalized interactable renderer for tables
	/// @author Martin
	/// </summary>
	public interface TableRenderer<V> : InteractableRenderer<Table<V>>
	{
		void drawComponent(TextGUIGraphics graphics, Table<V> component);

		TerminalSize getPreferredSize(Table<V> component);
	}

}


text:
<?php

namespace Jstewmc\ActiveResourceModel\Tests;

/**
 * Tests for the Model class
 *
 * Keep in mind, I (Jack) did a few things differently here:
 *
 *     - Because the library defines interfaces, not concreate classes, I had to
 *       define the concrete classes.
 *     - As a result, tests are in their own namespace, not the library's main
 *       namespace.
 *     - Because I define the output each request will give me, I know exactly
 *       what I should expect (see the Model class for details).
 */
class ModelTest extends \PHPUnit_Framework_TestCase
{
	/* !create() */

	/**
	 * create() should throw a BadMethodCallException if the model does have id
	 */
	public function test_create_throwsBadMethodCallException_ifModelDoesHaveId()
	{
		$this->setExpectedException('BadMethodCallException');

		$client = new Api\Client();

		$model = new Model($client);
		$model->id = 1;
		$model->foo = 'bar';

		$model->create();

		return;
	}

	/**
	 * create() should set the model's id and return self if model does not have id
	 */
	public function test_create_returnsSelf_ifModelDoesNotHaveId()
	{
		$client = new Api\Client();

		$model = new Model($client);
		$model->foo = 'bar';

		$model->create();

		$this->assertEquals(1, $model->id);

		return;
	}

	/* !delete() */

	/**
	 * delete() should throw BadMethodCallException if model does not have id
	 */
	public function test_delete_throwsBadMethodCallException_ifModelDoesNotHaveId()
	{
		$this->setExpectedException('BadMethodCallException');

		$client = new Api\Client();

		$model = new Model($client);
		$model->delete();

		return;
	}

	/**
	 * delete() should return self if model does have id
	 */
	public function test_delete_returnsSelf_ifModelDoesHaveId()
	{
		$client = new Api\Client();

		$model = new Model($client);
		$model->id = 1;

		$model->delete();

		$this->assertNull($model->id);

		return;
	}

	/* !index() */

	/**
	 * index() should return an array if entities exist
	 */
	public function test_index_returnsArray()
	{
		$client = new Api\Client();

		$model = new Model($client);

		$model1 = new Model($client);
		$model1->id = 1;
		$model1->foo = 'bar';

		$model2 = new Model($client);
		$model2->id = 2;
		$model2->foo = 'baz';

		$this->assertEquals([$model1, $model2], $model->index());

		return;
	}

	/* !read() */

	/**
	 * read() should throw InvalidArgumentException if $id is not a positive int
	 */
	public function test_read_throwsInvalidArgumentException_ifIdIsNotPositiveInt()
	{
		$this->setExpectedException('InvalidArgumentException');

		(new Model(new Api\Client()))->read('foo');

		return;
	}

	/**
	 * read() should return self if id is a positive int
	 */
	public function test_read_returnsSelf_ifIdIsPositiveInt()
	{
		$client = new Api\Client();

		$model = new Model($client);

		$this->assertSame($model, $model->read(1));

		return;
	}

	/* !update() */

	/**
	 * update() should throw BadMethodCallException if the model does not have id
	 */
	public function test_update_throwsBadMethodCallException_ifModelDoesNotHaveId()
	{
		$this->setExpectedException('BadMethodCallException');

		(new Model(new Api\Client()))->update();

		return;
	}

	/**
	 * update() should return self if the model does have id
	 */
	public function test_update_returnsSelf_ifModelDoesHaveId()
	{
		$client = new Api\Client();

		$model = new Model($client);
		$model->id = 1;

		$model->update();

		$this->assertSame($model, $model->update());

		return;
	}
}